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.

278998 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 || JUCE_IOS
  76. #if defined (DEBUG) || defined (_DEBUG) || ! (defined (NDEBUG) || defined (_NDEBUG))
  77. #define JUCE_DEBUG 1
  78. #endif
  79. #if ! (defined (DEBUG) || defined (_DEBUG) || defined (NDEBUG) || defined (_NDEBUG))
  80. #warning "Neither NDEBUG or DEBUG has been defined - you should set one of these to make it clear whether this is a release build,"
  81. #endif
  82. #ifdef __LITTLE_ENDIAN__
  83. #define JUCE_LITTLE_ENDIAN 1
  84. #else
  85. #define JUCE_BIG_ENDIAN 1
  86. #endif
  87. #endif
  88. #if JUCE_MAC
  89. #if defined (__ppc__) || defined (__ppc64__)
  90. #define JUCE_PPC 1
  91. #else
  92. #define JUCE_INTEL 1
  93. #endif
  94. #ifdef __LP64__
  95. #define JUCE_64BIT 1
  96. #else
  97. #define JUCE_32BIT 1
  98. #endif
  99. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  100. #error "Building for OSX 10.3 is no longer supported!"
  101. #endif
  102. #ifndef MAC_OS_X_VERSION_10_5
  103. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  104. #endif
  105. #endif
  106. #if JUCE_LINUX
  107. #ifdef _DEBUG
  108. #define JUCE_DEBUG 1
  109. #endif
  110. // Allow override for big-endian Linux platforms
  111. #ifndef JUCE_BIG_ENDIAN
  112. #define JUCE_LITTLE_ENDIAN 1
  113. #endif
  114. #if defined (__LP64__) || defined (_LP64)
  115. #define JUCE_64BIT 1
  116. #else
  117. #define JUCE_32BIT 1
  118. #endif
  119. #define JUCE_INTEL 1
  120. #endif
  121. // Compiler type macros.
  122. #ifdef __GNUC__
  123. #define JUCE_GCC 1
  124. #elif defined (_MSC_VER)
  125. #define JUCE_MSVC 1
  126. #if _MSC_VER < 1500
  127. #define JUCE_VC8_OR_EARLIER 1
  128. #if _MSC_VER < 1400
  129. #define JUCE_VC7_OR_EARLIER 1
  130. #if _MSC_VER < 1300
  131. #define JUCE_VC6 1
  132. #endif
  133. #endif
  134. #endif
  135. #if ! JUCE_VC7_OR_EARLIER
  136. #define JUCE_USE_INTRINSICS 1
  137. #endif
  138. #else
  139. #error unknown compiler
  140. #endif
  141. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  142. /*** End of inlined file: juce_TargetPlatform.h ***/
  143. // FORCE_AMALGAMATOR_INCLUDE
  144. /*** Start of inlined file: juce_Config.h ***/
  145. #ifndef __JUCE_CONFIG_JUCEHEADER__
  146. #define __JUCE_CONFIG_JUCEHEADER__
  147. /*
  148. This file contains macros that enable/disable various JUCE features.
  149. */
  150. /** The name of the namespace that all Juce classes and functions will be
  151. put inside. If this is not defined, no namespace will be used.
  152. */
  153. #ifndef JUCE_NAMESPACE
  154. #define JUCE_NAMESPACE juce
  155. #endif
  156. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  157. project settings, but if you define this value, you can override this to force
  158. it to be true or false.
  159. */
  160. #ifndef JUCE_FORCE_DEBUG
  161. //#define JUCE_FORCE_DEBUG 0
  162. #endif
  163. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  164. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  165. Enabling it will also leave this turned on in release builds. When it's disabled,
  166. however, the jassert and jassertfalse macros will not be compiled in a
  167. release build.
  168. @see jassert, jassertfalse, Logger
  169. */
  170. #ifndef JUCE_LOG_ASSERTIONS
  171. #define JUCE_LOG_ASSERTIONS 0
  172. #endif
  173. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  174. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  175. on your Windows build machine.
  176. See the comments in the ASIOAudioIODevice class's header file for more
  177. info about this.
  178. */
  179. #ifndef JUCE_ASIO
  180. #define JUCE_ASIO 0
  181. #endif
  182. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  183. */
  184. #ifndef JUCE_WASAPI
  185. #define JUCE_WASAPI 0
  186. #endif
  187. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  188. */
  189. #ifndef JUCE_DIRECTSOUND
  190. #define JUCE_DIRECTSOUND 1
  191. #endif
  192. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  193. #ifndef JUCE_ALSA
  194. #define JUCE_ALSA 1
  195. #endif
  196. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  197. #ifndef JUCE_JACK
  198. #define JUCE_JACK 0
  199. #endif
  200. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  201. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  202. installed, and its header files will need to be on your include path.
  203. */
  204. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  205. #define JUCE_QUICKTIME 0
  206. #endif
  207. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  208. #undef JUCE_QUICKTIME
  209. #endif
  210. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  211. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  212. */
  213. #ifndef JUCE_OPENGL
  214. #define JUCE_OPENGL 1
  215. #endif
  216. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  217. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  218. */
  219. #ifndef JUCE_DIRECT2D
  220. #define JUCE_DIRECT2D 0
  221. #endif
  222. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  223. If your app doesn't need to read FLAC files, you might want to disable this to
  224. reduce the size of your codebase and build time.
  225. */
  226. #ifndef JUCE_USE_FLAC
  227. #define JUCE_USE_FLAC 1
  228. #endif
  229. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  230. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  231. reduce the size of your codebase and build time.
  232. */
  233. #ifndef JUCE_USE_OGGVORBIS
  234. #define JUCE_USE_OGGVORBIS 1
  235. #endif
  236. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  237. Unless you're using CD-burning, you should probably turn this flag off to
  238. reduce code size.
  239. */
  240. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  241. #define JUCE_USE_CDBURNER 1
  242. #endif
  243. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  244. Unless you're using CD-reading, you should probably turn this flag off to
  245. reduce code size.
  246. */
  247. #ifndef JUCE_USE_CDREADER
  248. #define JUCE_USE_CDREADER 1
  249. #endif
  250. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  251. */
  252. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  253. #define JUCE_USE_CAMERA 0
  254. #endif
  255. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  256. gets repainted will flash in a random colour, so that you can check exactly how much and how
  257. often your components are being drawn.
  258. */
  259. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  260. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  261. #endif
  262. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  263. Unless you specifically want to disable this, it's best to leave this option turned on.
  264. */
  265. #ifndef JUCE_USE_XINERAMA
  266. #define JUCE_USE_XINERAMA 1
  267. #endif
  268. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  269. turned on unless you have a good reason to disable it.
  270. */
  271. #ifndef JUCE_USE_XSHM
  272. #define JUCE_USE_XSHM 1
  273. #endif
  274. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  275. */
  276. #ifndef JUCE_USE_XRENDER
  277. #define JUCE_USE_XRENDER 0
  278. #endif
  279. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  280. unless you have a good reason to disable it.
  281. */
  282. #ifndef JUCE_USE_XCURSOR
  283. #define JUCE_USE_XCURSOR 1
  284. #endif
  285. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  286. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  287. you're building a plugin hosting app.
  288. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  289. */
  290. #ifndef JUCE_PLUGINHOST_VST
  291. #define JUCE_PLUGINHOST_VST 0
  292. #endif
  293. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  294. of course, and should only be enabled if you're building a plugin hosting app.
  295. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  296. */
  297. #ifndef JUCE_PLUGINHOST_AU
  298. #define JUCE_PLUGINHOST_AU 0
  299. #endif
  300. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  301. This should be enabled if you're writing a console application.
  302. */
  303. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  304. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  305. #endif
  306. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  307. If you're not using any embedded web-pages, turning this off may reduce your code size.
  308. */
  309. #ifndef JUCE_WEB_BROWSER
  310. #define JUCE_WEB_BROWSER 1
  311. #endif
  312. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  313. Carbon isn't required for a normal app, but may be needed by specialised classes like
  314. plugin-hosts, which support older APIs.
  315. */
  316. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  317. #define JUCE_SUPPORT_CARBON 1
  318. #endif
  319. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  320. You might need to tweak this if you're linking to an external zlib library in your app,
  321. but for normal apps, this option should be left alone.
  322. */
  323. #ifndef JUCE_INCLUDE_ZLIB_CODE
  324. #define JUCE_INCLUDE_ZLIB_CODE 1
  325. #endif
  326. #ifndef JUCE_INCLUDE_FLAC_CODE
  327. #define JUCE_INCLUDE_FLAC_CODE 1
  328. #endif
  329. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  330. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  331. #endif
  332. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  333. #define JUCE_INCLUDE_PNGLIB_CODE 1
  334. #endif
  335. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  336. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  337. #endif
  338. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check for certain objects when
  339. the app terminates. See the LeakedObjectDetector class and the JUCE_LEAK_DETECTOR
  340. macro for more details about enabling leak checking for specific classes.
  341. */
  342. #if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
  343. #define JUCE_CHECK_MEMORY_LEAKS 1
  344. #endif
  345. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  346. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  347. are passed to the JUCEApplication::unhandledException() callback for logging.
  348. */
  349. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  350. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  351. #endif
  352. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  353. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  354. #undef JUCE_QUICKTIME
  355. #define JUCE_QUICKTIME 0
  356. #undef JUCE_OPENGL
  357. #define JUCE_OPENGL 0
  358. #undef JUCE_USE_CDBURNER
  359. #define JUCE_USE_CDBURNER 0
  360. #undef JUCE_USE_CDREADER
  361. #define JUCE_USE_CDREADER 0
  362. #undef JUCE_WEB_BROWSER
  363. #define JUCE_WEB_BROWSER 0
  364. #undef JUCE_PLUGINHOST_AU
  365. #define JUCE_PLUGINHOST_AU 0
  366. #undef JUCE_PLUGINHOST_VST
  367. #define JUCE_PLUGINHOST_VST 0
  368. #endif
  369. #endif
  370. /*** End of inlined file: juce_Config.h ***/
  371. // FORCE_AMALGAMATOR_INCLUDE
  372. #ifndef JUCE_BUILD_CORE
  373. #define JUCE_BUILD_CORE 1
  374. #endif
  375. #ifndef JUCE_BUILD_MISC
  376. #define JUCE_BUILD_MISC 1
  377. #endif
  378. #ifndef JUCE_BUILD_GUI
  379. #define JUCE_BUILD_GUI 1
  380. #endif
  381. #ifndef JUCE_BUILD_NATIVE
  382. #define JUCE_BUILD_NATIVE 1
  383. #endif
  384. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  385. #undef JUCE_BUILD_MISC
  386. #undef JUCE_BUILD_GUI
  387. #endif
  388. //==============================================================================
  389. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  390. #if JUCE_WINDOWS
  391. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  392. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  393. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  394. #ifndef STRICT
  395. #define STRICT 1
  396. #endif
  397. #undef WIN32_LEAN_AND_MEAN
  398. #define WIN32_LEAN_AND_MEAN 1
  399. #if JUCE_MSVC
  400. #pragma warning (push)
  401. #pragma warning (disable : 4100 4201 4514 4312 4995)
  402. #endif
  403. #define _WIN32_WINNT 0x0500
  404. #define _UNICODE 1
  405. #define UNICODE 1
  406. #ifndef _WIN32_IE
  407. #define _WIN32_IE 0x0400
  408. #endif
  409. #include <windows.h>
  410. #include <windowsx.h>
  411. #include <commdlg.h>
  412. #include <shellapi.h>
  413. #include <mmsystem.h>
  414. #include <vfw.h>
  415. #include <tchar.h>
  416. #include <stddef.h>
  417. #include <ctime>
  418. #include <wininet.h>
  419. #include <nb30.h>
  420. #include <iphlpapi.h>
  421. #include <mapi.h>
  422. #include <float.h>
  423. #include <process.h>
  424. #include <Exdisp.h>
  425. #include <exdispid.h>
  426. #include <shlobj.h>
  427. #if ! JUCE_MINGW
  428. #include <crtdbg.h>
  429. #include <comutil.h>
  430. #endif
  431. #if JUCE_OPENGL
  432. #include <gl/gl.h>
  433. #endif
  434. #undef PACKED
  435. #if JUCE_ASIO && JUCE_BUILD_NATIVE
  436. /*
  437. This is very frustrating - we only need to use a handful of definitions from
  438. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  439. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  440. implementation...
  441. ..unfortunately that would break Steinberg's license agreement for use of
  442. their SDK, so I'm not allowed to do this.
  443. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  444. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  445. (see www.steinberg.net/Steinberg/Developers.asp).
  446. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  447. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  448. if you prefer). Make sure that your header search path will find the
  449. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  450. files are actually needed - so to simplify things, you could just copy
  451. these into your JUCE directory).
  452. If you're compiling and you get an error here because you don't have the
  453. ASIO SDK installed, you can disable ASIO support by commenting-out the
  454. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  455. */
  456. #include <iasiodrv.h>
  457. #endif
  458. #if JUCE_USE_CDBURNER && JUCE_BUILD_NATIVE
  459. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  460. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  461. flag in juce_Config.h to avoid these includes.
  462. */
  463. #include <imapi.h>
  464. #include <imapierror.h>
  465. #endif
  466. #if JUCE_USE_CAMERA && JUCE_BUILD_NATIVE
  467. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  468. These files are provided in the normal Windows SDK, but some Microsoft plonker
  469. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  470. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  471. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  472. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  473. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  474. The dummy file just needs to contain the following content:
  475. #define __IDxtCompositor_INTERFACE_DEFINED__
  476. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  477. #define __IDxtJpeg_INTERFACE_DEFINED__
  478. #define __IDxtKey_INTERFACE_DEFINED__
  479. ..and that should be enough to convince qedit.h that you have the SDK!
  480. */
  481. #include <dshow.h>
  482. #include <qedit.h>
  483. #include <dshowasf.h>
  484. #endif
  485. #if JUCE_WASAPI && JUCE_BUILD_NATIVE
  486. #include <MMReg.h>
  487. #include <mmdeviceapi.h>
  488. #include <Audioclient.h>
  489. #include <Avrt.h>
  490. #include <functiondiscoverykeys.h>
  491. #endif
  492. #if JUCE_QUICKTIME
  493. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  494. add its header directory to your include path.
  495. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  496. flag in juce_Config.h
  497. */
  498. #include <Movies.h>
  499. #include <QTML.h>
  500. #include <QuickTimeComponents.h>
  501. #include <MediaHandlers.h>
  502. #include <ImageCodec.h>
  503. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  504. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  505. your include search path to make these import statements work.
  506. */
  507. #import <QTOLibrary.dll>
  508. #import <QTOControl.dll>
  509. #endif
  510. #if JUCE_MSVC
  511. #pragma warning (pop)
  512. #endif
  513. #if JUCE_DIRECT2D && JUCE_BUILD_NATIVE
  514. #include <d2d1.h>
  515. #include <dwrite.h>
  516. #endif
  517. /** A simple COM smart pointer.
  518. Avoids having to include ATL just to get one of these.
  519. */
  520. template <class ComClass>
  521. class ComSmartPtr
  522. {
  523. public:
  524. ComSmartPtr() throw() : p (0) {}
  525. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  526. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  527. ~ComSmartPtr() { release(); }
  528. operator ComClass*() const throw() { return p; }
  529. ComClass& operator*() const throw() { return *p; }
  530. ComClass* operator->() const throw() { return p; }
  531. ComSmartPtr& operator= (ComClass* const newP)
  532. {
  533. if (newP != 0) newP->AddRef();
  534. release();
  535. p = newP;
  536. return *this;
  537. }
  538. ComSmartPtr& operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  539. // Releases and nullifies this pointer and returns its address
  540. ComClass** resetAndGetPointerAddress()
  541. {
  542. release();
  543. p = 0;
  544. return &p;
  545. }
  546. HRESULT CoCreateInstance (REFCLSID classUUID, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  547. {
  548. #ifndef __MINGW32__
  549. return ::CoCreateInstance (classUUID, 0, dwClsContext, __uuidof (ComClass), (void**) resetAndGetPointerAddress());
  550. #else
  551. return E_NOTIMPL;
  552. #endif
  553. }
  554. template <class OtherComClass>
  555. HRESULT QueryInterface (REFCLSID classUUID, ComSmartPtr<OtherComClass>& destObject) const
  556. {
  557. if (p == 0)
  558. return E_POINTER;
  559. return p->QueryInterface (classUUID, (void**) destObject.resetAndGetPointerAddress());
  560. }
  561. private:
  562. ComClass* p;
  563. void release() { if (p != 0) p->Release(); }
  564. ComClass** operator&() throw(); // private to avoid it being used accidentally
  565. };
  566. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  567. */
  568. template <class ComClass>
  569. class ComBaseClassHelper : public ComClass
  570. {
  571. public:
  572. ComBaseClassHelper() : refCount (1) {}
  573. virtual ~ComBaseClassHelper() {}
  574. HRESULT __stdcall QueryInterface (REFIID refId, void** result)
  575. {
  576. #ifndef __MINGW32__
  577. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  578. #endif
  579. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  580. *result = 0;
  581. return E_NOINTERFACE;
  582. }
  583. ULONG __stdcall AddRef() { return ++refCount; }
  584. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  585. protected:
  586. int refCount;
  587. };
  588. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  589. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  590. #elif JUCE_LINUX
  591. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  592. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  593. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  594. /*
  595. This file wraps together all the linux-specific headers, so
  596. that we can include them all just once, and compile all our
  597. platform-specific stuff in one big lump, keeping it out of the
  598. way of the rest of the codebase.
  599. */
  600. #include <sched.h>
  601. #include <pthread.h>
  602. #include <sys/time.h>
  603. #include <errno.h>
  604. #include <sys/stat.h>
  605. #include <sys/dir.h>
  606. #include <sys/ptrace.h>
  607. #include <sys/vfs.h>
  608. #include <sys/wait.h>
  609. #include <fnmatch.h>
  610. #include <utime.h>
  611. #include <pwd.h>
  612. #include <fcntl.h>
  613. #include <dlfcn.h>
  614. #include <netdb.h>
  615. #include <arpa/inet.h>
  616. #include <netinet/in.h>
  617. #include <sys/types.h>
  618. #include <sys/ioctl.h>
  619. #include <sys/socket.h>
  620. #include <net/if.h>
  621. #include <sys/sysinfo.h>
  622. #include <sys/file.h>
  623. #include <signal.h>
  624. /* Got a build error here? You'll need to install the freetype library...
  625. The name of the package to install is "libfreetype6-dev".
  626. */
  627. #include <ft2build.h>
  628. #include FT_FREETYPE_H
  629. #include <X11/Xlib.h>
  630. #include <X11/Xatom.h>
  631. #include <X11/Xresource.h>
  632. #include <X11/Xutil.h>
  633. #include <X11/Xmd.h>
  634. #include <X11/keysym.h>
  635. #include <X11/cursorfont.h>
  636. #if JUCE_USE_XINERAMA
  637. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  638. #include <X11/extensions/Xinerama.h>
  639. #endif
  640. #if JUCE_USE_XSHM
  641. #include <X11/extensions/XShm.h>
  642. #include <sys/shm.h>
  643. #include <sys/ipc.h>
  644. #endif
  645. #if JUCE_USE_XRENDER
  646. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  647. #include <X11/extensions/Xrender.h>
  648. #include <X11/extensions/Xcomposite.h>
  649. #endif
  650. #if JUCE_USE_XCURSOR
  651. // If you're missing this header, try installing the libxcursor-dev package
  652. #include <X11/Xcursor/Xcursor.h>
  653. #endif
  654. #if JUCE_OPENGL
  655. /* Got an include error here?
  656. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  657. and "freeglut3-dev".
  658. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  659. want to disable it.
  660. */
  661. #include <GL/glx.h>
  662. #endif
  663. #undef KeyPress
  664. #if JUCE_ALSA
  665. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  666. not got your paths set up correctly to find its header files.
  667. The package you need to install to get ASLA support is "libasound2-dev".
  668. If you don't have the ALSA library and don't want to build Juce with audio support,
  669. just disable the JUCE_ALSA flag in juce_Config.h
  670. */
  671. #include <alsa/asoundlib.h>
  672. #endif
  673. #if JUCE_JACK
  674. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  675. installed, or you've not got your paths set up correctly to find its header files.
  676. The package you need to install to get JACK support is "libjack-dev".
  677. If you don't have the jack-audio-connection-kit library and don't want to build
  678. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  679. */
  680. #include <jack/jack.h>
  681. //#include <jack/transport.h>
  682. #endif
  683. #undef SIZEOF
  684. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  685. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  686. #elif JUCE_MAC || JUCE_IPHONE
  687. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  688. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  689. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  690. /*
  691. This file wraps together all the mac-specific code, so that
  692. we can include all the native headers just once, and compile all our
  693. platform-specific stuff in one big lump, keeping it out of the way of
  694. the rest of the codebase.
  695. */
  696. #define USE_COREGRAPHICS_RENDERING 1
  697. #if JUCE_IOS
  698. #import <Foundation/Foundation.h>
  699. #import <UIKit/UIKit.h>
  700. #import <AudioToolbox/AudioToolbox.h>
  701. #import <AVFoundation/AVFoundation.h>
  702. #import <CoreData/CoreData.h>
  703. #import <MobileCoreServices/MobileCoreServices.h>
  704. #import <QuartzCore/QuartzCore.h>
  705. #include <sys/fcntl.h>
  706. #if JUCE_OPENGL
  707. #include <OpenGLES/ES1/gl.h>
  708. #include <OpenGLES/ES1/glext.h>
  709. #endif
  710. #else
  711. #import <Cocoa/Cocoa.h>
  712. #import <CoreAudio/HostTime.h>
  713. #if JUCE_BUILD_NATIVE
  714. #import <CoreAudio/AudioHardware.h>
  715. #import <CoreMIDI/MIDIServices.h>
  716. #import <QTKit/QTKit.h>
  717. #import <WebKit/WebKit.h>
  718. #import <DiscRecording/DiscRecording.h>
  719. #import <IOKit/IOKitLib.h>
  720. #import <IOKit/IOCFPlugIn.h>
  721. #import <IOKit/hid/IOHIDLib.h>
  722. #import <IOKit/hid/IOHIDKeys.h>
  723. #import <IOKit/pwr_mgt/IOPMLib.h>
  724. #endif
  725. #if (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU)) \
  726. || ! (defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6)
  727. #include <Carbon/Carbon.h>
  728. #endif
  729. #include <sys/dir.h>
  730. #endif
  731. #include <sys/socket.h>
  732. #include <sys/sysctl.h>
  733. #include <sys/stat.h>
  734. #include <sys/param.h>
  735. #include <sys/mount.h>
  736. #include <fnmatch.h>
  737. #include <utime.h>
  738. #include <dlfcn.h>
  739. #include <ifaddrs.h>
  740. #include <net/if_dl.h>
  741. #include <mach/mach_time.h>
  742. #include <mach-o/dyld.h>
  743. #if MACOS_10_4_OR_EARLIER
  744. #include <GLUT/glut.h>
  745. #endif
  746. #if ! CGFLOAT_DEFINED
  747. #define CGFloat float
  748. #endif
  749. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  750. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  751. #else
  752. #error "Unknown platform!"
  753. #endif
  754. #endif
  755. //==============================================================================
  756. #define DONT_SET_USING_JUCE_NAMESPACE 1
  757. #undef max
  758. #undef min
  759. #define NO_DUMMY_DECL
  760. #define JUCE_AMALGAMATED_TEMPLATE 1
  761. #if JUCE_BUILD_NATIVE
  762. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  763. #endif
  764. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  765. #pragma warning (disable: 4309 4305)
  766. #endif
  767. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  768. BEGIN_JUCE_NAMESPACE
  769. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  770. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  771. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  772. /**
  773. Creates a floating carbon window that can be used to hold a carbon UI.
  774. This is a handy class that's designed to be inlined where needed, e.g.
  775. in the audio plugin hosting code.
  776. */
  777. class CarbonViewWrapperComponent : public Component,
  778. public ComponentMovementWatcher,
  779. public Timer
  780. {
  781. public:
  782. CarbonViewWrapperComponent()
  783. : ComponentMovementWatcher (this),
  784. wrapperWindow (0),
  785. carbonWindow (0),
  786. embeddedView (0),
  787. recursiveResize (false)
  788. {
  789. }
  790. virtual ~CarbonViewWrapperComponent()
  791. {
  792. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  793. }
  794. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  795. virtual void removeView (HIViewRef embeddedView) = 0;
  796. virtual void mouseDown (int, int) {}
  797. virtual void paint() {}
  798. virtual bool getEmbeddedViewSize (int& w, int& h)
  799. {
  800. if (embeddedView == 0)
  801. return false;
  802. HIRect bounds;
  803. HIViewGetBounds (embeddedView, &bounds);
  804. w = jmax (1, roundToInt (bounds.size.width));
  805. h = jmax (1, roundToInt (bounds.size.height));
  806. return true;
  807. }
  808. void createWindow()
  809. {
  810. if (wrapperWindow == 0)
  811. {
  812. Rect r;
  813. r.left = getScreenX();
  814. r.top = getScreenY();
  815. r.right = r.left + getWidth();
  816. r.bottom = r.top + getHeight();
  817. CreateNewWindow (kDocumentWindowClass,
  818. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  819. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  820. &r, &wrapperWindow);
  821. jassert (wrapperWindow != 0);
  822. if (wrapperWindow == 0)
  823. return;
  824. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  825. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  826. [ownerWindow addChildWindow: carbonWindow
  827. ordered: NSWindowAbove];
  828. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  829. EventTypeSpec windowEventTypes[] =
  830. {
  831. { kEventClassWindow, kEventWindowGetClickActivation },
  832. { kEventClassWindow, kEventWindowHandleDeactivate },
  833. { kEventClassWindow, kEventWindowBoundsChanging },
  834. { kEventClassMouse, kEventMouseDown },
  835. { kEventClassMouse, kEventMouseMoved },
  836. { kEventClassMouse, kEventMouseDragged },
  837. { kEventClassMouse, kEventMouseUp},
  838. { kEventClassWindow, kEventWindowDrawContent },
  839. { kEventClassWindow, kEventWindowShown },
  840. { kEventClassWindow, kEventWindowHidden }
  841. };
  842. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  843. InstallWindowEventHandler (wrapperWindow, upp,
  844. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  845. windowEventTypes, this, &eventHandlerRef);
  846. setOurSizeToEmbeddedViewSize();
  847. setEmbeddedWindowToOurSize();
  848. creationTime = Time::getCurrentTime();
  849. }
  850. }
  851. void deleteWindow()
  852. {
  853. removeView (embeddedView);
  854. embeddedView = 0;
  855. if (wrapperWindow != 0)
  856. {
  857. RemoveEventHandler (eventHandlerRef);
  858. DisposeWindow (wrapperWindow);
  859. wrapperWindow = 0;
  860. }
  861. }
  862. void setOurSizeToEmbeddedViewSize()
  863. {
  864. int w, h;
  865. if (getEmbeddedViewSize (w, h))
  866. {
  867. if (w != getWidth() || h != getHeight())
  868. {
  869. startTimer (50);
  870. setSize (w, h);
  871. if (getParentComponent() != 0)
  872. getParentComponent()->setSize (w, h);
  873. }
  874. else
  875. {
  876. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  877. }
  878. }
  879. else
  880. {
  881. stopTimer();
  882. }
  883. }
  884. void setEmbeddedWindowToOurSize()
  885. {
  886. if (! recursiveResize)
  887. {
  888. recursiveResize = true;
  889. if (embeddedView != 0)
  890. {
  891. HIRect r;
  892. r.origin.x = 0;
  893. r.origin.y = 0;
  894. r.size.width = (float) getWidth();
  895. r.size.height = (float) getHeight();
  896. HIViewSetFrame (embeddedView, &r);
  897. }
  898. if (wrapperWindow != 0)
  899. {
  900. Rect wr;
  901. wr.left = getScreenX();
  902. wr.top = getScreenY();
  903. wr.right = wr.left + getWidth();
  904. wr.bottom = wr.top + getHeight();
  905. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  906. ShowWindow (wrapperWindow);
  907. }
  908. recursiveResize = false;
  909. }
  910. }
  911. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  912. {
  913. setEmbeddedWindowToOurSize();
  914. }
  915. void componentPeerChanged()
  916. {
  917. deleteWindow();
  918. createWindow();
  919. }
  920. void componentVisibilityChanged()
  921. {
  922. if (isShowing())
  923. createWindow();
  924. else
  925. deleteWindow();
  926. setEmbeddedWindowToOurSize();
  927. }
  928. static void recursiveHIViewRepaint (HIViewRef view)
  929. {
  930. HIViewSetNeedsDisplay (view, true);
  931. HIViewRef child = HIViewGetFirstSubview (view);
  932. while (child != 0)
  933. {
  934. recursiveHIViewRepaint (child);
  935. child = HIViewGetNextView (child);
  936. }
  937. }
  938. void timerCallback()
  939. {
  940. setOurSizeToEmbeddedViewSize();
  941. // To avoid strange overpainting problems when the UI is first opened, we'll
  942. // repaint it a few times during the first second that it's on-screen..
  943. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  944. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  945. }
  946. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  947. {
  948. switch (GetEventKind (event))
  949. {
  950. case kEventWindowHandleDeactivate:
  951. ActivateWindow (wrapperWindow, TRUE);
  952. return noErr;
  953. case kEventWindowGetClickActivation:
  954. {
  955. getTopLevelComponent()->toFront (false);
  956. [carbonWindow makeKeyAndOrderFront: nil];
  957. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  958. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  959. sizeof (ClickActivationResult), &howToHandleClick);
  960. HIViewSetNeedsDisplay (embeddedView, true);
  961. return noErr;
  962. }
  963. }
  964. return eventNotHandledErr;
  965. }
  966. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  967. {
  968. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  969. }
  970. protected:
  971. WindowRef wrapperWindow;
  972. NSWindow* carbonWindow;
  973. HIViewRef embeddedView;
  974. bool recursiveResize;
  975. Time creationTime;
  976. EventHandlerRef eventHandlerRef;
  977. };
  978. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  979. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  980. END_JUCE_NAMESPACE
  981. #endif
  982. //==============================================================================
  983. #if JUCE_BUILD_CORE
  984. /*** Start of inlined file: juce_FileLogger.cpp ***/
  985. BEGIN_JUCE_NAMESPACE
  986. FileLogger::FileLogger (const File& logFile_,
  987. const String& welcomeMessage,
  988. const int maxInitialFileSizeBytes)
  989. : logFile (logFile_)
  990. {
  991. if (maxInitialFileSizeBytes >= 0)
  992. trimFileSize (maxInitialFileSizeBytes);
  993. if (! logFile_.exists())
  994. {
  995. // do this so that the parent directories get created..
  996. logFile_.create();
  997. }
  998. String welcome;
  999. welcome << newLine
  1000. << "**********************************************************" << newLine
  1001. << welcomeMessage << newLine
  1002. << "Log started: " << Time::getCurrentTime().toString (true, true) << newLine;
  1003. logMessage (welcome);
  1004. }
  1005. FileLogger::~FileLogger()
  1006. {
  1007. }
  1008. void FileLogger::logMessage (const String& message)
  1009. {
  1010. DBG (message);
  1011. const ScopedLock sl (logLock);
  1012. FileOutputStream out (logFile, 256);
  1013. out << message << newLine;
  1014. }
  1015. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1016. {
  1017. if (maxFileSizeBytes <= 0)
  1018. {
  1019. logFile.deleteFile();
  1020. }
  1021. else
  1022. {
  1023. const int64 fileSize = logFile.getSize();
  1024. if (fileSize > maxFileSizeBytes)
  1025. {
  1026. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1027. jassert (in != 0);
  1028. if (in != 0)
  1029. {
  1030. in->setPosition (fileSize - maxFileSizeBytes);
  1031. String content;
  1032. {
  1033. MemoryBlock contentToSave;
  1034. contentToSave.setSize (maxFileSizeBytes + 4);
  1035. contentToSave.fillWith (0);
  1036. in->read (contentToSave.getData(), maxFileSizeBytes);
  1037. in = 0;
  1038. content = contentToSave.toString();
  1039. }
  1040. int newStart = 0;
  1041. while (newStart < fileSize
  1042. && content[newStart] != '\n'
  1043. && content[newStart] != '\r')
  1044. ++newStart;
  1045. logFile.deleteFile();
  1046. logFile.appendText (content.substring (newStart), false, false);
  1047. }
  1048. }
  1049. }
  1050. }
  1051. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1052. const String& logFileName,
  1053. const String& welcomeMessage,
  1054. const int maxInitialFileSizeBytes)
  1055. {
  1056. #if JUCE_MAC
  1057. File logFile ("~/Library/Logs");
  1058. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1059. .getChildFile (logFileName);
  1060. #else
  1061. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1062. if (logFile.isDirectory())
  1063. {
  1064. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1065. .getChildFile (logFileName);
  1066. }
  1067. #endif
  1068. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1069. }
  1070. END_JUCE_NAMESPACE
  1071. /*** End of inlined file: juce_FileLogger.cpp ***/
  1072. /*** Start of inlined file: juce_Logger.cpp ***/
  1073. BEGIN_JUCE_NAMESPACE
  1074. Logger::Logger()
  1075. {
  1076. }
  1077. Logger::~Logger()
  1078. {
  1079. }
  1080. Logger* Logger::currentLogger = 0;
  1081. void Logger::setCurrentLogger (Logger* const newLogger,
  1082. const bool deleteOldLogger)
  1083. {
  1084. Logger* const oldLogger = currentLogger;
  1085. currentLogger = newLogger;
  1086. if (deleteOldLogger)
  1087. delete oldLogger;
  1088. }
  1089. void Logger::writeToLog (const String& message)
  1090. {
  1091. if (currentLogger != 0)
  1092. currentLogger->logMessage (message);
  1093. else
  1094. outputDebugString (message);
  1095. }
  1096. #if JUCE_LOG_ASSERTIONS
  1097. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1098. {
  1099. String m ("JUCE Assertion failure in ");
  1100. m << filename << ", line " << lineNum;
  1101. Logger::writeToLog (m);
  1102. }
  1103. #endif
  1104. END_JUCE_NAMESPACE
  1105. /*** End of inlined file: juce_Logger.cpp ***/
  1106. /*** Start of inlined file: juce_Random.cpp ***/
  1107. BEGIN_JUCE_NAMESPACE
  1108. Random::Random (const int64 seedValue) throw()
  1109. : seed (seedValue)
  1110. {
  1111. }
  1112. Random::~Random() throw()
  1113. {
  1114. }
  1115. void Random::setSeed (const int64 newSeed) throw()
  1116. {
  1117. seed = newSeed;
  1118. }
  1119. void Random::combineSeed (const int64 seedValue) throw()
  1120. {
  1121. seed ^= nextInt64() ^ seedValue;
  1122. }
  1123. void Random::setSeedRandomly()
  1124. {
  1125. combineSeed ((int64) (pointer_sized_int) this);
  1126. combineSeed (Time::getMillisecondCounter());
  1127. combineSeed (Time::getHighResolutionTicks());
  1128. combineSeed (Time::getHighResolutionTicksPerSecond());
  1129. combineSeed (Time::currentTimeMillis());
  1130. }
  1131. int Random::nextInt() throw()
  1132. {
  1133. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1134. return (int) (seed >> 16);
  1135. }
  1136. int Random::nextInt (const int maxValue) throw()
  1137. {
  1138. jassert (maxValue > 0);
  1139. return (nextInt() & 0x7fffffff) % maxValue;
  1140. }
  1141. int64 Random::nextInt64() throw()
  1142. {
  1143. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1144. }
  1145. bool Random::nextBool() throw()
  1146. {
  1147. return (nextInt() & 0x80000000) != 0;
  1148. }
  1149. float Random::nextFloat() throw()
  1150. {
  1151. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1152. }
  1153. double Random::nextDouble() throw()
  1154. {
  1155. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1156. }
  1157. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1158. {
  1159. BigInteger n;
  1160. do
  1161. {
  1162. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1163. }
  1164. while (n >= maximumValue);
  1165. return n;
  1166. }
  1167. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1168. {
  1169. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1170. while ((startBit & 31) != 0 && numBits > 0)
  1171. {
  1172. arrayToChange.setBit (startBit++, nextBool());
  1173. --numBits;
  1174. }
  1175. while (numBits >= 32)
  1176. {
  1177. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1178. startBit += 32;
  1179. numBits -= 32;
  1180. }
  1181. while (--numBits >= 0)
  1182. arrayToChange.setBit (startBit + numBits, nextBool());
  1183. }
  1184. Random& Random::getSystemRandom() throw()
  1185. {
  1186. static Random sysRand (1);
  1187. return sysRand;
  1188. }
  1189. END_JUCE_NAMESPACE
  1190. /*** End of inlined file: juce_Random.cpp ***/
  1191. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1192. BEGIN_JUCE_NAMESPACE
  1193. RelativeTime::RelativeTime (const double seconds_) throw()
  1194. : seconds (seconds_)
  1195. {
  1196. }
  1197. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1198. : seconds (other.seconds)
  1199. {
  1200. }
  1201. RelativeTime::~RelativeTime() throw()
  1202. {
  1203. }
  1204. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1205. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1206. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw() { return RelativeTime (numberOfMinutes * 60.0); }
  1207. const RelativeTime RelativeTime::hours (const double numberOfHours) throw() { return RelativeTime (numberOfHours * (60.0 * 60.0)); }
  1208. const RelativeTime RelativeTime::days (const double numberOfDays) throw() { return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0)); }
  1209. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw() { return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0)); }
  1210. int64 RelativeTime::inMilliseconds() const throw() { return (int64) (seconds * 1000.0); }
  1211. double RelativeTime::inMinutes() const throw() { return seconds / 60.0; }
  1212. double RelativeTime::inHours() const throw() { return seconds / (60.0 * 60.0); }
  1213. double RelativeTime::inDays() const throw() { return seconds / (60.0 * 60.0 * 24.0); }
  1214. double RelativeTime::inWeeks() const throw() { return seconds / (60.0 * 60.0 * 24.0 * 7.0); }
  1215. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1216. {
  1217. if (seconds < 0.001 && seconds > -0.001)
  1218. return returnValueForZeroTime;
  1219. String result;
  1220. result.preallocateStorage (16);
  1221. if (seconds < 0)
  1222. result << '-';
  1223. int fieldsShown = 0;
  1224. int n = std::abs ((int) inWeeks());
  1225. if (n > 0)
  1226. {
  1227. result << n << (n == 1 ? TRANS(" week ")
  1228. : TRANS(" weeks "));
  1229. ++fieldsShown;
  1230. }
  1231. n = std::abs ((int) inDays()) % 7;
  1232. if (n > 0)
  1233. {
  1234. result << n << (n == 1 ? TRANS(" day ")
  1235. : TRANS(" days "));
  1236. ++fieldsShown;
  1237. }
  1238. if (fieldsShown < 2)
  1239. {
  1240. n = std::abs ((int) inHours()) % 24;
  1241. if (n > 0)
  1242. {
  1243. result << n << (n == 1 ? TRANS(" hr ")
  1244. : TRANS(" hrs "));
  1245. ++fieldsShown;
  1246. }
  1247. if (fieldsShown < 2)
  1248. {
  1249. n = std::abs ((int) inMinutes()) % 60;
  1250. if (n > 0)
  1251. {
  1252. result << n << (n == 1 ? TRANS(" min ")
  1253. : TRANS(" mins "));
  1254. ++fieldsShown;
  1255. }
  1256. if (fieldsShown < 2)
  1257. {
  1258. n = std::abs ((int) inSeconds()) % 60;
  1259. if (n > 0)
  1260. {
  1261. result << n << (n == 1 ? TRANS(" sec ")
  1262. : TRANS(" secs "));
  1263. ++fieldsShown;
  1264. }
  1265. if (fieldsShown == 0)
  1266. {
  1267. n = std::abs ((int) inMilliseconds()) % 1000;
  1268. if (n > 0)
  1269. result << n << TRANS(" ms");
  1270. }
  1271. }
  1272. }
  1273. }
  1274. return result.trimEnd();
  1275. }
  1276. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1277. {
  1278. seconds = other.seconds;
  1279. return *this;
  1280. }
  1281. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1282. {
  1283. seconds += timeToAdd.seconds;
  1284. return *this;
  1285. }
  1286. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1287. {
  1288. seconds -= timeToSubtract.seconds;
  1289. return *this;
  1290. }
  1291. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1292. {
  1293. seconds += secondsToAdd;
  1294. return *this;
  1295. }
  1296. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1297. {
  1298. seconds -= secondsToSubtract;
  1299. return *this;
  1300. }
  1301. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() == t2.inSeconds(); }
  1302. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() != t2.inSeconds(); }
  1303. bool operator> (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() > t2.inSeconds(); }
  1304. bool operator< (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() < t2.inSeconds(); }
  1305. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() >= t2.inSeconds(); }
  1306. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() <= t2.inSeconds(); }
  1307. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t += t2; }
  1308. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t -= t2; }
  1309. END_JUCE_NAMESPACE
  1310. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1311. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1312. BEGIN_JUCE_NAMESPACE
  1313. SystemStats::CPUFlags SystemStats::cpuFlags;
  1314. const String SystemStats::getJUCEVersion()
  1315. {
  1316. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1317. + "." + String (JUCE_MINOR_VERSION)
  1318. + "." + String (JUCE_BUILDNUMBER);
  1319. }
  1320. #ifdef JUCE_DLL
  1321. void* juce_Malloc (int size) { return malloc (size); }
  1322. void* juce_Calloc (int size) { return calloc (1, size); }
  1323. void* juce_Realloc (void* block, int size) { return realloc (block, size); }
  1324. void juce_Free (void* block) { free (block); }
  1325. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1326. void* juce_DebugMalloc (int size, const char* file, int line) { return _malloc_dbg (size, _NORMAL_BLOCK, file, line); }
  1327. void* juce_DebugCalloc (int size, const char* file, int line) { return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line); }
  1328. void* juce_DebugRealloc (void* block, int size, const char* file, int line) { return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line); }
  1329. void juce_DebugFree (void* block) { _free_dbg (block, _NORMAL_BLOCK); }
  1330. #endif
  1331. #endif
  1332. END_JUCE_NAMESPACE
  1333. /*** End of inlined file: juce_SystemStats.cpp ***/
  1334. /*** Start of inlined file: juce_Time.cpp ***/
  1335. #if JUCE_MSVC
  1336. #pragma warning (push)
  1337. #pragma warning (disable: 4514)
  1338. #endif
  1339. #ifndef JUCE_WINDOWS
  1340. #include <sys/time.h>
  1341. #else
  1342. #include <ctime>
  1343. #endif
  1344. #include <sys/timeb.h>
  1345. #if JUCE_MSVC
  1346. #pragma warning (pop)
  1347. #ifdef _INC_TIME_INL
  1348. #define USE_NEW_SECURE_TIME_FNS
  1349. #endif
  1350. #endif
  1351. BEGIN_JUCE_NAMESPACE
  1352. namespace TimeHelpers
  1353. {
  1354. static struct tm millisToLocal (const int64 millis) throw()
  1355. {
  1356. struct tm result;
  1357. const int64 seconds = millis / 1000;
  1358. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1359. {
  1360. // use extended maths for dates beyond 1970 to 2037..
  1361. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1362. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1363. const int days = (int) (jdm / literal64bit (86400));
  1364. const int a = 32044 + days;
  1365. const int b = (4 * a + 3) / 146097;
  1366. const int c = a - (b * 146097) / 4;
  1367. const int d = (4 * c + 3) / 1461;
  1368. const int e = c - (d * 1461) / 4;
  1369. const int m = (5 * e + 2) / 153;
  1370. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1371. result.tm_mon = m + 2 - 12 * (m / 10);
  1372. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1373. result.tm_wday = (days + 1) % 7;
  1374. result.tm_yday = -1;
  1375. int t = (int) (jdm % literal64bit (86400));
  1376. result.tm_hour = t / 3600;
  1377. t %= 3600;
  1378. result.tm_min = t / 60;
  1379. result.tm_sec = t % 60;
  1380. result.tm_isdst = -1;
  1381. }
  1382. else
  1383. {
  1384. time_t now = static_cast <time_t> (seconds);
  1385. #if JUCE_WINDOWS
  1386. #ifdef USE_NEW_SECURE_TIME_FNS
  1387. if (now >= 0 && now <= 0x793406fff)
  1388. localtime_s (&result, &now);
  1389. else
  1390. zeromem (&result, sizeof (result));
  1391. #else
  1392. result = *localtime (&now);
  1393. #endif
  1394. #else
  1395. // more thread-safe
  1396. localtime_r (&now, &result);
  1397. #endif
  1398. }
  1399. return result;
  1400. }
  1401. static int extendedModulo (const int64 value, const int modulo) throw()
  1402. {
  1403. return (int) (value >= 0 ? (value % modulo)
  1404. : (value - ((value / modulo) + 1) * modulo));
  1405. }
  1406. static uint32 lastMSCounterValue = 0;
  1407. }
  1408. Time::Time() throw()
  1409. : millisSinceEpoch (0)
  1410. {
  1411. }
  1412. Time::Time (const Time& other) throw()
  1413. : millisSinceEpoch (other.millisSinceEpoch)
  1414. {
  1415. }
  1416. Time::Time (const int64 ms) throw()
  1417. : millisSinceEpoch (ms)
  1418. {
  1419. }
  1420. Time::Time (const int year,
  1421. const int month,
  1422. const int day,
  1423. const int hours,
  1424. const int minutes,
  1425. const int seconds,
  1426. const int milliseconds,
  1427. const bool useLocalTime) throw()
  1428. {
  1429. jassert (year > 100); // year must be a 4-digit version
  1430. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1431. {
  1432. // use extended maths for dates beyond 1970 to 2037..
  1433. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1434. : 0;
  1435. const int a = (13 - month) / 12;
  1436. const int y = year + 4800 - a;
  1437. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1438. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1439. - 32045;
  1440. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1441. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1442. + milliseconds;
  1443. }
  1444. else
  1445. {
  1446. struct tm t;
  1447. t.tm_year = year - 1900;
  1448. t.tm_mon = month;
  1449. t.tm_mday = day;
  1450. t.tm_hour = hours;
  1451. t.tm_min = minutes;
  1452. t.tm_sec = seconds;
  1453. t.tm_isdst = -1;
  1454. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1455. if (millisSinceEpoch < 0)
  1456. millisSinceEpoch = 0;
  1457. else
  1458. millisSinceEpoch += milliseconds;
  1459. }
  1460. }
  1461. Time::~Time() throw()
  1462. {
  1463. }
  1464. Time& Time::operator= (const Time& other) throw()
  1465. {
  1466. millisSinceEpoch = other.millisSinceEpoch;
  1467. return *this;
  1468. }
  1469. int64 Time::currentTimeMillis() throw()
  1470. {
  1471. static uint32 lastCounterResult = 0xffffffff;
  1472. static int64 correction = 0;
  1473. const uint32 now = getMillisecondCounter();
  1474. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1475. if (now < lastCounterResult)
  1476. {
  1477. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1478. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1479. {
  1480. // get the time once using normal library calls, and store the difference needed to
  1481. // turn the millisecond counter into a real time.
  1482. #if JUCE_WINDOWS
  1483. struct _timeb t;
  1484. #ifdef USE_NEW_SECURE_TIME_FNS
  1485. _ftime_s (&t);
  1486. #else
  1487. _ftime (&t);
  1488. #endif
  1489. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1490. #else
  1491. struct timeval tv;
  1492. struct timezone tz;
  1493. gettimeofday (&tv, &tz);
  1494. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1495. #endif
  1496. }
  1497. }
  1498. lastCounterResult = now;
  1499. return correction + now;
  1500. }
  1501. uint32 juce_millisecondsSinceStartup() throw();
  1502. uint32 Time::getMillisecondCounter() throw()
  1503. {
  1504. const uint32 now = juce_millisecondsSinceStartup();
  1505. if (now < TimeHelpers::lastMSCounterValue)
  1506. {
  1507. // in multi-threaded apps this might be called concurrently, so
  1508. // make sure that our last counter value only increases and doesn't
  1509. // go backwards..
  1510. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1511. TimeHelpers::lastMSCounterValue = now;
  1512. }
  1513. else
  1514. {
  1515. TimeHelpers::lastMSCounterValue = now;
  1516. }
  1517. return now;
  1518. }
  1519. uint32 Time::getApproximateMillisecondCounter() throw()
  1520. {
  1521. jassert (TimeHelpers::lastMSCounterValue != 0);
  1522. return TimeHelpers::lastMSCounterValue;
  1523. }
  1524. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1525. {
  1526. for (;;)
  1527. {
  1528. const uint32 now = getMillisecondCounter();
  1529. if (now >= targetTime)
  1530. break;
  1531. const int toWait = targetTime - now;
  1532. if (toWait > 2)
  1533. {
  1534. Thread::sleep (jmin (20, toWait >> 1));
  1535. }
  1536. else
  1537. {
  1538. // xxx should consider using mutex_pause on the mac as it apparently
  1539. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1540. for (int i = 10; --i >= 0;)
  1541. Thread::yield();
  1542. }
  1543. }
  1544. }
  1545. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1546. {
  1547. return ticks / (double) getHighResolutionTicksPerSecond();
  1548. }
  1549. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1550. {
  1551. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1552. }
  1553. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1554. {
  1555. return Time (currentTimeMillis());
  1556. }
  1557. const String Time::toString (const bool includeDate,
  1558. const bool includeTime,
  1559. const bool includeSeconds,
  1560. const bool use24HourClock) const throw()
  1561. {
  1562. String result;
  1563. if (includeDate)
  1564. {
  1565. result << getDayOfMonth() << ' '
  1566. << getMonthName (true) << ' '
  1567. << getYear();
  1568. if (includeTime)
  1569. result << ' ';
  1570. }
  1571. if (includeTime)
  1572. {
  1573. const int mins = getMinutes();
  1574. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1575. << (mins < 10 ? ":0" : ":") << mins;
  1576. if (includeSeconds)
  1577. {
  1578. const int secs = getSeconds();
  1579. result << (secs < 10 ? ":0" : ":") << secs;
  1580. }
  1581. if (! use24HourClock)
  1582. result << (isAfternoon() ? "pm" : "am");
  1583. }
  1584. return result.trimEnd();
  1585. }
  1586. const String Time::formatted (const String& format) const
  1587. {
  1588. String buffer;
  1589. int bufferSize = 128;
  1590. buffer.preallocateStorage (bufferSize);
  1591. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1592. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1593. {
  1594. bufferSize += 128;
  1595. buffer.preallocateStorage (bufferSize);
  1596. }
  1597. return buffer;
  1598. }
  1599. int Time::getYear() const throw()
  1600. {
  1601. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1602. }
  1603. int Time::getMonth() const throw()
  1604. {
  1605. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1606. }
  1607. int Time::getDayOfMonth() const throw()
  1608. {
  1609. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1610. }
  1611. int Time::getDayOfWeek() const throw()
  1612. {
  1613. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1614. }
  1615. int Time::getHours() const throw()
  1616. {
  1617. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1618. }
  1619. int Time::getHoursInAmPmFormat() const throw()
  1620. {
  1621. const int hours = getHours();
  1622. if (hours == 0)
  1623. return 12;
  1624. else if (hours <= 12)
  1625. return hours;
  1626. else
  1627. return hours - 12;
  1628. }
  1629. bool Time::isAfternoon() const throw()
  1630. {
  1631. return getHours() >= 12;
  1632. }
  1633. int Time::getMinutes() const throw()
  1634. {
  1635. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1636. }
  1637. int Time::getSeconds() const throw()
  1638. {
  1639. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1640. }
  1641. int Time::getMilliseconds() const throw()
  1642. {
  1643. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1644. }
  1645. bool Time::isDaylightSavingTime() const throw()
  1646. {
  1647. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1648. }
  1649. const String Time::getTimeZone() const throw()
  1650. {
  1651. String zone[2];
  1652. #if JUCE_WINDOWS
  1653. _tzset();
  1654. #ifdef USE_NEW_SECURE_TIME_FNS
  1655. {
  1656. char name [128];
  1657. size_t length;
  1658. for (int i = 0; i < 2; ++i)
  1659. {
  1660. zeromem (name, sizeof (name));
  1661. _get_tzname (&length, name, 127, i);
  1662. zone[i] = name;
  1663. }
  1664. }
  1665. #else
  1666. const char** const zonePtr = (const char**) _tzname;
  1667. zone[0] = zonePtr[0];
  1668. zone[1] = zonePtr[1];
  1669. #endif
  1670. #else
  1671. tzset();
  1672. const char** const zonePtr = (const char**) tzname;
  1673. zone[0] = zonePtr[0];
  1674. zone[1] = zonePtr[1];
  1675. #endif
  1676. if (isDaylightSavingTime())
  1677. {
  1678. zone[0] = zone[1];
  1679. if (zone[0].length() > 3
  1680. && zone[0].containsIgnoreCase ("daylight")
  1681. && zone[0].contains ("GMT"))
  1682. zone[0] = "BST";
  1683. }
  1684. return zone[0].substring (0, 3);
  1685. }
  1686. const String Time::getMonthName (const bool threeLetterVersion) const
  1687. {
  1688. return getMonthName (getMonth(), threeLetterVersion);
  1689. }
  1690. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1691. {
  1692. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1693. }
  1694. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1695. {
  1696. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1697. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1698. monthNumber %= 12;
  1699. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1700. : longMonthNames [monthNumber]);
  1701. }
  1702. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1703. {
  1704. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1705. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1706. day %= 7;
  1707. return TRANS (threeLetterVersion ? shortDayNames [day]
  1708. : longDayNames [day]);
  1709. }
  1710. Time& Time::operator+= (const RelativeTime& delta) { millisSinceEpoch += delta.inMilliseconds(); return *this; }
  1711. Time& Time::operator-= (const RelativeTime& delta) { millisSinceEpoch -= delta.inMilliseconds(); return *this; }
  1712. const Time operator+ (const Time& time, const RelativeTime& delta) { Time t (time); return t += delta; }
  1713. const Time operator- (const Time& time, const RelativeTime& delta) { Time t (time); return t -= delta; }
  1714. const Time operator+ (const RelativeTime& delta, const Time& time) { Time t (time); return t += delta; }
  1715. const RelativeTime operator- (const Time& time1, const Time& time2) { return RelativeTime::milliseconds (time1.toMilliseconds() - time2.toMilliseconds()); }
  1716. bool operator== (const Time& time1, const Time& time2) { return time1.toMilliseconds() == time2.toMilliseconds(); }
  1717. bool operator!= (const Time& time1, const Time& time2) { return time1.toMilliseconds() != time2.toMilliseconds(); }
  1718. bool operator< (const Time& time1, const Time& time2) { return time1.toMilliseconds() < time2.toMilliseconds(); }
  1719. bool operator> (const Time& time1, const Time& time2) { return time1.toMilliseconds() > time2.toMilliseconds(); }
  1720. bool operator<= (const Time& time1, const Time& time2) { return time1.toMilliseconds() <= time2.toMilliseconds(); }
  1721. bool operator>= (const Time& time1, const Time& time2) { return time1.toMilliseconds() >= time2.toMilliseconds(); }
  1722. END_JUCE_NAMESPACE
  1723. /*** End of inlined file: juce_Time.cpp ***/
  1724. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1725. BEGIN_JUCE_NAMESPACE
  1726. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1727. #endif
  1728. #if JUCE_WINDOWS
  1729. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1730. #endif
  1731. #if JUCE_DEBUG
  1732. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1733. #endif
  1734. static bool juceInitialisedNonGUI = false;
  1735. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1736. {
  1737. if (! juceInitialisedNonGUI)
  1738. {
  1739. juceInitialisedNonGUI = true;
  1740. JUCE_AUTORELEASEPOOL
  1741. DBG (SystemStats::getJUCEVersion());
  1742. SystemStats::initialiseStats();
  1743. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1744. }
  1745. // Some basic tests, to keep an eye on things and make sure these types work ok
  1746. // on all platforms. Let me know if any of these assertions fail on your system!
  1747. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1748. static_jassert (sizeof (int8) == 1);
  1749. static_jassert (sizeof (uint8) == 1);
  1750. static_jassert (sizeof (int16) == 2);
  1751. static_jassert (sizeof (uint16) == 2);
  1752. static_jassert (sizeof (int32) == 4);
  1753. static_jassert (sizeof (uint32) == 4);
  1754. static_jassert (sizeof (int64) == 8);
  1755. static_jassert (sizeof (uint64) == 8);
  1756. }
  1757. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1758. {
  1759. if (juceInitialisedNonGUI)
  1760. {
  1761. juceInitialisedNonGUI = false;
  1762. JUCE_AUTORELEASEPOOL
  1763. LocalisedStrings::setCurrentMappings (0);
  1764. Thread::stopAllThreads (3000);
  1765. #if JUCE_WINDOWS
  1766. juce_shutdownWin32Sockets();
  1767. #endif
  1768. #if JUCE_DEBUG
  1769. juce_CheckForDanglingStreams();
  1770. #endif
  1771. }
  1772. }
  1773. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1774. static bool juceInitialisedGUI = false;
  1775. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1776. {
  1777. if (! juceInitialisedGUI)
  1778. {
  1779. juceInitialisedGUI = true;
  1780. JUCE_AUTORELEASEPOOL
  1781. initialiseJuce_NonGUI();
  1782. MessageManager::getInstance();
  1783. LookAndFeel::setDefaultLookAndFeel (0);
  1784. #if JUCE_DEBUG
  1785. try // This section is just a safety-net for catching builds without RTTI enabled..
  1786. {
  1787. MemoryOutputStream mo;
  1788. OutputStream* o = &mo;
  1789. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1790. o = dynamic_cast <MemoryOutputStream*> (o);
  1791. jassert (o != 0);
  1792. }
  1793. catch (...)
  1794. {
  1795. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1796. jassertfalse;
  1797. }
  1798. #endif
  1799. }
  1800. }
  1801. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1802. {
  1803. if (juceInitialisedGUI)
  1804. {
  1805. juceInitialisedGUI = false;
  1806. JUCE_AUTORELEASEPOOL
  1807. DeletedAtShutdown::deleteAll();
  1808. LookAndFeel::clearDefaultLookAndFeel();
  1809. delete MessageManager::getInstance();
  1810. shutdownJuce_NonGUI();
  1811. }
  1812. }
  1813. #endif
  1814. #if JUCE_UNIT_TESTS
  1815. class AtomicTests : public UnitTest
  1816. {
  1817. public:
  1818. AtomicTests() : UnitTest ("Atomics") {}
  1819. void runTest()
  1820. {
  1821. beginTest ("Misc");
  1822. char a1[7];
  1823. expect (numElementsInArray(a1) == 7);
  1824. int a2[3];
  1825. expect (numElementsInArray(a2) == 3);
  1826. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1827. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1828. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1829. beginTest ("Atomic types");
  1830. AtomicTester <int>::testInteger (*this);
  1831. AtomicTester <unsigned int>::testInteger (*this);
  1832. AtomicTester <int32>::testInteger (*this);
  1833. AtomicTester <uint32>::testInteger (*this);
  1834. AtomicTester <long>::testInteger (*this);
  1835. AtomicTester <void*>::testInteger (*this);
  1836. AtomicTester <int*>::testInteger (*this);
  1837. AtomicTester <float>::testFloat (*this);
  1838. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1839. AtomicTester <int64>::testInteger (*this);
  1840. AtomicTester <uint64>::testInteger (*this);
  1841. AtomicTester <double>::testFloat (*this);
  1842. #endif
  1843. }
  1844. template <typename Type>
  1845. class AtomicTester
  1846. {
  1847. public:
  1848. AtomicTester() {}
  1849. static void testInteger (UnitTest& test)
  1850. {
  1851. Atomic<Type> a, b;
  1852. a.set ((Type) 10);
  1853. a += (Type) 15;
  1854. a.memoryBarrier();
  1855. a -= (Type) 5;
  1856. ++a; ++a; --a;
  1857. a.memoryBarrier();
  1858. testFloat (test);
  1859. }
  1860. static void testFloat (UnitTest& test)
  1861. {
  1862. Atomic<Type> a, b;
  1863. a = (Type) 21;
  1864. a.memoryBarrier();
  1865. /* These are some simple test cases to check the atomics - let me know
  1866. if any of these assertions fail on your system!
  1867. */
  1868. test.expect (a.get() == (Type) 21);
  1869. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1870. test.expect (a.get() == (Type) 21);
  1871. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1872. test.expect (a.get() == (Type) 101);
  1873. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1874. test.expect (a.get() == (Type) 101);
  1875. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1876. test.expect (a.get() == (Type) 200);
  1877. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1878. test.expect (a.get() == (Type) 300);
  1879. b = a;
  1880. test.expect (b.get() == a.get());
  1881. }
  1882. };
  1883. };
  1884. static AtomicTests atomicUnitTests;
  1885. #endif
  1886. END_JUCE_NAMESPACE
  1887. /*** End of inlined file: juce_Initialisation.cpp ***/
  1888. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1889. BEGIN_JUCE_NAMESPACE
  1890. AbstractFifo::AbstractFifo (const int capacity) throw()
  1891. : bufferSize (capacity)
  1892. {
  1893. jassert (bufferSize > 0);
  1894. }
  1895. AbstractFifo::~AbstractFifo() {}
  1896. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1897. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1898. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1899. void AbstractFifo::reset() throw()
  1900. {
  1901. validEnd = 0;
  1902. validStart = 0;
  1903. }
  1904. void AbstractFifo::setTotalSize (int newSize) throw()
  1905. {
  1906. jassert (newSize > 0);
  1907. reset();
  1908. bufferSize = newSize;
  1909. }
  1910. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1911. {
  1912. const int vs = validStart.get();
  1913. const int ve = validEnd.get();
  1914. const int freeSpace = bufferSize - (ve - vs);
  1915. numToWrite = jmin (numToWrite, freeSpace);
  1916. if (numToWrite <= 0)
  1917. {
  1918. startIndex1 = 0;
  1919. startIndex2 = 0;
  1920. blockSize1 = 0;
  1921. blockSize2 = 0;
  1922. }
  1923. else
  1924. {
  1925. startIndex1 = (int) (ve % bufferSize);
  1926. startIndex2 = 0;
  1927. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1928. numToWrite -= blockSize1;
  1929. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  1930. }
  1931. }
  1932. void AbstractFifo::finishedWrite (int numWritten) throw()
  1933. {
  1934. jassert (numWritten >= 0 && numWritten < bufferSize);
  1935. validEnd += numWritten;
  1936. }
  1937. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1938. {
  1939. const int vs = validStart.get();
  1940. const int ve = validEnd.get();
  1941. const int numReady = ve - vs;
  1942. numWanted = jmin (numWanted, numReady);
  1943. if (numWanted <= 0)
  1944. {
  1945. startIndex1 = 0;
  1946. startIndex2 = 0;
  1947. blockSize1 = 0;
  1948. blockSize2 = 0;
  1949. }
  1950. else
  1951. {
  1952. startIndex1 = (int) (vs % bufferSize);
  1953. startIndex2 = 0;
  1954. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  1955. numWanted -= blockSize1;
  1956. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  1957. }
  1958. }
  1959. void AbstractFifo::finishedRead (int numRead) throw()
  1960. {
  1961. jassert (numRead >= 0 && numRead < bufferSize);
  1962. validStart += numRead;
  1963. }
  1964. END_JUCE_NAMESPACE
  1965. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  1966. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1967. BEGIN_JUCE_NAMESPACE
  1968. BigInteger::BigInteger()
  1969. : numValues (4),
  1970. highestBit (-1),
  1971. negative (false)
  1972. {
  1973. values.calloc (numValues + 1);
  1974. }
  1975. BigInteger::BigInteger (const int32 value)
  1976. : numValues (4),
  1977. highestBit (31),
  1978. negative (value < 0)
  1979. {
  1980. values.calloc (numValues + 1);
  1981. values[0] = abs (value);
  1982. highestBit = getHighestBit();
  1983. }
  1984. BigInteger::BigInteger (const uint32 value)
  1985. : numValues (4),
  1986. highestBit (31),
  1987. negative (false)
  1988. {
  1989. values.calloc (numValues + 1);
  1990. values[0] = value;
  1991. highestBit = getHighestBit();
  1992. }
  1993. BigInteger::BigInteger (int64 value)
  1994. : numValues (4),
  1995. highestBit (63),
  1996. negative (value < 0)
  1997. {
  1998. values.calloc (numValues + 1);
  1999. if (value < 0)
  2000. value = -value;
  2001. values[0] = (uint32) value;
  2002. values[1] = (uint32) (value >> 32);
  2003. highestBit = getHighestBit();
  2004. }
  2005. BigInteger::BigInteger (const BigInteger& other)
  2006. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2007. highestBit (other.getHighestBit()),
  2008. negative (other.negative)
  2009. {
  2010. values.malloc (numValues + 1);
  2011. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2012. }
  2013. BigInteger::~BigInteger()
  2014. {
  2015. }
  2016. void BigInteger::swapWith (BigInteger& other) throw()
  2017. {
  2018. values.swapWith (other.values);
  2019. swapVariables (numValues, other.numValues);
  2020. swapVariables (highestBit, other.highestBit);
  2021. swapVariables (negative, other.negative);
  2022. }
  2023. BigInteger& BigInteger::operator= (const BigInteger& other)
  2024. {
  2025. if (this != &other)
  2026. {
  2027. highestBit = other.getHighestBit();
  2028. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2029. negative = other.negative;
  2030. values.malloc (numValues + 1);
  2031. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2032. }
  2033. return *this;
  2034. }
  2035. void BigInteger::ensureSize (const int numVals)
  2036. {
  2037. if (numVals + 2 >= numValues)
  2038. {
  2039. int oldSize = numValues;
  2040. numValues = ((numVals + 2) * 3) / 2;
  2041. values.realloc (numValues + 1);
  2042. while (oldSize < numValues)
  2043. values [oldSize++] = 0;
  2044. }
  2045. }
  2046. bool BigInteger::operator[] (const int bit) const throw()
  2047. {
  2048. return bit <= highestBit && bit >= 0
  2049. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2050. }
  2051. int BigInteger::toInteger() const throw()
  2052. {
  2053. const int n = (int) (values[0] & 0x7fffffff);
  2054. return negative ? -n : n;
  2055. }
  2056. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2057. {
  2058. BigInteger r;
  2059. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2060. r.ensureSize (bitToIndex (numBits));
  2061. r.highestBit = numBits;
  2062. int i = 0;
  2063. while (numBits > 0)
  2064. {
  2065. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2066. numBits -= 32;
  2067. startBit += 32;
  2068. }
  2069. r.highestBit = r.getHighestBit();
  2070. return r;
  2071. }
  2072. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2073. {
  2074. if (numBits > 32)
  2075. {
  2076. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2077. numBits = 32;
  2078. }
  2079. numBits = jmin (numBits, highestBit + 1 - startBit);
  2080. if (numBits <= 0)
  2081. return 0;
  2082. const int pos = bitToIndex (startBit);
  2083. const int offset = startBit & 31;
  2084. const int endSpace = 32 - numBits;
  2085. uint32 n = ((uint32) values [pos]) >> offset;
  2086. if (offset > endSpace)
  2087. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2088. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2089. }
  2090. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2091. {
  2092. if (numBits > 32)
  2093. {
  2094. jassertfalse;
  2095. numBits = 32;
  2096. }
  2097. for (int i = 0; i < numBits; ++i)
  2098. {
  2099. setBit (startBit + i, (valueToSet & 1) != 0);
  2100. valueToSet >>= 1;
  2101. }
  2102. }
  2103. void BigInteger::clear()
  2104. {
  2105. if (numValues > 16)
  2106. {
  2107. numValues = 4;
  2108. values.calloc (numValues + 1);
  2109. }
  2110. else
  2111. {
  2112. zeromem (values, sizeof (uint32) * (numValues + 1));
  2113. }
  2114. highestBit = -1;
  2115. negative = false;
  2116. }
  2117. void BigInteger::setBit (const int bit)
  2118. {
  2119. if (bit >= 0)
  2120. {
  2121. if (bit > highestBit)
  2122. {
  2123. ensureSize (bitToIndex (bit));
  2124. highestBit = bit;
  2125. }
  2126. values [bitToIndex (bit)] |= bitToMask (bit);
  2127. }
  2128. }
  2129. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2130. {
  2131. if (shouldBeSet)
  2132. setBit (bit);
  2133. else
  2134. clearBit (bit);
  2135. }
  2136. void BigInteger::clearBit (const int bit) throw()
  2137. {
  2138. if (bit >= 0 && bit <= highestBit)
  2139. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2140. }
  2141. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2142. {
  2143. while (--numBits >= 0)
  2144. setBit (startBit++, shouldBeSet);
  2145. }
  2146. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2147. {
  2148. if (bit >= 0)
  2149. shiftBits (1, bit);
  2150. setBit (bit, shouldBeSet);
  2151. }
  2152. bool BigInteger::isZero() const throw()
  2153. {
  2154. return getHighestBit() < 0;
  2155. }
  2156. bool BigInteger::isOne() const throw()
  2157. {
  2158. return getHighestBit() == 0 && ! negative;
  2159. }
  2160. bool BigInteger::isNegative() const throw()
  2161. {
  2162. return negative && ! isZero();
  2163. }
  2164. void BigInteger::setNegative (const bool neg) throw()
  2165. {
  2166. negative = neg;
  2167. }
  2168. void BigInteger::negate() throw()
  2169. {
  2170. negative = (! negative) && ! isZero();
  2171. }
  2172. #if JUCE_USE_INTRINSICS
  2173. #pragma intrinsic (_BitScanReverse)
  2174. #endif
  2175. namespace BitFunctions
  2176. {
  2177. inline int countBitsInInt32 (uint32 n) throw()
  2178. {
  2179. n -= ((n >> 1) & 0x55555555);
  2180. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2181. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2182. n += (n >> 8);
  2183. n += (n >> 16);
  2184. return n & 0x3f;
  2185. }
  2186. inline int highestBitInInt (uint32 n) throw()
  2187. {
  2188. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2189. #if JUCE_GCC
  2190. return 31 - __builtin_clz (n);
  2191. #elif JUCE_USE_INTRINSICS
  2192. unsigned long highest;
  2193. _BitScanReverse (&highest, n);
  2194. return (int) highest;
  2195. #else
  2196. n |= (n >> 1);
  2197. n |= (n >> 2);
  2198. n |= (n >> 4);
  2199. n |= (n >> 8);
  2200. n |= (n >> 16);
  2201. return countBitsInInt32 (n >> 1);
  2202. #endif
  2203. }
  2204. }
  2205. int BigInteger::countNumberOfSetBits() const throw()
  2206. {
  2207. int total = 0;
  2208. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2209. total += BitFunctions::countBitsInInt32 (values[i]);
  2210. return total;
  2211. }
  2212. int BigInteger::getHighestBit() const throw()
  2213. {
  2214. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2215. {
  2216. const uint32 n = values[i];
  2217. if (n != 0)
  2218. return BitFunctions::highestBitInInt (n) + (i << 5);
  2219. }
  2220. return -1;
  2221. }
  2222. int BigInteger::findNextSetBit (int i) const throw()
  2223. {
  2224. for (; i <= highestBit; ++i)
  2225. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2226. return i;
  2227. return -1;
  2228. }
  2229. int BigInteger::findNextClearBit (int i) const throw()
  2230. {
  2231. for (; i <= highestBit; ++i)
  2232. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2233. break;
  2234. return i;
  2235. }
  2236. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2237. {
  2238. if (other.isNegative())
  2239. return operator-= (-other);
  2240. if (isNegative())
  2241. {
  2242. if (compareAbsolute (other) < 0)
  2243. {
  2244. BigInteger temp (*this);
  2245. temp.negate();
  2246. *this = other;
  2247. operator-= (temp);
  2248. }
  2249. else
  2250. {
  2251. negate();
  2252. operator-= (other);
  2253. negate();
  2254. }
  2255. }
  2256. else
  2257. {
  2258. if (other.highestBit > highestBit)
  2259. highestBit = other.highestBit;
  2260. ++highestBit;
  2261. const int numInts = bitToIndex (highestBit) + 1;
  2262. ensureSize (numInts);
  2263. int64 remainder = 0;
  2264. for (int i = 0; i <= numInts; ++i)
  2265. {
  2266. if (i < numValues)
  2267. remainder += values[i];
  2268. if (i < other.numValues)
  2269. remainder += other.values[i];
  2270. values[i] = (uint32) remainder;
  2271. remainder >>= 32;
  2272. }
  2273. jassert (remainder == 0);
  2274. highestBit = getHighestBit();
  2275. }
  2276. return *this;
  2277. }
  2278. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2279. {
  2280. if (other.isNegative())
  2281. return operator+= (-other);
  2282. if (! isNegative())
  2283. {
  2284. if (compareAbsolute (other) < 0)
  2285. {
  2286. BigInteger temp (other);
  2287. swapWith (temp);
  2288. operator-= (temp);
  2289. negate();
  2290. return *this;
  2291. }
  2292. }
  2293. else
  2294. {
  2295. negate();
  2296. operator+= (other);
  2297. negate();
  2298. return *this;
  2299. }
  2300. const int numInts = bitToIndex (highestBit) + 1;
  2301. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2302. int64 amountToSubtract = 0;
  2303. for (int i = 0; i <= numInts; ++i)
  2304. {
  2305. if (i <= maxOtherInts)
  2306. amountToSubtract += (int64) other.values[i];
  2307. if (values[i] >= amountToSubtract)
  2308. {
  2309. values[i] = (uint32) (values[i] - amountToSubtract);
  2310. amountToSubtract = 0;
  2311. }
  2312. else
  2313. {
  2314. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2315. values[i] = (uint32) n;
  2316. amountToSubtract = 1;
  2317. }
  2318. }
  2319. return *this;
  2320. }
  2321. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2322. {
  2323. BigInteger total;
  2324. highestBit = getHighestBit();
  2325. const bool wasNegative = isNegative();
  2326. setNegative (false);
  2327. for (int i = 0; i <= highestBit; ++i)
  2328. {
  2329. if (operator[](i))
  2330. {
  2331. BigInteger n (other);
  2332. n.setNegative (false);
  2333. n <<= i;
  2334. total += n;
  2335. }
  2336. }
  2337. total.setNegative (wasNegative ^ other.isNegative());
  2338. swapWith (total);
  2339. return *this;
  2340. }
  2341. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2342. {
  2343. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2344. const int divHB = divisor.getHighestBit();
  2345. const int ourHB = getHighestBit();
  2346. if (divHB < 0 || ourHB < 0)
  2347. {
  2348. // division by zero
  2349. remainder.clear();
  2350. clear();
  2351. }
  2352. else
  2353. {
  2354. const bool wasNegative = isNegative();
  2355. swapWith (remainder);
  2356. remainder.setNegative (false);
  2357. clear();
  2358. BigInteger temp (divisor);
  2359. temp.setNegative (false);
  2360. int leftShift = ourHB - divHB;
  2361. temp <<= leftShift;
  2362. while (leftShift >= 0)
  2363. {
  2364. if (remainder.compareAbsolute (temp) >= 0)
  2365. {
  2366. remainder -= temp;
  2367. setBit (leftShift);
  2368. }
  2369. if (--leftShift >= 0)
  2370. temp >>= 1;
  2371. }
  2372. negative = wasNegative ^ divisor.isNegative();
  2373. remainder.setNegative (wasNegative);
  2374. }
  2375. }
  2376. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2377. {
  2378. BigInteger remainder;
  2379. divideBy (other, remainder);
  2380. return *this;
  2381. }
  2382. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2383. {
  2384. // this operation doesn't take into account negative values..
  2385. jassert (isNegative() == other.isNegative());
  2386. if (other.highestBit >= 0)
  2387. {
  2388. ensureSize (bitToIndex (other.highestBit));
  2389. int n = bitToIndex (other.highestBit) + 1;
  2390. while (--n >= 0)
  2391. values[n] |= other.values[n];
  2392. if (other.highestBit > highestBit)
  2393. highestBit = other.highestBit;
  2394. highestBit = getHighestBit();
  2395. }
  2396. return *this;
  2397. }
  2398. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2399. {
  2400. // this operation doesn't take into account negative values..
  2401. jassert (isNegative() == other.isNegative());
  2402. int n = numValues;
  2403. while (n > other.numValues)
  2404. values[--n] = 0;
  2405. while (--n >= 0)
  2406. values[n] &= other.values[n];
  2407. if (other.highestBit < highestBit)
  2408. highestBit = other.highestBit;
  2409. highestBit = getHighestBit();
  2410. return *this;
  2411. }
  2412. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2413. {
  2414. // this operation will only work with the absolute values
  2415. jassert (isNegative() == other.isNegative());
  2416. if (other.highestBit >= 0)
  2417. {
  2418. ensureSize (bitToIndex (other.highestBit));
  2419. int n = bitToIndex (other.highestBit) + 1;
  2420. while (--n >= 0)
  2421. values[n] ^= other.values[n];
  2422. if (other.highestBit > highestBit)
  2423. highestBit = other.highestBit;
  2424. highestBit = getHighestBit();
  2425. }
  2426. return *this;
  2427. }
  2428. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2429. {
  2430. BigInteger remainder;
  2431. divideBy (divisor, remainder);
  2432. swapWith (remainder);
  2433. return *this;
  2434. }
  2435. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2436. {
  2437. shiftBits (numBitsToShift, 0);
  2438. return *this;
  2439. }
  2440. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2441. {
  2442. return operator<<= (-numBitsToShift);
  2443. }
  2444. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2445. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2446. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2447. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2448. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2449. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2450. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2451. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2452. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2453. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2454. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2455. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2456. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2457. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2458. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2459. int BigInteger::compare (const BigInteger& other) const throw()
  2460. {
  2461. if (isNegative() == other.isNegative())
  2462. {
  2463. const int absComp = compareAbsolute (other);
  2464. return isNegative() ? -absComp : absComp;
  2465. }
  2466. else
  2467. {
  2468. return isNegative() ? -1 : 1;
  2469. }
  2470. }
  2471. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2472. {
  2473. const int h1 = getHighestBit();
  2474. const int h2 = other.getHighestBit();
  2475. if (h1 > h2)
  2476. return 1;
  2477. else if (h1 < h2)
  2478. return -1;
  2479. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2480. if (values[i] != other.values[i])
  2481. return (values[i] > other.values[i]) ? 1 : -1;
  2482. return 0;
  2483. }
  2484. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2485. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2486. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2487. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2488. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2489. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2490. void BigInteger::shiftBits (int bits, const int startBit)
  2491. {
  2492. if (highestBit < 0)
  2493. return;
  2494. if (startBit > 0)
  2495. {
  2496. if (bits < 0)
  2497. {
  2498. // right shift
  2499. for (int i = startBit; i <= highestBit; ++i)
  2500. setBit (i, operator[] (i - bits));
  2501. highestBit = getHighestBit();
  2502. }
  2503. else if (bits > 0)
  2504. {
  2505. // left shift
  2506. for (int i = highestBit + 1; --i >= startBit;)
  2507. setBit (i + bits, operator[] (i));
  2508. while (--bits >= 0)
  2509. clearBit (bits + startBit);
  2510. }
  2511. }
  2512. else
  2513. {
  2514. if (bits < 0)
  2515. {
  2516. // right shift
  2517. bits = -bits;
  2518. if (bits > highestBit)
  2519. {
  2520. clear();
  2521. }
  2522. else
  2523. {
  2524. const int wordsToMove = bitToIndex (bits);
  2525. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2526. highestBit -= bits;
  2527. if (wordsToMove > 0)
  2528. {
  2529. int i;
  2530. for (i = 0; i < top; ++i)
  2531. values [i] = values [i + wordsToMove];
  2532. for (i = 0; i < wordsToMove; ++i)
  2533. values [top + i] = 0;
  2534. bits &= 31;
  2535. }
  2536. if (bits != 0)
  2537. {
  2538. const int invBits = 32 - bits;
  2539. --top;
  2540. for (int i = 0; i < top; ++i)
  2541. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2542. values[top] = (values[top] >> bits);
  2543. }
  2544. highestBit = getHighestBit();
  2545. }
  2546. }
  2547. else if (bits > 0)
  2548. {
  2549. // left shift
  2550. ensureSize (bitToIndex (highestBit + bits) + 1);
  2551. const int wordsToMove = bitToIndex (bits);
  2552. int top = 1 + bitToIndex (highestBit);
  2553. highestBit += bits;
  2554. if (wordsToMove > 0)
  2555. {
  2556. int i;
  2557. for (i = top; --i >= 0;)
  2558. values [i + wordsToMove] = values [i];
  2559. for (i = 0; i < wordsToMove; ++i)
  2560. values [i] = 0;
  2561. bits &= 31;
  2562. }
  2563. if (bits != 0)
  2564. {
  2565. const int invBits = 32 - bits;
  2566. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2567. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2568. values [wordsToMove] = values [wordsToMove] << bits;
  2569. }
  2570. highestBit = getHighestBit();
  2571. }
  2572. }
  2573. }
  2574. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2575. {
  2576. while (! m->isZero())
  2577. {
  2578. if (n->compareAbsolute (*m) > 0)
  2579. swapVariables (m, n);
  2580. *m -= *n;
  2581. }
  2582. return *n;
  2583. }
  2584. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2585. {
  2586. BigInteger m (*this);
  2587. while (! n.isZero())
  2588. {
  2589. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2590. return simpleGCD (&m, &n);
  2591. BigInteger temp1 (m), temp2;
  2592. temp1.divideBy (n, temp2);
  2593. m = n;
  2594. n = temp2;
  2595. }
  2596. return m;
  2597. }
  2598. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2599. {
  2600. BigInteger exp (exponent);
  2601. exp %= modulus;
  2602. BigInteger value (1);
  2603. swapWith (value);
  2604. value %= modulus;
  2605. while (! exp.isZero())
  2606. {
  2607. if (exp [0])
  2608. {
  2609. operator*= (value);
  2610. operator%= (modulus);
  2611. }
  2612. value *= value;
  2613. value %= modulus;
  2614. exp >>= 1;
  2615. }
  2616. }
  2617. void BigInteger::inverseModulo (const BigInteger& modulus)
  2618. {
  2619. if (modulus.isOne() || modulus.isNegative())
  2620. {
  2621. clear();
  2622. return;
  2623. }
  2624. if (isNegative() || compareAbsolute (modulus) >= 0)
  2625. operator%= (modulus);
  2626. if (isOne())
  2627. return;
  2628. if (! (*this)[0])
  2629. {
  2630. // not invertible
  2631. clear();
  2632. return;
  2633. }
  2634. BigInteger a1 (modulus);
  2635. BigInteger a2 (*this);
  2636. BigInteger b1 (modulus);
  2637. BigInteger b2 (1);
  2638. while (! a2.isOne())
  2639. {
  2640. BigInteger temp1, temp2, multiplier (a1);
  2641. multiplier.divideBy (a2, temp1);
  2642. temp1 = a2;
  2643. temp1 *= multiplier;
  2644. temp2 = a1;
  2645. temp2 -= temp1;
  2646. a1 = a2;
  2647. a2 = temp2;
  2648. temp1 = b2;
  2649. temp1 *= multiplier;
  2650. temp2 = b1;
  2651. temp2 -= temp1;
  2652. b1 = b2;
  2653. b2 = temp2;
  2654. }
  2655. while (b2.isNegative())
  2656. b2 += modulus;
  2657. b2 %= modulus;
  2658. swapWith (b2);
  2659. }
  2660. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2661. {
  2662. return stream << value.toString (10);
  2663. }
  2664. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2665. {
  2666. String s;
  2667. BigInteger v (*this);
  2668. if (base == 2 || base == 8 || base == 16)
  2669. {
  2670. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2671. static const char* const hexDigits = "0123456789abcdef";
  2672. for (;;)
  2673. {
  2674. const int remainder = v.getBitRangeAsInt (0, bits);
  2675. v >>= bits;
  2676. if (remainder == 0 && v.isZero())
  2677. break;
  2678. s = String::charToString (hexDigits [remainder]) + s;
  2679. }
  2680. }
  2681. else if (base == 10)
  2682. {
  2683. const BigInteger ten (10);
  2684. BigInteger remainder;
  2685. for (;;)
  2686. {
  2687. v.divideBy (ten, remainder);
  2688. if (remainder.isZero() && v.isZero())
  2689. break;
  2690. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2691. }
  2692. }
  2693. else
  2694. {
  2695. jassertfalse; // can't do the specified base!
  2696. return String::empty;
  2697. }
  2698. s = s.paddedLeft ('0', minimumNumCharacters);
  2699. return isNegative() ? "-" + s : s;
  2700. }
  2701. void BigInteger::parseString (const String& text, const int base)
  2702. {
  2703. clear();
  2704. const juce_wchar* t = text;
  2705. if (base == 2 || base == 8 || base == 16)
  2706. {
  2707. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2708. for (;;)
  2709. {
  2710. const juce_wchar c = *t++;
  2711. const int digit = CharacterFunctions::getHexDigitValue (c);
  2712. if (((uint32) digit) < (uint32) base)
  2713. {
  2714. operator<<= (bits);
  2715. operator+= (digit);
  2716. }
  2717. else if (c == 0)
  2718. {
  2719. break;
  2720. }
  2721. }
  2722. }
  2723. else if (base == 10)
  2724. {
  2725. const BigInteger ten ((uint32) 10);
  2726. for (;;)
  2727. {
  2728. const juce_wchar c = *t++;
  2729. if (c >= '0' && c <= '9')
  2730. {
  2731. operator*= (ten);
  2732. operator+= ((int) (c - '0'));
  2733. }
  2734. else if (c == 0)
  2735. {
  2736. break;
  2737. }
  2738. }
  2739. }
  2740. setNegative (text.trimStart().startsWithChar ('-'));
  2741. }
  2742. const MemoryBlock BigInteger::toMemoryBlock() const
  2743. {
  2744. const int numBytes = (getHighestBit() + 8) >> 3;
  2745. MemoryBlock mb ((size_t) numBytes);
  2746. for (int i = 0; i < numBytes; ++i)
  2747. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2748. return mb;
  2749. }
  2750. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2751. {
  2752. clear();
  2753. for (int i = (int) data.getSize(); --i >= 0;)
  2754. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2755. }
  2756. END_JUCE_NAMESPACE
  2757. /*** End of inlined file: juce_BigInteger.cpp ***/
  2758. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2759. BEGIN_JUCE_NAMESPACE
  2760. MemoryBlock::MemoryBlock() throw()
  2761. : size (0)
  2762. {
  2763. }
  2764. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2765. {
  2766. if (initialSize > 0)
  2767. {
  2768. size = initialSize;
  2769. data.allocate (initialSize, initialiseToZero);
  2770. }
  2771. else
  2772. {
  2773. size = 0;
  2774. }
  2775. }
  2776. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2777. : size (other.size)
  2778. {
  2779. if (size > 0)
  2780. {
  2781. jassert (other.data != 0);
  2782. data.malloc (size);
  2783. memcpy (data, other.data, size);
  2784. }
  2785. }
  2786. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2787. : size (jmax ((size_t) 0, sizeInBytes))
  2788. {
  2789. jassert (sizeInBytes >= 0);
  2790. if (size > 0)
  2791. {
  2792. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2793. data.malloc (size);
  2794. if (dataToInitialiseFrom != 0)
  2795. memcpy (data, dataToInitialiseFrom, size);
  2796. }
  2797. }
  2798. MemoryBlock::~MemoryBlock() throw()
  2799. {
  2800. jassert (size >= 0); // should never happen
  2801. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2802. }
  2803. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2804. {
  2805. if (this != &other)
  2806. {
  2807. setSize (other.size, false);
  2808. memcpy (data, other.data, size);
  2809. }
  2810. return *this;
  2811. }
  2812. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2813. {
  2814. return matches (other.data, other.size);
  2815. }
  2816. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2817. {
  2818. return ! operator== (other);
  2819. }
  2820. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2821. {
  2822. return size == dataSize
  2823. && memcmp (data, dataToCompare, size) == 0;
  2824. }
  2825. // this will resize the block to this size
  2826. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2827. {
  2828. if (size != newSize)
  2829. {
  2830. if (newSize <= 0)
  2831. {
  2832. data.free();
  2833. size = 0;
  2834. }
  2835. else
  2836. {
  2837. if (data != 0)
  2838. {
  2839. data.realloc (newSize);
  2840. if (initialiseToZero && (newSize > size))
  2841. zeromem (data + size, newSize - size);
  2842. }
  2843. else
  2844. {
  2845. data.allocate (newSize, initialiseToZero);
  2846. }
  2847. size = newSize;
  2848. }
  2849. }
  2850. }
  2851. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2852. {
  2853. if (size < minimumSize)
  2854. setSize (minimumSize, initialiseToZero);
  2855. }
  2856. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2857. {
  2858. swapVariables (size, other.size);
  2859. data.swapWith (other.data);
  2860. }
  2861. void MemoryBlock::fillWith (const uint8 value) throw()
  2862. {
  2863. memset (data, (int) value, size);
  2864. }
  2865. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2866. {
  2867. if (numBytes > 0)
  2868. {
  2869. const size_t oldSize = size;
  2870. setSize (size + numBytes);
  2871. memcpy (data + oldSize, srcData, numBytes);
  2872. }
  2873. }
  2874. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2875. {
  2876. const char* d = static_cast<const char*> (src);
  2877. if (offset < 0)
  2878. {
  2879. d -= offset;
  2880. num -= offset;
  2881. offset = 0;
  2882. }
  2883. if (offset + num > size)
  2884. num = size - offset;
  2885. if (num > 0)
  2886. memcpy (data + offset, d, num);
  2887. }
  2888. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2889. {
  2890. char* d = static_cast<char*> (dst);
  2891. if (offset < 0)
  2892. {
  2893. zeromem (d, -offset);
  2894. d -= offset;
  2895. num += offset;
  2896. offset = 0;
  2897. }
  2898. if (offset + num > size)
  2899. {
  2900. const size_t newNum = size - offset;
  2901. zeromem (d + newNum, num - newNum);
  2902. num = newNum;
  2903. }
  2904. if (num > 0)
  2905. memcpy (d, data + offset, num);
  2906. }
  2907. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2908. {
  2909. if (startByte < 0)
  2910. {
  2911. numBytesToRemove += startByte;
  2912. startByte = 0;
  2913. }
  2914. if (startByte + numBytesToRemove >= size)
  2915. {
  2916. setSize (startByte);
  2917. }
  2918. else if (numBytesToRemove > 0)
  2919. {
  2920. memmove (data + startByte,
  2921. data + startByte + numBytesToRemove,
  2922. size - (startByte + numBytesToRemove));
  2923. setSize (size - numBytesToRemove);
  2924. }
  2925. }
  2926. const String MemoryBlock::toString() const
  2927. {
  2928. return String (static_cast <const char*> (getData()), size);
  2929. }
  2930. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2931. {
  2932. int res = 0;
  2933. size_t byte = bitRangeStart >> 3;
  2934. int offsetInByte = (int) bitRangeStart & 7;
  2935. size_t bitsSoFar = 0;
  2936. while (numBits > 0 && (size_t) byte < size)
  2937. {
  2938. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2939. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2940. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2941. bitsSoFar += bitsThisTime;
  2942. numBits -= bitsThisTime;
  2943. ++byte;
  2944. offsetInByte = 0;
  2945. }
  2946. return res;
  2947. }
  2948. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2949. {
  2950. size_t byte = bitRangeStart >> 3;
  2951. int offsetInByte = (int) bitRangeStart & 7;
  2952. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2953. while (numBits > 0 && (size_t) byte < size)
  2954. {
  2955. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2956. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2957. const unsigned int tempBits = bitsToSet << offsetInByte;
  2958. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2959. ++byte;
  2960. numBits -= bitsThisTime;
  2961. bitsToSet >>= bitsThisTime;
  2962. mask >>= bitsThisTime;
  2963. offsetInByte = 0;
  2964. }
  2965. }
  2966. void MemoryBlock::loadFromHexString (const String& hex)
  2967. {
  2968. ensureSize (hex.length() >> 1);
  2969. char* dest = data;
  2970. int i = 0;
  2971. for (;;)
  2972. {
  2973. int byte = 0;
  2974. for (int loop = 2; --loop >= 0;)
  2975. {
  2976. byte <<= 4;
  2977. for (;;)
  2978. {
  2979. const juce_wchar c = hex [i++];
  2980. if (c >= '0' && c <= '9')
  2981. {
  2982. byte |= c - '0';
  2983. break;
  2984. }
  2985. else if (c >= 'a' && c <= 'z')
  2986. {
  2987. byte |= c - ('a' - 10);
  2988. break;
  2989. }
  2990. else if (c >= 'A' && c <= 'Z')
  2991. {
  2992. byte |= c - ('A' - 10);
  2993. break;
  2994. }
  2995. else if (c == 0)
  2996. {
  2997. setSize (static_cast <size_t> (dest - data));
  2998. return;
  2999. }
  3000. }
  3001. }
  3002. *dest++ = (char) byte;
  3003. }
  3004. }
  3005. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3006. const String MemoryBlock::toBase64Encoding() const
  3007. {
  3008. const size_t numChars = ((size << 3) + 5) / 6;
  3009. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3010. const int initialLen = destString.length();
  3011. destString.preallocateStorage (initialLen + 2 + numChars);
  3012. juce_wchar* d = destString;
  3013. d += initialLen;
  3014. *d++ = '.';
  3015. for (size_t i = 0; i < numChars; ++i)
  3016. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3017. *d++ = 0;
  3018. return destString;
  3019. }
  3020. bool MemoryBlock::fromBase64Encoding (const String& s)
  3021. {
  3022. const int startPos = s.indexOfChar ('.') + 1;
  3023. if (startPos <= 0)
  3024. return false;
  3025. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3026. setSize (numBytesNeeded, true);
  3027. const int numChars = s.length() - startPos;
  3028. const juce_wchar* srcChars = s;
  3029. srcChars += startPos;
  3030. int pos = 0;
  3031. for (int i = 0; i < numChars; ++i)
  3032. {
  3033. const char c = (char) srcChars[i];
  3034. for (int j = 0; j < 64; ++j)
  3035. {
  3036. if (encodingTable[j] == c)
  3037. {
  3038. setBitRange (pos, 6, j);
  3039. pos += 6;
  3040. break;
  3041. }
  3042. }
  3043. }
  3044. return true;
  3045. }
  3046. END_JUCE_NAMESPACE
  3047. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3048. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3049. BEGIN_JUCE_NAMESPACE
  3050. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3051. : properties (ignoreCaseOfKeyNames),
  3052. fallbackProperties (0),
  3053. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3054. {
  3055. }
  3056. PropertySet::PropertySet (const PropertySet& other)
  3057. : properties (other.properties),
  3058. fallbackProperties (other.fallbackProperties),
  3059. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3060. {
  3061. }
  3062. PropertySet& PropertySet::operator= (const PropertySet& other)
  3063. {
  3064. properties = other.properties;
  3065. fallbackProperties = other.fallbackProperties;
  3066. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3067. propertyChanged();
  3068. return *this;
  3069. }
  3070. PropertySet::~PropertySet()
  3071. {
  3072. }
  3073. void PropertySet::clear()
  3074. {
  3075. const ScopedLock sl (lock);
  3076. if (properties.size() > 0)
  3077. {
  3078. properties.clear();
  3079. propertyChanged();
  3080. }
  3081. }
  3082. const String PropertySet::getValue (const String& keyName,
  3083. const String& defaultValue) const throw()
  3084. {
  3085. const ScopedLock sl (lock);
  3086. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3087. if (index >= 0)
  3088. return properties.getAllValues() [index];
  3089. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3090. : defaultValue;
  3091. }
  3092. int PropertySet::getIntValue (const String& keyName,
  3093. const int defaultValue) const throw()
  3094. {
  3095. const ScopedLock sl (lock);
  3096. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3097. if (index >= 0)
  3098. return properties.getAllValues() [index].getIntValue();
  3099. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3100. : defaultValue;
  3101. }
  3102. double PropertySet::getDoubleValue (const String& keyName,
  3103. const double defaultValue) const throw()
  3104. {
  3105. const ScopedLock sl (lock);
  3106. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3107. if (index >= 0)
  3108. return properties.getAllValues()[index].getDoubleValue();
  3109. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3110. : defaultValue;
  3111. }
  3112. bool PropertySet::getBoolValue (const String& keyName,
  3113. const bool defaultValue) const throw()
  3114. {
  3115. const ScopedLock sl (lock);
  3116. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3117. if (index >= 0)
  3118. return properties.getAllValues() [index].getIntValue() != 0;
  3119. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3120. : defaultValue;
  3121. }
  3122. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3123. {
  3124. return XmlDocument::parse (getValue (keyName));
  3125. }
  3126. void PropertySet::setValue (const String& keyName, const var& v)
  3127. {
  3128. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3129. if (keyName.isNotEmpty())
  3130. {
  3131. const String value (v.toString());
  3132. const ScopedLock sl (lock);
  3133. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3134. if (index < 0 || properties.getAllValues() [index] != value)
  3135. {
  3136. properties.set (keyName, value);
  3137. propertyChanged();
  3138. }
  3139. }
  3140. }
  3141. void PropertySet::removeValue (const String& keyName)
  3142. {
  3143. if (keyName.isNotEmpty())
  3144. {
  3145. const ScopedLock sl (lock);
  3146. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3147. if (index >= 0)
  3148. {
  3149. properties.remove (keyName);
  3150. propertyChanged();
  3151. }
  3152. }
  3153. }
  3154. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3155. {
  3156. setValue (keyName, xml == 0 ? var::null
  3157. : var (xml->createDocument (String::empty, true)));
  3158. }
  3159. bool PropertySet::containsKey (const String& keyName) const throw()
  3160. {
  3161. const ScopedLock sl (lock);
  3162. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3163. }
  3164. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3165. {
  3166. const ScopedLock sl (lock);
  3167. fallbackProperties = fallbackProperties_;
  3168. }
  3169. XmlElement* PropertySet::createXml (const String& nodeName) const
  3170. {
  3171. const ScopedLock sl (lock);
  3172. XmlElement* const xml = new XmlElement (nodeName);
  3173. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3174. {
  3175. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3176. e->setAttribute ("name", properties.getAllKeys()[i]);
  3177. e->setAttribute ("val", properties.getAllValues()[i]);
  3178. }
  3179. return xml;
  3180. }
  3181. void PropertySet::restoreFromXml (const XmlElement& xml)
  3182. {
  3183. const ScopedLock sl (lock);
  3184. clear();
  3185. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3186. {
  3187. if (e->hasAttribute ("name")
  3188. && e->hasAttribute ("val"))
  3189. {
  3190. properties.set (e->getStringAttribute ("name"),
  3191. e->getStringAttribute ("val"));
  3192. }
  3193. }
  3194. if (properties.size() > 0)
  3195. propertyChanged();
  3196. }
  3197. void PropertySet::propertyChanged()
  3198. {
  3199. }
  3200. END_JUCE_NAMESPACE
  3201. /*** End of inlined file: juce_PropertySet.cpp ***/
  3202. /*** Start of inlined file: juce_Identifier.cpp ***/
  3203. BEGIN_JUCE_NAMESPACE
  3204. StringPool& Identifier::getPool()
  3205. {
  3206. static StringPool pool;
  3207. return pool;
  3208. }
  3209. Identifier::Identifier() throw()
  3210. : name (0)
  3211. {
  3212. }
  3213. Identifier::Identifier (const Identifier& other) throw()
  3214. : name (other.name)
  3215. {
  3216. }
  3217. Identifier& Identifier::operator= (const Identifier& other) throw()
  3218. {
  3219. name = other.name;
  3220. return *this;
  3221. }
  3222. Identifier::Identifier (const String& name_)
  3223. : name (Identifier::getPool().getPooledString (name_))
  3224. {
  3225. /* An Identifier string must be suitable for use as a script variable or XML
  3226. attribute, so it can only contain this limited set of characters.. */
  3227. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3228. }
  3229. Identifier::Identifier (const char* const name_)
  3230. : name (Identifier::getPool().getPooledString (name_))
  3231. {
  3232. /* An Identifier string must be suitable for use as a script variable or XML
  3233. attribute, so it can only contain this limited set of characters.. */
  3234. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3235. }
  3236. Identifier::~Identifier()
  3237. {
  3238. }
  3239. END_JUCE_NAMESPACE
  3240. /*** End of inlined file: juce_Identifier.cpp ***/
  3241. /*** Start of inlined file: juce_Variant.cpp ***/
  3242. BEGIN_JUCE_NAMESPACE
  3243. class var::VariantType
  3244. {
  3245. public:
  3246. VariantType() {}
  3247. virtual ~VariantType() {}
  3248. virtual int toInt (const ValueUnion&) const { return 0; }
  3249. virtual double toDouble (const ValueUnion&) const { return 0; }
  3250. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3251. virtual bool toBool (const ValueUnion&) const { return false; }
  3252. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3253. virtual bool isVoid() const throw() { return false; }
  3254. virtual bool isInt() const throw() { return false; }
  3255. virtual bool isBool() const throw() { return false; }
  3256. virtual bool isDouble() const throw() { return false; }
  3257. virtual bool isString() const throw() { return false; }
  3258. virtual bool isObject() const throw() { return false; }
  3259. virtual bool isMethod() const throw() { return false; }
  3260. virtual void cleanUp (ValueUnion&) const throw() {}
  3261. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3262. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3263. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3264. };
  3265. class var::VariantType_Void : public var::VariantType
  3266. {
  3267. public:
  3268. VariantType_Void() {}
  3269. static const VariantType_Void instance;
  3270. bool isVoid() const throw() { return true; }
  3271. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3272. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3273. };
  3274. class var::VariantType_Int : public var::VariantType
  3275. {
  3276. public:
  3277. VariantType_Int() {}
  3278. static const VariantType_Int instance;
  3279. int toInt (const ValueUnion& data) const { return data.intValue; };
  3280. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3281. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3282. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3283. bool isInt() const throw() { return true; }
  3284. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3285. {
  3286. return otherType.toInt (otherData) == data.intValue;
  3287. }
  3288. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3289. {
  3290. output.writeCompressedInt (5);
  3291. output.writeByte (1);
  3292. output.writeInt (data.intValue);
  3293. }
  3294. };
  3295. class var::VariantType_Double : public var::VariantType
  3296. {
  3297. public:
  3298. VariantType_Double() {}
  3299. static const VariantType_Double instance;
  3300. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3301. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3302. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3303. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3304. bool isDouble() const throw() { return true; }
  3305. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3306. {
  3307. return otherType.toDouble (otherData) == data.doubleValue;
  3308. }
  3309. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3310. {
  3311. output.writeCompressedInt (9);
  3312. output.writeByte (4);
  3313. output.writeDouble (data.doubleValue);
  3314. }
  3315. };
  3316. class var::VariantType_Bool : public var::VariantType
  3317. {
  3318. public:
  3319. VariantType_Bool() {}
  3320. static const VariantType_Bool instance;
  3321. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3322. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3323. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3324. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3325. bool isBool() const throw() { return true; }
  3326. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3327. {
  3328. return otherType.toBool (otherData) == data.boolValue;
  3329. }
  3330. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3331. {
  3332. output.writeCompressedInt (1);
  3333. output.writeByte (data.boolValue ? 2 : 3);
  3334. }
  3335. };
  3336. class var::VariantType_String : public var::VariantType
  3337. {
  3338. public:
  3339. VariantType_String() {}
  3340. static const VariantType_String instance;
  3341. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3342. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3343. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3344. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3345. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3346. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3347. || data.stringValue->trim().equalsIgnoreCase ("true")
  3348. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3349. bool isString() const throw() { return true; }
  3350. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3351. {
  3352. return otherType.toString (otherData) == *data.stringValue;
  3353. }
  3354. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3355. {
  3356. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3357. output.writeCompressedInt (len + 1);
  3358. output.writeByte (5);
  3359. HeapBlock<char> temp (len);
  3360. data.stringValue->copyToUTF8 (temp, len);
  3361. output.write (temp, len);
  3362. }
  3363. };
  3364. class var::VariantType_Object : public var::VariantType
  3365. {
  3366. public:
  3367. VariantType_Object() {}
  3368. static const VariantType_Object instance;
  3369. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3370. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3371. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3372. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3373. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3374. bool isObject() const throw() { return true; }
  3375. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3376. {
  3377. return otherType.toObject (otherData) == data.objectValue;
  3378. }
  3379. void writeToStream (const ValueUnion&, OutputStream& output) const
  3380. {
  3381. jassertfalse; // Can't write an object to a stream!
  3382. output.writeCompressedInt (0);
  3383. }
  3384. };
  3385. class var::VariantType_Method : public var::VariantType
  3386. {
  3387. public:
  3388. VariantType_Method() {}
  3389. static const VariantType_Method instance;
  3390. const String toString (const ValueUnion&) const { return "Method"; }
  3391. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3392. bool isMethod() const throw() { return true; }
  3393. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3394. {
  3395. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3396. }
  3397. void writeToStream (const ValueUnion&, OutputStream& output) const
  3398. {
  3399. jassertfalse; // Can't write a method to a stream!
  3400. output.writeCompressedInt (0);
  3401. }
  3402. };
  3403. const var::VariantType_Void var::VariantType_Void::instance;
  3404. const var::VariantType_Int var::VariantType_Int::instance;
  3405. const var::VariantType_Bool var::VariantType_Bool::instance;
  3406. const var::VariantType_Double var::VariantType_Double::instance;
  3407. const var::VariantType_String var::VariantType_String::instance;
  3408. const var::VariantType_Object var::VariantType_Object::instance;
  3409. const var::VariantType_Method var::VariantType_Method::instance;
  3410. var::var() throw() : type (&VariantType_Void::instance)
  3411. {
  3412. }
  3413. var::~var() throw()
  3414. {
  3415. type->cleanUp (value);
  3416. }
  3417. const var var::null;
  3418. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3419. {
  3420. type->createCopy (value, valueToCopy.value);
  3421. }
  3422. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3423. {
  3424. value.intValue = value_;
  3425. }
  3426. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3427. {
  3428. value.boolValue = value_;
  3429. }
  3430. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3431. {
  3432. value.doubleValue = value_;
  3433. }
  3434. var::var (const String& value_) : type (&VariantType_String::instance)
  3435. {
  3436. value.stringValue = new String (value_);
  3437. }
  3438. var::var (const char* const value_) : type (&VariantType_String::instance)
  3439. {
  3440. value.stringValue = new String (value_);
  3441. }
  3442. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3443. {
  3444. value.stringValue = new String (value_);
  3445. }
  3446. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3447. {
  3448. value.objectValue = object;
  3449. if (object != 0)
  3450. object->incReferenceCount();
  3451. }
  3452. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3453. {
  3454. value.methodValue = method_;
  3455. }
  3456. bool var::isVoid() const throw() { return type->isVoid(); }
  3457. bool var::isInt() const throw() { return type->isInt(); }
  3458. bool var::isBool() const throw() { return type->isBool(); }
  3459. bool var::isDouble() const throw() { return type->isDouble(); }
  3460. bool var::isString() const throw() { return type->isString(); }
  3461. bool var::isObject() const throw() { return type->isObject(); }
  3462. bool var::isMethod() const throw() { return type->isMethod(); }
  3463. var::operator int() const { return type->toInt (value); }
  3464. var::operator bool() const { return type->toBool (value); }
  3465. var::operator float() const { return (float) type->toDouble (value); }
  3466. var::operator double() const { return type->toDouble (value); }
  3467. const String var::toString() const { return type->toString (value); }
  3468. var::operator const String() const { return type->toString (value); }
  3469. DynamicObject* var::getObject() const { return type->toObject (value); }
  3470. void var::swapWith (var& other) throw()
  3471. {
  3472. swapVariables (type, other.type);
  3473. swapVariables (value, other.value);
  3474. }
  3475. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3476. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3477. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3478. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3479. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3480. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3481. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3482. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3483. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3484. bool var::equals (const var& other) const throw()
  3485. {
  3486. return type->equals (value, other.value, *other.type);
  3487. }
  3488. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3489. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3490. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3491. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3492. void var::writeToStream (OutputStream& output) const
  3493. {
  3494. type->writeToStream (value, output);
  3495. }
  3496. const var var::readFromStream (InputStream& input)
  3497. {
  3498. const int numBytes = input.readCompressedInt();
  3499. if (numBytes > 0)
  3500. {
  3501. switch (input.readByte())
  3502. {
  3503. case 1: return var (input.readInt());
  3504. case 2: return var (true);
  3505. case 3: return var (false);
  3506. case 4: return var (input.readDouble());
  3507. case 5:
  3508. {
  3509. MemoryOutputStream mo;
  3510. mo.writeFromInputStream (input, numBytes - 1);
  3511. return var (mo.toUTF8());
  3512. }
  3513. default: input.skipNextBytes (numBytes - 1); break;
  3514. }
  3515. }
  3516. return var::null;
  3517. }
  3518. const var var::operator[] (const Identifier& propertyName) const
  3519. {
  3520. DynamicObject* const o = getObject();
  3521. return o != 0 ? o->getProperty (propertyName) : var::null;
  3522. }
  3523. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3524. {
  3525. DynamicObject* const o = getObject();
  3526. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3527. }
  3528. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3529. {
  3530. if (isMethod())
  3531. {
  3532. DynamicObject* const target = targetObject.getObject();
  3533. if (target != 0)
  3534. return (target->*(value.methodValue)) (arguments, numArguments);
  3535. }
  3536. return var::null;
  3537. }
  3538. const var var::call (const Identifier& method) const
  3539. {
  3540. return invoke (method, 0, 0);
  3541. }
  3542. const var var::call (const Identifier& method, const var& arg1) const
  3543. {
  3544. return invoke (method, &arg1, 1);
  3545. }
  3546. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3547. {
  3548. var args[] = { arg1, arg2 };
  3549. return invoke (method, args, 2);
  3550. }
  3551. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3552. {
  3553. var args[] = { arg1, arg2, arg3 };
  3554. return invoke (method, args, 3);
  3555. }
  3556. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3557. {
  3558. var args[] = { arg1, arg2, arg3, arg4 };
  3559. return invoke (method, args, 4);
  3560. }
  3561. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3562. {
  3563. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3564. return invoke (method, args, 5);
  3565. }
  3566. END_JUCE_NAMESPACE
  3567. /*** End of inlined file: juce_Variant.cpp ***/
  3568. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3569. BEGIN_JUCE_NAMESPACE
  3570. NamedValueSet::NamedValue::NamedValue() throw()
  3571. {
  3572. }
  3573. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3574. : name (name_), value (value_)
  3575. {
  3576. }
  3577. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3578. {
  3579. return name == other.name && value == other.value;
  3580. }
  3581. NamedValueSet::NamedValueSet() throw()
  3582. {
  3583. }
  3584. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3585. {
  3586. values.addCopyOfList (other.values);
  3587. }
  3588. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3589. {
  3590. clear();
  3591. values.addCopyOfList (other.values);
  3592. return *this;
  3593. }
  3594. NamedValueSet::~NamedValueSet()
  3595. {
  3596. clear();
  3597. }
  3598. void NamedValueSet::clear()
  3599. {
  3600. values.deleteAll();
  3601. }
  3602. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3603. {
  3604. const NamedValue* i1 = values;
  3605. const NamedValue* i2 = other.values;
  3606. while (i1 != 0 && i2 != 0)
  3607. {
  3608. if (! (*i1 == *i2))
  3609. return false;
  3610. i1 = i1->nextListItem;
  3611. i2 = i2->nextListItem;
  3612. }
  3613. return true;
  3614. }
  3615. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3616. {
  3617. return ! operator== (other);
  3618. }
  3619. int NamedValueSet::size() const throw()
  3620. {
  3621. return values.size();
  3622. }
  3623. const var& NamedValueSet::operator[] (const Identifier& name) const
  3624. {
  3625. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3626. if (i->name == name)
  3627. return i->value;
  3628. return var::null;
  3629. }
  3630. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3631. {
  3632. const var* v = getVarPointer (name);
  3633. return v != 0 ? *v : defaultReturnValue;
  3634. }
  3635. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3636. {
  3637. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3638. if (i->name == name)
  3639. return &(i->value);
  3640. return 0;
  3641. }
  3642. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3643. {
  3644. LinkedListPointer<NamedValue>* i = &values;
  3645. while (i->get() != 0)
  3646. {
  3647. NamedValue* const v = i->get();
  3648. if (v->name == name)
  3649. {
  3650. if (v->value == newValue)
  3651. return false;
  3652. v->value = newValue;
  3653. return true;
  3654. }
  3655. i = &(v->nextListItem);
  3656. }
  3657. i->insertNext (new NamedValue (name, newValue));
  3658. return true;
  3659. }
  3660. bool NamedValueSet::contains (const Identifier& name) const
  3661. {
  3662. return getVarPointer (name) != 0;
  3663. }
  3664. bool NamedValueSet::remove (const Identifier& name)
  3665. {
  3666. LinkedListPointer<NamedValue>* i = &values;
  3667. for (;;)
  3668. {
  3669. NamedValue* const v = i->get();
  3670. if (v == 0)
  3671. break;
  3672. if (v->name == name)
  3673. {
  3674. delete i->removeNext();
  3675. return true;
  3676. }
  3677. i = &(v->nextListItem);
  3678. }
  3679. return false;
  3680. }
  3681. const Identifier NamedValueSet::getName (const int index) const
  3682. {
  3683. const NamedValue* const v = values[index];
  3684. jassert (v != 0);
  3685. return v->name;
  3686. }
  3687. const var NamedValueSet::getValueAt (const int index) const
  3688. {
  3689. const NamedValue* const v = values[index];
  3690. jassert (v != 0);
  3691. return v->value;
  3692. }
  3693. void NamedValueSet::setFromXmlAttributes (const XmlElement& xml)
  3694. {
  3695. clear();
  3696. LinkedListPointer<NamedValue>::Appender appender (values);
  3697. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  3698. for (int i = 0; i < numAtts; ++i)
  3699. appender.append (new NamedValue (xml.getAttributeName (i), var (xml.getAttributeValue (i))));
  3700. }
  3701. void NamedValueSet::copyToXmlAttributes (XmlElement& xml) const
  3702. {
  3703. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3704. {
  3705. jassert (! i->value.isObject()); // DynamicObjects can't be stored as XML!
  3706. xml.setAttribute (i->name.toString(),
  3707. i->value.toString());
  3708. }
  3709. }
  3710. END_JUCE_NAMESPACE
  3711. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3712. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3713. BEGIN_JUCE_NAMESPACE
  3714. DynamicObject::DynamicObject()
  3715. {
  3716. }
  3717. DynamicObject::~DynamicObject()
  3718. {
  3719. }
  3720. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3721. {
  3722. var* const v = properties.getVarPointer (propertyName);
  3723. return v != 0 && ! v->isMethod();
  3724. }
  3725. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3726. {
  3727. return properties [propertyName];
  3728. }
  3729. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3730. {
  3731. properties.set (propertyName, newValue);
  3732. }
  3733. void DynamicObject::removeProperty (const Identifier& propertyName)
  3734. {
  3735. properties.remove (propertyName);
  3736. }
  3737. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3738. {
  3739. return getProperty (methodName).isMethod();
  3740. }
  3741. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3742. const var* parameters,
  3743. int numParameters)
  3744. {
  3745. return properties [methodName].invoke (var (this), parameters, numParameters);
  3746. }
  3747. void DynamicObject::setMethod (const Identifier& name,
  3748. var::MethodFunction methodFunction)
  3749. {
  3750. properties.set (name, var (methodFunction));
  3751. }
  3752. void DynamicObject::clear()
  3753. {
  3754. properties.clear();
  3755. }
  3756. END_JUCE_NAMESPACE
  3757. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3758. /*** Start of inlined file: juce_Expression.cpp ***/
  3759. BEGIN_JUCE_NAMESPACE
  3760. class Expression::Helpers
  3761. {
  3762. public:
  3763. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3764. // This helper function is needed to work around VC6 scoping bugs
  3765. static const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  3766. friend class Expression::Term; // (also only needed as a VC6 workaround)
  3767. class Constant : public Term
  3768. {
  3769. public:
  3770. Constant (const double value_, bool isResolutionTarget_)
  3771. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3772. Type getType() const throw() { return constantType; }
  3773. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3774. double evaluate (const EvaluationContext&, int) const { return value; }
  3775. int getNumInputs() const { return 0; }
  3776. Term* getInput (int) const { return 0; }
  3777. const TermPtr negated()
  3778. {
  3779. return new Constant (-value, isResolutionTarget);
  3780. }
  3781. const String toString() const
  3782. {
  3783. if (isResolutionTarget)
  3784. return "@" + String (value);
  3785. return String (value);
  3786. }
  3787. double value;
  3788. bool isResolutionTarget;
  3789. };
  3790. class Symbol : public Term
  3791. {
  3792. public:
  3793. explicit Symbol (const String& symbol_)
  3794. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3795. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3796. {}
  3797. Symbol (const String& symbol_, const String& member_)
  3798. : mainSymbol (symbol_),
  3799. member (member_)
  3800. {}
  3801. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3802. {
  3803. if (++recursionDepth > 256)
  3804. throw EvaluationError ("Recursive symbol references");
  3805. try
  3806. {
  3807. return getTermFor (c.getSymbolValue (mainSymbol, member))->evaluate (c, recursionDepth);
  3808. }
  3809. catch (...)
  3810. {}
  3811. return 0;
  3812. }
  3813. Type getType() const throw() { return symbolType; }
  3814. Term* clone() const { return new Symbol (mainSymbol, member); }
  3815. int getNumInputs() const { return 0; }
  3816. Term* getInput (int) const { return 0; }
  3817. const String toString() const { return joinParts (mainSymbol, member); }
  3818. void getSymbolParts (String& objectName, String& memberName) const { objectName = mainSymbol; memberName = member; }
  3819. static const String joinParts (const String& mainSymbol, const String& member)
  3820. {
  3821. return member.isEmpty() ? mainSymbol
  3822. : mainSymbol + "." + member;
  3823. }
  3824. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3825. {
  3826. if (s == mainSymbol)
  3827. return true;
  3828. if (++recursionDepth > 256)
  3829. throw EvaluationError ("Recursive symbol references");
  3830. try
  3831. {
  3832. return c != 0 && getTermFor (c->getSymbolValue (mainSymbol, member))->referencesSymbol (s, c, recursionDepth);
  3833. }
  3834. catch (EvaluationError&)
  3835. {
  3836. return false;
  3837. }
  3838. }
  3839. String mainSymbol, member;
  3840. };
  3841. class Function : public Term
  3842. {
  3843. public:
  3844. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3845. : functionName (functionName_), parameters (parameters_)
  3846. {}
  3847. Term* clone() const { return new Function (functionName, parameters); }
  3848. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3849. {
  3850. HeapBlock <double> params (parameters.size());
  3851. for (int i = 0; i < parameters.size(); ++i)
  3852. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3853. return c.evaluateFunction (functionName, params, parameters.size());
  3854. }
  3855. Type getType() const throw() { return functionType; }
  3856. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3857. int getNumInputs() const { return parameters.size(); }
  3858. Term* getInput (int i) const { return parameters [i]; }
  3859. const String getFunctionName() const { return functionName; }
  3860. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3861. {
  3862. for (int i = 0; i < parameters.size(); ++i)
  3863. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3864. return true;
  3865. return false;
  3866. }
  3867. const String toString() const
  3868. {
  3869. if (parameters.size() == 0)
  3870. return functionName + "()";
  3871. String s (functionName + " (");
  3872. for (int i = 0; i < parameters.size(); ++i)
  3873. {
  3874. s << parameters.getUnchecked(i)->toString();
  3875. if (i < parameters.size() - 1)
  3876. s << ", ";
  3877. }
  3878. s << ')';
  3879. return s;
  3880. }
  3881. const String functionName;
  3882. ReferenceCountedArray<Term> parameters;
  3883. };
  3884. class Negate : public Term
  3885. {
  3886. public:
  3887. explicit Negate (const TermPtr& input_) : input (input_)
  3888. {
  3889. jassert (input_ != 0);
  3890. }
  3891. Type getType() const throw() { return operatorType; }
  3892. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3893. int getNumInputs() const { return 1; }
  3894. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3895. Term* clone() const { return new Negate (input->clone()); }
  3896. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3897. const String getFunctionName() const { return "-"; }
  3898. const TermPtr negated()
  3899. {
  3900. return input;
  3901. }
  3902. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3903. {
  3904. (void) input_;
  3905. jassert (input_ == input);
  3906. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3907. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3908. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3909. }
  3910. const String toString() const
  3911. {
  3912. if (input->getOperatorPrecedence() > 0)
  3913. return "-(" + input->toString() + ")";
  3914. else
  3915. return "-" + input->toString();
  3916. }
  3917. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3918. {
  3919. return input->referencesSymbol (s, c, recursionDepth);
  3920. }
  3921. private:
  3922. const TermPtr input;
  3923. };
  3924. class BinaryTerm : public Term
  3925. {
  3926. public:
  3927. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3928. {
  3929. jassert (left_ != 0 && right_ != 0);
  3930. }
  3931. int getInputIndexFor (const Term* possibleInput) const
  3932. {
  3933. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3934. }
  3935. Type getType() const throw() { return operatorType; }
  3936. int getNumInputs() const { return 2; }
  3937. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3938. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3939. {
  3940. return left->referencesSymbol (s, c, recursionDepth)
  3941. || right->referencesSymbol (s, c, recursionDepth);
  3942. }
  3943. const String toString() const
  3944. {
  3945. String s;
  3946. const int ourPrecendence = getOperatorPrecedence();
  3947. if (left->getOperatorPrecedence() > ourPrecendence)
  3948. s << '(' << left->toString() << ')';
  3949. else
  3950. s = left->toString();
  3951. s << ' ' << getFunctionName() << ' ';
  3952. if (right->getOperatorPrecedence() >= ourPrecendence)
  3953. s << '(' << right->toString() << ')';
  3954. else
  3955. s << right->toString();
  3956. return s;
  3957. }
  3958. protected:
  3959. const TermPtr left, right;
  3960. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3961. {
  3962. jassert (input == left || input == right);
  3963. if (input != left && input != right)
  3964. return 0;
  3965. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3966. if (dest == 0)
  3967. return new Constant (overallTarget, false);
  3968. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3969. }
  3970. };
  3971. class Add : public BinaryTerm
  3972. {
  3973. public:
  3974. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3975. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3976. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3977. int getOperatorPrecedence() const { return 2; }
  3978. const String getFunctionName() const { return "+"; }
  3979. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3980. {
  3981. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3982. if (newDest == 0)
  3983. return 0;
  3984. return new Subtract (newDest, (input == left ? right : left)->clone());
  3985. }
  3986. private:
  3987. JUCE_DECLARE_NON_COPYABLE (Add);
  3988. };
  3989. class Subtract : public BinaryTerm
  3990. {
  3991. public:
  3992. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3993. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  3994. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  3995. int getOperatorPrecedence() const { return 2; }
  3996. const String getFunctionName() const { return "-"; }
  3997. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3998. {
  3999. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4000. if (newDest == 0)
  4001. return 0;
  4002. if (input == left)
  4003. return new Add (newDest, right->clone());
  4004. else
  4005. return new Subtract (left->clone(), newDest);
  4006. }
  4007. private:
  4008. JUCE_DECLARE_NON_COPYABLE (Subtract);
  4009. };
  4010. class Multiply : public BinaryTerm
  4011. {
  4012. public:
  4013. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4014. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4015. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4016. const String getFunctionName() const { return "*"; }
  4017. int getOperatorPrecedence() const { return 1; }
  4018. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4019. {
  4020. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4021. if (newDest == 0)
  4022. return 0;
  4023. return new Divide (newDest, (input == left ? right : left)->clone());
  4024. }
  4025. private:
  4026. JUCE_DECLARE_NON_COPYABLE (Multiply);
  4027. };
  4028. class Divide : public BinaryTerm
  4029. {
  4030. public:
  4031. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4032. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4033. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4034. const String getFunctionName() const { return "/"; }
  4035. int getOperatorPrecedence() const { return 1; }
  4036. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4037. {
  4038. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4039. if (newDest == 0)
  4040. return 0;
  4041. if (input == left)
  4042. return new Multiply (newDest, right->clone());
  4043. else
  4044. return new Divide (left->clone(), newDest);
  4045. }
  4046. private:
  4047. JUCE_DECLARE_NON_COPYABLE (Divide);
  4048. };
  4049. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4050. {
  4051. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4052. if (inputIndex >= 0)
  4053. return topLevel;
  4054. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4055. {
  4056. Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4057. if (t != 0)
  4058. return t;
  4059. }
  4060. return 0;
  4061. }
  4062. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4063. {
  4064. {
  4065. Constant* const c = dynamic_cast<Constant*> (term);
  4066. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4067. return c;
  4068. }
  4069. if (dynamic_cast<Function*> (term) != 0)
  4070. return 0;
  4071. int i;
  4072. const int numIns = term->getNumInputs();
  4073. for (i = 0; i < numIns; ++i)
  4074. {
  4075. Constant* const c = dynamic_cast<Constant*> (term->getInput (i));
  4076. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4077. return c;
  4078. }
  4079. for (i = 0; i < numIns; ++i)
  4080. {
  4081. Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4082. if (c != 0)
  4083. return c;
  4084. }
  4085. return 0;
  4086. }
  4087. static bool containsAnySymbols (const Term* const t)
  4088. {
  4089. if (t->getType() == Expression::symbolType)
  4090. return true;
  4091. for (int i = t->getNumInputs(); --i >= 0;)
  4092. if (containsAnySymbols (t->getInput (i)))
  4093. return true;
  4094. return false;
  4095. }
  4096. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4097. {
  4098. Symbol* const sym = dynamic_cast<Symbol*> (t);
  4099. if (sym != 0 && sym->mainSymbol == oldName)
  4100. {
  4101. sym->mainSymbol = newName;
  4102. return true;
  4103. }
  4104. bool anyChanged = false;
  4105. for (int i = t->getNumInputs(); --i >= 0;)
  4106. if (renameSymbol (t->getInput (i), oldName, newName))
  4107. anyChanged = true;
  4108. return anyChanged;
  4109. }
  4110. class Parser
  4111. {
  4112. public:
  4113. Parser (const String& stringToParse, int& textIndex_)
  4114. : textString (stringToParse), textIndex (textIndex_)
  4115. {
  4116. text = textString;
  4117. }
  4118. const TermPtr readExpression()
  4119. {
  4120. TermPtr lhs (readMultiplyOrDivideExpression());
  4121. char opType;
  4122. while (lhs != 0 && readOperator ("+-", &opType))
  4123. {
  4124. TermPtr rhs (readMultiplyOrDivideExpression());
  4125. if (rhs == 0)
  4126. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4127. if (opType == '+')
  4128. lhs = new Add (lhs, rhs);
  4129. else
  4130. lhs = new Subtract (lhs, rhs);
  4131. }
  4132. return lhs;
  4133. }
  4134. private:
  4135. const String textString;
  4136. const juce_wchar* text;
  4137. int& textIndex;
  4138. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4139. {
  4140. return c >= '0' && c <= '9';
  4141. }
  4142. void skipWhitespace (int& i) throw()
  4143. {
  4144. while (CharacterFunctions::isWhitespace (text [i]))
  4145. ++i;
  4146. }
  4147. bool readChar (const juce_wchar required) throw()
  4148. {
  4149. if (text[textIndex] == required)
  4150. {
  4151. ++textIndex;
  4152. return true;
  4153. }
  4154. return false;
  4155. }
  4156. bool readOperator (const char* ops, char* const opType = 0) throw()
  4157. {
  4158. skipWhitespace (textIndex);
  4159. while (*ops != 0)
  4160. {
  4161. if (readChar (*ops))
  4162. {
  4163. if (opType != 0)
  4164. *opType = *ops;
  4165. return true;
  4166. }
  4167. ++ops;
  4168. }
  4169. return false;
  4170. }
  4171. bool readIdentifier (String& identifier) throw()
  4172. {
  4173. skipWhitespace (textIndex);
  4174. int i = textIndex;
  4175. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4176. {
  4177. ++i;
  4178. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4179. ++i;
  4180. }
  4181. if (i > textIndex)
  4182. {
  4183. identifier = String (text + textIndex, i - textIndex);
  4184. textIndex = i;
  4185. return true;
  4186. }
  4187. return false;
  4188. }
  4189. Term* readNumber() throw()
  4190. {
  4191. skipWhitespace (textIndex);
  4192. int i = textIndex;
  4193. const bool isResolutionTarget = (text[i] == '@');
  4194. if (isResolutionTarget)
  4195. {
  4196. ++i;
  4197. skipWhitespace (i);
  4198. textIndex = i;
  4199. }
  4200. if (text[i] == '-')
  4201. {
  4202. ++i;
  4203. skipWhitespace (i);
  4204. }
  4205. int numDigits = 0;
  4206. while (isDecimalDigit (text[i]))
  4207. {
  4208. ++i;
  4209. ++numDigits;
  4210. }
  4211. const bool hasPoint = (text[i] == '.');
  4212. if (hasPoint)
  4213. {
  4214. ++i;
  4215. while (isDecimalDigit (text[i]))
  4216. {
  4217. ++i;
  4218. ++numDigits;
  4219. }
  4220. }
  4221. if (numDigits == 0)
  4222. return 0;
  4223. juce_wchar c = text[i];
  4224. const bool hasExponent = (c == 'e' || c == 'E');
  4225. if (hasExponent)
  4226. {
  4227. ++i;
  4228. c = text[i];
  4229. if (c == '+' || c == '-')
  4230. ++i;
  4231. int numExpDigits = 0;
  4232. while (isDecimalDigit (text[i]))
  4233. {
  4234. ++i;
  4235. ++numExpDigits;
  4236. }
  4237. if (numExpDigits == 0)
  4238. return 0;
  4239. }
  4240. const int start = textIndex;
  4241. textIndex = i;
  4242. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4243. }
  4244. const TermPtr readMultiplyOrDivideExpression()
  4245. {
  4246. TermPtr lhs (readUnaryExpression());
  4247. char opType;
  4248. while (lhs != 0 && readOperator ("*/", &opType))
  4249. {
  4250. TermPtr rhs (readUnaryExpression());
  4251. if (rhs == 0)
  4252. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4253. if (opType == '*')
  4254. lhs = new Multiply (lhs, rhs);
  4255. else
  4256. lhs = new Divide (lhs, rhs);
  4257. }
  4258. return lhs;
  4259. }
  4260. const TermPtr readUnaryExpression()
  4261. {
  4262. char opType;
  4263. if (readOperator ("+-", &opType))
  4264. {
  4265. TermPtr term (readUnaryExpression());
  4266. if (term == 0)
  4267. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4268. if (opType == '-')
  4269. term = term->negated();
  4270. return term;
  4271. }
  4272. return readPrimaryExpression();
  4273. }
  4274. const TermPtr readPrimaryExpression()
  4275. {
  4276. TermPtr e (readParenthesisedExpression());
  4277. if (e != 0)
  4278. return e;
  4279. e = readNumber();
  4280. if (e != 0)
  4281. return e;
  4282. String identifier;
  4283. if (readIdentifier (identifier))
  4284. {
  4285. if (readOperator ("(")) // method call...
  4286. {
  4287. Function* const f = new Function (identifier, ReferenceCountedArray<Term>());
  4288. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4289. TermPtr param (readExpression());
  4290. if (param == 0)
  4291. {
  4292. if (readOperator (")"))
  4293. return func.release();
  4294. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4295. }
  4296. f->parameters.add (param);
  4297. while (readOperator (","))
  4298. {
  4299. param = readExpression();
  4300. if (param == 0)
  4301. throw ParseError ("Expected expression after \",\"");
  4302. f->parameters.add (param);
  4303. }
  4304. if (readOperator (")"))
  4305. return func.release();
  4306. throw ParseError ("Expected \")\"");
  4307. }
  4308. else // just a symbol..
  4309. {
  4310. return new Symbol (identifier);
  4311. }
  4312. }
  4313. return 0;
  4314. }
  4315. const TermPtr readParenthesisedExpression()
  4316. {
  4317. if (! readOperator ("("))
  4318. return 0;
  4319. const TermPtr e (readExpression());
  4320. if (e == 0 || ! readOperator (")"))
  4321. return 0;
  4322. return e;
  4323. }
  4324. JUCE_DECLARE_NON_COPYABLE (Parser);
  4325. };
  4326. };
  4327. Expression::Expression()
  4328. : term (new Expression::Helpers::Constant (0, false))
  4329. {
  4330. }
  4331. Expression::~Expression()
  4332. {
  4333. }
  4334. Expression::Expression (Term* const term_)
  4335. : term (term_)
  4336. {
  4337. jassert (term != 0);
  4338. }
  4339. Expression::Expression (const double constant)
  4340. : term (new Expression::Helpers::Constant (constant, false))
  4341. {
  4342. }
  4343. Expression::Expression (const Expression& other)
  4344. : term (other.term)
  4345. {
  4346. }
  4347. Expression& Expression::operator= (const Expression& other)
  4348. {
  4349. term = other.term;
  4350. return *this;
  4351. }
  4352. Expression::Expression (const String& stringToParse)
  4353. {
  4354. int i = 0;
  4355. Helpers::Parser parser (stringToParse, i);
  4356. term = parser.readExpression();
  4357. if (term == 0)
  4358. term = new Helpers::Constant (0, false);
  4359. }
  4360. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4361. {
  4362. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4363. const Helpers::TermPtr term (parser.readExpression());
  4364. if (term != 0)
  4365. return Expression (term);
  4366. return Expression();
  4367. }
  4368. double Expression::evaluate() const
  4369. {
  4370. return evaluate (Expression::EvaluationContext());
  4371. }
  4372. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4373. {
  4374. return term->evaluate (context, 0);
  4375. }
  4376. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4377. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4378. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4379. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4380. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4381. const String Expression::toString() const
  4382. {
  4383. return term->toString();
  4384. }
  4385. const Expression Expression::symbol (const String& symbol)
  4386. {
  4387. return Expression (new Helpers::Symbol (symbol));
  4388. }
  4389. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4390. {
  4391. ReferenceCountedArray<Term> params;
  4392. for (int i = 0; i < parameters.size(); ++i)
  4393. params.add (parameters.getReference(i).term);
  4394. return Expression (new Helpers::Function (functionName, params));
  4395. }
  4396. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4397. const Expression::EvaluationContext& context) const
  4398. {
  4399. ScopedPointer<Term> newTerm (term->clone());
  4400. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4401. if (termToAdjust == 0)
  4402. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4403. if (termToAdjust == 0)
  4404. {
  4405. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4406. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4407. }
  4408. jassert (termToAdjust != 0);
  4409. const Term* const parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4410. if (parent == 0)
  4411. {
  4412. termToAdjust->value = targetValue;
  4413. }
  4414. else
  4415. {
  4416. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4417. if (reverseTerm == 0)
  4418. return Expression (targetValue);
  4419. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4420. }
  4421. return Expression (newTerm.release());
  4422. }
  4423. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4424. {
  4425. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4426. if (oldSymbol == newSymbol)
  4427. return *this;
  4428. Expression newExpression (term->clone());
  4429. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4430. return newExpression;
  4431. }
  4432. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4433. {
  4434. return term->referencesSymbol (symbol, context, 0);
  4435. }
  4436. bool Expression::usesAnySymbols() const
  4437. {
  4438. return Helpers::containsAnySymbols (term);
  4439. }
  4440. Expression::Type Expression::getType() const throw()
  4441. {
  4442. return term->getType();
  4443. }
  4444. const String Expression::getSymbol() const
  4445. {
  4446. String objectName, memberName;
  4447. term->getSymbolParts (objectName, memberName);
  4448. return Expression::Helpers::Symbol::joinParts (objectName, memberName);
  4449. }
  4450. void Expression::getSymbolParts (String& objectName, String& memberName) const
  4451. {
  4452. term->getSymbolParts (objectName, memberName);
  4453. }
  4454. const String Expression::getFunction() const
  4455. {
  4456. return term->getFunctionName();
  4457. }
  4458. const String Expression::getOperator() const
  4459. {
  4460. return term->getFunctionName();
  4461. }
  4462. int Expression::getNumInputs() const
  4463. {
  4464. return term->getNumInputs();
  4465. }
  4466. const Expression Expression::getInput (int index) const
  4467. {
  4468. return Expression (term->getInput (index));
  4469. }
  4470. int Expression::Term::getOperatorPrecedence() const
  4471. {
  4472. return 0;
  4473. }
  4474. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4475. {
  4476. return false;
  4477. }
  4478. int Expression::Term::getInputIndexFor (const Term*) const
  4479. {
  4480. return -1;
  4481. }
  4482. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4483. {
  4484. jassertfalse;
  4485. return 0;
  4486. }
  4487. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4488. {
  4489. return new Helpers::Negate (this);
  4490. }
  4491. void Expression::Term::getSymbolParts (String&, String&) const
  4492. {
  4493. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4494. }
  4495. const String Expression::Term::getFunctionName() const
  4496. {
  4497. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4498. return String::empty;
  4499. }
  4500. Expression::ParseError::ParseError (const String& message)
  4501. : description (message)
  4502. {
  4503. DBG ("Expression::ParseError: " + message);
  4504. }
  4505. Expression::EvaluationError::EvaluationError (const String& message)
  4506. : description (message)
  4507. {
  4508. DBG ("Expression::EvaluationError: " + description);
  4509. }
  4510. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4511. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4512. {
  4513. DBG ("Expression::EvaluationError: " + description);
  4514. }
  4515. Expression::EvaluationContext::EvaluationContext() {}
  4516. Expression::EvaluationContext::~EvaluationContext() {}
  4517. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4518. {
  4519. throw EvaluationError (symbol, member);
  4520. }
  4521. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4522. {
  4523. if (numParams > 0)
  4524. {
  4525. if (functionName == "min")
  4526. {
  4527. double v = parameters[0];
  4528. for (int i = 1; i < numParams; ++i)
  4529. v = jmin (v, parameters[i]);
  4530. return v;
  4531. }
  4532. else if (functionName == "max")
  4533. {
  4534. double v = parameters[0];
  4535. for (int i = 1; i < numParams; ++i)
  4536. v = jmax (v, parameters[i]);
  4537. return v;
  4538. }
  4539. else if (numParams == 1)
  4540. {
  4541. if (functionName == "sin") return sin (parameters[0]);
  4542. else if (functionName == "cos") return cos (parameters[0]);
  4543. else if (functionName == "tan") return tan (parameters[0]);
  4544. else if (functionName == "abs") return std::abs (parameters[0]);
  4545. }
  4546. }
  4547. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4548. }
  4549. END_JUCE_NAMESPACE
  4550. /*** End of inlined file: juce_Expression.cpp ***/
  4551. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4552. BEGIN_JUCE_NAMESPACE
  4553. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4554. {
  4555. jassert (keyData != 0);
  4556. jassert (keyBytes > 0);
  4557. static const uint32 initialPValues [18] =
  4558. {
  4559. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4560. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4561. 0x9216d5d9, 0x8979fb1b
  4562. };
  4563. static const uint32 initialSValues [4 * 256] =
  4564. {
  4565. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4566. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4567. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4568. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4569. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4570. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4571. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4572. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4573. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4574. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4575. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4576. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4577. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4578. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4579. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4580. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4581. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4582. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4583. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4584. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4585. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4586. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4587. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4588. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4589. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4590. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4591. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4592. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4593. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4594. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4595. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4596. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4597. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4598. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4599. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4600. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4601. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4602. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4603. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4604. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4605. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4606. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4607. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4608. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4609. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4610. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4611. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4612. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4613. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4614. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4615. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4616. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4617. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4618. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4619. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4620. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4621. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4622. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4623. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4624. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4625. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4626. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4627. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4628. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4629. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4630. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4631. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4632. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4633. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4634. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4635. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4636. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4637. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4638. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4639. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4640. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4641. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4642. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4643. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4644. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4645. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4646. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4647. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4648. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4649. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4650. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4651. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4652. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4653. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4654. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4655. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4656. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4657. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4658. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4659. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4660. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4661. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4662. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4663. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4664. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4665. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4666. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4667. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4668. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4669. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4670. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4671. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4672. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4673. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4674. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4675. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4676. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4677. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4678. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4679. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4680. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4681. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4682. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4683. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4684. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4685. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4686. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4687. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4688. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4689. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4690. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4691. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4692. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4693. };
  4694. memcpy (p, initialPValues, sizeof (p));
  4695. int i, j = 0;
  4696. for (i = 4; --i >= 0;)
  4697. {
  4698. s[i].malloc (256);
  4699. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4700. }
  4701. for (i = 0; i < 18; ++i)
  4702. {
  4703. uint32 d = 0;
  4704. for (int k = 0; k < 4; ++k)
  4705. {
  4706. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4707. if (++j >= keyBytes)
  4708. j = 0;
  4709. }
  4710. p[i] = initialPValues[i] ^ d;
  4711. }
  4712. uint32 l = 0, r = 0;
  4713. for (i = 0; i < 18; i += 2)
  4714. {
  4715. encrypt (l, r);
  4716. p[i] = l;
  4717. p[i + 1] = r;
  4718. }
  4719. for (i = 0; i < 4; ++i)
  4720. {
  4721. for (j = 0; j < 256; j += 2)
  4722. {
  4723. encrypt (l, r);
  4724. s[i][j] = l;
  4725. s[i][j + 1] = r;
  4726. }
  4727. }
  4728. }
  4729. BlowFish::BlowFish (const BlowFish& other)
  4730. {
  4731. for (int i = 4; --i >= 0;)
  4732. s[i].malloc (256);
  4733. operator= (other);
  4734. }
  4735. BlowFish& BlowFish::operator= (const BlowFish& other)
  4736. {
  4737. memcpy (p, other.p, sizeof (p));
  4738. for (int i = 4; --i >= 0;)
  4739. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4740. return *this;
  4741. }
  4742. BlowFish::~BlowFish()
  4743. {
  4744. }
  4745. uint32 BlowFish::F (const uint32 x) const throw()
  4746. {
  4747. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4748. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4749. }
  4750. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4751. {
  4752. uint32 l = data1;
  4753. uint32 r = data2;
  4754. for (int i = 0; i < 16; ++i)
  4755. {
  4756. l ^= p[i];
  4757. r ^= F(l);
  4758. swapVariables (l, r);
  4759. }
  4760. data1 = r ^ p[17];
  4761. data2 = l ^ p[16];
  4762. }
  4763. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4764. {
  4765. uint32 l = data1;
  4766. uint32 r = data2;
  4767. for (int i = 17; i > 1; --i)
  4768. {
  4769. l ^= p[i];
  4770. r ^= F(l);
  4771. swapVariables (l, r);
  4772. }
  4773. data1 = r ^ p[0];
  4774. data2 = l ^ p[1];
  4775. }
  4776. END_JUCE_NAMESPACE
  4777. /*** End of inlined file: juce_BlowFish.cpp ***/
  4778. /*** Start of inlined file: juce_MD5.cpp ***/
  4779. BEGIN_JUCE_NAMESPACE
  4780. MD5::MD5()
  4781. {
  4782. zerostruct (result);
  4783. }
  4784. MD5::MD5 (const MD5& other)
  4785. {
  4786. memcpy (result, other.result, sizeof (result));
  4787. }
  4788. MD5& MD5::operator= (const MD5& other)
  4789. {
  4790. memcpy (result, other.result, sizeof (result));
  4791. return *this;
  4792. }
  4793. MD5::MD5 (const MemoryBlock& data)
  4794. {
  4795. ProcessContext context;
  4796. context.processBlock (data.getData(), data.getSize());
  4797. context.finish (result);
  4798. }
  4799. MD5::MD5 (const void* data, const size_t numBytes)
  4800. {
  4801. ProcessContext context;
  4802. context.processBlock (data, numBytes);
  4803. context.finish (result);
  4804. }
  4805. MD5::MD5 (const String& text)
  4806. {
  4807. ProcessContext context;
  4808. const int len = text.length();
  4809. const juce_wchar* const t = text;
  4810. for (int i = 0; i < len; ++i)
  4811. {
  4812. // force the string into integer-sized unicode characters, to try to make it
  4813. // get the same results on all platforms + compilers.
  4814. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4815. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4816. }
  4817. context.finish (result);
  4818. }
  4819. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4820. {
  4821. ProcessContext context;
  4822. if (numBytesToRead < 0)
  4823. numBytesToRead = std::numeric_limits<int64>::max();
  4824. while (numBytesToRead > 0)
  4825. {
  4826. uint8 tempBuffer [512];
  4827. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4828. if (bytesRead <= 0)
  4829. break;
  4830. numBytesToRead -= bytesRead;
  4831. context.processBlock (tempBuffer, bytesRead);
  4832. }
  4833. context.finish (result);
  4834. }
  4835. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4836. {
  4837. processStream (input, numBytesToRead);
  4838. }
  4839. MD5::MD5 (const File& file)
  4840. {
  4841. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4842. if (fin != 0)
  4843. processStream (*fin, -1);
  4844. else
  4845. zerostruct (result);
  4846. }
  4847. MD5::~MD5()
  4848. {
  4849. }
  4850. namespace MD5Functions
  4851. {
  4852. void encode (void* const output, const void* const input, const int numBytes) throw()
  4853. {
  4854. for (int i = 0; i < (numBytes >> 2); ++i)
  4855. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4856. }
  4857. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4858. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4859. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4860. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4861. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4862. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4863. {
  4864. a += F (b, c, d) + x + ac;
  4865. a = rotateLeft (a, s) + b;
  4866. }
  4867. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4868. {
  4869. a += G (b, c, d) + x + ac;
  4870. a = rotateLeft (a, s) + b;
  4871. }
  4872. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4873. {
  4874. a += H (b, c, d) + x + ac;
  4875. a = rotateLeft (a, s) + b;
  4876. }
  4877. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4878. {
  4879. a += I (b, c, d) + x + ac;
  4880. a = rotateLeft (a, s) + b;
  4881. }
  4882. }
  4883. MD5::ProcessContext::ProcessContext()
  4884. {
  4885. state[0] = 0x67452301;
  4886. state[1] = 0xefcdab89;
  4887. state[2] = 0x98badcfe;
  4888. state[3] = 0x10325476;
  4889. count[0] = 0;
  4890. count[1] = 0;
  4891. }
  4892. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4893. {
  4894. int bufferPos = ((count[0] >> 3) & 0x3F);
  4895. count[0] += (uint32) (dataSize << 3);
  4896. if (count[0] < ((uint32) dataSize << 3))
  4897. count[1]++;
  4898. count[1] += (uint32) (dataSize >> 29);
  4899. const size_t spaceLeft = 64 - bufferPos;
  4900. size_t i = 0;
  4901. if (dataSize >= spaceLeft)
  4902. {
  4903. memcpy (buffer + bufferPos, data, spaceLeft);
  4904. transform (buffer);
  4905. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4906. transform (static_cast <const char*> (data) + i);
  4907. bufferPos = 0;
  4908. }
  4909. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4910. }
  4911. void MD5::ProcessContext::finish (void* const result)
  4912. {
  4913. unsigned char encodedLength[8];
  4914. MD5Functions::encode (encodedLength, count, 8);
  4915. // Pad out to 56 mod 64.
  4916. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4917. const int paddingLength = (index < 56) ? (56 - index)
  4918. : (120 - index);
  4919. uint8 paddingBuffer [64];
  4920. zeromem (paddingBuffer, paddingLength);
  4921. paddingBuffer [0] = 0x80;
  4922. processBlock (paddingBuffer, paddingLength);
  4923. processBlock (encodedLength, 8);
  4924. MD5Functions::encode (result, state, 16);
  4925. zerostruct (buffer);
  4926. }
  4927. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4928. {
  4929. using namespace MD5Functions;
  4930. uint32 a = state[0];
  4931. uint32 b = state[1];
  4932. uint32 c = state[2];
  4933. uint32 d = state[3];
  4934. uint32 x[16];
  4935. encode (x, bufferToTransform, 64);
  4936. enum Constants
  4937. {
  4938. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4939. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4940. };
  4941. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4942. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4943. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4944. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4945. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4946. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4947. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4948. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4949. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4950. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4951. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4952. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4953. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4954. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4955. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4956. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4957. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4958. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4959. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4960. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4961. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4962. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4963. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4964. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4965. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4966. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4967. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4968. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4969. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4970. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4971. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4972. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4973. state[0] += a;
  4974. state[1] += b;
  4975. state[2] += c;
  4976. state[3] += d;
  4977. zerostruct (x);
  4978. }
  4979. const MemoryBlock MD5::getRawChecksumData() const
  4980. {
  4981. return MemoryBlock (result, sizeof (result));
  4982. }
  4983. const String MD5::toHexString() const
  4984. {
  4985. return String::toHexString (result, sizeof (result), 0);
  4986. }
  4987. bool MD5::operator== (const MD5& other) const
  4988. {
  4989. return memcmp (result, other.result, sizeof (result)) == 0;
  4990. }
  4991. bool MD5::operator!= (const MD5& other) const
  4992. {
  4993. return ! operator== (other);
  4994. }
  4995. END_JUCE_NAMESPACE
  4996. /*** End of inlined file: juce_MD5.cpp ***/
  4997. /*** Start of inlined file: juce_Primes.cpp ***/
  4998. BEGIN_JUCE_NAMESPACE
  4999. namespace PrimesHelpers
  5000. {
  5001. void createSmallSieve (const int numBits, BigInteger& result)
  5002. {
  5003. result.setBit (numBits);
  5004. result.clearBit (numBits); // to enlarge the array
  5005. result.setBit (0);
  5006. int n = 2;
  5007. do
  5008. {
  5009. for (int i = n + n; i < numBits; i += n)
  5010. result.setBit (i);
  5011. n = result.findNextClearBit (n + 1);
  5012. }
  5013. while (n <= (numBits >> 1));
  5014. }
  5015. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5016. const BigInteger& smallSieve, const int smallSieveSize)
  5017. {
  5018. jassert (! base[0]); // must be even!
  5019. result.setBit (numBits);
  5020. result.clearBit (numBits); // to enlarge the array
  5021. int index = smallSieve.findNextClearBit (0);
  5022. do
  5023. {
  5024. const int prime = (index << 1) + 1;
  5025. BigInteger r (base), remainder;
  5026. r.divideBy (prime, remainder);
  5027. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5028. if (r.isZero())
  5029. i += prime;
  5030. if ((i & 1) == 0)
  5031. i += prime;
  5032. i = (i - 1) >> 1;
  5033. while (i < numBits)
  5034. {
  5035. result.setBit (i);
  5036. i += prime;
  5037. }
  5038. index = smallSieve.findNextClearBit (index + 1);
  5039. }
  5040. while (index < smallSieveSize);
  5041. }
  5042. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5043. const int numBits, BigInteger& result, const int certainty)
  5044. {
  5045. for (int i = 0; i < numBits; ++i)
  5046. {
  5047. if (! sieve[i])
  5048. {
  5049. result = base + (unsigned int) ((i << 1) + 1);
  5050. if (Primes::isProbablyPrime (result, certainty))
  5051. return true;
  5052. }
  5053. }
  5054. return false;
  5055. }
  5056. bool passesMillerRabin (const BigInteger& n, int iterations)
  5057. {
  5058. const BigInteger one (1), two (2);
  5059. const BigInteger nMinusOne (n - one);
  5060. BigInteger d (nMinusOne);
  5061. const int s = d.findNextSetBit (0);
  5062. d >>= s;
  5063. BigInteger smallPrimes;
  5064. int numBitsInSmallPrimes = 0;
  5065. for (;;)
  5066. {
  5067. numBitsInSmallPrimes += 256;
  5068. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5069. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5070. if (numPrimesFound > iterations + 1)
  5071. break;
  5072. }
  5073. int smallPrime = 2;
  5074. while (--iterations >= 0)
  5075. {
  5076. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5077. BigInteger r (smallPrime);
  5078. r.exponentModulo (d, n);
  5079. if (r != one && r != nMinusOne)
  5080. {
  5081. for (int j = 0; j < s; ++j)
  5082. {
  5083. r.exponentModulo (two, n);
  5084. if (r == nMinusOne)
  5085. break;
  5086. }
  5087. if (r != nMinusOne)
  5088. return false;
  5089. }
  5090. }
  5091. return true;
  5092. }
  5093. }
  5094. const BigInteger Primes::createProbablePrime (const int bitLength,
  5095. const int certainty,
  5096. const int* randomSeeds,
  5097. int numRandomSeeds)
  5098. {
  5099. using namespace PrimesHelpers;
  5100. int defaultSeeds [16];
  5101. if (numRandomSeeds <= 0)
  5102. {
  5103. randomSeeds = defaultSeeds;
  5104. numRandomSeeds = numElementsInArray (defaultSeeds);
  5105. Random r (0);
  5106. for (int j = 10; --j >= 0;)
  5107. {
  5108. r.setSeedRandomly();
  5109. for (int i = numRandomSeeds; --i >= 0;)
  5110. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5111. }
  5112. }
  5113. BigInteger smallSieve;
  5114. const int smallSieveSize = 15000;
  5115. createSmallSieve (smallSieveSize, smallSieve);
  5116. BigInteger p;
  5117. for (int i = numRandomSeeds; --i >= 0;)
  5118. {
  5119. BigInteger p2;
  5120. Random r (randomSeeds[i]);
  5121. r.fillBitsRandomly (p2, 0, bitLength);
  5122. p ^= p2;
  5123. }
  5124. p.setBit (bitLength - 1);
  5125. p.clearBit (0);
  5126. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5127. while (p.getHighestBit() < bitLength)
  5128. {
  5129. p += 2 * searchLen;
  5130. BigInteger sieve;
  5131. bigSieve (p, searchLen, sieve,
  5132. smallSieve, smallSieveSize);
  5133. BigInteger candidate;
  5134. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5135. return candidate;
  5136. }
  5137. jassertfalse;
  5138. return BigInteger();
  5139. }
  5140. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5141. {
  5142. using namespace PrimesHelpers;
  5143. if (! number[0])
  5144. return false;
  5145. if (number.getHighestBit() <= 10)
  5146. {
  5147. const int num = number.getBitRangeAsInt (0, 10);
  5148. for (int i = num / 2; --i > 1;)
  5149. if (num % i == 0)
  5150. return false;
  5151. return true;
  5152. }
  5153. else
  5154. {
  5155. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5156. return false;
  5157. return passesMillerRabin (number, certainty);
  5158. }
  5159. }
  5160. END_JUCE_NAMESPACE
  5161. /*** End of inlined file: juce_Primes.cpp ***/
  5162. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5163. BEGIN_JUCE_NAMESPACE
  5164. RSAKey::RSAKey()
  5165. {
  5166. }
  5167. RSAKey::RSAKey (const String& s)
  5168. {
  5169. if (s.containsChar (','))
  5170. {
  5171. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5172. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5173. }
  5174. else
  5175. {
  5176. // the string needs to be two hex numbers, comma-separated..
  5177. jassertfalse;
  5178. }
  5179. }
  5180. RSAKey::~RSAKey()
  5181. {
  5182. }
  5183. bool RSAKey::operator== (const RSAKey& other) const throw()
  5184. {
  5185. return part1 == other.part1 && part2 == other.part2;
  5186. }
  5187. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5188. {
  5189. return ! operator== (other);
  5190. }
  5191. const String RSAKey::toString() const
  5192. {
  5193. return part1.toString (16) + "," + part2.toString (16);
  5194. }
  5195. bool RSAKey::applyToValue (BigInteger& value) const
  5196. {
  5197. if (part1.isZero() || part2.isZero() || value <= 0)
  5198. {
  5199. jassertfalse; // using an uninitialised key
  5200. value.clear();
  5201. return false;
  5202. }
  5203. BigInteger result;
  5204. while (! value.isZero())
  5205. {
  5206. result *= part2;
  5207. BigInteger remainder;
  5208. value.divideBy (part2, remainder);
  5209. remainder.exponentModulo (part1, part2);
  5210. result += remainder;
  5211. }
  5212. value.swapWith (result);
  5213. return true;
  5214. }
  5215. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5216. {
  5217. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5218. // are fast to divide + multiply
  5219. for (int i = 2; i <= 65536; i *= 2)
  5220. {
  5221. const BigInteger e (1 + i);
  5222. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5223. return e;
  5224. }
  5225. BigInteger e (4);
  5226. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5227. ++e;
  5228. return e;
  5229. }
  5230. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5231. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5232. {
  5233. jassert (numBits > 16); // not much point using less than this..
  5234. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5235. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5236. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5237. const BigInteger n (p * q);
  5238. const BigInteger m (--p * --q);
  5239. const BigInteger e (findBestCommonDivisor (p, q));
  5240. BigInteger d (e);
  5241. d.inverseModulo (m);
  5242. publicKey.part1 = e;
  5243. publicKey.part2 = n;
  5244. privateKey.part1 = d;
  5245. privateKey.part2 = n;
  5246. }
  5247. END_JUCE_NAMESPACE
  5248. /*** End of inlined file: juce_RSAKey.cpp ***/
  5249. /*** Start of inlined file: juce_InputStream.cpp ***/
  5250. BEGIN_JUCE_NAMESPACE
  5251. char InputStream::readByte()
  5252. {
  5253. char temp = 0;
  5254. read (&temp, 1);
  5255. return temp;
  5256. }
  5257. bool InputStream::readBool()
  5258. {
  5259. return readByte() != 0;
  5260. }
  5261. short InputStream::readShort()
  5262. {
  5263. char temp[2];
  5264. if (read (temp, 2) == 2)
  5265. return (short) ByteOrder::littleEndianShort (temp);
  5266. return 0;
  5267. }
  5268. short InputStream::readShortBigEndian()
  5269. {
  5270. char temp[2];
  5271. if (read (temp, 2) == 2)
  5272. return (short) ByteOrder::bigEndianShort (temp);
  5273. return 0;
  5274. }
  5275. int InputStream::readInt()
  5276. {
  5277. char temp[4];
  5278. if (read (temp, 4) == 4)
  5279. return (int) ByteOrder::littleEndianInt (temp);
  5280. return 0;
  5281. }
  5282. int InputStream::readIntBigEndian()
  5283. {
  5284. char temp[4];
  5285. if (read (temp, 4) == 4)
  5286. return (int) ByteOrder::bigEndianInt (temp);
  5287. return 0;
  5288. }
  5289. int InputStream::readCompressedInt()
  5290. {
  5291. const unsigned char sizeByte = readByte();
  5292. if (sizeByte == 0)
  5293. return 0;
  5294. const int numBytes = (sizeByte & 0x7f);
  5295. if (numBytes > 4)
  5296. {
  5297. jassertfalse; // trying to read corrupt data - this method must only be used
  5298. // to read data that was written by OutputStream::writeCompressedInt()
  5299. return 0;
  5300. }
  5301. char bytes[4] = { 0, 0, 0, 0 };
  5302. if (read (bytes, numBytes) != numBytes)
  5303. return 0;
  5304. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5305. return (sizeByte >> 7) ? -num : num;
  5306. }
  5307. int64 InputStream::readInt64()
  5308. {
  5309. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5310. if (read (n.asBytes, 8) == 8)
  5311. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5312. return 0;
  5313. }
  5314. int64 InputStream::readInt64BigEndian()
  5315. {
  5316. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5317. if (read (n.asBytes, 8) == 8)
  5318. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5319. return 0;
  5320. }
  5321. float InputStream::readFloat()
  5322. {
  5323. // the union below relies on these types being the same size...
  5324. static_jassert (sizeof (int32) == sizeof (float));
  5325. union { int32 asInt; float asFloat; } n;
  5326. n.asInt = (int32) readInt();
  5327. return n.asFloat;
  5328. }
  5329. float InputStream::readFloatBigEndian()
  5330. {
  5331. union { int32 asInt; float asFloat; } n;
  5332. n.asInt = (int32) readIntBigEndian();
  5333. return n.asFloat;
  5334. }
  5335. double InputStream::readDouble()
  5336. {
  5337. union { int64 asInt; double asDouble; } n;
  5338. n.asInt = readInt64();
  5339. return n.asDouble;
  5340. }
  5341. double InputStream::readDoubleBigEndian()
  5342. {
  5343. union { int64 asInt; double asDouble; } n;
  5344. n.asInt = readInt64BigEndian();
  5345. return n.asDouble;
  5346. }
  5347. const String InputStream::readString()
  5348. {
  5349. MemoryBlock buffer (256);
  5350. char* data = static_cast<char*> (buffer.getData());
  5351. size_t i = 0;
  5352. while ((data[i] = readByte()) != 0)
  5353. {
  5354. if (++i >= buffer.getSize())
  5355. {
  5356. buffer.setSize (buffer.getSize() + 512);
  5357. data = static_cast<char*> (buffer.getData());
  5358. }
  5359. }
  5360. return String::fromUTF8 (data, (int) i);
  5361. }
  5362. const String InputStream::readNextLine()
  5363. {
  5364. MemoryBlock buffer (256);
  5365. char* data = static_cast<char*> (buffer.getData());
  5366. size_t i = 0;
  5367. while ((data[i] = readByte()) != 0)
  5368. {
  5369. if (data[i] == '\n')
  5370. break;
  5371. if (data[i] == '\r')
  5372. {
  5373. const int64 lastPos = getPosition();
  5374. if (readByte() != '\n')
  5375. setPosition (lastPos);
  5376. break;
  5377. }
  5378. if (++i >= buffer.getSize())
  5379. {
  5380. buffer.setSize (buffer.getSize() + 512);
  5381. data = static_cast<char*> (buffer.getData());
  5382. }
  5383. }
  5384. return String::fromUTF8 (data, (int) i);
  5385. }
  5386. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5387. {
  5388. MemoryOutputStream mo (block, true);
  5389. return mo.writeFromInputStream (*this, numBytes);
  5390. }
  5391. const String InputStream::readEntireStreamAsString()
  5392. {
  5393. MemoryOutputStream mo;
  5394. mo.writeFromInputStream (*this, -1);
  5395. return mo.toString();
  5396. }
  5397. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5398. {
  5399. if (numBytesToSkip > 0)
  5400. {
  5401. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5402. HeapBlock<char> temp (skipBufferSize);
  5403. while (numBytesToSkip > 0 && ! isExhausted())
  5404. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5405. }
  5406. }
  5407. END_JUCE_NAMESPACE
  5408. /*** End of inlined file: juce_InputStream.cpp ***/
  5409. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5410. BEGIN_JUCE_NAMESPACE
  5411. #if JUCE_DEBUG
  5412. static Array<void*, CriticalSection> activeStreams;
  5413. void juce_CheckForDanglingStreams()
  5414. {
  5415. /*
  5416. It's always a bad idea to leak any object, but if you're leaking output
  5417. streams, then there's a good chance that you're failing to flush a file
  5418. to disk properly, which could result in corrupted data and other similar
  5419. nastiness..
  5420. */
  5421. jassert (activeStreams.size() == 0);
  5422. };
  5423. #endif
  5424. OutputStream::OutputStream()
  5425. : newLineString (NewLine::getDefault())
  5426. {
  5427. #if JUCE_DEBUG
  5428. activeStreams.add (this);
  5429. #endif
  5430. }
  5431. OutputStream::~OutputStream()
  5432. {
  5433. #if JUCE_DEBUG
  5434. activeStreams.removeValue (this);
  5435. #endif
  5436. }
  5437. void OutputStream::writeBool (const bool b)
  5438. {
  5439. writeByte (b ? (char) 1
  5440. : (char) 0);
  5441. }
  5442. void OutputStream::writeByte (char byte)
  5443. {
  5444. write (&byte, 1);
  5445. }
  5446. void OutputStream::writeShort (short value)
  5447. {
  5448. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5449. write (&v, 2);
  5450. }
  5451. void OutputStream::writeShortBigEndian (short value)
  5452. {
  5453. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5454. write (&v, 2);
  5455. }
  5456. void OutputStream::writeInt (int value)
  5457. {
  5458. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5459. write (&v, 4);
  5460. }
  5461. void OutputStream::writeIntBigEndian (int value)
  5462. {
  5463. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5464. write (&v, 4);
  5465. }
  5466. void OutputStream::writeCompressedInt (int value)
  5467. {
  5468. unsigned int un = (value < 0) ? (unsigned int) -value
  5469. : (unsigned int) value;
  5470. uint8 data[5];
  5471. int num = 0;
  5472. while (un > 0)
  5473. {
  5474. data[++num] = (uint8) un;
  5475. un >>= 8;
  5476. }
  5477. data[0] = (uint8) num;
  5478. if (value < 0)
  5479. data[0] |= 0x80;
  5480. write (data, num + 1);
  5481. }
  5482. void OutputStream::writeInt64 (int64 value)
  5483. {
  5484. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5485. write (&v, 8);
  5486. }
  5487. void OutputStream::writeInt64BigEndian (int64 value)
  5488. {
  5489. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5490. write (&v, 8);
  5491. }
  5492. void OutputStream::writeFloat (float value)
  5493. {
  5494. union { int asInt; float asFloat; } n;
  5495. n.asFloat = value;
  5496. writeInt (n.asInt);
  5497. }
  5498. void OutputStream::writeFloatBigEndian (float value)
  5499. {
  5500. union { int asInt; float asFloat; } n;
  5501. n.asFloat = value;
  5502. writeIntBigEndian (n.asInt);
  5503. }
  5504. void OutputStream::writeDouble (double value)
  5505. {
  5506. union { int64 asInt; double asDouble; } n;
  5507. n.asDouble = value;
  5508. writeInt64 (n.asInt);
  5509. }
  5510. void OutputStream::writeDoubleBigEndian (double value)
  5511. {
  5512. union { int64 asInt; double asDouble; } n;
  5513. n.asDouble = value;
  5514. writeInt64BigEndian (n.asInt);
  5515. }
  5516. void OutputStream::writeString (const String& text)
  5517. {
  5518. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5519. // if lots of large, persistent strings were to be written to streams).
  5520. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5521. HeapBlock<char> temp (numBytes);
  5522. text.copyToUTF8 (temp, numBytes);
  5523. write (temp, numBytes);
  5524. }
  5525. void OutputStream::writeText (const String& text, const bool asUnicode,
  5526. const bool writeUnicodeHeaderBytes)
  5527. {
  5528. if (asUnicode)
  5529. {
  5530. if (writeUnicodeHeaderBytes)
  5531. write ("\x0ff\x0fe", 2);
  5532. const juce_wchar* src = text;
  5533. bool lastCharWasReturn = false;
  5534. while (*src != 0)
  5535. {
  5536. if (*src == L'\n' && ! lastCharWasReturn)
  5537. writeShort ((short) L'\r');
  5538. lastCharWasReturn = (*src == L'\r');
  5539. writeShort ((short) *src++);
  5540. }
  5541. }
  5542. else
  5543. {
  5544. const char* src = text.toUTF8();
  5545. const char* t = src;
  5546. for (;;)
  5547. {
  5548. if (*t == '\n')
  5549. {
  5550. if (t > src)
  5551. write (src, (int) (t - src));
  5552. write ("\r\n", 2);
  5553. src = t + 1;
  5554. }
  5555. else if (*t == '\r')
  5556. {
  5557. if (t[1] == '\n')
  5558. ++t;
  5559. }
  5560. else if (*t == 0)
  5561. {
  5562. if (t > src)
  5563. write (src, (int) (t - src));
  5564. break;
  5565. }
  5566. ++t;
  5567. }
  5568. }
  5569. }
  5570. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5571. {
  5572. if (numBytesToWrite < 0)
  5573. numBytesToWrite = std::numeric_limits<int64>::max();
  5574. int numWritten = 0;
  5575. while (numBytesToWrite > 0 && ! source.isExhausted())
  5576. {
  5577. char buffer [8192];
  5578. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5579. if (num <= 0)
  5580. break;
  5581. write (buffer, num);
  5582. numBytesToWrite -= num;
  5583. numWritten += num;
  5584. }
  5585. return numWritten;
  5586. }
  5587. void OutputStream::setNewLineString (const String& newLineString_)
  5588. {
  5589. newLineString = newLineString_;
  5590. }
  5591. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5592. {
  5593. return stream << String (number);
  5594. }
  5595. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5596. {
  5597. return stream << String (number);
  5598. }
  5599. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5600. {
  5601. stream.writeByte (character);
  5602. return stream;
  5603. }
  5604. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5605. {
  5606. stream.write (text, (int) strlen (text));
  5607. return stream;
  5608. }
  5609. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5610. {
  5611. stream.write (data.getData(), (int) data.getSize());
  5612. return stream;
  5613. }
  5614. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5615. {
  5616. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5617. if (in != 0)
  5618. stream.writeFromInputStream (*in, -1);
  5619. return stream;
  5620. }
  5621. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&)
  5622. {
  5623. return stream << stream.getNewLineString();
  5624. }
  5625. END_JUCE_NAMESPACE
  5626. /*** End of inlined file: juce_OutputStream.cpp ***/
  5627. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5628. BEGIN_JUCE_NAMESPACE
  5629. DirectoryIterator::DirectoryIterator (const File& directory,
  5630. bool isRecursive_,
  5631. const String& wildCard_,
  5632. const int whatToLookFor_)
  5633. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5634. wildCard (wildCard_),
  5635. path (File::addTrailingSeparator (directory.getFullPathName())),
  5636. index (-1),
  5637. totalNumFiles (-1),
  5638. whatToLookFor (whatToLookFor_),
  5639. isRecursive (isRecursive_),
  5640. hasBeenAdvanced (false)
  5641. {
  5642. // you have to specify the type of files you're looking for!
  5643. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5644. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5645. }
  5646. DirectoryIterator::~DirectoryIterator()
  5647. {
  5648. }
  5649. bool DirectoryIterator::next()
  5650. {
  5651. return next (0, 0, 0, 0, 0, 0);
  5652. }
  5653. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5654. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5655. {
  5656. hasBeenAdvanced = true;
  5657. if (subIterator != 0)
  5658. {
  5659. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5660. return true;
  5661. subIterator = 0;
  5662. }
  5663. String filename;
  5664. bool isDirectory, isHidden;
  5665. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5666. {
  5667. ++index;
  5668. if (! filename.containsOnly ("."))
  5669. {
  5670. const File fileFound (path + filename, 0);
  5671. bool matches = false;
  5672. if (isDirectory)
  5673. {
  5674. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5675. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5676. matches = (whatToLookFor & File::findDirectories) != 0;
  5677. }
  5678. else
  5679. {
  5680. matches = (whatToLookFor & File::findFiles) != 0;
  5681. }
  5682. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5683. if (matches && isRecursive)
  5684. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5685. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5686. matches = ! isHidden;
  5687. if (matches)
  5688. {
  5689. currentFile = fileFound;
  5690. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5691. if (isDirResult != 0) *isDirResult = isDirectory;
  5692. return true;
  5693. }
  5694. else if (subIterator != 0)
  5695. {
  5696. return next();
  5697. }
  5698. }
  5699. }
  5700. return false;
  5701. }
  5702. const File DirectoryIterator::getFile() const
  5703. {
  5704. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5705. return subIterator->getFile();
  5706. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5707. jassert (hasBeenAdvanced);
  5708. return currentFile;
  5709. }
  5710. float DirectoryIterator::getEstimatedProgress() const
  5711. {
  5712. if (totalNumFiles < 0)
  5713. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5714. if (totalNumFiles <= 0)
  5715. return 0.0f;
  5716. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5717. : (float) index;
  5718. return detailedIndex / totalNumFiles;
  5719. }
  5720. END_JUCE_NAMESPACE
  5721. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5722. /*** Start of inlined file: juce_File.cpp ***/
  5723. #if ! JUCE_WINDOWS
  5724. #include <pwd.h>
  5725. #endif
  5726. BEGIN_JUCE_NAMESPACE
  5727. File::File (const String& fullPathName)
  5728. : fullPath (parseAbsolutePath (fullPathName))
  5729. {
  5730. }
  5731. File::File (const String& path, int)
  5732. : fullPath (path)
  5733. {
  5734. }
  5735. const File File::createFileWithoutCheckingPath (const String& path)
  5736. {
  5737. return File (path, 0);
  5738. }
  5739. File::File (const File& other)
  5740. : fullPath (other.fullPath)
  5741. {
  5742. }
  5743. File& File::operator= (const String& newPath)
  5744. {
  5745. fullPath = parseAbsolutePath (newPath);
  5746. return *this;
  5747. }
  5748. File& File::operator= (const File& other)
  5749. {
  5750. fullPath = other.fullPath;
  5751. return *this;
  5752. }
  5753. const File File::nonexistent;
  5754. const String File::parseAbsolutePath (const String& p)
  5755. {
  5756. if (p.isEmpty())
  5757. return String::empty;
  5758. #if JUCE_WINDOWS
  5759. // Windows..
  5760. String path (p.replaceCharacter ('/', '\\'));
  5761. if (path.startsWithChar (File::separator))
  5762. {
  5763. if (path[1] != File::separator)
  5764. {
  5765. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5766. If you're trying to parse a string that may be either a relative path or an absolute path,
  5767. you MUST provide a context against which the partial path can be evaluated - you can do
  5768. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5769. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5770. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5771. */
  5772. jassertfalse;
  5773. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5774. }
  5775. }
  5776. else if (! path.containsChar (':'))
  5777. {
  5778. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5779. If you're trying to parse a string that may be either a relative path or an absolute path,
  5780. you MUST provide a context against which the partial path can be evaluated - you can do
  5781. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5782. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5783. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5784. */
  5785. jassertfalse;
  5786. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5787. }
  5788. #else
  5789. // Mac or Linux..
  5790. String path (p.replaceCharacter ('\\', '/'));
  5791. if (path.startsWithChar ('~'))
  5792. {
  5793. if (path[1] == File::separator || path[1] == 0)
  5794. {
  5795. // expand a name of the form "~/abc"
  5796. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5797. + path.substring (1);
  5798. }
  5799. else
  5800. {
  5801. // expand a name of type "~dave/abc"
  5802. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5803. struct passwd* const pw = getpwnam (userName.toUTF8());
  5804. if (pw != 0)
  5805. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5806. }
  5807. }
  5808. else if (! path.startsWithChar (File::separator))
  5809. {
  5810. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5811. If you're trying to parse a string that may be either a relative path or an absolute path,
  5812. you MUST provide a context against which the partial path can be evaluated - you can do
  5813. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5814. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5815. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5816. */
  5817. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5818. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5819. }
  5820. #endif
  5821. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5822. path = path.dropLastCharacters (1);
  5823. return path;
  5824. }
  5825. const String File::addTrailingSeparator (const String& path)
  5826. {
  5827. return path.endsWithChar (File::separator) ? path
  5828. : path + File::separator;
  5829. }
  5830. #if JUCE_LINUX
  5831. #define NAMES_ARE_CASE_SENSITIVE 1
  5832. #endif
  5833. bool File::areFileNamesCaseSensitive()
  5834. {
  5835. #if NAMES_ARE_CASE_SENSITIVE
  5836. return true;
  5837. #else
  5838. return false;
  5839. #endif
  5840. }
  5841. bool File::operator== (const File& other) const
  5842. {
  5843. #if NAMES_ARE_CASE_SENSITIVE
  5844. return fullPath == other.fullPath;
  5845. #else
  5846. return fullPath.equalsIgnoreCase (other.fullPath);
  5847. #endif
  5848. }
  5849. bool File::operator!= (const File& other) const
  5850. {
  5851. return ! operator== (other);
  5852. }
  5853. bool File::operator< (const File& other) const
  5854. {
  5855. #if NAMES_ARE_CASE_SENSITIVE
  5856. return fullPath < other.fullPath;
  5857. #else
  5858. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5859. #endif
  5860. }
  5861. bool File::operator> (const File& other) const
  5862. {
  5863. #if NAMES_ARE_CASE_SENSITIVE
  5864. return fullPath > other.fullPath;
  5865. #else
  5866. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5867. #endif
  5868. }
  5869. bool File::setReadOnly (const bool shouldBeReadOnly,
  5870. const bool applyRecursively) const
  5871. {
  5872. bool worked = true;
  5873. if (applyRecursively && isDirectory())
  5874. {
  5875. Array <File> subFiles;
  5876. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5877. for (int i = subFiles.size(); --i >= 0;)
  5878. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5879. }
  5880. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5881. }
  5882. bool File::deleteRecursively() const
  5883. {
  5884. bool worked = true;
  5885. if (isDirectory())
  5886. {
  5887. Array<File> subFiles;
  5888. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5889. for (int i = subFiles.size(); --i >= 0;)
  5890. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5891. }
  5892. return deleteFile() && worked;
  5893. }
  5894. bool File::moveFileTo (const File& newFile) const
  5895. {
  5896. if (newFile.fullPath == fullPath)
  5897. return true;
  5898. #if ! NAMES_ARE_CASE_SENSITIVE
  5899. if (*this != newFile)
  5900. #endif
  5901. if (! newFile.deleteFile())
  5902. return false;
  5903. return moveInternal (newFile);
  5904. }
  5905. bool File::copyFileTo (const File& newFile) const
  5906. {
  5907. return (*this == newFile)
  5908. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5909. }
  5910. bool File::copyDirectoryTo (const File& newDirectory) const
  5911. {
  5912. if (isDirectory() && newDirectory.createDirectory())
  5913. {
  5914. Array<File> subFiles;
  5915. findChildFiles (subFiles, File::findFiles, false);
  5916. int i;
  5917. for (i = 0; i < subFiles.size(); ++i)
  5918. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5919. return false;
  5920. subFiles.clear();
  5921. findChildFiles (subFiles, File::findDirectories, false);
  5922. for (i = 0; i < subFiles.size(); ++i)
  5923. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5924. return false;
  5925. return true;
  5926. }
  5927. return false;
  5928. }
  5929. const String File::getPathUpToLastSlash() const
  5930. {
  5931. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5932. if (lastSlash > 0)
  5933. return fullPath.substring (0, lastSlash);
  5934. else if (lastSlash == 0)
  5935. return separatorString;
  5936. else
  5937. return fullPath;
  5938. }
  5939. const File File::getParentDirectory() const
  5940. {
  5941. return File (getPathUpToLastSlash(), (int) 0);
  5942. }
  5943. const String File::getFileName() const
  5944. {
  5945. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5946. }
  5947. int File::hashCode() const
  5948. {
  5949. return fullPath.hashCode();
  5950. }
  5951. int64 File::hashCode64() const
  5952. {
  5953. return fullPath.hashCode64();
  5954. }
  5955. const String File::getFileNameWithoutExtension() const
  5956. {
  5957. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5958. const int lastDot = fullPath.lastIndexOfChar ('.');
  5959. if (lastDot > lastSlash)
  5960. return fullPath.substring (lastSlash, lastDot);
  5961. else
  5962. return fullPath.substring (lastSlash);
  5963. }
  5964. bool File::isAChildOf (const File& potentialParent) const
  5965. {
  5966. if (potentialParent == File::nonexistent)
  5967. return false;
  5968. const String ourPath (getPathUpToLastSlash());
  5969. #if NAMES_ARE_CASE_SENSITIVE
  5970. if (potentialParent.fullPath == ourPath)
  5971. #else
  5972. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5973. #endif
  5974. {
  5975. return true;
  5976. }
  5977. else if (potentialParent.fullPath.length() >= ourPath.length())
  5978. {
  5979. return false;
  5980. }
  5981. else
  5982. {
  5983. return getParentDirectory().isAChildOf (potentialParent);
  5984. }
  5985. }
  5986. bool File::isAbsolutePath (const String& path)
  5987. {
  5988. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5989. #if JUCE_WINDOWS
  5990. || (path.isNotEmpty() && path[1] == ':');
  5991. #else
  5992. || path.startsWithChar ('~');
  5993. #endif
  5994. }
  5995. const File File::getChildFile (String relativePath) const
  5996. {
  5997. if (isAbsolutePath (relativePath))
  5998. {
  5999. // the path is really absolute..
  6000. return File (relativePath);
  6001. }
  6002. else
  6003. {
  6004. // it's relative, so remove any ../ or ./ bits at the start.
  6005. String path (fullPath);
  6006. if (relativePath[0] == '.')
  6007. {
  6008. #if JUCE_WINDOWS
  6009. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6010. #else
  6011. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6012. #endif
  6013. while (relativePath[0] == '.')
  6014. {
  6015. if (relativePath[1] == '.')
  6016. {
  6017. if (relativePath [2] == 0 || relativePath[2] == separator)
  6018. {
  6019. const int lastSlash = path.lastIndexOfChar (separator);
  6020. if (lastSlash >= 0)
  6021. path = path.substring (0, lastSlash);
  6022. relativePath = relativePath.substring (3);
  6023. }
  6024. else
  6025. {
  6026. break;
  6027. }
  6028. }
  6029. else if (relativePath[1] == separator)
  6030. {
  6031. relativePath = relativePath.substring (2);
  6032. }
  6033. else
  6034. {
  6035. break;
  6036. }
  6037. }
  6038. }
  6039. return File (addTrailingSeparator (path) + relativePath);
  6040. }
  6041. }
  6042. const File File::getSiblingFile (const String& fileName) const
  6043. {
  6044. return getParentDirectory().getChildFile (fileName);
  6045. }
  6046. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6047. {
  6048. if (bytes == 1)
  6049. {
  6050. return "1 byte";
  6051. }
  6052. else if (bytes < 1024)
  6053. {
  6054. return String ((int) bytes) + " bytes";
  6055. }
  6056. else if (bytes < 1024 * 1024)
  6057. {
  6058. return String (bytes / 1024.0, 1) + " KB";
  6059. }
  6060. else if (bytes < 1024 * 1024 * 1024)
  6061. {
  6062. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6063. }
  6064. else
  6065. {
  6066. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6067. }
  6068. }
  6069. bool File::create() const
  6070. {
  6071. if (exists())
  6072. return true;
  6073. {
  6074. const File parentDir (getParentDirectory());
  6075. if (parentDir == *this || ! parentDir.createDirectory())
  6076. return false;
  6077. FileOutputStream fo (*this, 8);
  6078. }
  6079. return exists();
  6080. }
  6081. bool File::createDirectory() const
  6082. {
  6083. if (! isDirectory())
  6084. {
  6085. const File parentDir (getParentDirectory());
  6086. if (parentDir == *this || ! parentDir.createDirectory())
  6087. return false;
  6088. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6089. return isDirectory();
  6090. }
  6091. return true;
  6092. }
  6093. const Time File::getCreationTime() const
  6094. {
  6095. int64 m, a, c;
  6096. getFileTimesInternal (m, a, c);
  6097. return Time (c);
  6098. }
  6099. const Time File::getLastModificationTime() const
  6100. {
  6101. int64 m, a, c;
  6102. getFileTimesInternal (m, a, c);
  6103. return Time (m);
  6104. }
  6105. const Time File::getLastAccessTime() const
  6106. {
  6107. int64 m, a, c;
  6108. getFileTimesInternal (m, a, c);
  6109. return Time (a);
  6110. }
  6111. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6112. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6113. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6114. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6115. {
  6116. if (! existsAsFile())
  6117. return false;
  6118. FileInputStream in (*this);
  6119. return getSize() == in.readIntoMemoryBlock (destBlock);
  6120. }
  6121. const String File::loadFileAsString() const
  6122. {
  6123. if (! existsAsFile())
  6124. return String::empty;
  6125. FileInputStream in (*this);
  6126. return in.readEntireStreamAsString();
  6127. }
  6128. int File::findChildFiles (Array<File>& results,
  6129. const int whatToLookFor,
  6130. const bool searchRecursively,
  6131. const String& wildCardPattern) const
  6132. {
  6133. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6134. int total = 0;
  6135. while (di.next())
  6136. {
  6137. results.add (di.getFile());
  6138. ++total;
  6139. }
  6140. return total;
  6141. }
  6142. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6143. {
  6144. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6145. int total = 0;
  6146. while (di.next())
  6147. ++total;
  6148. return total;
  6149. }
  6150. bool File::containsSubDirectories() const
  6151. {
  6152. if (isDirectory())
  6153. {
  6154. DirectoryIterator di (*this, false, "*", findDirectories);
  6155. return di.next();
  6156. }
  6157. return false;
  6158. }
  6159. const File File::getNonexistentChildFile (const String& prefix_,
  6160. const String& suffix,
  6161. bool putNumbersInBrackets) const
  6162. {
  6163. File f (getChildFile (prefix_ + suffix));
  6164. if (f.exists())
  6165. {
  6166. int num = 2;
  6167. String prefix (prefix_);
  6168. // remove any bracketed numbers that may already be on the end..
  6169. if (prefix.trim().endsWithChar (')'))
  6170. {
  6171. putNumbersInBrackets = true;
  6172. const int openBracks = prefix.lastIndexOfChar ('(');
  6173. const int closeBracks = prefix.lastIndexOfChar (')');
  6174. if (openBracks > 0
  6175. && closeBracks > openBracks
  6176. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6177. {
  6178. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6179. prefix = prefix.substring (0, openBracks);
  6180. }
  6181. }
  6182. // also use brackets if it ends in a digit.
  6183. putNumbersInBrackets = putNumbersInBrackets
  6184. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6185. do
  6186. {
  6187. if (putNumbersInBrackets)
  6188. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6189. else
  6190. f = getChildFile (prefix + String (num++) + suffix);
  6191. } while (f.exists());
  6192. }
  6193. return f;
  6194. }
  6195. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6196. {
  6197. if (exists())
  6198. {
  6199. return getParentDirectory()
  6200. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6201. getFileExtension(),
  6202. putNumbersInBrackets);
  6203. }
  6204. else
  6205. {
  6206. return *this;
  6207. }
  6208. }
  6209. const String File::getFileExtension() const
  6210. {
  6211. String ext;
  6212. if (! isDirectory())
  6213. {
  6214. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6215. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6216. ext = fullPath.substring (indexOfDot);
  6217. }
  6218. return ext;
  6219. }
  6220. bool File::hasFileExtension (const String& possibleSuffix) const
  6221. {
  6222. if (possibleSuffix.isEmpty())
  6223. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6224. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6225. if (semicolon >= 0)
  6226. {
  6227. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6228. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6229. }
  6230. else
  6231. {
  6232. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6233. {
  6234. if (possibleSuffix.startsWithChar ('.'))
  6235. return true;
  6236. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6237. if (dotPos >= 0)
  6238. return fullPath [dotPos] == '.';
  6239. }
  6240. }
  6241. return false;
  6242. }
  6243. const File File::withFileExtension (const String& newExtension) const
  6244. {
  6245. if (fullPath.isEmpty())
  6246. return File::nonexistent;
  6247. String filePart (getFileName());
  6248. int i = filePart.lastIndexOfChar ('.');
  6249. if (i >= 0)
  6250. filePart = filePart.substring (0, i);
  6251. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6252. filePart << '.';
  6253. return getSiblingFile (filePart + newExtension);
  6254. }
  6255. bool File::startAsProcess (const String& parameters) const
  6256. {
  6257. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6258. }
  6259. FileInputStream* File::createInputStream() const
  6260. {
  6261. if (existsAsFile())
  6262. return new FileInputStream (*this);
  6263. return 0;
  6264. }
  6265. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6266. {
  6267. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6268. if (out->failedToOpen())
  6269. return 0;
  6270. return out.release();
  6271. }
  6272. bool File::appendData (const void* const dataToAppend,
  6273. const int numberOfBytes) const
  6274. {
  6275. if (numberOfBytes > 0)
  6276. {
  6277. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6278. if (out == 0)
  6279. return false;
  6280. out->write (dataToAppend, numberOfBytes);
  6281. }
  6282. return true;
  6283. }
  6284. bool File::replaceWithData (const void* const dataToWrite,
  6285. const int numberOfBytes) const
  6286. {
  6287. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6288. if (numberOfBytes <= 0)
  6289. return deleteFile();
  6290. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6291. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6292. return tempFile.overwriteTargetFileWithTemporary();
  6293. }
  6294. bool File::appendText (const String& text,
  6295. const bool asUnicode,
  6296. const bool writeUnicodeHeaderBytes) const
  6297. {
  6298. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6299. if (out != 0)
  6300. {
  6301. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6302. return true;
  6303. }
  6304. return false;
  6305. }
  6306. bool File::replaceWithText (const String& textToWrite,
  6307. const bool asUnicode,
  6308. const bool writeUnicodeHeaderBytes) const
  6309. {
  6310. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6311. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6312. return tempFile.overwriteTargetFileWithTemporary();
  6313. }
  6314. bool File::hasIdenticalContentTo (const File& other) const
  6315. {
  6316. if (other == *this)
  6317. return true;
  6318. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6319. {
  6320. FileInputStream in1 (*this), in2 (other);
  6321. const int bufferSize = 4096;
  6322. HeapBlock <char> buffer1, buffer2;
  6323. buffer1.malloc (bufferSize);
  6324. buffer2.malloc (bufferSize);
  6325. for (;;)
  6326. {
  6327. const int num1 = in1.read (buffer1, bufferSize);
  6328. const int num2 = in2.read (buffer2, bufferSize);
  6329. if (num1 != num2)
  6330. break;
  6331. if (num1 <= 0)
  6332. return true;
  6333. if (memcmp (buffer1, buffer2, num1) != 0)
  6334. break;
  6335. }
  6336. }
  6337. return false;
  6338. }
  6339. const String File::createLegalPathName (const String& original)
  6340. {
  6341. String s (original);
  6342. String start;
  6343. if (s[1] == ':')
  6344. {
  6345. start = s.substring (0, 2);
  6346. s = s.substring (2);
  6347. }
  6348. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6349. .substring (0, 1024);
  6350. }
  6351. const String File::createLegalFileName (const String& original)
  6352. {
  6353. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6354. const int maxLength = 128; // only the length of the filename, not the whole path
  6355. const int len = s.length();
  6356. if (len > maxLength)
  6357. {
  6358. const int lastDot = s.lastIndexOfChar ('.');
  6359. if (lastDot > jmax (0, len - 12))
  6360. {
  6361. s = s.substring (0, maxLength - (len - lastDot))
  6362. + s.substring (lastDot);
  6363. }
  6364. else
  6365. {
  6366. s = s.substring (0, maxLength);
  6367. }
  6368. }
  6369. return s;
  6370. }
  6371. const String File::getRelativePathFrom (const File& dir) const
  6372. {
  6373. String thisPath (fullPath);
  6374. {
  6375. int len = thisPath.length();
  6376. while (--len >= 0 && thisPath [len] == File::separator)
  6377. thisPath [len] = 0;
  6378. }
  6379. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6380. : dir.fullPath));
  6381. const int len = jmin (thisPath.length(), dirPath.length());
  6382. int commonBitLength = 0;
  6383. for (int i = 0; i < len; ++i)
  6384. {
  6385. #if NAMES_ARE_CASE_SENSITIVE
  6386. if (thisPath[i] != dirPath[i])
  6387. #else
  6388. if (CharacterFunctions::toLowerCase (thisPath[i])
  6389. != CharacterFunctions::toLowerCase (dirPath[i]))
  6390. #endif
  6391. {
  6392. break;
  6393. }
  6394. ++commonBitLength;
  6395. }
  6396. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6397. --commonBitLength;
  6398. // if the only common bit is the root, then just return the full path..
  6399. if (commonBitLength <= 0
  6400. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6401. return fullPath;
  6402. thisPath = thisPath.substring (commonBitLength);
  6403. dirPath = dirPath.substring (commonBitLength);
  6404. while (dirPath.isNotEmpty())
  6405. {
  6406. #if JUCE_WINDOWS
  6407. thisPath = "..\\" + thisPath;
  6408. #else
  6409. thisPath = "../" + thisPath;
  6410. #endif
  6411. const int sep = dirPath.indexOfChar (separator);
  6412. if (sep >= 0)
  6413. dirPath = dirPath.substring (sep + 1);
  6414. else
  6415. dirPath = String::empty;
  6416. }
  6417. return thisPath;
  6418. }
  6419. const File File::createTempFile (const String& fileNameEnding)
  6420. {
  6421. const File tempFile (getSpecialLocation (tempDirectory)
  6422. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6423. .withFileExtension (fileNameEnding));
  6424. if (tempFile.exists())
  6425. return createTempFile (fileNameEnding);
  6426. else
  6427. return tempFile;
  6428. }
  6429. #if JUCE_UNIT_TESTS
  6430. class FileTests : public UnitTest
  6431. {
  6432. public:
  6433. FileTests() : UnitTest ("Files") {}
  6434. void runTest()
  6435. {
  6436. beginTest ("Reading");
  6437. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6438. const File temp (File::getSpecialLocation (File::tempDirectory));
  6439. expect (! File::nonexistent.exists());
  6440. expect (home.isDirectory());
  6441. expect (home.exists());
  6442. expect (! home.existsAsFile());
  6443. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6444. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6445. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6446. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6447. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6448. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6449. expect (home.getBytesFreeOnVolume() > 0);
  6450. expect (! home.isHidden());
  6451. expect (home.isOnHardDisk());
  6452. expect (! home.isOnCDRomDrive());
  6453. expect (File::getCurrentWorkingDirectory().exists());
  6454. expect (home.setAsCurrentWorkingDirectory());
  6455. expect (File::getCurrentWorkingDirectory() == home);
  6456. {
  6457. Array<File> roots;
  6458. File::findFileSystemRoots (roots);
  6459. expect (roots.size() > 0);
  6460. int numRootsExisting = 0;
  6461. for (int i = 0; i < roots.size(); ++i)
  6462. if (roots[i].exists())
  6463. ++numRootsExisting;
  6464. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6465. expect (numRootsExisting > 0);
  6466. }
  6467. beginTest ("Writing");
  6468. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6469. expect (demoFolder.deleteRecursively());
  6470. expect (demoFolder.createDirectory());
  6471. expect (demoFolder.isDirectory());
  6472. expect (demoFolder.getParentDirectory() == temp);
  6473. expect (temp.isDirectory());
  6474. {
  6475. Array<File> files;
  6476. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6477. expect (files.contains (demoFolder));
  6478. }
  6479. {
  6480. Array<File> files;
  6481. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6482. expect (files.contains (demoFolder));
  6483. }
  6484. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6485. expect (tempFile.getFileExtension() == ".txt");
  6486. expect (tempFile.hasFileExtension (".txt"));
  6487. expect (tempFile.hasFileExtension ("txt"));
  6488. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6489. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6490. expect (tempFile.hasWriteAccess());
  6491. {
  6492. FileOutputStream fo (tempFile);
  6493. fo.write ("0123456789", 10);
  6494. }
  6495. expect (tempFile.exists());
  6496. expect (tempFile.getSize() == 10);
  6497. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6498. expect (tempFile.loadFileAsString() == "0123456789");
  6499. expect (! demoFolder.containsSubDirectories());
  6500. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6501. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6502. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6503. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6504. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6505. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6506. expect (demoFolder.containsSubDirectories());
  6507. expect (tempFile.hasWriteAccess());
  6508. tempFile.setReadOnly (true);
  6509. expect (! tempFile.hasWriteAccess());
  6510. tempFile.setReadOnly (false);
  6511. expect (tempFile.hasWriteAccess());
  6512. Time t (Time::getCurrentTime());
  6513. tempFile.setLastModificationTime (t);
  6514. Time t2 = tempFile.getLastModificationTime();
  6515. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6516. {
  6517. MemoryBlock mb;
  6518. tempFile.loadFileAsData (mb);
  6519. expect (mb.getSize() == 10);
  6520. expect (mb[0] == '0');
  6521. }
  6522. expect (tempFile.appendData ("abcdefghij", 10));
  6523. expect (tempFile.getSize() == 20);
  6524. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6525. expect (tempFile.getSize() == 10);
  6526. File tempFile2 (tempFile.getNonexistentSibling (false));
  6527. expect (tempFile.copyFileTo (tempFile2));
  6528. expect (tempFile2.exists());
  6529. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6530. expect (tempFile.deleteFile());
  6531. expect (! tempFile.exists());
  6532. expect (tempFile2.moveFileTo (tempFile));
  6533. expect (tempFile.exists());
  6534. expect (! tempFile2.exists());
  6535. expect (demoFolder.deleteRecursively());
  6536. expect (! demoFolder.exists());
  6537. }
  6538. };
  6539. static FileTests fileUnitTests;
  6540. #endif
  6541. END_JUCE_NAMESPACE
  6542. /*** End of inlined file: juce_File.cpp ***/
  6543. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6544. BEGIN_JUCE_NAMESPACE
  6545. int64 juce_fileSetPosition (void* handle, int64 pos);
  6546. FileInputStream::FileInputStream (const File& f)
  6547. : file (f),
  6548. fileHandle (0),
  6549. currentPosition (0),
  6550. totalSize (0),
  6551. needToSeek (true)
  6552. {
  6553. openHandle();
  6554. }
  6555. FileInputStream::~FileInputStream()
  6556. {
  6557. closeHandle();
  6558. }
  6559. int64 FileInputStream::getTotalLength()
  6560. {
  6561. return totalSize;
  6562. }
  6563. int FileInputStream::read (void* buffer, int bytesToRead)
  6564. {
  6565. if (needToSeek)
  6566. {
  6567. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6568. return 0;
  6569. needToSeek = false;
  6570. }
  6571. const size_t num = readInternal (buffer, bytesToRead);
  6572. currentPosition += num;
  6573. return (int) num;
  6574. }
  6575. bool FileInputStream::isExhausted()
  6576. {
  6577. return currentPosition >= totalSize;
  6578. }
  6579. int64 FileInputStream::getPosition()
  6580. {
  6581. return currentPosition;
  6582. }
  6583. bool FileInputStream::setPosition (int64 pos)
  6584. {
  6585. pos = jlimit ((int64) 0, totalSize, pos);
  6586. needToSeek |= (currentPosition != pos);
  6587. currentPosition = pos;
  6588. return true;
  6589. }
  6590. END_JUCE_NAMESPACE
  6591. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6592. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6593. BEGIN_JUCE_NAMESPACE
  6594. int64 juce_fileSetPosition (void* handle, int64 pos);
  6595. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6596. : file (f),
  6597. fileHandle (0),
  6598. currentPosition (0),
  6599. bufferSize (bufferSize_),
  6600. bytesInBuffer (0),
  6601. buffer (jmax (bufferSize_, 16))
  6602. {
  6603. openHandle();
  6604. }
  6605. FileOutputStream::~FileOutputStream()
  6606. {
  6607. flush();
  6608. closeHandle();
  6609. }
  6610. int64 FileOutputStream::getPosition()
  6611. {
  6612. return currentPosition;
  6613. }
  6614. bool FileOutputStream::setPosition (int64 newPosition)
  6615. {
  6616. if (newPosition != currentPosition)
  6617. {
  6618. flush();
  6619. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6620. }
  6621. return newPosition == currentPosition;
  6622. }
  6623. void FileOutputStream::flush()
  6624. {
  6625. if (bytesInBuffer > 0)
  6626. {
  6627. writeInternal (buffer, bytesInBuffer);
  6628. bytesInBuffer = 0;
  6629. }
  6630. flushInternal();
  6631. }
  6632. bool FileOutputStream::write (const void* const src, const int numBytes)
  6633. {
  6634. if (bytesInBuffer + numBytes < bufferSize)
  6635. {
  6636. memcpy (buffer + bytesInBuffer, src, numBytes);
  6637. bytesInBuffer += numBytes;
  6638. currentPosition += numBytes;
  6639. }
  6640. else
  6641. {
  6642. if (bytesInBuffer > 0)
  6643. {
  6644. // flush the reservoir
  6645. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6646. bytesInBuffer = 0;
  6647. if (! wroteOk)
  6648. return false;
  6649. }
  6650. if (numBytes < bufferSize)
  6651. {
  6652. memcpy (buffer + bytesInBuffer, src, numBytes);
  6653. bytesInBuffer += numBytes;
  6654. currentPosition += numBytes;
  6655. }
  6656. else
  6657. {
  6658. const int bytesWritten = writeInternal (src, numBytes);
  6659. if (bytesWritten < 0)
  6660. return false;
  6661. currentPosition += bytesWritten;
  6662. return bytesWritten == numBytes;
  6663. }
  6664. }
  6665. return true;
  6666. }
  6667. END_JUCE_NAMESPACE
  6668. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6669. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6670. BEGIN_JUCE_NAMESPACE
  6671. FileSearchPath::FileSearchPath()
  6672. {
  6673. }
  6674. FileSearchPath::FileSearchPath (const String& path)
  6675. {
  6676. init (path);
  6677. }
  6678. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6679. : directories (other.directories)
  6680. {
  6681. }
  6682. FileSearchPath::~FileSearchPath()
  6683. {
  6684. }
  6685. FileSearchPath& FileSearchPath::operator= (const String& path)
  6686. {
  6687. init (path);
  6688. return *this;
  6689. }
  6690. void FileSearchPath::init (const String& path)
  6691. {
  6692. directories.clear();
  6693. directories.addTokens (path, ";", "\"");
  6694. directories.trim();
  6695. directories.removeEmptyStrings();
  6696. for (int i = directories.size(); --i >= 0;)
  6697. directories.set (i, directories[i].unquoted());
  6698. }
  6699. int FileSearchPath::getNumPaths() const
  6700. {
  6701. return directories.size();
  6702. }
  6703. const File FileSearchPath::operator[] (const int index) const
  6704. {
  6705. return File (directories [index]);
  6706. }
  6707. const String FileSearchPath::toString() const
  6708. {
  6709. StringArray directories2 (directories);
  6710. for (int i = directories2.size(); --i >= 0;)
  6711. if (directories2[i].containsChar (';'))
  6712. directories2.set (i, directories2[i].quoted());
  6713. return directories2.joinIntoString (";");
  6714. }
  6715. void FileSearchPath::add (const File& dir, const int insertIndex)
  6716. {
  6717. directories.insert (insertIndex, dir.getFullPathName());
  6718. }
  6719. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6720. {
  6721. for (int i = 0; i < directories.size(); ++i)
  6722. if (File (directories[i]) == dir)
  6723. return;
  6724. add (dir);
  6725. }
  6726. void FileSearchPath::remove (const int index)
  6727. {
  6728. directories.remove (index);
  6729. }
  6730. void FileSearchPath::addPath (const FileSearchPath& other)
  6731. {
  6732. for (int i = 0; i < other.getNumPaths(); ++i)
  6733. addIfNotAlreadyThere (other[i]);
  6734. }
  6735. void FileSearchPath::removeRedundantPaths()
  6736. {
  6737. for (int i = directories.size(); --i >= 0;)
  6738. {
  6739. const File d1 (directories[i]);
  6740. for (int j = directories.size(); --j >= 0;)
  6741. {
  6742. const File d2 (directories[j]);
  6743. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6744. {
  6745. directories.remove (i);
  6746. break;
  6747. }
  6748. }
  6749. }
  6750. }
  6751. void FileSearchPath::removeNonExistentPaths()
  6752. {
  6753. for (int i = directories.size(); --i >= 0;)
  6754. if (! File (directories[i]).isDirectory())
  6755. directories.remove (i);
  6756. }
  6757. int FileSearchPath::findChildFiles (Array<File>& results,
  6758. const int whatToLookFor,
  6759. const bool searchRecursively,
  6760. const String& wildCardPattern) const
  6761. {
  6762. int total = 0;
  6763. for (int i = 0; i < directories.size(); ++i)
  6764. total += operator[] (i).findChildFiles (results,
  6765. whatToLookFor,
  6766. searchRecursively,
  6767. wildCardPattern);
  6768. return total;
  6769. }
  6770. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6771. const bool checkRecursively) const
  6772. {
  6773. for (int i = directories.size(); --i >= 0;)
  6774. {
  6775. const File d (directories[i]);
  6776. if (checkRecursively)
  6777. {
  6778. if (fileToCheck.isAChildOf (d))
  6779. return true;
  6780. }
  6781. else
  6782. {
  6783. if (fileToCheck.getParentDirectory() == d)
  6784. return true;
  6785. }
  6786. }
  6787. return false;
  6788. }
  6789. END_JUCE_NAMESPACE
  6790. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6791. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6792. BEGIN_JUCE_NAMESPACE
  6793. NamedPipe::NamedPipe()
  6794. : internal (0)
  6795. {
  6796. }
  6797. NamedPipe::~NamedPipe()
  6798. {
  6799. close();
  6800. }
  6801. bool NamedPipe::openExisting (const String& pipeName)
  6802. {
  6803. currentPipeName = pipeName;
  6804. return openInternal (pipeName, false);
  6805. }
  6806. bool NamedPipe::createNewPipe (const String& pipeName)
  6807. {
  6808. currentPipeName = pipeName;
  6809. return openInternal (pipeName, true);
  6810. }
  6811. bool NamedPipe::isOpen() const
  6812. {
  6813. return internal != 0;
  6814. }
  6815. const String NamedPipe::getName() const
  6816. {
  6817. return currentPipeName;
  6818. }
  6819. // other methods for this class are implemented in the platform-specific files
  6820. END_JUCE_NAMESPACE
  6821. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6822. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6823. BEGIN_JUCE_NAMESPACE
  6824. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6825. {
  6826. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6827. "temp_" + String (Random::getSystemRandom().nextInt()),
  6828. suffix,
  6829. optionFlags);
  6830. }
  6831. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6832. : targetFile (targetFile_)
  6833. {
  6834. // If you use this constructor, you need to give it a valid target file!
  6835. jassert (targetFile != File::nonexistent);
  6836. createTempFile (targetFile.getParentDirectory(),
  6837. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6838. targetFile.getFileExtension(),
  6839. optionFlags);
  6840. }
  6841. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6842. const String& suffix, const int optionFlags)
  6843. {
  6844. if ((optionFlags & useHiddenFile) != 0)
  6845. name = "." + name;
  6846. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6847. }
  6848. TemporaryFile::~TemporaryFile()
  6849. {
  6850. if (! deleteTemporaryFile())
  6851. {
  6852. /* Failed to delete our temporary file! The most likely reason for this would be
  6853. that you've not closed an output stream that was being used to write to file.
  6854. If you find that something beyond your control is changing permissions on
  6855. your temporary files and preventing them from being deleted, you may want to
  6856. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6857. handle them appropriately.
  6858. */
  6859. jassertfalse;
  6860. }
  6861. }
  6862. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6863. {
  6864. // This method only works if you created this object with the constructor
  6865. // that takes a target file!
  6866. jassert (targetFile != File::nonexistent);
  6867. if (temporaryFile.exists())
  6868. {
  6869. // Have a few attempts at overwriting the file before giving up..
  6870. for (int i = 5; --i >= 0;)
  6871. {
  6872. if (temporaryFile.moveFileTo (targetFile))
  6873. return true;
  6874. Thread::sleep (100);
  6875. }
  6876. }
  6877. else
  6878. {
  6879. // There's no temporary file to use. If your write failed, you should
  6880. // probably check, and not bother calling this method.
  6881. jassertfalse;
  6882. }
  6883. return false;
  6884. }
  6885. bool TemporaryFile::deleteTemporaryFile() const
  6886. {
  6887. // Have a few attempts at deleting the file before giving up..
  6888. for (int i = 5; --i >= 0;)
  6889. {
  6890. if (temporaryFile.deleteFile())
  6891. return true;
  6892. Thread::sleep (50);
  6893. }
  6894. return false;
  6895. }
  6896. END_JUCE_NAMESPACE
  6897. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6898. /*** Start of inlined file: juce_Socket.cpp ***/
  6899. #if JUCE_WINDOWS
  6900. #include <winsock2.h>
  6901. #if JUCE_MSVC
  6902. #pragma warning (push)
  6903. #pragma warning (disable : 4127 4389 4018)
  6904. #endif
  6905. #else
  6906. #if JUCE_LINUX
  6907. #include <sys/types.h>
  6908. #include <sys/socket.h>
  6909. #include <sys/errno.h>
  6910. #include <unistd.h>
  6911. #include <netinet/in.h>
  6912. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6913. #include <CoreServices/CoreServices.h>
  6914. #endif
  6915. #include <fcntl.h>
  6916. #include <netdb.h>
  6917. #include <arpa/inet.h>
  6918. #include <netinet/tcp.h>
  6919. #endif
  6920. BEGIN_JUCE_NAMESPACE
  6921. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6922. typedef socklen_t juce_socklen_t;
  6923. #else
  6924. typedef int juce_socklen_t;
  6925. #endif
  6926. #if JUCE_WINDOWS
  6927. namespace SocketHelpers
  6928. {
  6929. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6930. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6931. void initWin32Sockets()
  6932. {
  6933. static CriticalSection lock;
  6934. const ScopedLock sl (lock);
  6935. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6936. {
  6937. WSADATA wsaData;
  6938. const WORD wVersionRequested = MAKEWORD (1, 1);
  6939. WSAStartup (wVersionRequested, &wsaData);
  6940. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6941. }
  6942. }
  6943. }
  6944. void juce_shutdownWin32Sockets()
  6945. {
  6946. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6947. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6948. }
  6949. #endif
  6950. namespace SocketHelpers
  6951. {
  6952. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6953. {
  6954. const int sndBufSize = 65536;
  6955. const int rcvBufSize = 65536;
  6956. const int one = 1;
  6957. return handle > 0
  6958. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6959. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6960. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6961. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6962. }
  6963. bool bindSocketToPort (const int handle, const int port) throw()
  6964. {
  6965. if (handle <= 0 || port <= 0)
  6966. return false;
  6967. struct sockaddr_in servTmpAddr;
  6968. zerostruct (servTmpAddr);
  6969. servTmpAddr.sin_family = PF_INET;
  6970. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6971. servTmpAddr.sin_port = htons ((uint16) port);
  6972. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6973. }
  6974. int readSocket (const int handle,
  6975. void* const destBuffer, const int maxBytesToRead,
  6976. bool volatile& connected,
  6977. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6978. {
  6979. int bytesRead = 0;
  6980. while (bytesRead < maxBytesToRead)
  6981. {
  6982. int bytesThisTime;
  6983. #if JUCE_WINDOWS
  6984. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6985. #else
  6986. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6987. && errno == EINTR
  6988. && connected)
  6989. {
  6990. }
  6991. #endif
  6992. if (bytesThisTime <= 0 || ! connected)
  6993. {
  6994. if (bytesRead == 0)
  6995. bytesRead = -1;
  6996. break;
  6997. }
  6998. bytesRead += bytesThisTime;
  6999. if (! blockUntilSpecifiedAmountHasArrived)
  7000. break;
  7001. }
  7002. return bytesRead;
  7003. }
  7004. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  7005. {
  7006. struct timeval timeout;
  7007. struct timeval* timeoutp;
  7008. if (timeoutMsecs >= 0)
  7009. {
  7010. timeout.tv_sec = timeoutMsecs / 1000;
  7011. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7012. timeoutp = &timeout;
  7013. }
  7014. else
  7015. {
  7016. timeoutp = 0;
  7017. }
  7018. fd_set rset, wset;
  7019. FD_ZERO (&rset);
  7020. FD_SET (handle, &rset);
  7021. FD_ZERO (&wset);
  7022. FD_SET (handle, &wset);
  7023. fd_set* const prset = forReading ? &rset : 0;
  7024. fd_set* const pwset = forReading ? 0 : &wset;
  7025. #if JUCE_WINDOWS
  7026. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7027. return -1;
  7028. #else
  7029. {
  7030. int result;
  7031. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7032. && errno == EINTR)
  7033. {
  7034. }
  7035. if (result < 0)
  7036. return -1;
  7037. }
  7038. #endif
  7039. {
  7040. int opt;
  7041. juce_socklen_t len = sizeof (opt);
  7042. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7043. || opt != 0)
  7044. return -1;
  7045. }
  7046. if ((forReading && FD_ISSET (handle, &rset))
  7047. || ((! forReading) && FD_ISSET (handle, &wset)))
  7048. return 1;
  7049. return 0;
  7050. }
  7051. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7052. {
  7053. #if JUCE_WINDOWS
  7054. u_long nonBlocking = shouldBlock ? 0 : 1;
  7055. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7056. return false;
  7057. #else
  7058. int socketFlags = fcntl (handle, F_GETFL, 0);
  7059. if (socketFlags == -1)
  7060. return false;
  7061. if (shouldBlock)
  7062. socketFlags &= ~O_NONBLOCK;
  7063. else
  7064. socketFlags |= O_NONBLOCK;
  7065. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7066. return false;
  7067. #endif
  7068. return true;
  7069. }
  7070. bool connectSocket (int volatile& handle,
  7071. const bool isDatagram,
  7072. void** serverAddress,
  7073. const String& hostName,
  7074. const int portNumber,
  7075. const int timeOutMillisecs) throw()
  7076. {
  7077. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7078. if (hostEnt == 0)
  7079. return false;
  7080. struct in_addr targetAddress;
  7081. memcpy (&targetAddress.s_addr,
  7082. *(hostEnt->h_addr_list),
  7083. sizeof (targetAddress.s_addr));
  7084. struct sockaddr_in servTmpAddr;
  7085. zerostruct (servTmpAddr);
  7086. servTmpAddr.sin_family = PF_INET;
  7087. servTmpAddr.sin_addr = targetAddress;
  7088. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7089. if (handle < 0)
  7090. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7091. if (handle < 0)
  7092. return false;
  7093. if (isDatagram)
  7094. {
  7095. *serverAddress = new struct sockaddr_in();
  7096. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7097. return true;
  7098. }
  7099. setSocketBlockingState (handle, false);
  7100. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7101. if (result < 0)
  7102. {
  7103. #if JUCE_WINDOWS
  7104. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7105. #else
  7106. if (errno == EINPROGRESS)
  7107. #endif
  7108. {
  7109. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7110. {
  7111. setSocketBlockingState (handle, true);
  7112. return false;
  7113. }
  7114. }
  7115. }
  7116. setSocketBlockingState (handle, true);
  7117. resetSocketOptions (handle, false, false);
  7118. return true;
  7119. }
  7120. }
  7121. StreamingSocket::StreamingSocket()
  7122. : portNumber (0),
  7123. handle (-1),
  7124. connected (false),
  7125. isListener (false)
  7126. {
  7127. #if JUCE_WINDOWS
  7128. SocketHelpers::initWin32Sockets();
  7129. #endif
  7130. }
  7131. StreamingSocket::StreamingSocket (const String& hostName_,
  7132. const int portNumber_,
  7133. const int handle_)
  7134. : hostName (hostName_),
  7135. portNumber (portNumber_),
  7136. handle (handle_),
  7137. connected (true),
  7138. isListener (false)
  7139. {
  7140. #if JUCE_WINDOWS
  7141. SocketHelpers::initWin32Sockets();
  7142. #endif
  7143. SocketHelpers::resetSocketOptions (handle_, false, false);
  7144. }
  7145. StreamingSocket::~StreamingSocket()
  7146. {
  7147. close();
  7148. }
  7149. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7150. {
  7151. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7152. : -1;
  7153. }
  7154. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7155. {
  7156. if (isListener || ! connected)
  7157. return -1;
  7158. #if JUCE_WINDOWS
  7159. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7160. #else
  7161. int result;
  7162. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7163. && errno == EINTR)
  7164. {
  7165. }
  7166. return result;
  7167. #endif
  7168. }
  7169. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7170. const int timeoutMsecs) const
  7171. {
  7172. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7173. : -1;
  7174. }
  7175. bool StreamingSocket::bindToPort (const int port)
  7176. {
  7177. return SocketHelpers::bindSocketToPort (handle, port);
  7178. }
  7179. bool StreamingSocket::connect (const String& remoteHostName,
  7180. const int remotePortNumber,
  7181. const int timeOutMillisecs)
  7182. {
  7183. if (isListener)
  7184. {
  7185. jassertfalse; // a listener socket can't connect to another one!
  7186. return false;
  7187. }
  7188. if (connected)
  7189. close();
  7190. hostName = remoteHostName;
  7191. portNumber = remotePortNumber;
  7192. isListener = false;
  7193. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7194. remotePortNumber, timeOutMillisecs);
  7195. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7196. {
  7197. close();
  7198. return false;
  7199. }
  7200. return true;
  7201. }
  7202. void StreamingSocket::close()
  7203. {
  7204. #if JUCE_WINDOWS
  7205. if (handle != SOCKET_ERROR || connected)
  7206. closesocket (handle);
  7207. connected = false;
  7208. #else
  7209. if (connected)
  7210. {
  7211. connected = false;
  7212. if (isListener)
  7213. {
  7214. // need to do this to interrupt the accept() function..
  7215. StreamingSocket temp;
  7216. temp.connect ("localhost", portNumber, 1000);
  7217. }
  7218. }
  7219. if (handle != -1)
  7220. ::close (handle);
  7221. #endif
  7222. hostName = String::empty;
  7223. portNumber = 0;
  7224. handle = -1;
  7225. isListener = false;
  7226. }
  7227. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7228. {
  7229. if (connected)
  7230. close();
  7231. hostName = "listener";
  7232. portNumber = newPortNumber;
  7233. isListener = true;
  7234. struct sockaddr_in servTmpAddr;
  7235. zerostruct (servTmpAddr);
  7236. servTmpAddr.sin_family = PF_INET;
  7237. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7238. if (localHostName.isNotEmpty())
  7239. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7240. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7241. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7242. if (handle < 0)
  7243. return false;
  7244. const int reuse = 1;
  7245. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7246. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7247. || listen (handle, SOMAXCONN) < 0)
  7248. {
  7249. close();
  7250. return false;
  7251. }
  7252. connected = true;
  7253. return true;
  7254. }
  7255. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7256. {
  7257. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7258. // prepare this socket as a listener.
  7259. if (connected && isListener)
  7260. {
  7261. struct sockaddr address;
  7262. juce_socklen_t len = sizeof (sockaddr);
  7263. const int newSocket = (int) accept (handle, &address, &len);
  7264. if (newSocket >= 0 && connected)
  7265. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7266. portNumber, newSocket);
  7267. }
  7268. return 0;
  7269. }
  7270. bool StreamingSocket::isLocal() const throw()
  7271. {
  7272. return hostName == "127.0.0.1";
  7273. }
  7274. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7275. : portNumber (0),
  7276. handle (-1),
  7277. connected (true),
  7278. allowBroadcast (allowBroadcast_),
  7279. serverAddress (0)
  7280. {
  7281. #if JUCE_WINDOWS
  7282. SocketHelpers::initWin32Sockets();
  7283. #endif
  7284. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7285. bindToPort (localPortNumber);
  7286. }
  7287. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7288. const int handle_, const int localPortNumber)
  7289. : hostName (hostName_),
  7290. portNumber (portNumber_),
  7291. handle (handle_),
  7292. connected (true),
  7293. allowBroadcast (false),
  7294. serverAddress (0)
  7295. {
  7296. #if JUCE_WINDOWS
  7297. SocketHelpers::initWin32Sockets();
  7298. #endif
  7299. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7300. bindToPort (localPortNumber);
  7301. }
  7302. DatagramSocket::~DatagramSocket()
  7303. {
  7304. close();
  7305. delete static_cast <struct sockaddr_in*> (serverAddress);
  7306. serverAddress = 0;
  7307. }
  7308. void DatagramSocket::close()
  7309. {
  7310. #if JUCE_WINDOWS
  7311. closesocket (handle);
  7312. connected = false;
  7313. #else
  7314. connected = false;
  7315. ::close (handle);
  7316. #endif
  7317. hostName = String::empty;
  7318. portNumber = 0;
  7319. handle = -1;
  7320. }
  7321. bool DatagramSocket::bindToPort (const int port)
  7322. {
  7323. return SocketHelpers::bindSocketToPort (handle, port);
  7324. }
  7325. bool DatagramSocket::connect (const String& remoteHostName,
  7326. const int remotePortNumber,
  7327. const int timeOutMillisecs)
  7328. {
  7329. if (connected)
  7330. close();
  7331. hostName = remoteHostName;
  7332. portNumber = remotePortNumber;
  7333. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7334. remoteHostName, remotePortNumber,
  7335. timeOutMillisecs);
  7336. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7337. {
  7338. close();
  7339. return false;
  7340. }
  7341. return true;
  7342. }
  7343. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7344. {
  7345. struct sockaddr address;
  7346. juce_socklen_t len = sizeof (sockaddr);
  7347. while (waitUntilReady (true, -1) == 1)
  7348. {
  7349. char buf[1];
  7350. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7351. {
  7352. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7353. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7354. -1, -1);
  7355. }
  7356. }
  7357. return 0;
  7358. }
  7359. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7360. const int timeoutMsecs) const
  7361. {
  7362. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7363. : -1;
  7364. }
  7365. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7366. {
  7367. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7368. : -1;
  7369. }
  7370. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7371. {
  7372. // You need to call connect() first to set the server address..
  7373. jassert (serverAddress != 0 && connected);
  7374. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7375. numBytesToWrite, 0,
  7376. (const struct sockaddr*) serverAddress,
  7377. sizeof (struct sockaddr_in))
  7378. : -1;
  7379. }
  7380. bool DatagramSocket::isLocal() const throw()
  7381. {
  7382. return hostName == "127.0.0.1";
  7383. }
  7384. #if JUCE_MSVC
  7385. #pragma warning (pop)
  7386. #endif
  7387. END_JUCE_NAMESPACE
  7388. /*** End of inlined file: juce_Socket.cpp ***/
  7389. /*** Start of inlined file: juce_URL.cpp ***/
  7390. BEGIN_JUCE_NAMESPACE
  7391. URL::URL()
  7392. {
  7393. }
  7394. URL::URL (const String& url_)
  7395. : url (url_)
  7396. {
  7397. int i = url.indexOfChar ('?');
  7398. if (i >= 0)
  7399. {
  7400. do
  7401. {
  7402. const int nextAmp = url.indexOfChar (i + 1, '&');
  7403. const int equalsPos = url.indexOfChar (i + 1, '=');
  7404. if (equalsPos > i + 1)
  7405. {
  7406. if (nextAmp < 0)
  7407. {
  7408. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7409. removeEscapeChars (url.substring (equalsPos + 1)));
  7410. }
  7411. else if (nextAmp > 0 && equalsPos < nextAmp)
  7412. {
  7413. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7414. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7415. }
  7416. }
  7417. i = nextAmp;
  7418. }
  7419. while (i >= 0);
  7420. url = url.upToFirstOccurrenceOf ("?", false, false);
  7421. }
  7422. }
  7423. URL::URL (const URL& other)
  7424. : url (other.url),
  7425. postData (other.postData),
  7426. parameters (other.parameters),
  7427. filesToUpload (other.filesToUpload),
  7428. mimeTypes (other.mimeTypes)
  7429. {
  7430. }
  7431. URL& URL::operator= (const URL& other)
  7432. {
  7433. url = other.url;
  7434. postData = other.postData;
  7435. parameters = other.parameters;
  7436. filesToUpload = other.filesToUpload;
  7437. mimeTypes = other.mimeTypes;
  7438. return *this;
  7439. }
  7440. URL::~URL()
  7441. {
  7442. }
  7443. namespace URLHelpers
  7444. {
  7445. const String getMangledParameters (const StringPairArray& parameters)
  7446. {
  7447. String p;
  7448. for (int i = 0; i < parameters.size(); ++i)
  7449. {
  7450. if (i > 0)
  7451. p << '&';
  7452. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7453. << '='
  7454. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7455. }
  7456. return p;
  7457. }
  7458. int findStartOfDomain (const String& url)
  7459. {
  7460. int i = 0;
  7461. while (CharacterFunctions::isLetterOrDigit (url[i])
  7462. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7463. ++i;
  7464. return url[i] == ':' ? i + 1 : 0;
  7465. }
  7466. void createHeadersAndPostData (const URL& url, String& headers, MemoryBlock& postData)
  7467. {
  7468. MemoryOutputStream data (postData, false);
  7469. if (url.getFilesToUpload().size() > 0)
  7470. {
  7471. // need to upload some files, so do it as multi-part...
  7472. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7473. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7474. data << "--" << boundary;
  7475. int i;
  7476. for (i = 0; i < url.getParameters().size(); ++i)
  7477. {
  7478. data << "\r\nContent-Disposition: form-data; name=\""
  7479. << url.getParameters().getAllKeys() [i]
  7480. << "\"\r\n\r\n"
  7481. << url.getParameters().getAllValues() [i]
  7482. << "\r\n--"
  7483. << boundary;
  7484. }
  7485. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7486. {
  7487. const File file (url.getFilesToUpload().getAllValues() [i]);
  7488. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7489. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7490. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7491. const String mimeType (url.getMimeTypesOfUploadFiles()
  7492. .getValue (paramName, String::empty));
  7493. if (mimeType.isNotEmpty())
  7494. data << "Content-Type: " << mimeType << "\r\n";
  7495. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7496. << file << "\r\n--" << boundary;
  7497. }
  7498. data << "--\r\n";
  7499. data.flush();
  7500. }
  7501. else
  7502. {
  7503. data << getMangledParameters (url.getParameters()) << url.getPostData();
  7504. data.flush();
  7505. // just a short text attachment, so use simple url encoding..
  7506. headers << "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7507. << (unsigned int) postData.getSize() << "\r\n";
  7508. }
  7509. }
  7510. }
  7511. const String URL::toString (const bool includeGetParameters) const
  7512. {
  7513. if (includeGetParameters && parameters.size() > 0)
  7514. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7515. else
  7516. return url;
  7517. }
  7518. bool URL::isWellFormed() const
  7519. {
  7520. //xxx TODO
  7521. return url.isNotEmpty();
  7522. }
  7523. const String URL::getDomain() const
  7524. {
  7525. int start = URLHelpers::findStartOfDomain (url);
  7526. while (url[start] == '/')
  7527. ++start;
  7528. const int end1 = url.indexOfChar (start, '/');
  7529. const int end2 = url.indexOfChar (start, ':');
  7530. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7531. : jmin (end1, end2);
  7532. return url.substring (start, end);
  7533. }
  7534. const String URL::getSubPath() const
  7535. {
  7536. int start = URLHelpers::findStartOfDomain (url);
  7537. while (url[start] == '/')
  7538. ++start;
  7539. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7540. return startOfPath <= 0 ? String::empty
  7541. : url.substring (startOfPath);
  7542. }
  7543. const String URL::getScheme() const
  7544. {
  7545. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7546. }
  7547. const URL URL::withNewSubPath (const String& newPath) const
  7548. {
  7549. int start = URLHelpers::findStartOfDomain (url);
  7550. while (url[start] == '/')
  7551. ++start;
  7552. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7553. URL u (*this);
  7554. if (startOfPath > 0)
  7555. u.url = url.substring (0, startOfPath);
  7556. if (! u.url.endsWithChar ('/'))
  7557. u.url << '/';
  7558. if (newPath.startsWithChar ('/'))
  7559. u.url << newPath.substring (1);
  7560. else
  7561. u.url << newPath;
  7562. return u;
  7563. }
  7564. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7565. {
  7566. const char* validProtocols[] = { "http:", "ftp:", "https:" };
  7567. for (int i = 0; i < numElementsInArray (validProtocols); ++i)
  7568. if (possibleURL.startsWithIgnoreCase (validProtocols[i]))
  7569. return true;
  7570. if (possibleURL.containsChar ('@')
  7571. || possibleURL.containsChar (' '))
  7572. return false;
  7573. const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
  7574. .fromLastOccurrenceOf (".", false, false));
  7575. return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
  7576. }
  7577. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7578. {
  7579. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7580. return atSign > 0
  7581. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7582. && (! possibleEmailAddress.endsWithChar ('.'));
  7583. }
  7584. InputStream* URL::createInputStream (const bool usePostCommand,
  7585. OpenStreamProgressCallback* const progressCallback,
  7586. void* const progressCallbackContext,
  7587. const String& extraHeaders,
  7588. const int timeOutMs,
  7589. StringPairArray* const responseHeaders) const
  7590. {
  7591. String headers;
  7592. MemoryBlock headersAndPostData;
  7593. if (usePostCommand)
  7594. URLHelpers::createHeadersAndPostData (*this, headers, headersAndPostData);
  7595. headers += extraHeaders;
  7596. if (! headers.endsWithChar ('\n'))
  7597. headers << "\r\n";
  7598. return createNativeStream (toString (! usePostCommand), usePostCommand, headersAndPostData,
  7599. progressCallback, progressCallbackContext,
  7600. headers, timeOutMs, responseHeaders);
  7601. }
  7602. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7603. const bool usePostCommand) const
  7604. {
  7605. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7606. if (in != 0)
  7607. {
  7608. in->readIntoMemoryBlock (destData);
  7609. return true;
  7610. }
  7611. return false;
  7612. }
  7613. const String URL::readEntireTextStream (const bool usePostCommand) const
  7614. {
  7615. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7616. if (in != 0)
  7617. return in->readEntireStreamAsString();
  7618. return String::empty;
  7619. }
  7620. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7621. {
  7622. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7623. }
  7624. const URL URL::withParameter (const String& parameterName,
  7625. const String& parameterValue) const
  7626. {
  7627. URL u (*this);
  7628. u.parameters.set (parameterName, parameterValue);
  7629. return u;
  7630. }
  7631. const URL URL::withFileToUpload (const String& parameterName,
  7632. const File& fileToUpload,
  7633. const String& mimeType) const
  7634. {
  7635. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7636. URL u (*this);
  7637. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7638. u.mimeTypes.set (parameterName, mimeType);
  7639. return u;
  7640. }
  7641. const URL URL::withPOSTData (const String& postData_) const
  7642. {
  7643. URL u (*this);
  7644. u.postData = postData_;
  7645. return u;
  7646. }
  7647. const StringPairArray& URL::getParameters() const
  7648. {
  7649. return parameters;
  7650. }
  7651. const StringPairArray& URL::getFilesToUpload() const
  7652. {
  7653. return filesToUpload;
  7654. }
  7655. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7656. {
  7657. return mimeTypes;
  7658. }
  7659. const String URL::removeEscapeChars (const String& s)
  7660. {
  7661. String result (s.replaceCharacter ('+', ' '));
  7662. if (! result.containsChar ('%'))
  7663. return result;
  7664. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7665. // after all the replacements have been made, so that multi-byte chars are handled.
  7666. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7667. for (int i = 0; i < utf8.size(); ++i)
  7668. {
  7669. if (utf8.getUnchecked(i) == '%')
  7670. {
  7671. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7672. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7673. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7674. {
  7675. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7676. utf8.removeRange (i + 1, 2);
  7677. }
  7678. }
  7679. }
  7680. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7681. }
  7682. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7683. {
  7684. const char* const legalChars = isParameter ? "_-.*!'()"
  7685. : ",$_-.*!'()";
  7686. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7687. for (int i = 0; i < utf8.size(); ++i)
  7688. {
  7689. const char c = utf8.getUnchecked(i);
  7690. if (! (CharacterFunctions::isLetterOrDigit (c)
  7691. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7692. {
  7693. if (c == ' ')
  7694. {
  7695. utf8.set (i, '+');
  7696. }
  7697. else
  7698. {
  7699. static const char* const hexDigits = "0123456789abcdef";
  7700. utf8.set (i, '%');
  7701. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7702. utf8.insert (++i, hexDigits [c & 15]);
  7703. }
  7704. }
  7705. }
  7706. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7707. }
  7708. bool URL::launchInDefaultBrowser() const
  7709. {
  7710. String u (toString (true));
  7711. if (u.containsChar ('@') && ! u.containsChar (':'))
  7712. u = "mailto:" + u;
  7713. return PlatformUtilities::openDocument (u, String::empty);
  7714. }
  7715. END_JUCE_NAMESPACE
  7716. /*** End of inlined file: juce_URL.cpp ***/
  7717. /*** Start of inlined file: juce_MACAddress.cpp ***/
  7718. BEGIN_JUCE_NAMESPACE
  7719. MACAddress::MACAddress()
  7720. : asInt64 (0)
  7721. {
  7722. }
  7723. MACAddress::MACAddress (const MACAddress& other)
  7724. : asInt64 (other.asInt64)
  7725. {
  7726. }
  7727. MACAddress& MACAddress::operator= (const MACAddress& other)
  7728. {
  7729. asInt64 = other.asInt64;
  7730. return *this;
  7731. }
  7732. MACAddress::MACAddress (const uint8 bytes[6])
  7733. : asInt64 (0)
  7734. {
  7735. memcpy (asBytes, bytes, sizeof (asBytes));
  7736. }
  7737. const String MACAddress::toString() const
  7738. {
  7739. String s;
  7740. s.preallocateStorage (18);
  7741. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  7742. {
  7743. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  7744. if (i < numElementsInArray (asBytes) - 1)
  7745. s << '-';
  7746. }
  7747. return s;
  7748. }
  7749. int64 MACAddress::toInt64() const throw()
  7750. {
  7751. int64 n = 0;
  7752. for (int i = numElementsInArray (asBytes); --i >= 0;)
  7753. n = (n << 8) | asBytes[i];
  7754. return n;
  7755. }
  7756. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  7757. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  7758. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  7759. END_JUCE_NAMESPACE
  7760. /*** End of inlined file: juce_MACAddress.cpp ***/
  7761. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7762. BEGIN_JUCE_NAMESPACE
  7763. namespace
  7764. {
  7765. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  7766. {
  7767. // You need to supply a real stream when creating a BufferedInputStream
  7768. jassert (source != 0);
  7769. requestedSize = jmax (256, requestedSize);
  7770. const int64 sourceSize = source->getTotalLength();
  7771. if (sourceSize >= 0 && sourceSize < requestedSize)
  7772. requestedSize = jmax (32, (int) sourceSize);
  7773. return requestedSize;
  7774. }
  7775. }
  7776. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  7777. const bool deleteSourceWhenDestroyed)
  7778. : source (sourceStream),
  7779. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  7780. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  7781. position (sourceStream->getPosition()),
  7782. lastReadPos (0),
  7783. bufferStart (position),
  7784. bufferOverlap (128)
  7785. {
  7786. buffer.malloc (bufferSize);
  7787. }
  7788. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  7789. : source (&sourceStream),
  7790. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  7791. position (sourceStream.getPosition()),
  7792. lastReadPos (0),
  7793. bufferStart (position),
  7794. bufferOverlap (128)
  7795. {
  7796. buffer.malloc (bufferSize);
  7797. }
  7798. BufferedInputStream::~BufferedInputStream()
  7799. {
  7800. }
  7801. int64 BufferedInputStream::getTotalLength()
  7802. {
  7803. return source->getTotalLength();
  7804. }
  7805. int64 BufferedInputStream::getPosition()
  7806. {
  7807. return position;
  7808. }
  7809. bool BufferedInputStream::setPosition (int64 newPosition)
  7810. {
  7811. position = jmax ((int64) 0, newPosition);
  7812. return true;
  7813. }
  7814. bool BufferedInputStream::isExhausted()
  7815. {
  7816. return (position >= lastReadPos)
  7817. && source->isExhausted();
  7818. }
  7819. void BufferedInputStream::ensureBuffered()
  7820. {
  7821. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7822. if (position < bufferStart || position >= bufferEndOverlap)
  7823. {
  7824. int bytesRead;
  7825. if (position < lastReadPos
  7826. && position >= bufferEndOverlap
  7827. && position >= bufferStart)
  7828. {
  7829. const int bytesToKeep = (int) (lastReadPos - position);
  7830. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7831. bufferStart = position;
  7832. bytesRead = source->read (buffer + bytesToKeep,
  7833. bufferSize - bytesToKeep);
  7834. lastReadPos += bytesRead;
  7835. bytesRead += bytesToKeep;
  7836. }
  7837. else
  7838. {
  7839. bufferStart = position;
  7840. source->setPosition (bufferStart);
  7841. bytesRead = source->read (buffer, bufferSize);
  7842. lastReadPos = bufferStart + bytesRead;
  7843. }
  7844. while (bytesRead < bufferSize)
  7845. buffer [bytesRead++] = 0;
  7846. }
  7847. }
  7848. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7849. {
  7850. if (position >= bufferStart
  7851. && position + maxBytesToRead <= lastReadPos)
  7852. {
  7853. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7854. position += maxBytesToRead;
  7855. return maxBytesToRead;
  7856. }
  7857. else
  7858. {
  7859. if (position < bufferStart || position >= lastReadPos)
  7860. ensureBuffered();
  7861. int bytesRead = 0;
  7862. while (maxBytesToRead > 0)
  7863. {
  7864. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7865. if (bytesAvailable > 0)
  7866. {
  7867. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7868. maxBytesToRead -= bytesAvailable;
  7869. bytesRead += bytesAvailable;
  7870. position += bytesAvailable;
  7871. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7872. }
  7873. const int64 oldLastReadPos = lastReadPos;
  7874. ensureBuffered();
  7875. if (oldLastReadPos == lastReadPos)
  7876. break; // if ensureBuffered() failed to read any more data, bail out
  7877. if (isExhausted())
  7878. break;
  7879. }
  7880. return bytesRead;
  7881. }
  7882. }
  7883. const String BufferedInputStream::readString()
  7884. {
  7885. if (position >= bufferStart
  7886. && position < lastReadPos)
  7887. {
  7888. const int maxChars = (int) (lastReadPos - position);
  7889. const char* const src = buffer + (int) (position - bufferStart);
  7890. for (int i = 0; i < maxChars; ++i)
  7891. {
  7892. if (src[i] == 0)
  7893. {
  7894. position += i + 1;
  7895. return String::fromUTF8 (src, i);
  7896. }
  7897. }
  7898. }
  7899. return InputStream::readString();
  7900. }
  7901. END_JUCE_NAMESPACE
  7902. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7903. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7904. BEGIN_JUCE_NAMESPACE
  7905. FileInputSource::FileInputSource (const File& file_, bool useFileTimeInHashGeneration_)
  7906. : file (file_), useFileTimeInHashGeneration (useFileTimeInHashGeneration_)
  7907. {
  7908. }
  7909. FileInputSource::~FileInputSource()
  7910. {
  7911. }
  7912. InputStream* FileInputSource::createInputStream()
  7913. {
  7914. return file.createInputStream();
  7915. }
  7916. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7917. {
  7918. return file.getSiblingFile (relatedItemPath).createInputStream();
  7919. }
  7920. int64 FileInputSource::hashCode() const
  7921. {
  7922. int64 h = file.hashCode();
  7923. if (useFileTimeInHashGeneration)
  7924. h ^= file.getLastModificationTime().toMilliseconds();
  7925. return h;
  7926. }
  7927. END_JUCE_NAMESPACE
  7928. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7929. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7930. BEGIN_JUCE_NAMESPACE
  7931. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7932. const size_t sourceDataSize,
  7933. const bool keepInternalCopy)
  7934. : data (static_cast <const char*> (sourceData)),
  7935. dataSize (sourceDataSize),
  7936. position (0)
  7937. {
  7938. if (keepInternalCopy)
  7939. {
  7940. internalCopy.append (data, sourceDataSize);
  7941. data = static_cast <const char*> (internalCopy.getData());
  7942. }
  7943. }
  7944. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7945. const bool keepInternalCopy)
  7946. : data (static_cast <const char*> (sourceData.getData())),
  7947. dataSize (sourceData.getSize()),
  7948. position (0)
  7949. {
  7950. if (keepInternalCopy)
  7951. {
  7952. internalCopy = sourceData;
  7953. data = static_cast <const char*> (internalCopy.getData());
  7954. }
  7955. }
  7956. MemoryInputStream::~MemoryInputStream()
  7957. {
  7958. }
  7959. int64 MemoryInputStream::getTotalLength()
  7960. {
  7961. return dataSize;
  7962. }
  7963. int MemoryInputStream::read (void* const buffer, const int howMany)
  7964. {
  7965. jassert (howMany >= 0);
  7966. const int num = jmin (howMany, (int) (dataSize - position));
  7967. memcpy (buffer, data + position, num);
  7968. position += num;
  7969. return (int) num;
  7970. }
  7971. bool MemoryInputStream::isExhausted()
  7972. {
  7973. return (position >= dataSize);
  7974. }
  7975. bool MemoryInputStream::setPosition (const int64 pos)
  7976. {
  7977. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7978. return true;
  7979. }
  7980. int64 MemoryInputStream::getPosition()
  7981. {
  7982. return position;
  7983. }
  7984. #if JUCE_UNIT_TESTS
  7985. class MemoryStreamTests : public UnitTest
  7986. {
  7987. public:
  7988. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  7989. void runTest()
  7990. {
  7991. beginTest ("Basics");
  7992. int randomInt = Random::getSystemRandom().nextInt();
  7993. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  7994. double randomDouble = Random::getSystemRandom().nextDouble();
  7995. String randomString;
  7996. for (int i = 50; --i >= 0;)
  7997. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  7998. MemoryOutputStream mo;
  7999. mo.writeInt (randomInt);
  8000. mo.writeIntBigEndian (randomInt);
  8001. mo.writeCompressedInt (randomInt);
  8002. mo.writeString (randomString);
  8003. mo.writeInt64 (randomInt64);
  8004. mo.writeInt64BigEndian (randomInt64);
  8005. mo.writeDouble (randomDouble);
  8006. mo.writeDoubleBigEndian (randomDouble);
  8007. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8008. expect (mi.readInt() == randomInt);
  8009. expect (mi.readIntBigEndian() == randomInt);
  8010. expect (mi.readCompressedInt() == randomInt);
  8011. expect (mi.readString() == randomString);
  8012. expect (mi.readInt64() == randomInt64);
  8013. expect (mi.readInt64BigEndian() == randomInt64);
  8014. expect (mi.readDouble() == randomDouble);
  8015. expect (mi.readDoubleBigEndian() == randomDouble);
  8016. }
  8017. };
  8018. static MemoryStreamTests memoryInputStreamUnitTests;
  8019. #endif
  8020. END_JUCE_NAMESPACE
  8021. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8022. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8023. BEGIN_JUCE_NAMESPACE
  8024. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8025. : data (internalBlock),
  8026. position (0),
  8027. size (0)
  8028. {
  8029. internalBlock.setSize (initialSize, false);
  8030. }
  8031. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8032. const bool appendToExistingBlockContent)
  8033. : data (memoryBlockToWriteTo),
  8034. position (0),
  8035. size (0)
  8036. {
  8037. if (appendToExistingBlockContent)
  8038. position = size = memoryBlockToWriteTo.getSize();
  8039. }
  8040. MemoryOutputStream::~MemoryOutputStream()
  8041. {
  8042. flush();
  8043. }
  8044. void MemoryOutputStream::flush()
  8045. {
  8046. if (&data != &internalBlock)
  8047. data.setSize (size, false);
  8048. }
  8049. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8050. {
  8051. data.ensureSize (bytesToPreallocate + 1);
  8052. }
  8053. void MemoryOutputStream::reset() throw()
  8054. {
  8055. position = 0;
  8056. size = 0;
  8057. }
  8058. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8059. {
  8060. if (howMany > 0)
  8061. {
  8062. const size_t storageNeeded = position + howMany;
  8063. if (storageNeeded >= data.getSize())
  8064. data.ensureSize ((storageNeeded + jmin ((int) (storageNeeded / 2), 1024 * 1024) + 32) & ~31);
  8065. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8066. position += howMany;
  8067. size = jmax (size, position);
  8068. }
  8069. return true;
  8070. }
  8071. const void* MemoryOutputStream::getData() const throw()
  8072. {
  8073. void* const d = data.getData();
  8074. if (data.getSize() > size)
  8075. static_cast <char*> (d) [size] = 0;
  8076. return d;
  8077. }
  8078. bool MemoryOutputStream::setPosition (int64 newPosition)
  8079. {
  8080. if (newPosition <= (int64) size)
  8081. {
  8082. // ok to seek backwards
  8083. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8084. return true;
  8085. }
  8086. else
  8087. {
  8088. // trying to make it bigger isn't a good thing to do..
  8089. return false;
  8090. }
  8091. }
  8092. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8093. {
  8094. // before writing from an input, see if we can preallocate to make it more efficient..
  8095. int64 availableData = source.getTotalLength() - source.getPosition();
  8096. if (availableData > 0)
  8097. {
  8098. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8099. availableData = maxNumBytesToWrite;
  8100. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8101. }
  8102. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8103. }
  8104. const String MemoryOutputStream::toUTF8() const
  8105. {
  8106. return String (static_cast <const char*> (getData()), getDataSize());
  8107. }
  8108. const String MemoryOutputStream::toString() const
  8109. {
  8110. return String::createStringFromData (getData(), (int) getDataSize());
  8111. }
  8112. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8113. {
  8114. stream.write (streamToRead.getData(), (int) streamToRead.getDataSize());
  8115. return stream;
  8116. }
  8117. END_JUCE_NAMESPACE
  8118. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8119. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8120. BEGIN_JUCE_NAMESPACE
  8121. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8122. const int64 startPositionInSourceStream_,
  8123. const int64 lengthOfSourceStream_,
  8124. const bool deleteSourceWhenDestroyed)
  8125. : source (sourceStream),
  8126. startPositionInSourceStream (startPositionInSourceStream_),
  8127. lengthOfSourceStream (lengthOfSourceStream_)
  8128. {
  8129. if (deleteSourceWhenDestroyed)
  8130. sourceToDelete = source;
  8131. setPosition (0);
  8132. }
  8133. SubregionStream::~SubregionStream()
  8134. {
  8135. }
  8136. int64 SubregionStream::getTotalLength()
  8137. {
  8138. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8139. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8140. : srcLen;
  8141. }
  8142. int64 SubregionStream::getPosition()
  8143. {
  8144. return source->getPosition() - startPositionInSourceStream;
  8145. }
  8146. bool SubregionStream::setPosition (int64 newPosition)
  8147. {
  8148. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8149. }
  8150. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8151. {
  8152. if (lengthOfSourceStream < 0)
  8153. {
  8154. return source->read (destBuffer, maxBytesToRead);
  8155. }
  8156. else
  8157. {
  8158. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8159. if (maxBytesToRead <= 0)
  8160. return 0;
  8161. return source->read (destBuffer, maxBytesToRead);
  8162. }
  8163. }
  8164. bool SubregionStream::isExhausted()
  8165. {
  8166. if (lengthOfSourceStream >= 0)
  8167. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8168. else
  8169. return source->isExhausted();
  8170. }
  8171. END_JUCE_NAMESPACE
  8172. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8173. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8174. BEGIN_JUCE_NAMESPACE
  8175. PerformanceCounter::PerformanceCounter (const String& name_,
  8176. int runsPerPrintout,
  8177. const File& loggingFile)
  8178. : name (name_),
  8179. numRuns (0),
  8180. runsPerPrint (runsPerPrintout),
  8181. totalTime (0),
  8182. outputFile (loggingFile)
  8183. {
  8184. if (outputFile != File::nonexistent)
  8185. {
  8186. String s ("**** Counter for \"");
  8187. s << name_ << "\" started at: "
  8188. << Time::getCurrentTime().toString (true, true)
  8189. << newLine;
  8190. outputFile.appendText (s, false, false);
  8191. }
  8192. }
  8193. PerformanceCounter::~PerformanceCounter()
  8194. {
  8195. printStatistics();
  8196. }
  8197. void PerformanceCounter::start()
  8198. {
  8199. started = Time::getHighResolutionTicks();
  8200. }
  8201. void PerformanceCounter::stop()
  8202. {
  8203. const int64 now = Time::getHighResolutionTicks();
  8204. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8205. if (++numRuns == runsPerPrint)
  8206. printStatistics();
  8207. }
  8208. void PerformanceCounter::printStatistics()
  8209. {
  8210. if (numRuns > 0)
  8211. {
  8212. String s ("Performance count for \"");
  8213. s << name << "\" - average over " << numRuns << " run(s) = ";
  8214. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8215. if (micros > 10000)
  8216. s << (micros/1000) << " millisecs";
  8217. else
  8218. s << micros << " microsecs";
  8219. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8220. Logger::outputDebugString (s);
  8221. s << newLine;
  8222. if (outputFile != File::nonexistent)
  8223. outputFile.appendText (s, false, false);
  8224. numRuns = 0;
  8225. totalTime = 0;
  8226. }
  8227. }
  8228. END_JUCE_NAMESPACE
  8229. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8230. /*** Start of inlined file: juce_Uuid.cpp ***/
  8231. BEGIN_JUCE_NAMESPACE
  8232. Uuid::Uuid()
  8233. {
  8234. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8235. // to make it very very unlikely that two UUIDs will ever be the same..
  8236. static int64 macAddresses[2];
  8237. static bool hasCheckedMacAddresses = false;
  8238. if (! hasCheckedMacAddresses)
  8239. {
  8240. hasCheckedMacAddresses = true;
  8241. Array<MACAddress> result;
  8242. MACAddress::findAllAddresses (result);
  8243. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8244. macAddresses[i] = result[i].toInt64();
  8245. }
  8246. value.asInt64[0] = macAddresses[0];
  8247. value.asInt64[1] = macAddresses[1];
  8248. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8249. // whose seed will carry over between calls to this method.
  8250. Random r (macAddresses[0] ^ macAddresses[1]
  8251. ^ Random::getSystemRandom().nextInt64());
  8252. for (int i = 4; --i >= 0;)
  8253. {
  8254. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8255. value.asInt[i] ^= r.nextInt();
  8256. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8257. }
  8258. }
  8259. Uuid::~Uuid() throw()
  8260. {
  8261. }
  8262. Uuid::Uuid (const Uuid& other)
  8263. : value (other.value)
  8264. {
  8265. }
  8266. Uuid& Uuid::operator= (const Uuid& other)
  8267. {
  8268. value = other.value;
  8269. return *this;
  8270. }
  8271. bool Uuid::operator== (const Uuid& other) const
  8272. {
  8273. return value.asInt64[0] == other.value.asInt64[0]
  8274. && value.asInt64[1] == other.value.asInt64[1];
  8275. }
  8276. bool Uuid::operator!= (const Uuid& other) const
  8277. {
  8278. return ! operator== (other);
  8279. }
  8280. bool Uuid::isNull() const throw()
  8281. {
  8282. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8283. }
  8284. const String Uuid::toString() const
  8285. {
  8286. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8287. }
  8288. Uuid::Uuid (const String& uuidString)
  8289. {
  8290. operator= (uuidString);
  8291. }
  8292. Uuid& Uuid::operator= (const String& uuidString)
  8293. {
  8294. MemoryBlock mb;
  8295. mb.loadFromHexString (uuidString);
  8296. mb.ensureSize (sizeof (value.asBytes), true);
  8297. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8298. return *this;
  8299. }
  8300. Uuid::Uuid (const uint8* const rawData)
  8301. {
  8302. operator= (rawData);
  8303. }
  8304. Uuid& Uuid::operator= (const uint8* const rawData)
  8305. {
  8306. if (rawData != 0)
  8307. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8308. else
  8309. zeromem (value.asBytes, sizeof (value.asBytes));
  8310. return *this;
  8311. }
  8312. END_JUCE_NAMESPACE
  8313. /*** End of inlined file: juce_Uuid.cpp ***/
  8314. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8315. BEGIN_JUCE_NAMESPACE
  8316. class ZipFile::ZipEntryInfo
  8317. {
  8318. public:
  8319. ZipFile::ZipEntry entry;
  8320. int streamOffset;
  8321. int compressedSize;
  8322. bool compressed;
  8323. };
  8324. class ZipFile::ZipInputStream : public InputStream
  8325. {
  8326. public:
  8327. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8328. : file (file_),
  8329. zipEntryInfo (zei),
  8330. pos (0),
  8331. headerSize (0),
  8332. inputStream (0)
  8333. {
  8334. inputStream = file_.inputStream;
  8335. if (file_.inputSource != 0)
  8336. {
  8337. inputStream = streamToDelete = file.inputSource->createInputStream();
  8338. }
  8339. else
  8340. {
  8341. #if JUCE_DEBUG
  8342. file_.numOpenStreams++;
  8343. #endif
  8344. }
  8345. char buffer [30];
  8346. if (inputStream != 0
  8347. && inputStream->setPosition (zei.streamOffset)
  8348. && inputStream->read (buffer, 30) == 30
  8349. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8350. {
  8351. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8352. + ByteOrder::littleEndianShort (buffer + 28);
  8353. }
  8354. }
  8355. ~ZipInputStream()
  8356. {
  8357. #if JUCE_DEBUG
  8358. if (inputStream != 0 && inputStream == file.inputStream)
  8359. file.numOpenStreams--;
  8360. #endif
  8361. }
  8362. int64 getTotalLength()
  8363. {
  8364. return zipEntryInfo.compressedSize;
  8365. }
  8366. int read (void* buffer, int howMany)
  8367. {
  8368. if (headerSize <= 0)
  8369. return 0;
  8370. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8371. if (inputStream == 0)
  8372. return 0;
  8373. int num;
  8374. if (inputStream == file.inputStream)
  8375. {
  8376. const ScopedLock sl (file.lock);
  8377. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8378. num = inputStream->read (buffer, howMany);
  8379. }
  8380. else
  8381. {
  8382. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8383. num = inputStream->read (buffer, howMany);
  8384. }
  8385. pos += num;
  8386. return num;
  8387. }
  8388. bool isExhausted()
  8389. {
  8390. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8391. }
  8392. int64 getPosition()
  8393. {
  8394. return pos;
  8395. }
  8396. bool setPosition (int64 newPos)
  8397. {
  8398. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8399. return true;
  8400. }
  8401. private:
  8402. ZipFile& file;
  8403. ZipEntryInfo zipEntryInfo;
  8404. int64 pos;
  8405. int headerSize;
  8406. InputStream* inputStream;
  8407. ScopedPointer<InputStream> streamToDelete;
  8408. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  8409. };
  8410. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8411. : inputStream (source_)
  8412. #if JUCE_DEBUG
  8413. , numOpenStreams (0)
  8414. #endif
  8415. {
  8416. if (deleteStreamWhenDestroyed)
  8417. streamToDelete = inputStream;
  8418. init();
  8419. }
  8420. ZipFile::ZipFile (const File& file)
  8421. : inputStream (0)
  8422. #if JUCE_DEBUG
  8423. , numOpenStreams (0)
  8424. #endif
  8425. {
  8426. inputSource = new FileInputSource (file);
  8427. init();
  8428. }
  8429. ZipFile::ZipFile (InputSource* const inputSource_)
  8430. : inputStream (0),
  8431. inputSource (inputSource_)
  8432. #if JUCE_DEBUG
  8433. , numOpenStreams (0)
  8434. #endif
  8435. {
  8436. init();
  8437. }
  8438. ZipFile::~ZipFile()
  8439. {
  8440. #if JUCE_DEBUG
  8441. entries.clear();
  8442. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8443. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8444. Streams can't be kept open after the file is deleted because they need to share the input
  8445. stream that the file uses to read itself.
  8446. */
  8447. jassert (numOpenStreams == 0);
  8448. #endif
  8449. }
  8450. int ZipFile::getNumEntries() const throw()
  8451. {
  8452. return entries.size();
  8453. }
  8454. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8455. {
  8456. ZipEntryInfo* const zei = entries [index];
  8457. return zei != 0 ? &(zei->entry) : 0;
  8458. }
  8459. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8460. {
  8461. for (int i = 0; i < entries.size(); ++i)
  8462. if (entries.getUnchecked (i)->entry.filename == fileName)
  8463. return i;
  8464. return -1;
  8465. }
  8466. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8467. {
  8468. return getEntry (getIndexOfFileName (fileName));
  8469. }
  8470. InputStream* ZipFile::createStreamForEntry (const int index)
  8471. {
  8472. ZipEntryInfo* const zei = entries[index];
  8473. InputStream* stream = 0;
  8474. if (zei != 0)
  8475. {
  8476. stream = new ZipInputStream (*this, *zei);
  8477. if (zei->compressed)
  8478. {
  8479. stream = new GZIPDecompressorInputStream (stream, true, true,
  8480. zei->entry.uncompressedSize);
  8481. // (much faster to unzip in big blocks using a buffer..)
  8482. stream = new BufferedInputStream (stream, 32768, true);
  8483. }
  8484. }
  8485. return stream;
  8486. }
  8487. class ZipFile::ZipFilenameComparator
  8488. {
  8489. public:
  8490. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8491. {
  8492. return first->entry.filename.compare (second->entry.filename);
  8493. }
  8494. };
  8495. void ZipFile::sortEntriesByFilename()
  8496. {
  8497. ZipFilenameComparator sorter;
  8498. entries.sort (sorter);
  8499. }
  8500. void ZipFile::init()
  8501. {
  8502. ScopedPointer <InputStream> toDelete;
  8503. InputStream* in = inputStream;
  8504. if (inputSource != 0)
  8505. {
  8506. in = inputSource->createInputStream();
  8507. toDelete = in;
  8508. }
  8509. if (in != 0)
  8510. {
  8511. int numEntries = 0;
  8512. int pos = findEndOfZipEntryTable (*in, numEntries);
  8513. if (pos >= 0 && pos < in->getTotalLength())
  8514. {
  8515. const int size = (int) (in->getTotalLength() - pos);
  8516. in->setPosition (pos);
  8517. MemoryBlock headerData;
  8518. if (in->readIntoMemoryBlock (headerData, size) == size)
  8519. {
  8520. pos = 0;
  8521. for (int i = 0; i < numEntries; ++i)
  8522. {
  8523. if (pos + 46 > size)
  8524. break;
  8525. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8526. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8527. if (pos + 46 + fileNameLen > size)
  8528. break;
  8529. ZipEntryInfo* const zei = new ZipEntryInfo();
  8530. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8531. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8532. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8533. const int year = 1980 + (date >> 9);
  8534. const int month = ((date >> 5) & 15) - 1;
  8535. const int day = date & 31;
  8536. const int hours = time >> 11;
  8537. const int minutes = (time >> 5) & 63;
  8538. const int seconds = (time & 31) << 1;
  8539. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8540. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8541. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8542. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8543. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8544. entries.add (zei);
  8545. pos += 46 + fileNameLen
  8546. + ByteOrder::littleEndianShort (buffer + 30)
  8547. + ByteOrder::littleEndianShort (buffer + 32);
  8548. }
  8549. }
  8550. }
  8551. }
  8552. }
  8553. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8554. {
  8555. BufferedInputStream in (input, 8192);
  8556. in.setPosition (in.getTotalLength());
  8557. int64 pos = in.getPosition();
  8558. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8559. char buffer [32];
  8560. zeromem (buffer, sizeof (buffer));
  8561. while (pos > lowestPos)
  8562. {
  8563. in.setPosition (pos - 22);
  8564. pos = in.getPosition();
  8565. memcpy (buffer + 22, buffer, 4);
  8566. if (in.read (buffer, 22) != 22)
  8567. return 0;
  8568. for (int i = 0; i < 22; ++i)
  8569. {
  8570. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8571. {
  8572. in.setPosition (pos + i);
  8573. in.read (buffer, 22);
  8574. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8575. return ByteOrder::littleEndianInt (buffer + 16);
  8576. }
  8577. }
  8578. }
  8579. return 0;
  8580. }
  8581. bool ZipFile::uncompressTo (const File& targetDirectory,
  8582. const bool shouldOverwriteFiles)
  8583. {
  8584. for (int i = 0; i < entries.size(); ++i)
  8585. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8586. return false;
  8587. return true;
  8588. }
  8589. bool ZipFile::uncompressEntry (const int index,
  8590. const File& targetDirectory,
  8591. bool shouldOverwriteFiles)
  8592. {
  8593. const ZipEntryInfo* zei = entries [index];
  8594. if (zei != 0)
  8595. {
  8596. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8597. if (zei->entry.filename.endsWithChar ('/'))
  8598. {
  8599. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8600. }
  8601. else
  8602. {
  8603. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8604. if (in != 0)
  8605. {
  8606. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8607. return false;
  8608. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8609. {
  8610. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8611. if (out != 0)
  8612. {
  8613. out->writeFromInputStream (*in, -1);
  8614. out = 0;
  8615. targetFile.setCreationTime (zei->entry.fileTime);
  8616. targetFile.setLastModificationTime (zei->entry.fileTime);
  8617. targetFile.setLastAccessTime (zei->entry.fileTime);
  8618. return true;
  8619. }
  8620. }
  8621. }
  8622. }
  8623. }
  8624. return false;
  8625. }
  8626. END_JUCE_NAMESPACE
  8627. /*** End of inlined file: juce_ZipFile.cpp ***/
  8628. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8629. #if JUCE_MSVC
  8630. #pragma warning (push)
  8631. #pragma warning (disable: 4514 4996)
  8632. #endif
  8633. #include <cwctype>
  8634. #include <cctype>
  8635. #include <ctime>
  8636. BEGIN_JUCE_NAMESPACE
  8637. int CharacterFunctions::length (const char* const s) throw()
  8638. {
  8639. return (int) strlen (s);
  8640. }
  8641. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8642. {
  8643. return (int) wcslen (s);
  8644. }
  8645. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8646. {
  8647. strncpy (dest, src, maxChars);
  8648. }
  8649. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8650. {
  8651. wcsncpy (dest, src, maxChars);
  8652. }
  8653. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8654. {
  8655. mbstowcs (dest, src, maxChars);
  8656. }
  8657. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8658. {
  8659. wcstombs (dest, src, maxChars);
  8660. }
  8661. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8662. {
  8663. return (int) wcstombs (0, src, 0);
  8664. }
  8665. void CharacterFunctions::append (char* dest, const char* src) throw()
  8666. {
  8667. strcat (dest, src);
  8668. }
  8669. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8670. {
  8671. wcscat (dest, src);
  8672. }
  8673. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8674. {
  8675. return strcmp (s1, s2);
  8676. }
  8677. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8678. {
  8679. jassert (s1 != 0 && s2 != 0);
  8680. return wcscmp (s1, s2);
  8681. }
  8682. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8683. {
  8684. jassert (s1 != 0 && s2 != 0);
  8685. return strncmp (s1, s2, maxChars);
  8686. }
  8687. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8688. {
  8689. jassert (s1 != 0 && s2 != 0);
  8690. return wcsncmp (s1, s2, maxChars);
  8691. }
  8692. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8693. {
  8694. jassert (s1 != 0 && s2 != 0);
  8695. for (;;)
  8696. {
  8697. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8698. if (diff != 0)
  8699. return diff;
  8700. else if (*s1 == 0)
  8701. break;
  8702. ++s1;
  8703. ++s2;
  8704. }
  8705. return 0;
  8706. }
  8707. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8708. {
  8709. return -compare (s2, s1);
  8710. }
  8711. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8712. {
  8713. jassert (s1 != 0 && s2 != 0);
  8714. #if JUCE_WINDOWS
  8715. return stricmp (s1, s2);
  8716. #else
  8717. return strcasecmp (s1, s2);
  8718. #endif
  8719. }
  8720. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8721. {
  8722. jassert (s1 != 0 && s2 != 0);
  8723. #if JUCE_WINDOWS
  8724. return _wcsicmp (s1, s2);
  8725. #else
  8726. for (;;)
  8727. {
  8728. if (*s1 != *s2)
  8729. {
  8730. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8731. if (diff != 0)
  8732. return diff < 0 ? -1 : 1;
  8733. }
  8734. else if (*s1 == 0)
  8735. break;
  8736. ++s1;
  8737. ++s2;
  8738. }
  8739. return 0;
  8740. #endif
  8741. }
  8742. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8743. {
  8744. jassert (s1 != 0 && s2 != 0);
  8745. for (;;)
  8746. {
  8747. if (*s1 != *s2)
  8748. {
  8749. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8750. if (diff != 0)
  8751. return diff < 0 ? -1 : 1;
  8752. }
  8753. else if (*s1 == 0)
  8754. break;
  8755. ++s1;
  8756. ++s2;
  8757. }
  8758. return 0;
  8759. }
  8760. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8761. {
  8762. jassert (s1 != 0 && s2 != 0);
  8763. #if JUCE_WINDOWS
  8764. return strnicmp (s1, s2, maxChars);
  8765. #else
  8766. return strncasecmp (s1, s2, maxChars);
  8767. #endif
  8768. }
  8769. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8770. {
  8771. jassert (s1 != 0 && s2 != 0);
  8772. #if JUCE_WINDOWS
  8773. return _wcsnicmp (s1, s2, maxChars);
  8774. #else
  8775. while (--maxChars >= 0)
  8776. {
  8777. if (*s1 != *s2)
  8778. {
  8779. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8780. if (diff != 0)
  8781. return diff < 0 ? -1 : 1;
  8782. }
  8783. else if (*s1 == 0)
  8784. break;
  8785. ++s1;
  8786. ++s2;
  8787. }
  8788. return 0;
  8789. #endif
  8790. }
  8791. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8792. {
  8793. return strstr (haystack, needle);
  8794. }
  8795. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8796. {
  8797. return wcsstr (haystack, needle);
  8798. }
  8799. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8800. {
  8801. if (haystack != 0)
  8802. {
  8803. int i = 0;
  8804. if (ignoreCase)
  8805. {
  8806. const char n1 = toLowerCase (needle);
  8807. const char n2 = toUpperCase (needle);
  8808. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8809. {
  8810. while (haystack[i] != 0)
  8811. {
  8812. if (haystack[i] == n1 || haystack[i] == n2)
  8813. return i;
  8814. ++i;
  8815. }
  8816. return -1;
  8817. }
  8818. jassert (n1 == needle);
  8819. }
  8820. while (haystack[i] != 0)
  8821. {
  8822. if (haystack[i] == needle)
  8823. return i;
  8824. ++i;
  8825. }
  8826. }
  8827. return -1;
  8828. }
  8829. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8830. {
  8831. if (haystack != 0)
  8832. {
  8833. int i = 0;
  8834. if (ignoreCase)
  8835. {
  8836. const juce_wchar n1 = toLowerCase (needle);
  8837. const juce_wchar n2 = toUpperCase (needle);
  8838. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8839. {
  8840. while (haystack[i] != 0)
  8841. {
  8842. if (haystack[i] == n1 || haystack[i] == n2)
  8843. return i;
  8844. ++i;
  8845. }
  8846. return -1;
  8847. }
  8848. jassert (n1 == needle);
  8849. }
  8850. while (haystack[i] != 0)
  8851. {
  8852. if (haystack[i] == needle)
  8853. return i;
  8854. ++i;
  8855. }
  8856. }
  8857. return -1;
  8858. }
  8859. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8860. {
  8861. jassert (haystack != 0);
  8862. int i = 0;
  8863. while (haystack[i] != 0)
  8864. {
  8865. if (haystack[i] == needle)
  8866. return i;
  8867. ++i;
  8868. }
  8869. return -1;
  8870. }
  8871. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8872. {
  8873. jassert (haystack != 0);
  8874. int i = 0;
  8875. while (haystack[i] != 0)
  8876. {
  8877. if (haystack[i] == needle)
  8878. return i;
  8879. ++i;
  8880. }
  8881. return -1;
  8882. }
  8883. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8884. {
  8885. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8886. }
  8887. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8888. {
  8889. if (allowedChars == 0)
  8890. return 0;
  8891. int i = 0;
  8892. for (;;)
  8893. {
  8894. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8895. break;
  8896. ++i;
  8897. }
  8898. return i;
  8899. }
  8900. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8901. {
  8902. return (int) strftime (dest, maxChars, format, tm);
  8903. }
  8904. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8905. {
  8906. return (int) wcsftime (dest, maxChars, format, tm);
  8907. }
  8908. int CharacterFunctions::getIntValue (const char* const s) throw()
  8909. {
  8910. return atoi (s);
  8911. }
  8912. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8913. {
  8914. #if JUCE_WINDOWS
  8915. return _wtoi (s);
  8916. #else
  8917. int v = 0;
  8918. while (isWhitespace (*s))
  8919. ++s;
  8920. const bool isNeg = *s == '-';
  8921. if (isNeg)
  8922. ++s;
  8923. for (;;)
  8924. {
  8925. const wchar_t c = *s++;
  8926. if (c >= '0' && c <= '9')
  8927. v = v * 10 + (int) (c - '0');
  8928. else
  8929. break;
  8930. }
  8931. return isNeg ? -v : v;
  8932. #endif
  8933. }
  8934. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8935. {
  8936. #if JUCE_LINUX
  8937. return atoll (s);
  8938. #elif JUCE_WINDOWS
  8939. return _atoi64 (s);
  8940. #else
  8941. int64 v = 0;
  8942. while (isWhitespace (*s))
  8943. ++s;
  8944. const bool isNeg = *s == '-';
  8945. if (isNeg)
  8946. ++s;
  8947. for (;;)
  8948. {
  8949. const char c = *s++;
  8950. if (c >= '0' && c <= '9')
  8951. v = v * 10 + (int64) (c - '0');
  8952. else
  8953. break;
  8954. }
  8955. return isNeg ? -v : v;
  8956. #endif
  8957. }
  8958. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8959. {
  8960. #if JUCE_WINDOWS
  8961. return _wtoi64 (s);
  8962. #else
  8963. int64 v = 0;
  8964. while (isWhitespace (*s))
  8965. ++s;
  8966. const bool isNeg = *s == '-';
  8967. if (isNeg)
  8968. ++s;
  8969. for (;;)
  8970. {
  8971. const juce_wchar c = *s++;
  8972. if (c >= '0' && c <= '9')
  8973. v = v * 10 + (int64) (c - '0');
  8974. else
  8975. break;
  8976. }
  8977. return isNeg ? -v : v;
  8978. #endif
  8979. }
  8980. namespace
  8981. {
  8982. double juce_mulexp10 (const double value, int exponent) throw()
  8983. {
  8984. if (exponent == 0)
  8985. return value;
  8986. if (value == 0)
  8987. return 0;
  8988. const bool negative = (exponent < 0);
  8989. if (negative)
  8990. exponent = -exponent;
  8991. double result = 1.0, power = 10.0;
  8992. for (int bit = 1; exponent != 0; bit <<= 1)
  8993. {
  8994. if ((exponent & bit) != 0)
  8995. {
  8996. exponent ^= bit;
  8997. result *= power;
  8998. if (exponent == 0)
  8999. break;
  9000. }
  9001. power *= power;
  9002. }
  9003. return negative ? (value / result) : (value * result);
  9004. }
  9005. template <class CharType>
  9006. double juce_atof (const CharType* const original) throw()
  9007. {
  9008. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  9009. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  9010. int exponent = 0, decPointIndex = 0, digit = 0;
  9011. int lastDigit = 0, numSignificantDigits = 0;
  9012. bool isNegative = false, digitsFound = false;
  9013. const int maxSignificantDigits = 15 + 2;
  9014. const CharType* s = original;
  9015. while (CharacterFunctions::isWhitespace (*s))
  9016. ++s;
  9017. switch (*s)
  9018. {
  9019. case '-': isNegative = true; // fall-through..
  9020. case '+': ++s;
  9021. }
  9022. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9023. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9024. for (;;)
  9025. {
  9026. if (CharacterFunctions::isDigit (*s))
  9027. {
  9028. lastDigit = digit;
  9029. digit = *s++ - '0';
  9030. digitsFound = true;
  9031. if (decPointIndex != 0)
  9032. exponentAdjustment[1]++;
  9033. if (numSignificantDigits == 0 && digit == 0)
  9034. continue;
  9035. if (++numSignificantDigits > maxSignificantDigits)
  9036. {
  9037. if (digit > 5)
  9038. ++accumulator [decPointIndex];
  9039. else if (digit == 5 && (lastDigit & 1) != 0)
  9040. ++accumulator [decPointIndex];
  9041. if (decPointIndex > 0)
  9042. exponentAdjustment[1]--;
  9043. else
  9044. exponentAdjustment[0]++;
  9045. while (CharacterFunctions::isDigit (*s))
  9046. {
  9047. ++s;
  9048. if (decPointIndex == 0)
  9049. exponentAdjustment[0]++;
  9050. }
  9051. }
  9052. else
  9053. {
  9054. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9055. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9056. {
  9057. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9058. + accumulator [decPointIndex];
  9059. accumulator [decPointIndex] = 0;
  9060. exponentAccumulator [decPointIndex] = 0;
  9061. }
  9062. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9063. exponentAccumulator [decPointIndex]++;
  9064. }
  9065. }
  9066. else if (decPointIndex == 0 && *s == '.')
  9067. {
  9068. ++s;
  9069. decPointIndex = 1;
  9070. if (numSignificantDigits > maxSignificantDigits)
  9071. {
  9072. while (CharacterFunctions::isDigit (*s))
  9073. ++s;
  9074. break;
  9075. }
  9076. }
  9077. else
  9078. {
  9079. break;
  9080. }
  9081. }
  9082. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9083. if (decPointIndex != 0)
  9084. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9085. if ((*s == 'e' || *s == 'E') && digitsFound)
  9086. {
  9087. bool negativeExponent = false;
  9088. switch (*++s)
  9089. {
  9090. case '-': negativeExponent = true; // fall-through..
  9091. case '+': ++s;
  9092. }
  9093. while (CharacterFunctions::isDigit (*s))
  9094. exponent = (exponent * 10) + (*s++ - '0');
  9095. if (negativeExponent)
  9096. exponent = -exponent;
  9097. }
  9098. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9099. if (decPointIndex != 0)
  9100. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9101. return isNegative ? -r : r;
  9102. }
  9103. }
  9104. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9105. {
  9106. return juce_atof <char> (s);
  9107. }
  9108. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9109. {
  9110. return juce_atof <juce_wchar> (s);
  9111. }
  9112. char CharacterFunctions::toUpperCase (const char character) throw()
  9113. {
  9114. return (char) toupper (character);
  9115. }
  9116. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9117. {
  9118. return towupper (character);
  9119. }
  9120. void CharacterFunctions::toUpperCase (char* s) throw()
  9121. {
  9122. #if JUCE_WINDOWS
  9123. strupr (s);
  9124. #else
  9125. while (*s != 0)
  9126. {
  9127. *s = toUpperCase (*s);
  9128. ++s;
  9129. }
  9130. #endif
  9131. }
  9132. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9133. {
  9134. #if JUCE_WINDOWS
  9135. _wcsupr (s);
  9136. #else
  9137. while (*s != 0)
  9138. {
  9139. *s = toUpperCase (*s);
  9140. ++s;
  9141. }
  9142. #endif
  9143. }
  9144. bool CharacterFunctions::isUpperCase (const char character) throw()
  9145. {
  9146. return isupper (character) != 0;
  9147. }
  9148. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9149. {
  9150. #if JUCE_WINDOWS
  9151. return iswupper (character) != 0;
  9152. #else
  9153. return toLowerCase (character) != character;
  9154. #endif
  9155. }
  9156. char CharacterFunctions::toLowerCase (const char character) throw()
  9157. {
  9158. return (char) tolower (character);
  9159. }
  9160. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9161. {
  9162. return towlower (character);
  9163. }
  9164. void CharacterFunctions::toLowerCase (char* s) throw()
  9165. {
  9166. #if JUCE_WINDOWS
  9167. strlwr (s);
  9168. #else
  9169. while (*s != 0)
  9170. {
  9171. *s = toLowerCase (*s);
  9172. ++s;
  9173. }
  9174. #endif
  9175. }
  9176. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9177. {
  9178. #if JUCE_WINDOWS
  9179. _wcslwr (s);
  9180. #else
  9181. while (*s != 0)
  9182. {
  9183. *s = toLowerCase (*s);
  9184. ++s;
  9185. }
  9186. #endif
  9187. }
  9188. bool CharacterFunctions::isLowerCase (const char character) throw()
  9189. {
  9190. return islower (character) != 0;
  9191. }
  9192. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9193. {
  9194. #if JUCE_WINDOWS
  9195. return iswlower (character) != 0;
  9196. #else
  9197. return toUpperCase (character) != character;
  9198. #endif
  9199. }
  9200. bool CharacterFunctions::isWhitespace (const char character) throw()
  9201. {
  9202. return character == ' ' || (character <= 13 && character >= 9);
  9203. }
  9204. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9205. {
  9206. return iswspace (character) != 0;
  9207. }
  9208. bool CharacterFunctions::isDigit (const char character) throw()
  9209. {
  9210. return (character >= '0' && character <= '9');
  9211. }
  9212. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9213. {
  9214. return iswdigit (character) != 0;
  9215. }
  9216. bool CharacterFunctions::isLetter (const char character) throw()
  9217. {
  9218. return (character >= 'a' && character <= 'z')
  9219. || (character >= 'A' && character <= 'Z');
  9220. }
  9221. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9222. {
  9223. return iswalpha (character) != 0;
  9224. }
  9225. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9226. {
  9227. return (character >= 'a' && character <= 'z')
  9228. || (character >= 'A' && character <= 'Z')
  9229. || (character >= '0' && character <= '9');
  9230. }
  9231. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9232. {
  9233. return iswalnum (character) != 0;
  9234. }
  9235. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9236. {
  9237. unsigned int d = digit - '0';
  9238. if (d < (unsigned int) 10)
  9239. return (int) d;
  9240. d += (unsigned int) ('0' - 'a');
  9241. if (d < (unsigned int) 6)
  9242. return (int) d + 10;
  9243. d += (unsigned int) ('a' - 'A');
  9244. if (d < (unsigned int) 6)
  9245. return (int) d + 10;
  9246. return -1;
  9247. }
  9248. #if JUCE_MSVC
  9249. #pragma warning (pop)
  9250. #endif
  9251. END_JUCE_NAMESPACE
  9252. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9253. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9254. BEGIN_JUCE_NAMESPACE
  9255. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9256. {
  9257. loadFromText (fileContents);
  9258. }
  9259. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9260. {
  9261. loadFromText (fileToLoad.loadFileAsString());
  9262. }
  9263. LocalisedStrings::~LocalisedStrings()
  9264. {
  9265. }
  9266. const String LocalisedStrings::translate (const String& text) const
  9267. {
  9268. return translations.getValue (text, text);
  9269. }
  9270. namespace
  9271. {
  9272. CriticalSection currentMappingsLock;
  9273. LocalisedStrings* currentMappings = 0;
  9274. int findCloseQuote (const String& text, int startPos)
  9275. {
  9276. juce_wchar lastChar = 0;
  9277. for (;;)
  9278. {
  9279. const juce_wchar c = text [startPos];
  9280. if (c == 0 || (c == '"' && lastChar != '\\'))
  9281. break;
  9282. lastChar = c;
  9283. ++startPos;
  9284. }
  9285. return startPos;
  9286. }
  9287. const String unescapeString (const String& s)
  9288. {
  9289. return s.replace ("\\\"", "\"")
  9290. .replace ("\\\'", "\'")
  9291. .replace ("\\t", "\t")
  9292. .replace ("\\r", "\r")
  9293. .replace ("\\n", "\n");
  9294. }
  9295. }
  9296. void LocalisedStrings::loadFromText (const String& fileContents)
  9297. {
  9298. StringArray lines;
  9299. lines.addLines (fileContents);
  9300. for (int i = 0; i < lines.size(); ++i)
  9301. {
  9302. String line (lines[i].trim());
  9303. if (line.startsWithChar ('"'))
  9304. {
  9305. int closeQuote = findCloseQuote (line, 1);
  9306. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9307. if (originalText.isNotEmpty())
  9308. {
  9309. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9310. closeQuote = findCloseQuote (line, openingQuote + 1);
  9311. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9312. if (newText.isNotEmpty())
  9313. translations.set (originalText, newText);
  9314. }
  9315. }
  9316. else if (line.startsWithIgnoreCase ("language:"))
  9317. {
  9318. languageName = line.substring (9).trim();
  9319. }
  9320. else if (line.startsWithIgnoreCase ("countries:"))
  9321. {
  9322. countryCodes.addTokens (line.substring (10).trim(), true);
  9323. countryCodes.trim();
  9324. countryCodes.removeEmptyStrings();
  9325. }
  9326. }
  9327. }
  9328. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9329. {
  9330. translations.setIgnoresCase (shouldIgnoreCase);
  9331. }
  9332. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9333. {
  9334. const ScopedLock sl (currentMappingsLock);
  9335. delete currentMappings;
  9336. currentMappings = newTranslations;
  9337. }
  9338. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9339. {
  9340. return currentMappings;
  9341. }
  9342. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9343. {
  9344. const ScopedLock sl (currentMappingsLock);
  9345. if (currentMappings != 0)
  9346. return currentMappings->translate (text);
  9347. return text;
  9348. }
  9349. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9350. {
  9351. return translateWithCurrentMappings (String (text));
  9352. }
  9353. END_JUCE_NAMESPACE
  9354. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9355. /*** Start of inlined file: juce_String.cpp ***/
  9356. #if JUCE_MSVC
  9357. #pragma warning (push)
  9358. #pragma warning (disable: 4514)
  9359. #endif
  9360. #include <locale>
  9361. BEGIN_JUCE_NAMESPACE
  9362. #if JUCE_MSVC
  9363. #pragma warning (pop)
  9364. #endif
  9365. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9366. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9367. #endif
  9368. NewLine newLine;
  9369. class StringHolder
  9370. {
  9371. public:
  9372. StringHolder()
  9373. : refCount (0x3fffffff), allocatedNumChars (0)
  9374. {
  9375. text[0] = 0;
  9376. }
  9377. static juce_wchar* createUninitialised (const size_t numChars)
  9378. {
  9379. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9380. s->refCount.value = 0;
  9381. s->allocatedNumChars = numChars;
  9382. return &(s->text[0]);
  9383. }
  9384. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9385. {
  9386. juce_wchar* const dest = createUninitialised (numChars);
  9387. copyChars (dest, src, numChars);
  9388. return dest;
  9389. }
  9390. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9391. {
  9392. juce_wchar* const dest = createUninitialised (numChars);
  9393. CharacterFunctions::copy (dest, src, (int) numChars);
  9394. dest [numChars] = 0;
  9395. return dest;
  9396. }
  9397. static inline juce_wchar* getEmpty() throw()
  9398. {
  9399. return &(empty.text[0]);
  9400. }
  9401. static void retain (juce_wchar* const text) throw()
  9402. {
  9403. ++(bufferFromText (text)->refCount);
  9404. }
  9405. static inline void release (StringHolder* const b) throw()
  9406. {
  9407. if (--(b->refCount) == -1 && b != &empty)
  9408. delete[] reinterpret_cast <char*> (b);
  9409. }
  9410. static void release (juce_wchar* const text) throw()
  9411. {
  9412. release (bufferFromText (text));
  9413. }
  9414. static juce_wchar* makeUnique (juce_wchar* const text)
  9415. {
  9416. StringHolder* const b = bufferFromText (text);
  9417. if (b->refCount.get() <= 0)
  9418. return text;
  9419. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9420. release (b);
  9421. return newText;
  9422. }
  9423. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9424. {
  9425. StringHolder* const b = bufferFromText (text);
  9426. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9427. return text;
  9428. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9429. copyChars (newText, text, b->allocatedNumChars);
  9430. release (b);
  9431. return newText;
  9432. }
  9433. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9434. {
  9435. return bufferFromText (text)->allocatedNumChars;
  9436. }
  9437. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9438. {
  9439. jassert (src != 0 && dest != 0);
  9440. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9441. dest [numChars] = 0;
  9442. }
  9443. Atomic<int> refCount;
  9444. size_t allocatedNumChars;
  9445. juce_wchar text[1];
  9446. static StringHolder empty;
  9447. private:
  9448. static inline StringHolder* bufferFromText (void* const text) throw()
  9449. {
  9450. // (Can't use offsetof() here because of warnings about this not being a POD)
  9451. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9452. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9453. }
  9454. };
  9455. StringHolder StringHolder::empty;
  9456. const String String::empty;
  9457. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9458. {
  9459. jassert (t[numChars] == 0); // must have a null terminator
  9460. text = StringHolder::createCopy (t, numChars);
  9461. }
  9462. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9463. {
  9464. if (numExtraChars > 0)
  9465. {
  9466. const int oldLen = length();
  9467. const int newTotalLen = oldLen + numExtraChars;
  9468. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9469. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9470. }
  9471. }
  9472. void String::preallocateStorage (const size_t numChars)
  9473. {
  9474. text = StringHolder::makeUniqueWithSize (text, numChars);
  9475. }
  9476. String::String() throw()
  9477. : text (StringHolder::getEmpty())
  9478. {
  9479. }
  9480. String::~String() throw()
  9481. {
  9482. StringHolder::release (text);
  9483. }
  9484. String::String (const String& other) throw()
  9485. : text (other.text)
  9486. {
  9487. StringHolder::retain (text);
  9488. }
  9489. void String::swapWith (String& other) throw()
  9490. {
  9491. swapVariables (text, other.text);
  9492. }
  9493. String& String::operator= (const String& other) throw()
  9494. {
  9495. juce_wchar* const newText = other.text;
  9496. StringHolder::retain (newText);
  9497. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>&> (text).exchange (newText));
  9498. return *this;
  9499. }
  9500. inline String::Preallocation::Preallocation (const size_t numChars_) : numChars (numChars_) {}
  9501. String::String (const Preallocation& preallocationSize)
  9502. : text (StringHolder::createUninitialised (preallocationSize.numChars))
  9503. {
  9504. }
  9505. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9506. {
  9507. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9508. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9509. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9510. }
  9511. String::String (const char* const t)
  9512. {
  9513. if (t != 0 && *t != 0)
  9514. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9515. else
  9516. text = StringHolder::getEmpty();
  9517. }
  9518. String::String (const juce_wchar* const t)
  9519. {
  9520. if (t != 0 && *t != 0)
  9521. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9522. else
  9523. text = StringHolder::getEmpty();
  9524. }
  9525. String::String (const char* const t, const size_t maxChars)
  9526. {
  9527. int i;
  9528. for (i = 0; (size_t) i < maxChars; ++i)
  9529. if (t[i] == 0)
  9530. break;
  9531. if (i > 0)
  9532. text = StringHolder::createCopy (t, i);
  9533. else
  9534. text = StringHolder::getEmpty();
  9535. }
  9536. String::String (const juce_wchar* const t, const size_t maxChars)
  9537. {
  9538. int i;
  9539. for (i = 0; (size_t) i < maxChars; ++i)
  9540. if (t[i] == 0)
  9541. break;
  9542. if (i > 0)
  9543. text = StringHolder::createCopy (t, i);
  9544. else
  9545. text = StringHolder::getEmpty();
  9546. }
  9547. const String String::charToString (const juce_wchar character)
  9548. {
  9549. String result (Preallocation (1));
  9550. result.text[0] = character;
  9551. result.text[1] = 0;
  9552. return result;
  9553. }
  9554. namespace NumberToStringConverters
  9555. {
  9556. // pass in a pointer to the END of a buffer..
  9557. juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9558. {
  9559. *--t = 0;
  9560. int64 v = (n >= 0) ? n : -n;
  9561. do
  9562. {
  9563. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9564. v /= 10;
  9565. } while (v > 0);
  9566. if (n < 0)
  9567. *--t = '-';
  9568. return t;
  9569. }
  9570. juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9571. {
  9572. *--t = 0;
  9573. do
  9574. {
  9575. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9576. v /= 10;
  9577. } while (v > 0);
  9578. return t;
  9579. }
  9580. juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9581. {
  9582. if (n == (int) 0x80000000) // (would cause an overflow)
  9583. return int64ToString (t, n);
  9584. *--t = 0;
  9585. int v = abs (n);
  9586. do
  9587. {
  9588. *--t = (juce_wchar) ('0' + (v % 10));
  9589. v /= 10;
  9590. } while (v > 0);
  9591. if (n < 0)
  9592. *--t = '-';
  9593. return t;
  9594. }
  9595. juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9596. {
  9597. *--t = 0;
  9598. do
  9599. {
  9600. *--t = (juce_wchar) ('0' + (v % 10));
  9601. v /= 10;
  9602. } while (v > 0);
  9603. return t;
  9604. }
  9605. juce_wchar getDecimalPoint()
  9606. {
  9607. #if JUCE_VC7_OR_EARLIER
  9608. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9609. #else
  9610. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9611. #endif
  9612. return dp;
  9613. }
  9614. juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9615. {
  9616. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9617. {
  9618. juce_wchar* const end = buffer + numChars;
  9619. juce_wchar* t = end;
  9620. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9621. *--t = (juce_wchar) 0;
  9622. while (numDecPlaces >= 0 || v > 0)
  9623. {
  9624. if (numDecPlaces == 0)
  9625. *--t = getDecimalPoint();
  9626. *--t = (juce_wchar) ('0' + (v % 10));
  9627. v /= 10;
  9628. --numDecPlaces;
  9629. }
  9630. if (n < 0)
  9631. *--t = '-';
  9632. len = end - t - 1;
  9633. return t;
  9634. }
  9635. else
  9636. {
  9637. #if JUCE_WINDOWS
  9638. #if JUCE_VC7_OR_EARLIER || JUCE_MINGW
  9639. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9640. #else
  9641. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9642. #endif
  9643. #else
  9644. len = swprintf (buffer, numChars, L"%.9g", n);
  9645. #endif
  9646. return buffer;
  9647. }
  9648. }
  9649. }
  9650. String::String (const int number)
  9651. {
  9652. juce_wchar buffer [16];
  9653. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9654. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9655. createInternal (start, end - start - 1);
  9656. }
  9657. String::String (const unsigned int number)
  9658. {
  9659. juce_wchar buffer [16];
  9660. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9661. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9662. createInternal (start, end - start - 1);
  9663. }
  9664. String::String (const short number)
  9665. {
  9666. juce_wchar buffer [16];
  9667. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9668. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9669. createInternal (start, end - start - 1);
  9670. }
  9671. String::String (const unsigned short number)
  9672. {
  9673. juce_wchar buffer [16];
  9674. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9675. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9676. createInternal (start, end - start - 1);
  9677. }
  9678. String::String (const int64 number)
  9679. {
  9680. juce_wchar buffer [32];
  9681. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9682. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9683. createInternal (start, end - start - 1);
  9684. }
  9685. String::String (const uint64 number)
  9686. {
  9687. juce_wchar buffer [32];
  9688. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9689. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9690. createInternal (start, end - start - 1);
  9691. }
  9692. String::String (const float number, const int numberOfDecimalPlaces)
  9693. {
  9694. juce_wchar buffer [48];
  9695. size_t len;
  9696. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9697. createInternal (start, len);
  9698. }
  9699. String::String (const double number, const int numberOfDecimalPlaces)
  9700. {
  9701. juce_wchar buffer [48];
  9702. size_t len;
  9703. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9704. createInternal (start, len);
  9705. }
  9706. int String::length() const throw()
  9707. {
  9708. return CharacterFunctions::length (text);
  9709. }
  9710. int String::hashCode() const throw()
  9711. {
  9712. const juce_wchar* t = text;
  9713. int result = 0;
  9714. while (*t != (juce_wchar) 0)
  9715. result = 31 * result + *t++;
  9716. return result;
  9717. }
  9718. int64 String::hashCode64() const throw()
  9719. {
  9720. const juce_wchar* t = text;
  9721. int64 result = 0;
  9722. while (*t != (juce_wchar) 0)
  9723. result = 101 * result + *t++;
  9724. return result;
  9725. }
  9726. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9727. {
  9728. return string1.compare (string2) == 0;
  9729. }
  9730. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9731. {
  9732. return string1.compare (string2) == 0;
  9733. }
  9734. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9735. {
  9736. return string1.compare (string2) == 0;
  9737. }
  9738. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9739. {
  9740. return string1.compare (string2) != 0;
  9741. }
  9742. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9743. {
  9744. return string1.compare (string2) != 0;
  9745. }
  9746. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9747. {
  9748. return string1.compare (string2) != 0;
  9749. }
  9750. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9751. {
  9752. return string1.compare (string2) > 0;
  9753. }
  9754. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9755. {
  9756. return string1.compare (string2) < 0;
  9757. }
  9758. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9759. {
  9760. return string1.compare (string2) >= 0;
  9761. }
  9762. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9763. {
  9764. return string1.compare (string2) <= 0;
  9765. }
  9766. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9767. {
  9768. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9769. : isEmpty();
  9770. }
  9771. bool String::equalsIgnoreCase (const char* t) const throw()
  9772. {
  9773. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9774. : isEmpty();
  9775. }
  9776. bool String::equalsIgnoreCase (const String& other) const throw()
  9777. {
  9778. return text == other.text
  9779. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9780. }
  9781. int String::compare (const String& other) const throw()
  9782. {
  9783. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9784. }
  9785. int String::compare (const char* other) const throw()
  9786. {
  9787. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9788. }
  9789. int String::compare (const juce_wchar* other) const throw()
  9790. {
  9791. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9792. }
  9793. int String::compareIgnoreCase (const String& other) const throw()
  9794. {
  9795. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9796. }
  9797. int String::compareLexicographically (const String& other) const throw()
  9798. {
  9799. const juce_wchar* s1 = text;
  9800. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9801. ++s1;
  9802. const juce_wchar* s2 = other.text;
  9803. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9804. ++s2;
  9805. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9806. }
  9807. String& String::operator+= (const juce_wchar* const t)
  9808. {
  9809. if (t != 0)
  9810. appendInternal (t, CharacterFunctions::length (t));
  9811. return *this;
  9812. }
  9813. String& String::operator+= (const String& other)
  9814. {
  9815. if (isEmpty())
  9816. operator= (other);
  9817. else
  9818. appendInternal (other.text, other.length());
  9819. return *this;
  9820. }
  9821. String& String::operator+= (const char ch)
  9822. {
  9823. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9824. return operator+= (static_cast <const juce_wchar*> (asString));
  9825. }
  9826. String& String::operator+= (const juce_wchar ch)
  9827. {
  9828. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9829. return operator+= (static_cast <const juce_wchar*> (asString));
  9830. }
  9831. String& String::operator+= (const int number)
  9832. {
  9833. juce_wchar buffer [16];
  9834. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9835. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9836. appendInternal (start, (int) (end - start));
  9837. return *this;
  9838. }
  9839. String& String::operator+= (const unsigned int number)
  9840. {
  9841. juce_wchar buffer [16];
  9842. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9843. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9844. appendInternal (start, (int) (end - start));
  9845. return *this;
  9846. }
  9847. void String::append (const juce_wchar* const other, const int howMany)
  9848. {
  9849. if (howMany > 0)
  9850. {
  9851. int i;
  9852. for (i = 0; i < howMany; ++i)
  9853. if (other[i] == 0)
  9854. break;
  9855. appendInternal (other, i);
  9856. }
  9857. }
  9858. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9859. {
  9860. String s (string1);
  9861. return s += string2;
  9862. }
  9863. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9864. {
  9865. String s (string1);
  9866. return s += string2;
  9867. }
  9868. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9869. {
  9870. return String::charToString (string1) + string2;
  9871. }
  9872. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9873. {
  9874. return String::charToString (string1) + string2;
  9875. }
  9876. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9877. {
  9878. return string1 += string2;
  9879. }
  9880. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9881. {
  9882. return string1 += string2;
  9883. }
  9884. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9885. {
  9886. return string1 += string2;
  9887. }
  9888. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9889. {
  9890. return string1 += string2;
  9891. }
  9892. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9893. {
  9894. return string1 += string2;
  9895. }
  9896. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9897. {
  9898. return string1 += characterToAppend;
  9899. }
  9900. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9901. {
  9902. return string1 += characterToAppend;
  9903. }
  9904. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9905. {
  9906. return string1 += string2;
  9907. }
  9908. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9909. {
  9910. return string1 += string2;
  9911. }
  9912. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9913. {
  9914. return string1 += string2;
  9915. }
  9916. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9917. {
  9918. return string1 += (int) number;
  9919. }
  9920. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9921. {
  9922. return string1 += number;
  9923. }
  9924. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  9925. {
  9926. return string1 += number;
  9927. }
  9928. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9929. {
  9930. return string1 += (int) number;
  9931. }
  9932. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  9933. {
  9934. return string1 += (unsigned int) number;
  9935. }
  9936. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9937. {
  9938. return string1 += String (number);
  9939. }
  9940. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9941. {
  9942. return string1 += String (number);
  9943. }
  9944. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9945. {
  9946. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9947. // if lots of large, persistent strings were to be written to streams).
  9948. const int numBytes = text.getNumBytesAsUTF8();
  9949. HeapBlock<char> temp (numBytes + 1);
  9950. text.copyToUTF8 (temp, numBytes + 1);
  9951. stream.write (temp, numBytes);
  9952. return stream;
  9953. }
  9954. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&)
  9955. {
  9956. return string1 += NewLine::getDefault();
  9957. }
  9958. int String::indexOfChar (const juce_wchar character) const throw()
  9959. {
  9960. const juce_wchar* t = text;
  9961. for (;;)
  9962. {
  9963. if (*t == character)
  9964. return (int) (t - text);
  9965. if (*t++ == 0)
  9966. return -1;
  9967. }
  9968. }
  9969. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9970. {
  9971. for (int i = length(); --i >= 0;)
  9972. if (text[i] == character)
  9973. return i;
  9974. return -1;
  9975. }
  9976. int String::indexOf (const String& t) const throw()
  9977. {
  9978. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9979. return r == 0 ? -1 : (int) (r - text);
  9980. }
  9981. int String::indexOfChar (const int startIndex,
  9982. const juce_wchar character) const throw()
  9983. {
  9984. if (startIndex > 0 && startIndex >= length())
  9985. return -1;
  9986. const juce_wchar* t = text + jmax (0, startIndex);
  9987. for (;;)
  9988. {
  9989. if (*t == character)
  9990. return (int) (t - text);
  9991. if (*t == 0)
  9992. return -1;
  9993. ++t;
  9994. }
  9995. }
  9996. int String::indexOfAnyOf (const String& charactersToLookFor,
  9997. const int startIndex,
  9998. const bool ignoreCase) const throw()
  9999. {
  10000. if (startIndex > 0 && startIndex >= length())
  10001. return -1;
  10002. const juce_wchar* t = text + jmax (0, startIndex);
  10003. while (*t != 0)
  10004. {
  10005. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  10006. return (int) (t - text);
  10007. ++t;
  10008. }
  10009. return -1;
  10010. }
  10011. int String::indexOf (const int startIndex, const String& other) const throw()
  10012. {
  10013. if (startIndex > 0 && startIndex >= length())
  10014. return -1;
  10015. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  10016. return found == 0 ? -1 : (int) (found - text);
  10017. }
  10018. int String::indexOfIgnoreCase (const String& other) const throw()
  10019. {
  10020. if (other.isNotEmpty())
  10021. {
  10022. const int len = other.length();
  10023. const int end = length() - len;
  10024. for (int i = 0; i <= end; ++i)
  10025. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10026. return i;
  10027. }
  10028. return -1;
  10029. }
  10030. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  10031. {
  10032. if (other.isNotEmpty())
  10033. {
  10034. const int len = other.length();
  10035. const int end = length() - len;
  10036. for (int i = jmax (0, startIndex); i <= end; ++i)
  10037. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10038. return i;
  10039. }
  10040. return -1;
  10041. }
  10042. int String::lastIndexOf (const String& other) const throw()
  10043. {
  10044. if (other.isNotEmpty())
  10045. {
  10046. const int len = other.length();
  10047. int i = length() - len;
  10048. if (i >= 0)
  10049. {
  10050. const juce_wchar* n = text + i;
  10051. while (i >= 0)
  10052. {
  10053. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10054. return i;
  10055. --i;
  10056. }
  10057. }
  10058. }
  10059. return -1;
  10060. }
  10061. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10062. {
  10063. if (other.isNotEmpty())
  10064. {
  10065. const int len = other.length();
  10066. int i = length() - len;
  10067. if (i >= 0)
  10068. {
  10069. const juce_wchar* n = text + i;
  10070. while (i >= 0)
  10071. {
  10072. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10073. return i;
  10074. --i;
  10075. }
  10076. }
  10077. }
  10078. return -1;
  10079. }
  10080. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10081. {
  10082. for (int i = length(); --i >= 0;)
  10083. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10084. return i;
  10085. return -1;
  10086. }
  10087. bool String::contains (const String& other) const throw()
  10088. {
  10089. return indexOf (other) >= 0;
  10090. }
  10091. bool String::containsChar (const juce_wchar character) const throw()
  10092. {
  10093. const juce_wchar* t = text;
  10094. for (;;)
  10095. {
  10096. if (*t == 0)
  10097. return false;
  10098. if (*t == character)
  10099. return true;
  10100. ++t;
  10101. }
  10102. }
  10103. bool String::containsIgnoreCase (const String& t) const throw()
  10104. {
  10105. return indexOfIgnoreCase (t) >= 0;
  10106. }
  10107. int String::indexOfWholeWord (const String& word) const throw()
  10108. {
  10109. if (word.isNotEmpty())
  10110. {
  10111. const int wordLen = word.length();
  10112. const int end = length() - wordLen;
  10113. const juce_wchar* t = text;
  10114. for (int i = 0; i <= end; ++i)
  10115. {
  10116. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10117. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10118. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10119. {
  10120. return i;
  10121. }
  10122. ++t;
  10123. }
  10124. }
  10125. return -1;
  10126. }
  10127. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10128. {
  10129. if (word.isNotEmpty())
  10130. {
  10131. const int wordLen = word.length();
  10132. const int end = length() - wordLen;
  10133. const juce_wchar* t = text;
  10134. for (int i = 0; i <= end; ++i)
  10135. {
  10136. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10137. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10138. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10139. {
  10140. return i;
  10141. }
  10142. ++t;
  10143. }
  10144. }
  10145. return -1;
  10146. }
  10147. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10148. {
  10149. return indexOfWholeWord (wordToLookFor) >= 0;
  10150. }
  10151. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10152. {
  10153. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10154. }
  10155. namespace WildCardHelpers
  10156. {
  10157. int indexOfMatch (const juce_wchar* const wildcard,
  10158. const juce_wchar* const test,
  10159. const bool ignoreCase) throw()
  10160. {
  10161. int start = 0;
  10162. while (test [start] != 0)
  10163. {
  10164. int i = 0;
  10165. for (;;)
  10166. {
  10167. const juce_wchar wc = wildcard [i];
  10168. const juce_wchar c = test [i + start];
  10169. if (wc == c
  10170. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10171. || (wc == '?' && c != 0))
  10172. {
  10173. if (wc == 0)
  10174. return start;
  10175. ++i;
  10176. }
  10177. else
  10178. {
  10179. if (wc == '*' && (wildcard [i + 1] == 0
  10180. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10181. {
  10182. return start;
  10183. }
  10184. break;
  10185. }
  10186. }
  10187. ++start;
  10188. }
  10189. return -1;
  10190. }
  10191. }
  10192. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10193. {
  10194. int i = 0;
  10195. for (;;)
  10196. {
  10197. const juce_wchar wc = wildcard.text [i];
  10198. const juce_wchar c = text [i];
  10199. if (wc == c
  10200. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10201. || (wc == '?' && c != 0))
  10202. {
  10203. if (wc == 0)
  10204. return true;
  10205. ++i;
  10206. }
  10207. else
  10208. {
  10209. return wc == '*' && (wildcard [i + 1] == 0
  10210. || WildCardHelpers::indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10211. }
  10212. }
  10213. }
  10214. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10215. {
  10216. const int len = stringToRepeat.length();
  10217. String result (Preallocation (len * numberOfTimesToRepeat + 1));
  10218. juce_wchar* n = result.text;
  10219. *n = 0;
  10220. while (--numberOfTimesToRepeat >= 0)
  10221. {
  10222. StringHolder::copyChars (n, stringToRepeat.text, len);
  10223. n += len;
  10224. }
  10225. return result;
  10226. }
  10227. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10228. {
  10229. jassert (padCharacter != 0);
  10230. const int len = length();
  10231. if (len >= minimumLength || padCharacter == 0)
  10232. return *this;
  10233. String result (Preallocation (minimumLength + 1));
  10234. juce_wchar* n = result.text;
  10235. minimumLength -= len;
  10236. while (--minimumLength >= 0)
  10237. *n++ = padCharacter;
  10238. StringHolder::copyChars (n, text, len);
  10239. return result;
  10240. }
  10241. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10242. {
  10243. jassert (padCharacter != 0);
  10244. const int len = length();
  10245. if (len >= minimumLength || padCharacter == 0)
  10246. return *this;
  10247. String result (*this, (size_t) minimumLength);
  10248. juce_wchar* n = result.text + len;
  10249. minimumLength -= len;
  10250. while (--minimumLength >= 0)
  10251. *n++ = padCharacter;
  10252. *n = 0;
  10253. return result;
  10254. }
  10255. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10256. {
  10257. if (index < 0)
  10258. {
  10259. // a negative index to replace from?
  10260. jassertfalse;
  10261. index = 0;
  10262. }
  10263. if (numCharsToReplace < 0)
  10264. {
  10265. // replacing a negative number of characters?
  10266. numCharsToReplace = 0;
  10267. jassertfalse;
  10268. }
  10269. const int len = length();
  10270. if (index + numCharsToReplace > len)
  10271. {
  10272. if (index > len)
  10273. {
  10274. // replacing beyond the end of the string?
  10275. index = len;
  10276. jassertfalse;
  10277. }
  10278. numCharsToReplace = len - index;
  10279. }
  10280. const int newStringLen = stringToInsert.length();
  10281. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10282. if (newTotalLen <= 0)
  10283. return String::empty;
  10284. String result (Preallocation ((size_t) newTotalLen));
  10285. StringHolder::copyChars (result.text, text, index);
  10286. if (newStringLen > 0)
  10287. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10288. const int endStringLen = newTotalLen - (index + newStringLen);
  10289. if (endStringLen > 0)
  10290. StringHolder::copyChars (result.text + (index + newStringLen),
  10291. text + (index + numCharsToReplace),
  10292. endStringLen);
  10293. return result;
  10294. }
  10295. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10296. {
  10297. const int stringToReplaceLen = stringToReplace.length();
  10298. const int stringToInsertLen = stringToInsert.length();
  10299. int i = 0;
  10300. String result (*this);
  10301. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10302. : result.indexOf (i, stringToReplace))) >= 0)
  10303. {
  10304. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10305. i += stringToInsertLen;
  10306. }
  10307. return result;
  10308. }
  10309. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10310. {
  10311. const int index = indexOfChar (charToReplace);
  10312. if (index < 0)
  10313. return *this;
  10314. String result (*this, size_t());
  10315. juce_wchar* t = result.text + index;
  10316. while (*t != 0)
  10317. {
  10318. if (*t == charToReplace)
  10319. *t = charToInsert;
  10320. ++t;
  10321. }
  10322. return result;
  10323. }
  10324. const String String::replaceCharacters (const String& charactersToReplace,
  10325. const String& charactersToInsertInstead) const
  10326. {
  10327. String result (*this, size_t());
  10328. juce_wchar* t = result.text;
  10329. const int len2 = charactersToInsertInstead.length();
  10330. // the two strings passed in are supposed to be the same length!
  10331. jassert (len2 == charactersToReplace.length());
  10332. while (*t != 0)
  10333. {
  10334. const int index = charactersToReplace.indexOfChar (*t);
  10335. if (isPositiveAndBelow (index, len2))
  10336. *t = charactersToInsertInstead [index];
  10337. ++t;
  10338. }
  10339. return result;
  10340. }
  10341. bool String::startsWith (const String& other) const throw()
  10342. {
  10343. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10344. }
  10345. bool String::startsWithIgnoreCase (const String& other) const throw()
  10346. {
  10347. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10348. }
  10349. bool String::startsWithChar (const juce_wchar character) const throw()
  10350. {
  10351. jassert (character != 0); // strings can't contain a null character!
  10352. return text[0] == character;
  10353. }
  10354. bool String::endsWithChar (const juce_wchar character) const throw()
  10355. {
  10356. jassert (character != 0); // strings can't contain a null character!
  10357. return text[0] != 0
  10358. && text [length() - 1] == character;
  10359. }
  10360. bool String::endsWith (const String& other) const throw()
  10361. {
  10362. const int thisLen = length();
  10363. const int otherLen = other.length();
  10364. return thisLen >= otherLen
  10365. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10366. }
  10367. bool String::endsWithIgnoreCase (const String& other) const throw()
  10368. {
  10369. const int thisLen = length();
  10370. const int otherLen = other.length();
  10371. return thisLen >= otherLen
  10372. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10373. }
  10374. const String String::toUpperCase() const
  10375. {
  10376. String result (*this, size_t());
  10377. CharacterFunctions::toUpperCase (result.text);
  10378. return result;
  10379. }
  10380. const String String::toLowerCase() const
  10381. {
  10382. String result (*this, size_t());
  10383. CharacterFunctions::toLowerCase (result.text);
  10384. return result;
  10385. }
  10386. juce_wchar& String::operator[] (const int index)
  10387. {
  10388. jassert (isPositiveAndNotGreaterThan (index, length()));
  10389. text = StringHolder::makeUnique (text);
  10390. return text [index];
  10391. }
  10392. juce_wchar String::getLastCharacter() const throw()
  10393. {
  10394. return isEmpty() ? juce_wchar() : text [length() - 1];
  10395. }
  10396. const String String::substring (int start, int end) const
  10397. {
  10398. if (start < 0)
  10399. start = 0;
  10400. else if (end <= start)
  10401. return empty;
  10402. int len = 0;
  10403. while (len <= end && text [len] != 0)
  10404. ++len;
  10405. if (end >= len)
  10406. {
  10407. if (start == 0)
  10408. return *this;
  10409. end = len;
  10410. }
  10411. return String (text + start, end - start);
  10412. }
  10413. const String String::substring (const int start) const
  10414. {
  10415. if (start <= 0)
  10416. return *this;
  10417. const int len = length();
  10418. if (start >= len)
  10419. return empty;
  10420. return String (text + start, len - start);
  10421. }
  10422. const String String::dropLastCharacters (const int numberToDrop) const
  10423. {
  10424. return String (text, jmax (0, length() - numberToDrop));
  10425. }
  10426. const String String::getLastCharacters (const int numCharacters) const
  10427. {
  10428. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10429. }
  10430. const String String::fromFirstOccurrenceOf (const String& sub,
  10431. const bool includeSubString,
  10432. const bool ignoreCase) const
  10433. {
  10434. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10435. : indexOf (sub);
  10436. if (i < 0)
  10437. return empty;
  10438. return substring (includeSubString ? i : i + sub.length());
  10439. }
  10440. const String String::fromLastOccurrenceOf (const String& sub,
  10441. const bool includeSubString,
  10442. const bool ignoreCase) const
  10443. {
  10444. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10445. : lastIndexOf (sub);
  10446. if (i < 0)
  10447. return *this;
  10448. return substring (includeSubString ? i : i + sub.length());
  10449. }
  10450. const String String::upToFirstOccurrenceOf (const String& sub,
  10451. const bool includeSubString,
  10452. const bool ignoreCase) const
  10453. {
  10454. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10455. : indexOf (sub);
  10456. if (i < 0)
  10457. return *this;
  10458. return substring (0, includeSubString ? i + sub.length() : i);
  10459. }
  10460. const String String::upToLastOccurrenceOf (const String& sub,
  10461. const bool includeSubString,
  10462. const bool ignoreCase) const
  10463. {
  10464. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10465. : lastIndexOf (sub);
  10466. if (i < 0)
  10467. return *this;
  10468. return substring (0, includeSubString ? i + sub.length() : i);
  10469. }
  10470. bool String::isQuotedString() const
  10471. {
  10472. const String trimmed (trimStart());
  10473. return trimmed[0] == '"'
  10474. || trimmed[0] == '\'';
  10475. }
  10476. const String String::unquoted() const
  10477. {
  10478. String s (*this);
  10479. if (s.text[0] == '"' || s.text[0] == '\'')
  10480. s = s.substring (1);
  10481. const int lastCharIndex = s.length() - 1;
  10482. if (lastCharIndex >= 0
  10483. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10484. s [lastCharIndex] = 0;
  10485. return s;
  10486. }
  10487. const String String::quoted (const juce_wchar quoteCharacter) const
  10488. {
  10489. if (isEmpty())
  10490. return charToString (quoteCharacter) + quoteCharacter;
  10491. String t (*this);
  10492. if (! t.startsWithChar (quoteCharacter))
  10493. t = charToString (quoteCharacter) + t;
  10494. if (! t.endsWithChar (quoteCharacter))
  10495. t += quoteCharacter;
  10496. return t;
  10497. }
  10498. const String String::trim() const
  10499. {
  10500. if (isEmpty())
  10501. return empty;
  10502. int start = 0;
  10503. while (CharacterFunctions::isWhitespace (text [start]))
  10504. ++start;
  10505. const int len = length();
  10506. int end = len - 1;
  10507. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10508. --end;
  10509. ++end;
  10510. if (end <= start)
  10511. return empty;
  10512. else if (start > 0 || end < len)
  10513. return String (text + start, end - start);
  10514. return *this;
  10515. }
  10516. const String String::trimStart() const
  10517. {
  10518. if (isEmpty())
  10519. return empty;
  10520. const juce_wchar* t = text;
  10521. while (CharacterFunctions::isWhitespace (*t))
  10522. ++t;
  10523. if (t == text)
  10524. return *this;
  10525. return String (t);
  10526. }
  10527. const String String::trimEnd() const
  10528. {
  10529. if (isEmpty())
  10530. return empty;
  10531. const juce_wchar* endT = text + (length() - 1);
  10532. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10533. --endT;
  10534. return String (text, (int) (++endT - text));
  10535. }
  10536. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10537. {
  10538. const juce_wchar* t = text;
  10539. while (charactersToTrim.containsChar (*t))
  10540. ++t;
  10541. return t == text ? *this : String (t);
  10542. }
  10543. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10544. {
  10545. if (isEmpty())
  10546. return empty;
  10547. const int len = length();
  10548. const juce_wchar* endT = text + (len - 1);
  10549. int numToRemove = 0;
  10550. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10551. {
  10552. ++numToRemove;
  10553. --endT;
  10554. }
  10555. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10556. }
  10557. const String String::retainCharacters (const String& charactersToRetain) const
  10558. {
  10559. if (isEmpty())
  10560. return empty;
  10561. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10562. juce_wchar* dst = result.text;
  10563. const juce_wchar* src = text;
  10564. while (*src != 0)
  10565. {
  10566. if (charactersToRetain.containsChar (*src))
  10567. *dst++ = *src;
  10568. ++src;
  10569. }
  10570. *dst = 0;
  10571. return result;
  10572. }
  10573. const String String::removeCharacters (const String& charactersToRemove) const
  10574. {
  10575. if (isEmpty())
  10576. return empty;
  10577. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10578. juce_wchar* dst = result.text;
  10579. const juce_wchar* src = text;
  10580. while (*src != 0)
  10581. {
  10582. if (! charactersToRemove.containsChar (*src))
  10583. *dst++ = *src;
  10584. ++src;
  10585. }
  10586. *dst = 0;
  10587. return result;
  10588. }
  10589. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10590. {
  10591. int i = 0;
  10592. for (;;)
  10593. {
  10594. if (! permittedCharacters.containsChar (text[i]))
  10595. break;
  10596. ++i;
  10597. }
  10598. return substring (0, i);
  10599. }
  10600. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10601. {
  10602. const juce_wchar* const t = text;
  10603. int i = 0;
  10604. while (t[i] != 0)
  10605. {
  10606. if (charactersToStopAt.containsChar (t[i]))
  10607. return String (text, i);
  10608. ++i;
  10609. }
  10610. return empty;
  10611. }
  10612. bool String::containsOnly (const String& chars) const throw()
  10613. {
  10614. const juce_wchar* t = text;
  10615. while (*t != 0)
  10616. if (! chars.containsChar (*t++))
  10617. return false;
  10618. return true;
  10619. }
  10620. bool String::containsAnyOf (const String& chars) const throw()
  10621. {
  10622. const juce_wchar* t = text;
  10623. while (*t != 0)
  10624. if (chars.containsChar (*t++))
  10625. return true;
  10626. return false;
  10627. }
  10628. bool String::containsNonWhitespaceChars() const throw()
  10629. {
  10630. const juce_wchar* t = text;
  10631. while (*t != 0)
  10632. if (! CharacterFunctions::isWhitespace (*t++))
  10633. return true;
  10634. return false;
  10635. }
  10636. const String String::formatted (const juce_wchar* const pf, ... )
  10637. {
  10638. jassert (pf != 0);
  10639. va_list args;
  10640. va_start (args, pf);
  10641. size_t bufferSize = 256;
  10642. String result (Preallocation ((size_t) bufferSize));
  10643. result.text[0] = 0;
  10644. for (;;)
  10645. {
  10646. #if JUCE_LINUX && JUCE_64BIT
  10647. va_list tempArgs;
  10648. va_copy (tempArgs, args);
  10649. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10650. va_end (tempArgs);
  10651. #elif JUCE_WINDOWS
  10652. #if JUCE_MSVC
  10653. #pragma warning (push)
  10654. #pragma warning (disable: 4996)
  10655. #endif
  10656. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10657. #if JUCE_MSVC
  10658. #pragma warning (pop)
  10659. #endif
  10660. #else
  10661. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10662. #endif
  10663. if (num > 0)
  10664. return result;
  10665. bufferSize += 256;
  10666. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10667. break; // returns -1 because of an error rather than because it needs more space.
  10668. result.preallocateStorage (bufferSize);
  10669. }
  10670. return empty;
  10671. }
  10672. int String::getIntValue() const throw()
  10673. {
  10674. return CharacterFunctions::getIntValue (text);
  10675. }
  10676. int String::getTrailingIntValue() const throw()
  10677. {
  10678. int n = 0;
  10679. int mult = 1;
  10680. const juce_wchar* t = text + length();
  10681. while (--t >= text)
  10682. {
  10683. const juce_wchar c = *t;
  10684. if (! CharacterFunctions::isDigit (c))
  10685. {
  10686. if (c == '-')
  10687. n = -n;
  10688. break;
  10689. }
  10690. n += mult * (c - '0');
  10691. mult *= 10;
  10692. }
  10693. return n;
  10694. }
  10695. int64 String::getLargeIntValue() const throw()
  10696. {
  10697. return CharacterFunctions::getInt64Value (text);
  10698. }
  10699. float String::getFloatValue() const throw()
  10700. {
  10701. return (float) CharacterFunctions::getDoubleValue (text);
  10702. }
  10703. double String::getDoubleValue() const throw()
  10704. {
  10705. return CharacterFunctions::getDoubleValue (text);
  10706. }
  10707. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10708. const String String::toHexString (const int number)
  10709. {
  10710. juce_wchar buffer[32];
  10711. juce_wchar* const end = buffer + 32;
  10712. juce_wchar* t = end;
  10713. *--t = 0;
  10714. unsigned int v = (unsigned int) number;
  10715. do
  10716. {
  10717. *--t = hexDigits [v & 15];
  10718. v >>= 4;
  10719. } while (v != 0);
  10720. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10721. }
  10722. const String String::toHexString (const int64 number)
  10723. {
  10724. juce_wchar buffer[32];
  10725. juce_wchar* const end = buffer + 32;
  10726. juce_wchar* t = end;
  10727. *--t = 0;
  10728. uint64 v = (uint64) number;
  10729. do
  10730. {
  10731. *--t = hexDigits [(int) (v & 15)];
  10732. v >>= 4;
  10733. } while (v != 0);
  10734. return String (t, (int) (((char*) end) - (char*) t));
  10735. }
  10736. const String String::toHexString (const short number)
  10737. {
  10738. return toHexString ((int) (unsigned short) number);
  10739. }
  10740. const String String::toHexString (const unsigned char* data, const int size, const int groupSize)
  10741. {
  10742. if (size <= 0)
  10743. return empty;
  10744. int numChars = (size * 2) + 2;
  10745. if (groupSize > 0)
  10746. numChars += size / groupSize;
  10747. String s (Preallocation ((size_t) numChars));
  10748. juce_wchar* d = s.text;
  10749. for (int i = 0; i < size; ++i)
  10750. {
  10751. *d++ = hexDigits [(*data) >> 4];
  10752. *d++ = hexDigits [(*data) & 0xf];
  10753. ++data;
  10754. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10755. *d++ = ' ';
  10756. }
  10757. *d = 0;
  10758. return s;
  10759. }
  10760. int String::getHexValue32() const throw()
  10761. {
  10762. int result = 0;
  10763. const juce_wchar* c = text;
  10764. for (;;)
  10765. {
  10766. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10767. if (hexValue >= 0)
  10768. result = (result << 4) | hexValue;
  10769. else if (*c == 0)
  10770. break;
  10771. ++c;
  10772. }
  10773. return result;
  10774. }
  10775. int64 String::getHexValue64() const throw()
  10776. {
  10777. int64 result = 0;
  10778. const juce_wchar* c = text;
  10779. for (;;)
  10780. {
  10781. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10782. if (hexValue >= 0)
  10783. result = (result << 4) | hexValue;
  10784. else if (*c == 0)
  10785. break;
  10786. ++c;
  10787. }
  10788. return result;
  10789. }
  10790. const String String::createStringFromData (const void* const data_, const int size)
  10791. {
  10792. const char* const data = static_cast <const char*> (data_);
  10793. if (size <= 0 || data == 0)
  10794. {
  10795. return empty;
  10796. }
  10797. else if (size < 2)
  10798. {
  10799. return charToString (data[0]);
  10800. }
  10801. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10802. || (data[0] == (char)-1 && data[1] == (char)-2))
  10803. {
  10804. // assume it's 16-bit unicode
  10805. const bool bigEndian = (data[0] == (char)-2);
  10806. const int numChars = size / 2 - 1;
  10807. String result;
  10808. result.preallocateStorage (numChars + 2);
  10809. const uint16* const src = (const uint16*) (data + 2);
  10810. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10811. if (bigEndian)
  10812. {
  10813. for (int i = 0; i < numChars; ++i)
  10814. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10815. }
  10816. else
  10817. {
  10818. for (int i = 0; i < numChars; ++i)
  10819. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10820. }
  10821. dst [numChars] = 0;
  10822. return result;
  10823. }
  10824. else
  10825. {
  10826. return String::fromUTF8 (data, size);
  10827. }
  10828. }
  10829. const char* String::toUTF8() const
  10830. {
  10831. if (isEmpty())
  10832. {
  10833. return reinterpret_cast <const char*> (text);
  10834. }
  10835. else
  10836. {
  10837. const int currentLen = length() + 1;
  10838. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10839. String* const mutableThis = const_cast <String*> (this);
  10840. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10841. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10842. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10843. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10844. #endif
  10845. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10846. return otherCopy;
  10847. }
  10848. }
  10849. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10850. {
  10851. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10852. int num = 0, index = 0;
  10853. for (;;)
  10854. {
  10855. const uint32 c = (uint32) text [index++];
  10856. if (c >= 0x80)
  10857. {
  10858. int numExtraBytes = 1;
  10859. if (c >= 0x800)
  10860. {
  10861. ++numExtraBytes;
  10862. if (c >= 0x10000)
  10863. {
  10864. ++numExtraBytes;
  10865. if (c >= 0x200000)
  10866. {
  10867. ++numExtraBytes;
  10868. if (c >= 0x4000000)
  10869. ++numExtraBytes;
  10870. }
  10871. }
  10872. }
  10873. if (buffer != 0)
  10874. {
  10875. if (num + numExtraBytes >= maxBufferSizeBytes)
  10876. {
  10877. buffer [num++] = 0;
  10878. break;
  10879. }
  10880. else
  10881. {
  10882. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10883. while (--numExtraBytes >= 0)
  10884. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10885. }
  10886. }
  10887. else
  10888. {
  10889. num += numExtraBytes + 1;
  10890. }
  10891. }
  10892. else
  10893. {
  10894. if (buffer != 0)
  10895. {
  10896. if (num + 1 >= maxBufferSizeBytes)
  10897. {
  10898. buffer [num++] = 0;
  10899. break;
  10900. }
  10901. buffer [num] = (uint8) c;
  10902. }
  10903. ++num;
  10904. }
  10905. if (c == 0)
  10906. break;
  10907. }
  10908. return num;
  10909. }
  10910. int String::getNumBytesAsUTF8() const throw()
  10911. {
  10912. int num = 0;
  10913. const juce_wchar* t = text;
  10914. for (;;)
  10915. {
  10916. const uint32 c = (uint32) *t;
  10917. if (c >= 0x80)
  10918. {
  10919. ++num;
  10920. if (c >= 0x800)
  10921. {
  10922. ++num;
  10923. if (c >= 0x10000)
  10924. {
  10925. ++num;
  10926. if (c >= 0x200000)
  10927. {
  10928. ++num;
  10929. if (c >= 0x4000000)
  10930. ++num;
  10931. }
  10932. }
  10933. }
  10934. }
  10935. else if (c == 0)
  10936. break;
  10937. ++num;
  10938. ++t;
  10939. }
  10940. return num;
  10941. }
  10942. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10943. {
  10944. if (buffer == 0)
  10945. return empty;
  10946. if (bufferSizeBytes < 0)
  10947. bufferSizeBytes = std::numeric_limits<int>::max();
  10948. size_t numBytes;
  10949. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10950. if (buffer [numBytes] == 0)
  10951. break;
  10952. String result (Preallocation (numBytes + 1));
  10953. juce_wchar* dest = result.text;
  10954. size_t i = 0;
  10955. while (i < numBytes)
  10956. {
  10957. const char c = buffer [i++];
  10958. if (c < 0)
  10959. {
  10960. unsigned int mask = 0x7f;
  10961. int bit = 0x40;
  10962. int numExtraValues = 0;
  10963. while (bit != 0 && (c & bit) != 0)
  10964. {
  10965. bit >>= 1;
  10966. mask >>= 1;
  10967. ++numExtraValues;
  10968. }
  10969. int n = (mask & (unsigned char) c);
  10970. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10971. {
  10972. const char nextByte = buffer[i];
  10973. if ((nextByte & 0xc0) != 0x80)
  10974. break;
  10975. n <<= 6;
  10976. n |= (nextByte & 0x3f);
  10977. ++i;
  10978. }
  10979. *dest++ = (juce_wchar) n;
  10980. }
  10981. else
  10982. {
  10983. *dest++ = (juce_wchar) c;
  10984. }
  10985. }
  10986. *dest = 0;
  10987. return result;
  10988. }
  10989. const char* String::toCString() const
  10990. {
  10991. if (isEmpty())
  10992. {
  10993. return reinterpret_cast <const char*> (text);
  10994. }
  10995. else
  10996. {
  10997. const int len = length();
  10998. String* const mutableThis = const_cast <String*> (this);
  10999. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  11000. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  11001. CharacterFunctions::copy (otherCopy, text, len);
  11002. otherCopy [len] = 0;
  11003. return otherCopy;
  11004. }
  11005. }
  11006. #if JUCE_MSVC
  11007. #pragma warning (push)
  11008. #pragma warning (disable: 4514 4996)
  11009. #endif
  11010. int String::getNumBytesAsCString() const throw()
  11011. {
  11012. return (int) wcstombs (0, text, 0);
  11013. }
  11014. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  11015. {
  11016. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  11017. if (destBuffer != 0 && numBytes >= 0)
  11018. destBuffer [numBytes] = 0;
  11019. return numBytes;
  11020. }
  11021. #if JUCE_MSVC
  11022. #pragma warning (pop)
  11023. #endif
  11024. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  11025. {
  11026. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  11027. if (destBuffer != 0 && maxCharsToCopy >= 0)
  11028. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  11029. }
  11030. String::Concatenator::Concatenator (String& stringToAppendTo)
  11031. : result (stringToAppendTo),
  11032. nextIndex (stringToAppendTo.length())
  11033. {
  11034. }
  11035. String::Concatenator::~Concatenator()
  11036. {
  11037. }
  11038. void String::Concatenator::append (const String& s)
  11039. {
  11040. const int len = s.length();
  11041. if (len > 0)
  11042. {
  11043. result.preallocateStorage (nextIndex + len);
  11044. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11045. nextIndex += len;
  11046. }
  11047. }
  11048. #if JUCE_UNIT_TESTS
  11049. class StringTests : public UnitTest
  11050. {
  11051. public:
  11052. StringTests() : UnitTest ("String class") {}
  11053. void runTest()
  11054. {
  11055. {
  11056. beginTest ("Basics");
  11057. expect (String().length() == 0);
  11058. expect (String() == String::empty);
  11059. String s1, s2 ("abcd");
  11060. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11061. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11062. expect (s2.length() == 4);
  11063. s1 = "abcd";
  11064. expect (s2 == s1 && s1 == s2);
  11065. expect (s1 == "abcd" && s1 == L"abcd");
  11066. expect (String ("abcd") == String (L"abcd"));
  11067. expect (String ("abcdefg", 4) == L"abcd");
  11068. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11069. expect (String::charToString ('x') == "x");
  11070. expect (String::charToString (0) == String::empty);
  11071. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11072. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11073. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11074. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11075. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11076. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11077. expect (s1.indexOf (String::empty) == 0);
  11078. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11079. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11080. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11081. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11082. }
  11083. {
  11084. beginTest ("Operations");
  11085. String s ("012345678");
  11086. expect (s.hashCode() != 0);
  11087. expect (s.hashCode64() != 0);
  11088. expect (s.hashCode() != (s + s).hashCode());
  11089. expect (s.hashCode64() != (s + s).hashCode64());
  11090. expect (s.compare (String ("012345678")) == 0);
  11091. expect (s.compare (String ("012345679")) < 0);
  11092. expect (s.compare (String ("012345676")) > 0);
  11093. expect (s.substring (2, 3) == String::charToString (s[2]));
  11094. expect (s.substring (0, 1) == String::charToString (s[0]));
  11095. expect (s.getLastCharacter() == s [s.length() - 1]);
  11096. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11097. expect (s.substring (0, 3) == L"012");
  11098. expect (s.substring (0, 100) == s);
  11099. expect (s.substring (-1, 100) == s);
  11100. expect (s.substring (3) == "345678");
  11101. expect (s.indexOf (L"45") == 4);
  11102. expect (String ("444445").indexOf ("45") == 4);
  11103. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11104. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11105. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11106. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11107. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11108. expect (s.indexOfChar (L'4') == 4);
  11109. expect (s + s == "012345678012345678");
  11110. expect (s.startsWith (s));
  11111. expect (s.startsWith (s.substring (0, 4)));
  11112. expect (s.startsWith (s.dropLastCharacters (4)));
  11113. expect (s.endsWith (s.substring (5)));
  11114. expect (s.endsWith (s));
  11115. expect (s.contains (s.substring (3, 6)));
  11116. expect (s.contains (s.substring (3)));
  11117. expect (s.startsWithChar (s[0]));
  11118. expect (s.endsWithChar (s.getLastCharacter()));
  11119. expect (s [s.length()] == 0);
  11120. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11121. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11122. String s2 ("123");
  11123. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11124. s2 += "xyz";
  11125. expect (s2 == "1234567890xyz");
  11126. beginTest ("Numeric conversions");
  11127. expect (String::empty.getIntValue() == 0);
  11128. expect (String::empty.getDoubleValue() == 0.0);
  11129. expect (String::empty.getFloatValue() == 0.0f);
  11130. expect (s.getIntValue() == 12345678);
  11131. expect (s.getLargeIntValue() == (int64) 12345678);
  11132. expect (s.getDoubleValue() == 12345678.0);
  11133. expect (s.getFloatValue() == 12345678.0f);
  11134. expect (String (-1234).getIntValue() == -1234);
  11135. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11136. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11137. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11138. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11139. expect (s.getHexValue32() == 0x12345678);
  11140. expect (s.getHexValue64() == (int64) 0x12345678);
  11141. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11142. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11143. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11144. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11145. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11146. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11147. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11148. beginTest ("Subsections");
  11149. String s3;
  11150. s3 = "abcdeFGHIJ";
  11151. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11152. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11153. expect (s3.containsIgnoreCase (s3.substring (3)));
  11154. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11155. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11156. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11157. expect (s3.containsAnyOf (L"zzzFs"));
  11158. expect (s3.startsWith ("abcd"));
  11159. expect (s3.startsWithIgnoreCase (L"abCD"));
  11160. expect (s3.startsWith (String::empty));
  11161. expect (s3.startsWithChar ('a'));
  11162. expect (s3.endsWith (String ("HIJ")));
  11163. expect (s3.endsWithIgnoreCase (L"Hij"));
  11164. expect (s3.endsWith (String::empty));
  11165. expect (s3.endsWithChar (L'J'));
  11166. expect (s3.indexOf ("HIJ") == 7);
  11167. expect (s3.indexOf (L"HIJK") == -1);
  11168. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11169. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11170. String s4 (s3);
  11171. s4.append (String ("xyz123"), 3);
  11172. expect (s4 == s3 + "xyz");
  11173. expect (String (1234) < String (1235));
  11174. expect (String (1235) > String (1234));
  11175. expect (String (1234) >= String (1234));
  11176. expect (String (1234) <= String (1234));
  11177. expect (String (1235) >= String (1234));
  11178. expect (String (1234) <= String (1235));
  11179. String s5 ("word word2 word3");
  11180. expect (s5.containsWholeWord (String ("word2")));
  11181. expect (s5.indexOfWholeWord ("word2") == 5);
  11182. expect (s5.containsWholeWord (L"word"));
  11183. expect (s5.containsWholeWord ("word3"));
  11184. expect (s5.containsWholeWord (s5));
  11185. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11186. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11187. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11188. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11189. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11190. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11191. expect (s5.containsNonWhitespaceChars());
  11192. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11193. expect (s5.matchesWildcard (L"wor*", false));
  11194. expect (s5.matchesWildcard ("wOr*", true));
  11195. expect (s5.matchesWildcard (L"*word3", true));
  11196. expect (s5.matchesWildcard ("*word?", true));
  11197. expect (s5.matchesWildcard (L"Word*3", true));
  11198. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11199. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11200. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11201. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11202. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11203. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11204. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11205. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11206. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11207. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11208. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11209. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11210. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11211. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11212. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11213. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11214. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11215. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11216. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11217. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11218. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11219. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11220. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11221. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11222. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11223. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11224. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11225. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11226. expect (s5.replace ("Word", "", true) == " 2 3");
  11227. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11228. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11229. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11230. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11231. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11232. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11233. expect (s5.retainCharacters (String::empty).isEmpty());
  11234. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11235. expect (s5.removeCharacters (String::empty) == s5);
  11236. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11237. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11238. expect (! s5.isQuotedString());
  11239. expect (s5.quoted().isQuotedString());
  11240. expect (! s5.quoted().unquoted().isQuotedString());
  11241. expect (! String ("x'").isQuotedString());
  11242. expect (String ("'x").isQuotedString());
  11243. String s6 (" \t xyz \t\r\n");
  11244. expect (s6.trim() == String ("xyz"));
  11245. expect (s6.trim().trim() == "xyz");
  11246. expect (s5.trim() == s5);
  11247. expect (s6.trimStart().trimEnd() == s6.trim());
  11248. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11249. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11250. expect (s6.trimStart() != s6.trimEnd());
  11251. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11252. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11253. }
  11254. {
  11255. beginTest ("UTF8");
  11256. String s ("word word2 word3");
  11257. {
  11258. char buffer [100];
  11259. memset (buffer, 0xff, sizeof (buffer));
  11260. s.copyToUTF8 (buffer, 100);
  11261. expect (String::fromUTF8 (buffer, 100) == s);
  11262. juce_wchar bufferUnicode [100];
  11263. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11264. s.copyToUnicode (bufferUnicode, 100);
  11265. expect (String (bufferUnicode, 100) == s);
  11266. }
  11267. {
  11268. juce_wchar wideBuffer [50];
  11269. zerostruct (wideBuffer);
  11270. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11271. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11272. String wide (wideBuffer);
  11273. expect (wide == (const juce_wchar*) wideBuffer);
  11274. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11275. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11276. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11277. }
  11278. }
  11279. }
  11280. };
  11281. static StringTests stringUnitTests;
  11282. #endif
  11283. END_JUCE_NAMESPACE
  11284. /*** End of inlined file: juce_String.cpp ***/
  11285. /*** Start of inlined file: juce_StringArray.cpp ***/
  11286. BEGIN_JUCE_NAMESPACE
  11287. StringArray::StringArray() throw()
  11288. {
  11289. }
  11290. StringArray::StringArray (const StringArray& other)
  11291. : strings (other.strings)
  11292. {
  11293. }
  11294. StringArray::StringArray (const String& firstValue)
  11295. {
  11296. strings.add (firstValue);
  11297. }
  11298. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11299. const int numberOfStrings)
  11300. {
  11301. for (int i = 0; i < numberOfStrings; ++i)
  11302. strings.add (initialStrings [i]);
  11303. }
  11304. StringArray::StringArray (const char* const* const initialStrings,
  11305. const int numberOfStrings)
  11306. {
  11307. for (int i = 0; i < numberOfStrings; ++i)
  11308. strings.add (initialStrings [i]);
  11309. }
  11310. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11311. {
  11312. int i = 0;
  11313. while (initialStrings[i] != 0)
  11314. strings.add (initialStrings [i++]);
  11315. }
  11316. StringArray::StringArray (const char* const* const initialStrings)
  11317. {
  11318. int i = 0;
  11319. while (initialStrings[i] != 0)
  11320. strings.add (initialStrings [i++]);
  11321. }
  11322. StringArray& StringArray::operator= (const StringArray& other)
  11323. {
  11324. strings = other.strings;
  11325. return *this;
  11326. }
  11327. StringArray::~StringArray()
  11328. {
  11329. }
  11330. bool StringArray::operator== (const StringArray& other) const throw()
  11331. {
  11332. if (other.size() != size())
  11333. return false;
  11334. for (int i = size(); --i >= 0;)
  11335. if (other.strings.getReference(i) != strings.getReference(i))
  11336. return false;
  11337. return true;
  11338. }
  11339. bool StringArray::operator!= (const StringArray& other) const throw()
  11340. {
  11341. return ! operator== (other);
  11342. }
  11343. void StringArray::clear()
  11344. {
  11345. strings.clear();
  11346. }
  11347. const String& StringArray::operator[] (const int index) const throw()
  11348. {
  11349. if (isPositiveAndBelow (index, strings.size()))
  11350. return strings.getReference (index);
  11351. return String::empty;
  11352. }
  11353. String& StringArray::getReference (const int index) throw()
  11354. {
  11355. jassert (isPositiveAndBelow (index, strings.size()));
  11356. return strings.getReference (index);
  11357. }
  11358. void StringArray::add (const String& newString)
  11359. {
  11360. strings.add (newString);
  11361. }
  11362. void StringArray::insert (const int index, const String& newString)
  11363. {
  11364. strings.insert (index, newString);
  11365. }
  11366. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11367. {
  11368. if (! contains (newString, ignoreCase))
  11369. add (newString);
  11370. }
  11371. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11372. {
  11373. if (startIndex < 0)
  11374. {
  11375. jassertfalse;
  11376. startIndex = 0;
  11377. }
  11378. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11379. numElementsToAdd = otherArray.size() - startIndex;
  11380. while (--numElementsToAdd >= 0)
  11381. strings.add (otherArray.strings.getReference (startIndex++));
  11382. }
  11383. void StringArray::set (const int index, const String& newString)
  11384. {
  11385. strings.set (index, newString);
  11386. }
  11387. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11388. {
  11389. if (ignoreCase)
  11390. {
  11391. for (int i = size(); --i >= 0;)
  11392. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11393. return true;
  11394. }
  11395. else
  11396. {
  11397. for (int i = size(); --i >= 0;)
  11398. if (stringToLookFor == strings.getReference(i))
  11399. return true;
  11400. }
  11401. return false;
  11402. }
  11403. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11404. {
  11405. if (i < 0)
  11406. i = 0;
  11407. const int numElements = size();
  11408. if (ignoreCase)
  11409. {
  11410. while (i < numElements)
  11411. {
  11412. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11413. return i;
  11414. ++i;
  11415. }
  11416. }
  11417. else
  11418. {
  11419. while (i < numElements)
  11420. {
  11421. if (stringToLookFor == strings.getReference (i))
  11422. return i;
  11423. ++i;
  11424. }
  11425. }
  11426. return -1;
  11427. }
  11428. void StringArray::remove (const int index)
  11429. {
  11430. strings.remove (index);
  11431. }
  11432. void StringArray::removeString (const String& stringToRemove,
  11433. const bool ignoreCase)
  11434. {
  11435. if (ignoreCase)
  11436. {
  11437. for (int i = size(); --i >= 0;)
  11438. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11439. strings.remove (i);
  11440. }
  11441. else
  11442. {
  11443. for (int i = size(); --i >= 0;)
  11444. if (stringToRemove == strings.getReference (i))
  11445. strings.remove (i);
  11446. }
  11447. }
  11448. void StringArray::removeRange (int startIndex, int numberToRemove)
  11449. {
  11450. strings.removeRange (startIndex, numberToRemove);
  11451. }
  11452. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11453. {
  11454. if (removeWhitespaceStrings)
  11455. {
  11456. for (int i = size(); --i >= 0;)
  11457. if (! strings.getReference(i).containsNonWhitespaceChars())
  11458. strings.remove (i);
  11459. }
  11460. else
  11461. {
  11462. for (int i = size(); --i >= 0;)
  11463. if (strings.getReference(i).isEmpty())
  11464. strings.remove (i);
  11465. }
  11466. }
  11467. void StringArray::trim()
  11468. {
  11469. for (int i = size(); --i >= 0;)
  11470. {
  11471. String& s = strings.getReference(i);
  11472. s = s.trim();
  11473. }
  11474. }
  11475. class InternalStringArrayComparator_CaseSensitive
  11476. {
  11477. public:
  11478. static int compareElements (String& first, String& second) { return first.compare (second); }
  11479. };
  11480. class InternalStringArrayComparator_CaseInsensitive
  11481. {
  11482. public:
  11483. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11484. };
  11485. void StringArray::sort (const bool ignoreCase)
  11486. {
  11487. if (ignoreCase)
  11488. {
  11489. InternalStringArrayComparator_CaseInsensitive comp;
  11490. strings.sort (comp);
  11491. }
  11492. else
  11493. {
  11494. InternalStringArrayComparator_CaseSensitive comp;
  11495. strings.sort (comp);
  11496. }
  11497. }
  11498. void StringArray::move (const int currentIndex, int newIndex) throw()
  11499. {
  11500. strings.move (currentIndex, newIndex);
  11501. }
  11502. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11503. {
  11504. const int last = (numberToJoin < 0) ? size()
  11505. : jmin (size(), start + numberToJoin);
  11506. if (start < 0)
  11507. start = 0;
  11508. if (start >= last)
  11509. return String::empty;
  11510. if (start == last - 1)
  11511. return strings.getReference (start);
  11512. const int separatorLen = separator.length();
  11513. int charsNeeded = separatorLen * (last - start - 1);
  11514. for (int i = start; i < last; ++i)
  11515. charsNeeded += strings.getReference(i).length();
  11516. String result;
  11517. result.preallocateStorage (charsNeeded);
  11518. juce_wchar* dest = result;
  11519. while (start < last)
  11520. {
  11521. const String& s = strings.getReference (start);
  11522. const int len = s.length();
  11523. if (len > 0)
  11524. {
  11525. s.copyToUnicode (dest, len);
  11526. dest += len;
  11527. }
  11528. if (++start < last && separatorLen > 0)
  11529. {
  11530. separator.copyToUnicode (dest, separatorLen);
  11531. dest += separatorLen;
  11532. }
  11533. }
  11534. *dest = 0;
  11535. return result;
  11536. }
  11537. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11538. {
  11539. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11540. }
  11541. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11542. {
  11543. int num = 0;
  11544. if (text.isNotEmpty())
  11545. {
  11546. bool insideQuotes = false;
  11547. juce_wchar currentQuoteChar = 0;
  11548. int i = 0;
  11549. int tokenStart = 0;
  11550. for (;;)
  11551. {
  11552. const juce_wchar c = text[i];
  11553. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11554. if (! isBreak)
  11555. {
  11556. if (quoteCharacters.containsChar (c))
  11557. {
  11558. if (insideQuotes)
  11559. {
  11560. // only break out of quotes-mode if we find a matching quote to the
  11561. // one that we opened with..
  11562. if (currentQuoteChar == c)
  11563. insideQuotes = false;
  11564. }
  11565. else
  11566. {
  11567. insideQuotes = true;
  11568. currentQuoteChar = c;
  11569. }
  11570. }
  11571. }
  11572. else
  11573. {
  11574. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11575. ++num;
  11576. tokenStart = i + 1;
  11577. }
  11578. if (c == 0)
  11579. break;
  11580. ++i;
  11581. }
  11582. }
  11583. return num;
  11584. }
  11585. int StringArray::addLines (const String& sourceText)
  11586. {
  11587. int numLines = 0;
  11588. const juce_wchar* text = sourceText;
  11589. while (*text != 0)
  11590. {
  11591. const juce_wchar* const startOfLine = text;
  11592. while (*text != 0)
  11593. {
  11594. if (*text == '\r')
  11595. {
  11596. ++text;
  11597. if (*text == '\n')
  11598. ++text;
  11599. break;
  11600. }
  11601. if (*text == '\n')
  11602. {
  11603. ++text;
  11604. break;
  11605. }
  11606. ++text;
  11607. }
  11608. const juce_wchar* endOfLine = text;
  11609. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11610. --endOfLine;
  11611. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11612. --endOfLine;
  11613. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11614. ++numLines;
  11615. }
  11616. return numLines;
  11617. }
  11618. void StringArray::removeDuplicates (const bool ignoreCase)
  11619. {
  11620. for (int i = 0; i < size() - 1; ++i)
  11621. {
  11622. const String s (strings.getReference(i));
  11623. int nextIndex = i + 1;
  11624. for (;;)
  11625. {
  11626. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11627. if (nextIndex < 0)
  11628. break;
  11629. strings.remove (nextIndex);
  11630. }
  11631. }
  11632. }
  11633. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11634. const bool appendNumberToFirstInstance,
  11635. const juce_wchar* preNumberString,
  11636. const juce_wchar* postNumberString)
  11637. {
  11638. if (preNumberString == 0)
  11639. preNumberString = L" (";
  11640. if (postNumberString == 0)
  11641. postNumberString = L")";
  11642. for (int i = 0; i < size() - 1; ++i)
  11643. {
  11644. String& s = strings.getReference(i);
  11645. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11646. if (nextIndex >= 0)
  11647. {
  11648. const String original (s);
  11649. int number = 0;
  11650. if (appendNumberToFirstInstance)
  11651. s = original + preNumberString + String (++number) + postNumberString;
  11652. else
  11653. ++number;
  11654. while (nextIndex >= 0)
  11655. {
  11656. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11657. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11658. }
  11659. }
  11660. }
  11661. }
  11662. void StringArray::minimiseStorageOverheads()
  11663. {
  11664. strings.minimiseStorageOverheads();
  11665. }
  11666. END_JUCE_NAMESPACE
  11667. /*** End of inlined file: juce_StringArray.cpp ***/
  11668. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11669. BEGIN_JUCE_NAMESPACE
  11670. StringPairArray::StringPairArray (const bool ignoreCase_)
  11671. : ignoreCase (ignoreCase_)
  11672. {
  11673. }
  11674. StringPairArray::StringPairArray (const StringPairArray& other)
  11675. : keys (other.keys),
  11676. values (other.values),
  11677. ignoreCase (other.ignoreCase)
  11678. {
  11679. }
  11680. StringPairArray::~StringPairArray()
  11681. {
  11682. }
  11683. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11684. {
  11685. keys = other.keys;
  11686. values = other.values;
  11687. return *this;
  11688. }
  11689. bool StringPairArray::operator== (const StringPairArray& other) const
  11690. {
  11691. for (int i = keys.size(); --i >= 0;)
  11692. if (other [keys[i]] != values[i])
  11693. return false;
  11694. return true;
  11695. }
  11696. bool StringPairArray::operator!= (const StringPairArray& other) const
  11697. {
  11698. return ! operator== (other);
  11699. }
  11700. const String& StringPairArray::operator[] (const String& key) const
  11701. {
  11702. return values [keys.indexOf (key, ignoreCase)];
  11703. }
  11704. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11705. {
  11706. const int i = keys.indexOf (key, ignoreCase);
  11707. if (i >= 0)
  11708. return values[i];
  11709. return defaultReturnValue;
  11710. }
  11711. void StringPairArray::set (const String& key, const String& value)
  11712. {
  11713. const int i = keys.indexOf (key, ignoreCase);
  11714. if (i >= 0)
  11715. {
  11716. values.set (i, value);
  11717. }
  11718. else
  11719. {
  11720. keys.add (key);
  11721. values.add (value);
  11722. }
  11723. }
  11724. void StringPairArray::addArray (const StringPairArray& other)
  11725. {
  11726. for (int i = 0; i < other.size(); ++i)
  11727. set (other.keys[i], other.values[i]);
  11728. }
  11729. void StringPairArray::clear()
  11730. {
  11731. keys.clear();
  11732. values.clear();
  11733. }
  11734. void StringPairArray::remove (const String& key)
  11735. {
  11736. remove (keys.indexOf (key, ignoreCase));
  11737. }
  11738. void StringPairArray::remove (const int index)
  11739. {
  11740. keys.remove (index);
  11741. values.remove (index);
  11742. }
  11743. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11744. {
  11745. ignoreCase = shouldIgnoreCase;
  11746. }
  11747. const String StringPairArray::getDescription() const
  11748. {
  11749. String s;
  11750. for (int i = 0; i < keys.size(); ++i)
  11751. {
  11752. s << keys[i] << " = " << values[i];
  11753. if (i < keys.size())
  11754. s << ", ";
  11755. }
  11756. return s;
  11757. }
  11758. void StringPairArray::minimiseStorageOverheads()
  11759. {
  11760. keys.minimiseStorageOverheads();
  11761. values.minimiseStorageOverheads();
  11762. }
  11763. END_JUCE_NAMESPACE
  11764. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11765. /*** Start of inlined file: juce_StringPool.cpp ***/
  11766. BEGIN_JUCE_NAMESPACE
  11767. StringPool::StringPool() throw() {}
  11768. StringPool::~StringPool() {}
  11769. namespace StringPoolHelpers
  11770. {
  11771. template <class StringType>
  11772. const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11773. {
  11774. int start = 0;
  11775. int end = strings.size();
  11776. for (;;)
  11777. {
  11778. if (start >= end)
  11779. {
  11780. jassert (start <= end);
  11781. strings.insert (start, newString);
  11782. return strings.getReference (start);
  11783. }
  11784. else
  11785. {
  11786. const String& startString = strings.getReference (start);
  11787. if (startString == newString)
  11788. return startString;
  11789. const int halfway = (start + end) >> 1;
  11790. if (halfway == start)
  11791. {
  11792. if (startString.compare (newString) < 0)
  11793. ++start;
  11794. strings.insert (start, newString);
  11795. return strings.getReference (start);
  11796. }
  11797. const int comp = strings.getReference (halfway).compare (newString);
  11798. if (comp == 0)
  11799. return strings.getReference (halfway);
  11800. else if (comp < 0)
  11801. start = halfway;
  11802. else
  11803. end = halfway;
  11804. }
  11805. }
  11806. }
  11807. }
  11808. const juce_wchar* StringPool::getPooledString (const String& s)
  11809. {
  11810. if (s.isEmpty())
  11811. return String::empty;
  11812. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11813. }
  11814. const juce_wchar* StringPool::getPooledString (const char* const s)
  11815. {
  11816. if (s == 0 || *s == 0)
  11817. return String::empty;
  11818. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11819. }
  11820. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11821. {
  11822. if (s == 0 || *s == 0)
  11823. return String::empty;
  11824. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11825. }
  11826. int StringPool::size() const throw()
  11827. {
  11828. return strings.size();
  11829. }
  11830. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11831. {
  11832. return strings [index];
  11833. }
  11834. END_JUCE_NAMESPACE
  11835. /*** End of inlined file: juce_StringPool.cpp ***/
  11836. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11837. BEGIN_JUCE_NAMESPACE
  11838. XmlDocument::XmlDocument (const String& documentText)
  11839. : originalText (documentText),
  11840. ignoreEmptyTextElements (true)
  11841. {
  11842. }
  11843. XmlDocument::XmlDocument (const File& file)
  11844. : ignoreEmptyTextElements (true),
  11845. inputSource (new FileInputSource (file))
  11846. {
  11847. }
  11848. XmlDocument::~XmlDocument()
  11849. {
  11850. }
  11851. XmlElement* XmlDocument::parse (const File& file)
  11852. {
  11853. XmlDocument doc (file);
  11854. return doc.getDocumentElement();
  11855. }
  11856. XmlElement* XmlDocument::parse (const String& xmlData)
  11857. {
  11858. XmlDocument doc (xmlData);
  11859. return doc.getDocumentElement();
  11860. }
  11861. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11862. {
  11863. inputSource = newSource;
  11864. }
  11865. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11866. {
  11867. ignoreEmptyTextElements = shouldBeIgnored;
  11868. }
  11869. namespace XmlIdentifierChars
  11870. {
  11871. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11872. {
  11873. return CharacterFunctions::isLetterOrDigit (c)
  11874. || c == '_' || c == '-' || c == ':' || c == '.';
  11875. }
  11876. bool isIdentifierChar (const juce_wchar c) throw()
  11877. {
  11878. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11879. return (c < numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  11880. : isIdentifierCharSlow (c);
  11881. }
  11882. /*static void generateIdentifierCharConstants()
  11883. {
  11884. uint32 n[8];
  11885. zerostruct (n);
  11886. for (int i = 0; i < 256; ++i)
  11887. if (isIdentifierCharSlow (i))
  11888. n[i >> 5] |= (1 << (i & 31));
  11889. String s;
  11890. for (int i = 0; i < 8; ++i)
  11891. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  11892. DBG (s);
  11893. }*/
  11894. }
  11895. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11896. {
  11897. String textToParse (originalText);
  11898. if (textToParse.isEmpty() && inputSource != 0)
  11899. {
  11900. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11901. if (in != 0)
  11902. {
  11903. MemoryOutputStream data;
  11904. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11905. textToParse = data.toString();
  11906. if (! onlyReadOuterDocumentElement)
  11907. originalText = textToParse;
  11908. }
  11909. }
  11910. input = textToParse;
  11911. lastError = String::empty;
  11912. errorOccurred = false;
  11913. outOfData = false;
  11914. needToLoadDTD = true;
  11915. if (textToParse.isEmpty())
  11916. {
  11917. lastError = "not enough input";
  11918. }
  11919. else
  11920. {
  11921. skipHeader();
  11922. if (input != 0)
  11923. {
  11924. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11925. if (! errorOccurred)
  11926. return result.release();
  11927. }
  11928. else
  11929. {
  11930. lastError = "incorrect xml header";
  11931. }
  11932. }
  11933. return 0;
  11934. }
  11935. const String& XmlDocument::getLastParseError() const throw()
  11936. {
  11937. return lastError;
  11938. }
  11939. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11940. {
  11941. lastError = desc;
  11942. errorOccurred = ! carryOn;
  11943. }
  11944. const String XmlDocument::getFileContents (const String& filename) const
  11945. {
  11946. if (inputSource != 0)
  11947. {
  11948. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11949. if (in != 0)
  11950. return in->readEntireStreamAsString();
  11951. }
  11952. return String::empty;
  11953. }
  11954. juce_wchar XmlDocument::readNextChar() throw()
  11955. {
  11956. if (*input != 0)
  11957. return *input++;
  11958. outOfData = true;
  11959. return 0;
  11960. }
  11961. int XmlDocument::findNextTokenLength() throw()
  11962. {
  11963. int len = 0;
  11964. juce_wchar c = *input;
  11965. while (XmlIdentifierChars::isIdentifierChar (c))
  11966. c = input [++len];
  11967. return len;
  11968. }
  11969. void XmlDocument::skipHeader()
  11970. {
  11971. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11972. if (found != 0)
  11973. {
  11974. input = found;
  11975. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11976. if (input == 0)
  11977. return;
  11978. #if JUCE_DEBUG
  11979. const String header (found, input - found);
  11980. const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
  11981. .fromFirstOccurrenceOf ("=", false, false)
  11982. .fromFirstOccurrenceOf ("\"", false, false)
  11983. .upToFirstOccurrenceOf ("\"", false, false).trim());
  11984. /* If you load an XML document with a non-UTF encoding type, it may have been
  11985. loaded wrongly.. Since all the files are read via the normal juce file streams,
  11986. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  11987. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  11988. read, use your own code to convert them to a unicode String, and pass that to the
  11989. XML parser.
  11990. */
  11991. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  11992. #endif
  11993. input += 2;
  11994. }
  11995. skipNextWhiteSpace();
  11996. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  11997. if (docType == 0)
  11998. return;
  11999. input = docType + 9;
  12000. int n = 1;
  12001. while (n > 0)
  12002. {
  12003. const juce_wchar c = readNextChar();
  12004. if (outOfData)
  12005. return;
  12006. if (c == '<')
  12007. ++n;
  12008. else if (c == '>')
  12009. --n;
  12010. }
  12011. docType += 9;
  12012. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  12013. }
  12014. void XmlDocument::skipNextWhiteSpace()
  12015. {
  12016. for (;;)
  12017. {
  12018. juce_wchar c = *input;
  12019. while (CharacterFunctions::isWhitespace (c))
  12020. c = *++input;
  12021. if (c == 0)
  12022. {
  12023. outOfData = true;
  12024. break;
  12025. }
  12026. else if (c == '<')
  12027. {
  12028. if (input[1] == '!'
  12029. && input[2] == '-'
  12030. && input[3] == '-')
  12031. {
  12032. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  12033. if (closeComment == 0)
  12034. {
  12035. outOfData = true;
  12036. break;
  12037. }
  12038. input = closeComment + 3;
  12039. continue;
  12040. }
  12041. else if (input[1] == '?')
  12042. {
  12043. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12044. if (closeBracket == 0)
  12045. {
  12046. outOfData = true;
  12047. break;
  12048. }
  12049. input = closeBracket + 2;
  12050. continue;
  12051. }
  12052. }
  12053. break;
  12054. }
  12055. }
  12056. void XmlDocument::readQuotedString (String& result)
  12057. {
  12058. const juce_wchar quote = readNextChar();
  12059. while (! outOfData)
  12060. {
  12061. const juce_wchar c = readNextChar();
  12062. if (c == quote)
  12063. break;
  12064. if (c == '&')
  12065. {
  12066. --input;
  12067. readEntity (result);
  12068. }
  12069. else
  12070. {
  12071. --input;
  12072. const juce_wchar* const start = input;
  12073. for (;;)
  12074. {
  12075. const juce_wchar character = *input;
  12076. if (character == quote)
  12077. {
  12078. result.append (start, (int) (input - start));
  12079. ++input;
  12080. return;
  12081. }
  12082. else if (character == '&')
  12083. {
  12084. result.append (start, (int) (input - start));
  12085. break;
  12086. }
  12087. else if (character == 0)
  12088. {
  12089. outOfData = true;
  12090. setLastError ("unmatched quotes", false);
  12091. break;
  12092. }
  12093. ++input;
  12094. }
  12095. }
  12096. }
  12097. }
  12098. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12099. {
  12100. XmlElement* node = 0;
  12101. skipNextWhiteSpace();
  12102. if (outOfData)
  12103. return 0;
  12104. input = CharacterFunctions::find (input, JUCE_T("<"));
  12105. if (input != 0)
  12106. {
  12107. ++input;
  12108. int tagLen = findNextTokenLength();
  12109. if (tagLen == 0)
  12110. {
  12111. // no tag name - but allow for a gap after the '<' before giving an error
  12112. skipNextWhiteSpace();
  12113. tagLen = findNextTokenLength();
  12114. if (tagLen == 0)
  12115. {
  12116. setLastError ("tag name missing", false);
  12117. return node;
  12118. }
  12119. }
  12120. node = new XmlElement (String (input, tagLen));
  12121. input += tagLen;
  12122. LinkedListPointer<XmlElement::XmlAttributeNode>::Appender attributeAppender (node->attributes);
  12123. // look for attributes
  12124. for (;;)
  12125. {
  12126. skipNextWhiteSpace();
  12127. const juce_wchar c = *input;
  12128. // empty tag..
  12129. if (c == '/' && input[1] == '>')
  12130. {
  12131. input += 2;
  12132. break;
  12133. }
  12134. // parse the guts of the element..
  12135. if (c == '>')
  12136. {
  12137. ++input;
  12138. if (alsoParseSubElements)
  12139. readChildElements (node);
  12140. break;
  12141. }
  12142. // get an attribute..
  12143. if (XmlIdentifierChars::isIdentifierChar (c))
  12144. {
  12145. const int attNameLen = findNextTokenLength();
  12146. if (attNameLen > 0)
  12147. {
  12148. const juce_wchar* attNameStart = input;
  12149. input += attNameLen;
  12150. skipNextWhiteSpace();
  12151. if (readNextChar() == '=')
  12152. {
  12153. skipNextWhiteSpace();
  12154. const juce_wchar nextChar = *input;
  12155. if (nextChar == '"' || nextChar == '\'')
  12156. {
  12157. XmlElement::XmlAttributeNode* const newAtt
  12158. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12159. String::empty);
  12160. readQuotedString (newAtt->value);
  12161. attributeAppender.append (newAtt);
  12162. continue;
  12163. }
  12164. }
  12165. }
  12166. }
  12167. else
  12168. {
  12169. if (! outOfData)
  12170. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12171. }
  12172. break;
  12173. }
  12174. }
  12175. return node;
  12176. }
  12177. void XmlDocument::readChildElements (XmlElement* parent)
  12178. {
  12179. LinkedListPointer<XmlElement>::Appender childAppender (parent->firstChildElement);
  12180. for (;;)
  12181. {
  12182. const juce_wchar* const preWhitespaceInput = input;
  12183. skipNextWhiteSpace();
  12184. if (outOfData)
  12185. {
  12186. setLastError ("unmatched tags", false);
  12187. break;
  12188. }
  12189. if (*input == '<')
  12190. {
  12191. if (input[1] == '/')
  12192. {
  12193. // our close tag..
  12194. input = CharacterFunctions::find (input, JUCE_T(">"));
  12195. ++input;
  12196. break;
  12197. }
  12198. else if (input[1] == '!'
  12199. && input[2] == '['
  12200. && input[3] == 'C'
  12201. && input[4] == 'D'
  12202. && input[5] == 'A'
  12203. && input[6] == 'T'
  12204. && input[7] == 'A'
  12205. && input[8] == '[')
  12206. {
  12207. input += 9;
  12208. const juce_wchar* const inputStart = input;
  12209. int len = 0;
  12210. for (;;)
  12211. {
  12212. if (*input == 0)
  12213. {
  12214. setLastError ("unterminated CDATA section", false);
  12215. outOfData = true;
  12216. break;
  12217. }
  12218. else if (input[0] == ']'
  12219. && input[1] == ']'
  12220. && input[2] == '>')
  12221. {
  12222. input += 3;
  12223. break;
  12224. }
  12225. ++input;
  12226. ++len;
  12227. }
  12228. childAppender.append (XmlElement::createTextElement (String (inputStart, len)));
  12229. }
  12230. else
  12231. {
  12232. // this is some other element, so parse and add it..
  12233. XmlElement* const n = readNextElement (true);
  12234. if (n != 0)
  12235. childAppender.append (n);
  12236. else
  12237. return;
  12238. }
  12239. }
  12240. else // must be a character block
  12241. {
  12242. input = preWhitespaceInput; // roll back to include the leading whitespace
  12243. String textElementContent;
  12244. for (;;)
  12245. {
  12246. const juce_wchar c = *input;
  12247. if (c == '<')
  12248. break;
  12249. if (c == 0)
  12250. {
  12251. setLastError ("unmatched tags", false);
  12252. outOfData = true;
  12253. return;
  12254. }
  12255. if (c == '&')
  12256. {
  12257. String entity;
  12258. readEntity (entity);
  12259. if (entity.startsWithChar ('<') && entity [1] != 0)
  12260. {
  12261. const juce_wchar* const oldInput = input;
  12262. const bool oldOutOfData = outOfData;
  12263. input = entity;
  12264. outOfData = false;
  12265. for (;;)
  12266. {
  12267. XmlElement* const n = readNextElement (true);
  12268. if (n == 0)
  12269. break;
  12270. childAppender.append (n);
  12271. }
  12272. input = oldInput;
  12273. outOfData = oldOutOfData;
  12274. }
  12275. else
  12276. {
  12277. textElementContent += entity;
  12278. }
  12279. }
  12280. else
  12281. {
  12282. const juce_wchar* start = input;
  12283. int len = 0;
  12284. for (;;)
  12285. {
  12286. const juce_wchar nextChar = *input;
  12287. if (nextChar == '<' || nextChar == '&')
  12288. {
  12289. break;
  12290. }
  12291. else if (nextChar == 0)
  12292. {
  12293. setLastError ("unmatched tags", false);
  12294. outOfData = true;
  12295. return;
  12296. }
  12297. ++input;
  12298. ++len;
  12299. }
  12300. textElementContent.append (start, len);
  12301. }
  12302. }
  12303. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12304. {
  12305. childAppender.append (XmlElement::createTextElement (textElementContent));
  12306. }
  12307. }
  12308. }
  12309. }
  12310. void XmlDocument::readEntity (String& result)
  12311. {
  12312. // skip over the ampersand
  12313. ++input;
  12314. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12315. {
  12316. input += 4;
  12317. result += '&';
  12318. }
  12319. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12320. {
  12321. input += 5;
  12322. result += '"';
  12323. }
  12324. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12325. {
  12326. input += 5;
  12327. result += '\'';
  12328. }
  12329. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12330. {
  12331. input += 3;
  12332. result += '<';
  12333. }
  12334. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12335. {
  12336. input += 3;
  12337. result += '>';
  12338. }
  12339. else if (*input == '#')
  12340. {
  12341. int charCode = 0;
  12342. ++input;
  12343. if (*input == 'x' || *input == 'X')
  12344. {
  12345. ++input;
  12346. int numChars = 0;
  12347. while (input[0] != ';')
  12348. {
  12349. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12350. if (hexValue < 0 || ++numChars > 8)
  12351. {
  12352. setLastError ("illegal escape sequence", true);
  12353. break;
  12354. }
  12355. charCode = (charCode << 4) | hexValue;
  12356. ++input;
  12357. }
  12358. ++input;
  12359. }
  12360. else if (input[0] >= '0' && input[0] <= '9')
  12361. {
  12362. int numChars = 0;
  12363. while (input[0] != ';')
  12364. {
  12365. if (++numChars > 12)
  12366. {
  12367. setLastError ("illegal escape sequence", true);
  12368. break;
  12369. }
  12370. charCode = charCode * 10 + (input[0] - '0');
  12371. ++input;
  12372. }
  12373. ++input;
  12374. }
  12375. else
  12376. {
  12377. setLastError ("illegal escape sequence", true);
  12378. result += '&';
  12379. return;
  12380. }
  12381. result << (juce_wchar) charCode;
  12382. }
  12383. else
  12384. {
  12385. const juce_wchar* const entityNameStart = input;
  12386. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12387. if (closingSemiColon == 0)
  12388. {
  12389. outOfData = true;
  12390. result += '&';
  12391. }
  12392. else
  12393. {
  12394. input = closingSemiColon + 1;
  12395. result += expandExternalEntity (String (entityNameStart,
  12396. (int) (closingSemiColon - entityNameStart)));
  12397. }
  12398. }
  12399. }
  12400. const String XmlDocument::expandEntity (const String& ent)
  12401. {
  12402. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12403. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12404. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12405. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12406. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12407. if (ent[0] == '#')
  12408. {
  12409. if (ent[1] == 'x' || ent[1] == 'X')
  12410. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12411. if (ent[1] >= '0' && ent[1] <= '9')
  12412. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12413. setLastError ("illegal escape sequence", false);
  12414. return String::charToString ('&');
  12415. }
  12416. return expandExternalEntity (ent);
  12417. }
  12418. const String XmlDocument::expandExternalEntity (const String& entity)
  12419. {
  12420. if (needToLoadDTD)
  12421. {
  12422. if (dtdText.isNotEmpty())
  12423. {
  12424. dtdText = dtdText.trimCharactersAtEnd (">");
  12425. tokenisedDTD.addTokens (dtdText, true);
  12426. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12427. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12428. {
  12429. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12430. tokenisedDTD.clear();
  12431. tokenisedDTD.addTokens (getFileContents (fn), true);
  12432. }
  12433. else
  12434. {
  12435. tokenisedDTD.clear();
  12436. const int openBracket = dtdText.indexOfChar ('[');
  12437. if (openBracket > 0)
  12438. {
  12439. const int closeBracket = dtdText.lastIndexOfChar (']');
  12440. if (closeBracket > openBracket)
  12441. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12442. closeBracket), true);
  12443. }
  12444. }
  12445. for (int i = tokenisedDTD.size(); --i >= 0;)
  12446. {
  12447. if (tokenisedDTD[i].startsWithChar ('%')
  12448. && tokenisedDTD[i].endsWithChar (';'))
  12449. {
  12450. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12451. StringArray newToks;
  12452. newToks.addTokens (parsed, true);
  12453. tokenisedDTD.remove (i);
  12454. for (int j = newToks.size(); --j >= 0;)
  12455. tokenisedDTD.insert (i, newToks[j]);
  12456. }
  12457. }
  12458. }
  12459. needToLoadDTD = false;
  12460. }
  12461. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12462. {
  12463. if (tokenisedDTD[i] == entity)
  12464. {
  12465. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12466. {
  12467. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12468. // check for sub-entities..
  12469. int ampersand = ent.indexOfChar ('&');
  12470. while (ampersand >= 0)
  12471. {
  12472. const int semiColon = ent.indexOf (i + 1, ";");
  12473. if (semiColon < 0)
  12474. {
  12475. setLastError ("entity without terminating semi-colon", false);
  12476. break;
  12477. }
  12478. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12479. ent = ent.substring (0, ampersand)
  12480. + resolved
  12481. + ent.substring (semiColon + 1);
  12482. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12483. }
  12484. return ent;
  12485. }
  12486. }
  12487. }
  12488. setLastError ("unknown entity", true);
  12489. return entity;
  12490. }
  12491. const String XmlDocument::getParameterEntity (const String& entity)
  12492. {
  12493. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12494. {
  12495. if (tokenisedDTD[i] == entity
  12496. && tokenisedDTD [i - 1] == "%"
  12497. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12498. {
  12499. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12500. if (ent.equalsIgnoreCase ("system"))
  12501. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12502. else
  12503. return ent.trim().unquoted();
  12504. }
  12505. }
  12506. return entity;
  12507. }
  12508. END_JUCE_NAMESPACE
  12509. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12510. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12511. BEGIN_JUCE_NAMESPACE
  12512. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12513. : name (other.name),
  12514. value (other.value)
  12515. {
  12516. }
  12517. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12518. : name (name_),
  12519. value (value_)
  12520. {
  12521. #if JUCE_DEBUG
  12522. // this checks whether the attribute name string contains any illegals characters..
  12523. for (const juce_wchar* t = name; *t != 0; ++t)
  12524. jassert (CharacterFunctions::isLetterOrDigit (*t) || *t == '_' || *t == '-' || *t == ':');
  12525. #endif
  12526. }
  12527. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12528. {
  12529. return name.equalsIgnoreCase (nameToMatch);
  12530. }
  12531. XmlElement::XmlElement (const String& tagName_) throw()
  12532. : tagName (tagName_)
  12533. {
  12534. // the tag name mustn't be empty, or it'll look like a text element!
  12535. jassert (tagName_.containsNonWhitespaceChars())
  12536. // The tag can't contain spaces or other characters that would create invalid XML!
  12537. jassert (! tagName_.containsAnyOf (" <>/&"));
  12538. }
  12539. XmlElement::XmlElement (int /*dummy*/) throw()
  12540. {
  12541. }
  12542. XmlElement::XmlElement (const XmlElement& other)
  12543. : tagName (other.tagName)
  12544. {
  12545. copyChildrenAndAttributesFrom (other);
  12546. }
  12547. XmlElement& XmlElement::operator= (const XmlElement& other)
  12548. {
  12549. if (this != &other)
  12550. {
  12551. removeAllAttributes();
  12552. deleteAllChildElements();
  12553. tagName = other.tagName;
  12554. copyChildrenAndAttributesFrom (other);
  12555. }
  12556. return *this;
  12557. }
  12558. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12559. {
  12560. jassert (firstChildElement.get() == 0);
  12561. firstChildElement.addCopyOfList (other.firstChildElement);
  12562. jassert (attributes.get() == 0);
  12563. attributes.addCopyOfList (other.attributes);
  12564. }
  12565. XmlElement::~XmlElement() throw()
  12566. {
  12567. firstChildElement.deleteAll();
  12568. attributes.deleteAll();
  12569. }
  12570. namespace XmlOutputFunctions
  12571. {
  12572. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12573. {
  12574. if ((character >= 'a' && character <= 'z')
  12575. || (character >= 'A' && character <= 'Z')
  12576. || (character >= '0' && character <= '9'))
  12577. return true;
  12578. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12579. do
  12580. {
  12581. if (((juce_wchar) (uint8) *t) == character)
  12582. return true;
  12583. }
  12584. while (*++t != 0);
  12585. return false;
  12586. }
  12587. void generateLegalCharConstants()
  12588. {
  12589. uint8 n[32];
  12590. zerostruct (n);
  12591. for (int i = 0; i < 256; ++i)
  12592. if (isLegalXmlCharSlow (i))
  12593. n[i >> 3] |= (1 << (i & 7));
  12594. String s;
  12595. for (int i = 0; i < 32; ++i)
  12596. s << (int) n[i] << ", ";
  12597. DBG (s);
  12598. }*/
  12599. bool isLegalXmlChar (const uint32 c) throw()
  12600. {
  12601. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12602. return c < sizeof (legalChars) * 8
  12603. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12604. }
  12605. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12606. {
  12607. const juce_wchar* t = text;
  12608. for (;;)
  12609. {
  12610. const juce_wchar character = *t++;
  12611. if (character == 0)
  12612. break;
  12613. if (isLegalXmlChar ((uint32) character))
  12614. {
  12615. outputStream << (char) character;
  12616. }
  12617. else
  12618. {
  12619. switch (character)
  12620. {
  12621. case '&': outputStream << "&amp;"; break;
  12622. case '"': outputStream << "&quot;"; break;
  12623. case '>': outputStream << "&gt;"; break;
  12624. case '<': outputStream << "&lt;"; break;
  12625. case '\n':
  12626. case '\r':
  12627. if (! changeNewLines)
  12628. {
  12629. outputStream << (char) character;
  12630. break;
  12631. }
  12632. // Note: deliberate fall-through here!
  12633. default:
  12634. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12635. break;
  12636. }
  12637. }
  12638. }
  12639. }
  12640. void writeSpaces (OutputStream& out, int numSpaces)
  12641. {
  12642. if (numSpaces > 0)
  12643. {
  12644. const char blanks[] = " ";
  12645. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12646. while (numSpaces > blankSize)
  12647. {
  12648. out.write (blanks, blankSize);
  12649. numSpaces -= blankSize;
  12650. }
  12651. out.write (blanks, numSpaces);
  12652. }
  12653. }
  12654. }
  12655. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12656. const int indentationLevel,
  12657. const int lineWrapLength) const
  12658. {
  12659. using namespace XmlOutputFunctions;
  12660. writeSpaces (outputStream, indentationLevel);
  12661. if (! isTextElement())
  12662. {
  12663. outputStream.writeByte ('<');
  12664. outputStream << tagName;
  12665. {
  12666. const int attIndent = indentationLevel + tagName.length() + 1;
  12667. int lineLen = 0;
  12668. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12669. {
  12670. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12671. {
  12672. outputStream << newLine;
  12673. writeSpaces (outputStream, attIndent);
  12674. lineLen = 0;
  12675. }
  12676. const int64 startPos = outputStream.getPosition();
  12677. outputStream.writeByte (' ');
  12678. outputStream << att->name;
  12679. outputStream.write ("=\"", 2);
  12680. escapeIllegalXmlChars (outputStream, att->value, true);
  12681. outputStream.writeByte ('"');
  12682. lineLen += (int) (outputStream.getPosition() - startPos);
  12683. }
  12684. }
  12685. if (firstChildElement != 0)
  12686. {
  12687. outputStream.writeByte ('>');
  12688. XmlElement* child = firstChildElement;
  12689. bool lastWasTextNode = false;
  12690. while (child != 0)
  12691. {
  12692. if (child->isTextElement())
  12693. {
  12694. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12695. lastWasTextNode = true;
  12696. }
  12697. else
  12698. {
  12699. if (indentationLevel >= 0 && ! lastWasTextNode)
  12700. outputStream << newLine;
  12701. child->writeElementAsText (outputStream,
  12702. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12703. lastWasTextNode = false;
  12704. }
  12705. child = child->getNextElement();
  12706. }
  12707. if (indentationLevel >= 0 && ! lastWasTextNode)
  12708. {
  12709. outputStream << newLine;
  12710. writeSpaces (outputStream, indentationLevel);
  12711. }
  12712. outputStream.write ("</", 2);
  12713. outputStream << tagName;
  12714. outputStream.writeByte ('>');
  12715. }
  12716. else
  12717. {
  12718. outputStream.write ("/>", 2);
  12719. }
  12720. }
  12721. else
  12722. {
  12723. escapeIllegalXmlChars (outputStream, getText(), false);
  12724. }
  12725. }
  12726. const String XmlElement::createDocument (const String& dtdToUse,
  12727. const bool allOnOneLine,
  12728. const bool includeXmlHeader,
  12729. const String& encodingType,
  12730. const int lineWrapLength) const
  12731. {
  12732. MemoryOutputStream mem (2048);
  12733. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12734. return mem.toUTF8();
  12735. }
  12736. void XmlElement::writeToStream (OutputStream& output,
  12737. const String& dtdToUse,
  12738. const bool allOnOneLine,
  12739. const bool includeXmlHeader,
  12740. const String& encodingType,
  12741. const int lineWrapLength) const
  12742. {
  12743. using namespace XmlOutputFunctions;
  12744. if (includeXmlHeader)
  12745. {
  12746. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12747. if (allOnOneLine)
  12748. output.writeByte (' ');
  12749. else
  12750. output << newLine << newLine;
  12751. }
  12752. if (dtdToUse.isNotEmpty())
  12753. {
  12754. output << dtdToUse;
  12755. if (allOnOneLine)
  12756. output.writeByte (' ');
  12757. else
  12758. output << newLine;
  12759. }
  12760. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12761. if (! allOnOneLine)
  12762. output << newLine;
  12763. }
  12764. bool XmlElement::writeToFile (const File& file,
  12765. const String& dtdToUse,
  12766. const String& encodingType,
  12767. const int lineWrapLength) const
  12768. {
  12769. if (file.hasWriteAccess())
  12770. {
  12771. TemporaryFile tempFile (file);
  12772. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12773. if (out != 0)
  12774. {
  12775. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12776. out = 0;
  12777. return tempFile.overwriteTargetFileWithTemporary();
  12778. }
  12779. }
  12780. return false;
  12781. }
  12782. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12783. {
  12784. #if JUCE_DEBUG
  12785. // if debugging, check that the case is actually the same, because
  12786. // valid xml is case-sensitive, and although this lets it pass, it's
  12787. // better not to..
  12788. if (tagName.equalsIgnoreCase (tagNameWanted))
  12789. {
  12790. jassert (tagName == tagNameWanted);
  12791. return true;
  12792. }
  12793. else
  12794. {
  12795. return false;
  12796. }
  12797. #else
  12798. return tagName.equalsIgnoreCase (tagNameWanted);
  12799. #endif
  12800. }
  12801. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12802. {
  12803. XmlElement* e = nextListItem;
  12804. while (e != 0 && ! e->hasTagName (requiredTagName))
  12805. e = e->nextListItem;
  12806. return e;
  12807. }
  12808. int XmlElement::getNumAttributes() const throw()
  12809. {
  12810. return attributes.size();
  12811. }
  12812. const String& XmlElement::getAttributeName (const int index) const throw()
  12813. {
  12814. const XmlAttributeNode* const att = attributes [index];
  12815. return att != 0 ? att->name : String::empty;
  12816. }
  12817. const String& XmlElement::getAttributeValue (const int index) const throw()
  12818. {
  12819. const XmlAttributeNode* const att = attributes [index];
  12820. return att != 0 ? att->value : String::empty;
  12821. }
  12822. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12823. {
  12824. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12825. if (att->hasName (attributeName))
  12826. return true;
  12827. return false;
  12828. }
  12829. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12830. {
  12831. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12832. if (att->hasName (attributeName))
  12833. return att->value;
  12834. return String::empty;
  12835. }
  12836. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12837. {
  12838. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12839. if (att->hasName (attributeName))
  12840. return att->value;
  12841. return defaultReturnValue;
  12842. }
  12843. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12844. {
  12845. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12846. if (att->hasName (attributeName))
  12847. return att->value.getIntValue();
  12848. return defaultReturnValue;
  12849. }
  12850. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12851. {
  12852. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12853. if (att->hasName (attributeName))
  12854. return att->value.getDoubleValue();
  12855. return defaultReturnValue;
  12856. }
  12857. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12858. {
  12859. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12860. {
  12861. if (att->hasName (attributeName))
  12862. {
  12863. juce_wchar firstChar = att->value[0];
  12864. if (CharacterFunctions::isWhitespace (firstChar))
  12865. firstChar = att->value.trimStart() [0];
  12866. return firstChar == '1'
  12867. || firstChar == 't'
  12868. || firstChar == 'y'
  12869. || firstChar == 'T'
  12870. || firstChar == 'Y';
  12871. }
  12872. }
  12873. return defaultReturnValue;
  12874. }
  12875. bool XmlElement::compareAttribute (const String& attributeName,
  12876. const String& stringToCompareAgainst,
  12877. const bool ignoreCase) const throw()
  12878. {
  12879. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12880. if (att->hasName (attributeName))
  12881. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  12882. : att->value == stringToCompareAgainst;
  12883. return false;
  12884. }
  12885. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12886. {
  12887. if (attributes == 0)
  12888. {
  12889. attributes = new XmlAttributeNode (attributeName, value);
  12890. }
  12891. else
  12892. {
  12893. XmlAttributeNode* att = attributes;
  12894. for (;;)
  12895. {
  12896. if (att->hasName (attributeName))
  12897. {
  12898. att->value = value;
  12899. break;
  12900. }
  12901. else if (att->nextListItem == 0)
  12902. {
  12903. att->nextListItem = new XmlAttributeNode (attributeName, value);
  12904. break;
  12905. }
  12906. att = att->nextListItem;
  12907. }
  12908. }
  12909. }
  12910. void XmlElement::setAttribute (const String& attributeName, const int number)
  12911. {
  12912. setAttribute (attributeName, String (number));
  12913. }
  12914. void XmlElement::setAttribute (const String& attributeName, const double number)
  12915. {
  12916. setAttribute (attributeName, String (number));
  12917. }
  12918. void XmlElement::removeAttribute (const String& attributeName) throw()
  12919. {
  12920. LinkedListPointer<XmlAttributeNode>* att = &attributes;
  12921. while (att->get() != 0)
  12922. {
  12923. if (att->get()->hasName (attributeName))
  12924. {
  12925. delete att->removeNext();
  12926. break;
  12927. }
  12928. att = &(att->get()->nextListItem);
  12929. }
  12930. }
  12931. void XmlElement::removeAllAttributes() throw()
  12932. {
  12933. attributes.deleteAll();
  12934. }
  12935. int XmlElement::getNumChildElements() const throw()
  12936. {
  12937. return firstChildElement.size();
  12938. }
  12939. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12940. {
  12941. return firstChildElement [index].get();
  12942. }
  12943. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12944. {
  12945. XmlElement* child = firstChildElement;
  12946. while (child != 0)
  12947. {
  12948. if (child->hasTagName (childName))
  12949. break;
  12950. child = child->nextListItem;
  12951. }
  12952. return child;
  12953. }
  12954. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12955. {
  12956. if (newNode != 0)
  12957. firstChildElement.append (newNode);
  12958. }
  12959. void XmlElement::insertChildElement (XmlElement* const newNode,
  12960. int indexToInsertAt) throw()
  12961. {
  12962. if (newNode != 0)
  12963. {
  12964. removeChildElement (newNode, false);
  12965. firstChildElement.insertAtIndex (indexToInsertAt, newNode);
  12966. }
  12967. }
  12968. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  12969. {
  12970. XmlElement* const newElement = new XmlElement (childTagName);
  12971. addChildElement (newElement);
  12972. return newElement;
  12973. }
  12974. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12975. XmlElement* const newNode) throw()
  12976. {
  12977. if (newNode != 0)
  12978. {
  12979. LinkedListPointer<XmlElement>* const p = firstChildElement.findPointerTo (currentChildElement);
  12980. if (p != 0)
  12981. {
  12982. if (currentChildElement != newNode)
  12983. delete p->replaceNext (newNode);
  12984. return true;
  12985. }
  12986. }
  12987. return false;
  12988. }
  12989. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12990. const bool shouldDeleteTheChild) throw()
  12991. {
  12992. if (childToRemove != 0)
  12993. {
  12994. firstChildElement.remove (childToRemove);
  12995. if (shouldDeleteTheChild)
  12996. delete childToRemove;
  12997. }
  12998. }
  12999. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13000. const bool ignoreOrderOfAttributes) const throw()
  13001. {
  13002. if (this != other)
  13003. {
  13004. if (other == 0 || tagName != other->tagName)
  13005. return false;
  13006. if (ignoreOrderOfAttributes)
  13007. {
  13008. int totalAtts = 0;
  13009. const XmlAttributeNode* att = attributes;
  13010. while (att != 0)
  13011. {
  13012. if (! other->compareAttribute (att->name, att->value))
  13013. return false;
  13014. att = att->nextListItem;
  13015. ++totalAtts;
  13016. }
  13017. if (totalAtts != other->getNumAttributes())
  13018. return false;
  13019. }
  13020. else
  13021. {
  13022. const XmlAttributeNode* thisAtt = attributes;
  13023. const XmlAttributeNode* otherAtt = other->attributes;
  13024. for (;;)
  13025. {
  13026. if (thisAtt == 0 || otherAtt == 0)
  13027. {
  13028. if (thisAtt == otherAtt) // both 0, so it's a match
  13029. break;
  13030. return false;
  13031. }
  13032. if (thisAtt->name != otherAtt->name
  13033. || thisAtt->value != otherAtt->value)
  13034. {
  13035. return false;
  13036. }
  13037. thisAtt = thisAtt->nextListItem;
  13038. otherAtt = otherAtt->nextListItem;
  13039. }
  13040. }
  13041. const XmlElement* thisChild = firstChildElement;
  13042. const XmlElement* otherChild = other->firstChildElement;
  13043. for (;;)
  13044. {
  13045. if (thisChild == 0 || otherChild == 0)
  13046. {
  13047. if (thisChild == otherChild) // both 0, so it's a match
  13048. break;
  13049. return false;
  13050. }
  13051. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13052. return false;
  13053. thisChild = thisChild->nextListItem;
  13054. otherChild = otherChild->nextListItem;
  13055. }
  13056. }
  13057. return true;
  13058. }
  13059. void XmlElement::deleteAllChildElements() throw()
  13060. {
  13061. firstChildElement.deleteAll();
  13062. }
  13063. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13064. {
  13065. XmlElement* child = firstChildElement;
  13066. while (child != 0)
  13067. {
  13068. XmlElement* const nextChild = child->nextListItem;
  13069. if (child->hasTagName (name))
  13070. removeChildElement (child, true);
  13071. child = nextChild;
  13072. }
  13073. }
  13074. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13075. {
  13076. return firstChildElement.contains (possibleChild);
  13077. }
  13078. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13079. {
  13080. if (this == elementToLookFor || elementToLookFor == 0)
  13081. return 0;
  13082. XmlElement* child = firstChildElement;
  13083. while (child != 0)
  13084. {
  13085. if (elementToLookFor == child)
  13086. return this;
  13087. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13088. if (found != 0)
  13089. return found;
  13090. child = child->nextListItem;
  13091. }
  13092. return 0;
  13093. }
  13094. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13095. {
  13096. firstChildElement.copyToArray (elems);
  13097. }
  13098. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13099. {
  13100. XmlElement* e = firstChildElement = elems[0];
  13101. for (int i = 1; i < num; ++i)
  13102. {
  13103. e->nextListItem = elems[i];
  13104. e = e->nextListItem;
  13105. }
  13106. e->nextListItem = 0;
  13107. }
  13108. bool XmlElement::isTextElement() const throw()
  13109. {
  13110. return tagName.isEmpty();
  13111. }
  13112. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13113. const String& XmlElement::getText() const throw()
  13114. {
  13115. jassert (isTextElement()); // you're trying to get the text from an element that
  13116. // isn't actually a text element.. If this contains text sub-nodes, you
  13117. // probably want to use getAllSubText instead.
  13118. return getStringAttribute (juce_xmltextContentAttributeName);
  13119. }
  13120. void XmlElement::setText (const String& newText)
  13121. {
  13122. if (isTextElement())
  13123. setAttribute (juce_xmltextContentAttributeName, newText);
  13124. else
  13125. jassertfalse; // you can only change the text in a text element, not a normal one.
  13126. }
  13127. const String XmlElement::getAllSubText() const
  13128. {
  13129. if (isTextElement())
  13130. return getText();
  13131. String result;
  13132. String::Concatenator concatenator (result);
  13133. const XmlElement* child = firstChildElement;
  13134. while (child != 0)
  13135. {
  13136. concatenator.append (child->getAllSubText());
  13137. child = child->nextListItem;
  13138. }
  13139. return result;
  13140. }
  13141. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13142. const String& defaultReturnValue) const
  13143. {
  13144. const XmlElement* const child = getChildByName (childTagName);
  13145. if (child != 0)
  13146. return child->getAllSubText();
  13147. return defaultReturnValue;
  13148. }
  13149. XmlElement* XmlElement::createTextElement (const String& text)
  13150. {
  13151. XmlElement* const e = new XmlElement ((int) 0);
  13152. e->setAttribute (juce_xmltextContentAttributeName, text);
  13153. return e;
  13154. }
  13155. void XmlElement::addTextElement (const String& text)
  13156. {
  13157. addChildElement (createTextElement (text));
  13158. }
  13159. void XmlElement::deleteAllTextElements() throw()
  13160. {
  13161. XmlElement* child = firstChildElement;
  13162. while (child != 0)
  13163. {
  13164. XmlElement* const next = child->nextListItem;
  13165. if (child->isTextElement())
  13166. removeChildElement (child, true);
  13167. child = next;
  13168. }
  13169. }
  13170. END_JUCE_NAMESPACE
  13171. /*** End of inlined file: juce_XmlElement.cpp ***/
  13172. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13173. BEGIN_JUCE_NAMESPACE
  13174. ReadWriteLock::ReadWriteLock() throw()
  13175. : numWaitingWriters (0),
  13176. numWriters (0),
  13177. writerThreadId (0)
  13178. {
  13179. }
  13180. ReadWriteLock::~ReadWriteLock() throw()
  13181. {
  13182. jassert (readerThreads.size() == 0);
  13183. jassert (numWriters == 0);
  13184. }
  13185. void ReadWriteLock::enterRead() const throw()
  13186. {
  13187. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13188. const ScopedLock sl (accessLock);
  13189. for (;;)
  13190. {
  13191. jassert (readerThreads.size() % 2 == 0);
  13192. int i;
  13193. for (i = 0; i < readerThreads.size(); i += 2)
  13194. if (readerThreads.getUnchecked(i) == threadId)
  13195. break;
  13196. if (i < readerThreads.size()
  13197. || numWriters + numWaitingWriters == 0
  13198. || (threadId == writerThreadId && numWriters > 0))
  13199. {
  13200. if (i < readerThreads.size())
  13201. {
  13202. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13203. }
  13204. else
  13205. {
  13206. readerThreads.add (threadId);
  13207. readerThreads.add ((Thread::ThreadID) 1);
  13208. }
  13209. return;
  13210. }
  13211. const ScopedUnlock ul (accessLock);
  13212. waitEvent.wait (100);
  13213. }
  13214. }
  13215. void ReadWriteLock::exitRead() const throw()
  13216. {
  13217. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13218. const ScopedLock sl (accessLock);
  13219. for (int i = 0; i < readerThreads.size(); i += 2)
  13220. {
  13221. if (readerThreads.getUnchecked(i) == threadId)
  13222. {
  13223. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13224. if (newCount == 0)
  13225. {
  13226. readerThreads.removeRange (i, 2);
  13227. waitEvent.signal();
  13228. }
  13229. else
  13230. {
  13231. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13232. }
  13233. return;
  13234. }
  13235. }
  13236. jassertfalse; // unlocking a lock that wasn't locked..
  13237. }
  13238. void ReadWriteLock::enterWrite() const throw()
  13239. {
  13240. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13241. const ScopedLock sl (accessLock);
  13242. for (;;)
  13243. {
  13244. if (readerThreads.size() + numWriters == 0
  13245. || threadId == writerThreadId
  13246. || (readerThreads.size() == 2
  13247. && readerThreads.getUnchecked(0) == threadId))
  13248. {
  13249. writerThreadId = threadId;
  13250. ++numWriters;
  13251. break;
  13252. }
  13253. ++numWaitingWriters;
  13254. accessLock.exit();
  13255. waitEvent.wait (100);
  13256. accessLock.enter();
  13257. --numWaitingWriters;
  13258. }
  13259. }
  13260. bool ReadWriteLock::tryEnterWrite() const throw()
  13261. {
  13262. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13263. const ScopedLock sl (accessLock);
  13264. if (readerThreads.size() + numWriters == 0
  13265. || threadId == writerThreadId
  13266. || (readerThreads.size() == 2
  13267. && readerThreads.getUnchecked(0) == threadId))
  13268. {
  13269. writerThreadId = threadId;
  13270. ++numWriters;
  13271. return true;
  13272. }
  13273. return false;
  13274. }
  13275. void ReadWriteLock::exitWrite() const throw()
  13276. {
  13277. const ScopedLock sl (accessLock);
  13278. // check this thread actually had the lock..
  13279. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13280. if (--numWriters == 0)
  13281. {
  13282. writerThreadId = 0;
  13283. waitEvent.signal();
  13284. }
  13285. }
  13286. END_JUCE_NAMESPACE
  13287. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13288. /*** Start of inlined file: juce_Thread.cpp ***/
  13289. BEGIN_JUCE_NAMESPACE
  13290. class RunningThreadsList
  13291. {
  13292. public:
  13293. RunningThreadsList()
  13294. {
  13295. }
  13296. void add (Thread* const thread)
  13297. {
  13298. const ScopedLock sl (lock);
  13299. jassert (! threads.contains (thread));
  13300. threads.add (thread);
  13301. }
  13302. void remove (Thread* const thread)
  13303. {
  13304. const ScopedLock sl (lock);
  13305. jassert (threads.contains (thread));
  13306. threads.removeValue (thread);
  13307. }
  13308. int size() const throw()
  13309. {
  13310. return threads.size();
  13311. }
  13312. Thread* getThreadWithID (const Thread::ThreadID targetID) const throw()
  13313. {
  13314. const ScopedLock sl (lock);
  13315. for (int i = threads.size(); --i >= 0;)
  13316. {
  13317. Thread* const t = threads.getUnchecked(i);
  13318. if (t->getThreadId() == targetID)
  13319. return t;
  13320. }
  13321. return 0;
  13322. }
  13323. void stopAll (const int timeOutMilliseconds)
  13324. {
  13325. signalAllThreadsToStop();
  13326. for (;;)
  13327. {
  13328. Thread* firstThread = getFirstThread();
  13329. if (firstThread != 0)
  13330. firstThread->stopThread (timeOutMilliseconds);
  13331. else
  13332. break;
  13333. }
  13334. }
  13335. static RunningThreadsList& getInstance()
  13336. {
  13337. static RunningThreadsList runningThreads;
  13338. return runningThreads;
  13339. }
  13340. private:
  13341. Array<Thread*> threads;
  13342. CriticalSection lock;
  13343. void signalAllThreadsToStop()
  13344. {
  13345. const ScopedLock sl (lock);
  13346. for (int i = threads.size(); --i >= 0;)
  13347. threads.getUnchecked(i)->signalThreadShouldExit();
  13348. }
  13349. Thread* getFirstThread() const
  13350. {
  13351. const ScopedLock sl (lock);
  13352. return threads.getFirst();
  13353. }
  13354. };
  13355. void Thread::threadEntryPoint()
  13356. {
  13357. RunningThreadsList::getInstance().add (this);
  13358. JUCE_TRY
  13359. {
  13360. if (threadName_.isNotEmpty())
  13361. setCurrentThreadName (threadName_);
  13362. if (startSuspensionEvent_.wait (10000))
  13363. {
  13364. jassert (getCurrentThreadId() == threadId_);
  13365. if (affinityMask_ != 0)
  13366. setCurrentThreadAffinityMask (affinityMask_);
  13367. run();
  13368. }
  13369. }
  13370. JUCE_CATCH_ALL_ASSERT
  13371. RunningThreadsList::getInstance().remove (this);
  13372. closeThreadHandle();
  13373. }
  13374. // used to wrap the incoming call from the platform-specific code
  13375. void JUCE_API juce_threadEntryPoint (void* userData)
  13376. {
  13377. static_cast <Thread*> (userData)->threadEntryPoint();
  13378. }
  13379. Thread::Thread (const String& threadName)
  13380. : threadName_ (threadName),
  13381. threadHandle_ (0),
  13382. threadId_ (0),
  13383. threadPriority_ (5),
  13384. affinityMask_ (0),
  13385. threadShouldExit_ (false)
  13386. {
  13387. }
  13388. Thread::~Thread()
  13389. {
  13390. /* If your thread class's destructor has been called without first stopping the thread, that
  13391. means that this partially destructed object is still performing some work - and that's
  13392. probably a Bad Thing!
  13393. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13394. your subclass's destructor.
  13395. */
  13396. jassert (! isThreadRunning());
  13397. stopThread (100);
  13398. }
  13399. void Thread::startThread()
  13400. {
  13401. const ScopedLock sl (startStopLock);
  13402. threadShouldExit_ = false;
  13403. if (threadHandle_ == 0)
  13404. {
  13405. launchThread();
  13406. setThreadPriority (threadHandle_, threadPriority_);
  13407. startSuspensionEvent_.signal();
  13408. }
  13409. }
  13410. void Thread::startThread (const int priority)
  13411. {
  13412. const ScopedLock sl (startStopLock);
  13413. if (threadHandle_ == 0)
  13414. {
  13415. threadPriority_ = priority;
  13416. startThread();
  13417. }
  13418. else
  13419. {
  13420. setPriority (priority);
  13421. }
  13422. }
  13423. bool Thread::isThreadRunning() const
  13424. {
  13425. return threadHandle_ != 0;
  13426. }
  13427. void Thread::signalThreadShouldExit()
  13428. {
  13429. threadShouldExit_ = true;
  13430. }
  13431. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13432. {
  13433. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13434. jassert (getThreadId() != getCurrentThreadId());
  13435. const int sleepMsPerIteration = 5;
  13436. int count = timeOutMilliseconds / sleepMsPerIteration;
  13437. while (isThreadRunning())
  13438. {
  13439. if (timeOutMilliseconds > 0 && --count < 0)
  13440. return false;
  13441. sleep (sleepMsPerIteration);
  13442. }
  13443. return true;
  13444. }
  13445. void Thread::stopThread (const int timeOutMilliseconds)
  13446. {
  13447. // agh! You can't stop the thread that's calling this method! How on earth
  13448. // would that work??
  13449. jassert (getCurrentThreadId() != getThreadId());
  13450. const ScopedLock sl (startStopLock);
  13451. if (isThreadRunning())
  13452. {
  13453. signalThreadShouldExit();
  13454. notify();
  13455. if (timeOutMilliseconds != 0)
  13456. waitForThreadToExit (timeOutMilliseconds);
  13457. if (isThreadRunning())
  13458. {
  13459. // very bad karma if this point is reached, as there are bound to be
  13460. // locks and events left in silly states when a thread is killed by force..
  13461. jassertfalse;
  13462. Logger::writeToLog ("!! killing thread by force !!");
  13463. killThread();
  13464. RunningThreadsList::getInstance().remove (this);
  13465. threadHandle_ = 0;
  13466. threadId_ = 0;
  13467. }
  13468. }
  13469. }
  13470. bool Thread::setPriority (const int priority)
  13471. {
  13472. const ScopedLock sl (startStopLock);
  13473. if (setThreadPriority (threadHandle_, priority))
  13474. {
  13475. threadPriority_ = priority;
  13476. return true;
  13477. }
  13478. return false;
  13479. }
  13480. bool Thread::setCurrentThreadPriority (const int priority)
  13481. {
  13482. return setThreadPriority (0, priority);
  13483. }
  13484. void Thread::setAffinityMask (const uint32 affinityMask)
  13485. {
  13486. affinityMask_ = affinityMask;
  13487. }
  13488. bool Thread::wait (const int timeOutMilliseconds) const
  13489. {
  13490. return defaultEvent_.wait (timeOutMilliseconds);
  13491. }
  13492. void Thread::notify() const
  13493. {
  13494. defaultEvent_.signal();
  13495. }
  13496. int Thread::getNumRunningThreads()
  13497. {
  13498. return RunningThreadsList::getInstance().size();
  13499. }
  13500. Thread* Thread::getCurrentThread()
  13501. {
  13502. return RunningThreadsList::getInstance().getThreadWithID (getCurrentThreadId());
  13503. }
  13504. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13505. {
  13506. RunningThreadsList::getInstance().stopAll (timeOutMilliseconds);
  13507. }
  13508. END_JUCE_NAMESPACE
  13509. /*** End of inlined file: juce_Thread.cpp ***/
  13510. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13511. BEGIN_JUCE_NAMESPACE
  13512. ThreadPoolJob::ThreadPoolJob (const String& name)
  13513. : jobName (name),
  13514. pool (0),
  13515. shouldStop (false),
  13516. isActive (false),
  13517. shouldBeDeleted (false)
  13518. {
  13519. }
  13520. ThreadPoolJob::~ThreadPoolJob()
  13521. {
  13522. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13523. // to remove it first!
  13524. jassert (pool == 0 || ! pool->contains (this));
  13525. }
  13526. const String ThreadPoolJob::getJobName() const
  13527. {
  13528. return jobName;
  13529. }
  13530. void ThreadPoolJob::setJobName (const String& newName)
  13531. {
  13532. jobName = newName;
  13533. }
  13534. void ThreadPoolJob::signalJobShouldExit()
  13535. {
  13536. shouldStop = true;
  13537. }
  13538. class ThreadPool::ThreadPoolThread : public Thread
  13539. {
  13540. public:
  13541. ThreadPoolThread (ThreadPool& pool_)
  13542. : Thread ("Pool"),
  13543. pool (pool_),
  13544. busy (false)
  13545. {
  13546. }
  13547. void run()
  13548. {
  13549. while (! threadShouldExit())
  13550. {
  13551. if (! pool.runNextJob())
  13552. wait (500);
  13553. }
  13554. }
  13555. private:
  13556. ThreadPool& pool;
  13557. bool volatile busy;
  13558. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread);
  13559. };
  13560. ThreadPool::ThreadPool (const int numThreads,
  13561. const bool startThreadsOnlyWhenNeeded,
  13562. const int stopThreadsWhenNotUsedTimeoutMs)
  13563. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13564. priority (5)
  13565. {
  13566. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13567. for (int i = jmax (1, numThreads); --i >= 0;)
  13568. threads.add (new ThreadPoolThread (*this));
  13569. if (! startThreadsOnlyWhenNeeded)
  13570. for (int i = threads.size(); --i >= 0;)
  13571. threads.getUnchecked(i)->startThread (priority);
  13572. }
  13573. ThreadPool::~ThreadPool()
  13574. {
  13575. removeAllJobs (true, 4000);
  13576. int i;
  13577. for (i = threads.size(); --i >= 0;)
  13578. threads.getUnchecked(i)->signalThreadShouldExit();
  13579. for (i = threads.size(); --i >= 0;)
  13580. threads.getUnchecked(i)->stopThread (500);
  13581. }
  13582. void ThreadPool::addJob (ThreadPoolJob* const job)
  13583. {
  13584. jassert (job != 0);
  13585. jassert (job->pool == 0);
  13586. if (job->pool == 0)
  13587. {
  13588. job->pool = this;
  13589. job->shouldStop = false;
  13590. job->isActive = false;
  13591. {
  13592. const ScopedLock sl (lock);
  13593. jobs.add (job);
  13594. int numRunning = 0;
  13595. for (int i = threads.size(); --i >= 0;)
  13596. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13597. ++numRunning;
  13598. if (numRunning < threads.size())
  13599. {
  13600. bool startedOne = false;
  13601. int n = 1000;
  13602. while (--n >= 0 && ! startedOne)
  13603. {
  13604. for (int i = threads.size(); --i >= 0;)
  13605. {
  13606. if (! threads.getUnchecked(i)->isThreadRunning())
  13607. {
  13608. threads.getUnchecked(i)->startThread (priority);
  13609. startedOne = true;
  13610. break;
  13611. }
  13612. }
  13613. if (! startedOne)
  13614. Thread::sleep (2);
  13615. }
  13616. }
  13617. }
  13618. for (int i = threads.size(); --i >= 0;)
  13619. threads.getUnchecked(i)->notify();
  13620. }
  13621. }
  13622. int ThreadPool::getNumJobs() const
  13623. {
  13624. return jobs.size();
  13625. }
  13626. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13627. {
  13628. const ScopedLock sl (lock);
  13629. return jobs [index];
  13630. }
  13631. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13632. {
  13633. const ScopedLock sl (lock);
  13634. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13635. }
  13636. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13637. {
  13638. const ScopedLock sl (lock);
  13639. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13640. }
  13641. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13642. const int timeOutMs) const
  13643. {
  13644. if (job != 0)
  13645. {
  13646. const uint32 start = Time::getMillisecondCounter();
  13647. while (contains (job))
  13648. {
  13649. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13650. return false;
  13651. jobFinishedSignal.wait (2);
  13652. }
  13653. }
  13654. return true;
  13655. }
  13656. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13657. const bool interruptIfRunning,
  13658. const int timeOutMs)
  13659. {
  13660. bool dontWait = true;
  13661. if (job != 0)
  13662. {
  13663. const ScopedLock sl (lock);
  13664. if (jobs.contains (job))
  13665. {
  13666. if (job->isActive)
  13667. {
  13668. if (interruptIfRunning)
  13669. job->signalJobShouldExit();
  13670. dontWait = false;
  13671. }
  13672. else
  13673. {
  13674. jobs.removeValue (job);
  13675. job->pool = 0;
  13676. }
  13677. }
  13678. }
  13679. return dontWait || waitForJobToFinish (job, timeOutMs);
  13680. }
  13681. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13682. const int timeOutMs,
  13683. const bool deleteInactiveJobs,
  13684. ThreadPool::JobSelector* selectedJobsToRemove)
  13685. {
  13686. Array <ThreadPoolJob*> jobsToWaitFor;
  13687. {
  13688. const ScopedLock sl (lock);
  13689. for (int i = jobs.size(); --i >= 0;)
  13690. {
  13691. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13692. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13693. {
  13694. if (job->isActive)
  13695. {
  13696. jobsToWaitFor.add (job);
  13697. if (interruptRunningJobs)
  13698. job->signalJobShouldExit();
  13699. }
  13700. else
  13701. {
  13702. jobs.remove (i);
  13703. if (deleteInactiveJobs)
  13704. delete job;
  13705. else
  13706. job->pool = 0;
  13707. }
  13708. }
  13709. }
  13710. }
  13711. const uint32 start = Time::getMillisecondCounter();
  13712. for (;;)
  13713. {
  13714. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13715. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13716. jobsToWaitFor.remove (i);
  13717. if (jobsToWaitFor.size() == 0)
  13718. break;
  13719. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13720. return false;
  13721. jobFinishedSignal.wait (20);
  13722. }
  13723. return true;
  13724. }
  13725. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13726. {
  13727. StringArray s;
  13728. const ScopedLock sl (lock);
  13729. for (int i = 0; i < jobs.size(); ++i)
  13730. {
  13731. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13732. if (job->isActive || ! onlyReturnActiveJobs)
  13733. s.add (job->getJobName());
  13734. }
  13735. return s;
  13736. }
  13737. bool ThreadPool::setThreadPriorities (const int newPriority)
  13738. {
  13739. bool ok = true;
  13740. if (priority != newPriority)
  13741. {
  13742. priority = newPriority;
  13743. for (int i = threads.size(); --i >= 0;)
  13744. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13745. ok = false;
  13746. }
  13747. return ok;
  13748. }
  13749. bool ThreadPool::runNextJob()
  13750. {
  13751. ThreadPoolJob* job = 0;
  13752. {
  13753. const ScopedLock sl (lock);
  13754. for (int i = 0; i < jobs.size(); ++i)
  13755. {
  13756. job = jobs[i];
  13757. if (job != 0 && ! (job->isActive || job->shouldStop))
  13758. break;
  13759. job = 0;
  13760. }
  13761. if (job != 0)
  13762. job->isActive = true;
  13763. }
  13764. if (job != 0)
  13765. {
  13766. JUCE_TRY
  13767. {
  13768. ThreadPoolJob::JobStatus result = job->runJob();
  13769. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13770. const ScopedLock sl (lock);
  13771. if (jobs.contains (job))
  13772. {
  13773. job->isActive = false;
  13774. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13775. {
  13776. job->pool = 0;
  13777. job->shouldStop = true;
  13778. jobs.removeValue (job);
  13779. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13780. delete job;
  13781. jobFinishedSignal.signal();
  13782. }
  13783. else
  13784. {
  13785. // move the job to the end of the queue if it wants another go
  13786. jobs.move (jobs.indexOf (job), -1);
  13787. }
  13788. }
  13789. }
  13790. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13791. catch (...)
  13792. {
  13793. const ScopedLock sl (lock);
  13794. jobs.removeValue (job);
  13795. }
  13796. #endif
  13797. }
  13798. else
  13799. {
  13800. if (threadStopTimeout > 0
  13801. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13802. {
  13803. const ScopedLock sl (lock);
  13804. if (jobs.size() == 0)
  13805. for (int i = threads.size(); --i >= 0;)
  13806. threads.getUnchecked(i)->signalThreadShouldExit();
  13807. }
  13808. else
  13809. {
  13810. return false;
  13811. }
  13812. }
  13813. return true;
  13814. }
  13815. END_JUCE_NAMESPACE
  13816. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13817. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13818. BEGIN_JUCE_NAMESPACE
  13819. TimeSliceThread::TimeSliceThread (const String& threadName)
  13820. : Thread (threadName),
  13821. index (0),
  13822. clientBeingCalled (0),
  13823. clientsChanged (false)
  13824. {
  13825. }
  13826. TimeSliceThread::~TimeSliceThread()
  13827. {
  13828. stopThread (2000);
  13829. }
  13830. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  13831. {
  13832. const ScopedLock sl (listLock);
  13833. clients.addIfNotAlreadyThere (client);
  13834. clientsChanged = true;
  13835. notify();
  13836. }
  13837. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13838. {
  13839. const ScopedLock sl1 (listLock);
  13840. clientsChanged = true;
  13841. // if there's a chance we're in the middle of calling this client, we need to
  13842. // also lock the outer lock..
  13843. if (clientBeingCalled == client)
  13844. {
  13845. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13846. const ScopedLock sl2 (callbackLock);
  13847. const ScopedLock sl3 (listLock);
  13848. clients.removeValue (client);
  13849. }
  13850. else
  13851. {
  13852. clients.removeValue (client);
  13853. }
  13854. }
  13855. int TimeSliceThread::getNumClients() const
  13856. {
  13857. return clients.size();
  13858. }
  13859. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13860. {
  13861. const ScopedLock sl (listLock);
  13862. return clients [i];
  13863. }
  13864. void TimeSliceThread::run()
  13865. {
  13866. int numCallsSinceBusy = 0;
  13867. while (! threadShouldExit())
  13868. {
  13869. int timeToWait = 500;
  13870. {
  13871. const ScopedLock sl (callbackLock);
  13872. {
  13873. const ScopedLock sl2 (listLock);
  13874. if (clients.size() > 0)
  13875. {
  13876. index = (index + 1) % clients.size();
  13877. clientBeingCalled = clients [index];
  13878. }
  13879. else
  13880. {
  13881. index = 0;
  13882. clientBeingCalled = 0;
  13883. }
  13884. if (clientsChanged)
  13885. {
  13886. clientsChanged = false;
  13887. numCallsSinceBusy = 0;
  13888. }
  13889. }
  13890. if (clientBeingCalled != 0)
  13891. {
  13892. if (clientBeingCalled->useTimeSlice())
  13893. numCallsSinceBusy = 0;
  13894. else
  13895. ++numCallsSinceBusy;
  13896. if (numCallsSinceBusy >= clients.size())
  13897. timeToWait = 500;
  13898. else if (index == 0)
  13899. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  13900. else
  13901. timeToWait = 0;
  13902. }
  13903. }
  13904. if (timeToWait > 0)
  13905. wait (timeToWait);
  13906. }
  13907. }
  13908. END_JUCE_NAMESPACE
  13909. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  13910. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  13911. BEGIN_JUCE_NAMESPACE
  13912. DeletedAtShutdown::DeletedAtShutdown()
  13913. {
  13914. const ScopedLock sl (getLock());
  13915. getObjects().add (this);
  13916. }
  13917. DeletedAtShutdown::~DeletedAtShutdown()
  13918. {
  13919. const ScopedLock sl (getLock());
  13920. getObjects().removeValue (this);
  13921. }
  13922. void DeletedAtShutdown::deleteAll()
  13923. {
  13924. // make a local copy of the array, so it can't get into a loop if something
  13925. // creates another DeletedAtShutdown object during its destructor.
  13926. Array <DeletedAtShutdown*> localCopy;
  13927. {
  13928. const ScopedLock sl (getLock());
  13929. localCopy = getObjects();
  13930. }
  13931. for (int i = localCopy.size(); --i >= 0;)
  13932. {
  13933. JUCE_TRY
  13934. {
  13935. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  13936. // double-check that it's not already been deleted during another object's destructor.
  13937. {
  13938. const ScopedLock sl (getLock());
  13939. if (! getObjects().contains (deletee))
  13940. deletee = 0;
  13941. }
  13942. delete deletee;
  13943. }
  13944. JUCE_CATCH_EXCEPTION
  13945. }
  13946. // if no objects got re-created during shutdown, this should have been emptied by their
  13947. // destructors
  13948. jassert (getObjects().size() == 0);
  13949. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  13950. }
  13951. CriticalSection& DeletedAtShutdown::getLock()
  13952. {
  13953. static CriticalSection lock;
  13954. return lock;
  13955. }
  13956. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  13957. {
  13958. static Array <DeletedAtShutdown*> objects;
  13959. return objects;
  13960. }
  13961. END_JUCE_NAMESPACE
  13962. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  13963. /*** Start of inlined file: juce_UnitTest.cpp ***/
  13964. BEGIN_JUCE_NAMESPACE
  13965. UnitTest::UnitTest (const String& name_)
  13966. : name (name_), runner (0)
  13967. {
  13968. getAllTests().add (this);
  13969. }
  13970. UnitTest::~UnitTest()
  13971. {
  13972. getAllTests().removeValue (this);
  13973. }
  13974. Array<UnitTest*>& UnitTest::getAllTests()
  13975. {
  13976. static Array<UnitTest*> tests;
  13977. return tests;
  13978. }
  13979. void UnitTest::initialise() {}
  13980. void UnitTest::shutdown() {}
  13981. void UnitTest::performTest (UnitTestRunner* const runner_)
  13982. {
  13983. jassert (runner_ != 0);
  13984. runner = runner_;
  13985. initialise();
  13986. runTest();
  13987. shutdown();
  13988. }
  13989. void UnitTest::logMessage (const String& message)
  13990. {
  13991. runner->logMessage (message);
  13992. }
  13993. void UnitTest::beginTest (const String& testName)
  13994. {
  13995. runner->beginNewTest (this, testName);
  13996. }
  13997. void UnitTest::expect (const bool result, const String& failureMessage)
  13998. {
  13999. if (result)
  14000. runner->addPass();
  14001. else
  14002. runner->addFail (failureMessage);
  14003. }
  14004. UnitTestRunner::UnitTestRunner()
  14005. : currentTest (0), assertOnFailure (false)
  14006. {
  14007. }
  14008. UnitTestRunner::~UnitTestRunner()
  14009. {
  14010. }
  14011. int UnitTestRunner::getNumResults() const throw()
  14012. {
  14013. return results.size();
  14014. }
  14015. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  14016. {
  14017. return results [index];
  14018. }
  14019. void UnitTestRunner::resultsUpdated()
  14020. {
  14021. }
  14022. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14023. {
  14024. results.clear();
  14025. assertOnFailure = assertOnFailure_;
  14026. resultsUpdated();
  14027. for (int i = 0; i < tests.size(); ++i)
  14028. {
  14029. try
  14030. {
  14031. tests.getUnchecked(i)->performTest (this);
  14032. }
  14033. catch (...)
  14034. {
  14035. addFail ("An unhandled exception was thrown!");
  14036. }
  14037. }
  14038. endTest();
  14039. }
  14040. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14041. {
  14042. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14043. }
  14044. void UnitTestRunner::logMessage (const String& message)
  14045. {
  14046. Logger::writeToLog (message);
  14047. }
  14048. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14049. {
  14050. endTest();
  14051. currentTest = test;
  14052. TestResult* const r = new TestResult();
  14053. r->unitTestName = test->getName();
  14054. r->subcategoryName = subCategory;
  14055. r->passes = 0;
  14056. r->failures = 0;
  14057. results.add (r);
  14058. logMessage ("-----------------------------------------------------------------");
  14059. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14060. resultsUpdated();
  14061. }
  14062. void UnitTestRunner::endTest()
  14063. {
  14064. if (results.size() > 0)
  14065. {
  14066. TestResult* const r = results.getLast();
  14067. if (r->failures > 0)
  14068. {
  14069. String m ("FAILED!!");
  14070. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14071. << " failed, out of a total of " << (r->passes + r->failures);
  14072. logMessage (String::empty);
  14073. logMessage (m);
  14074. logMessage (String::empty);
  14075. }
  14076. else
  14077. {
  14078. logMessage ("All tests completed successfully");
  14079. }
  14080. }
  14081. }
  14082. void UnitTestRunner::addPass()
  14083. {
  14084. {
  14085. const ScopedLock sl (results.getLock());
  14086. TestResult* const r = results.getLast();
  14087. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14088. r->passes++;
  14089. String message ("Test ");
  14090. message << (r->failures + r->passes) << " passed";
  14091. logMessage (message);
  14092. }
  14093. resultsUpdated();
  14094. }
  14095. void UnitTestRunner::addFail (const String& failureMessage)
  14096. {
  14097. {
  14098. const ScopedLock sl (results.getLock());
  14099. TestResult* const r = results.getLast();
  14100. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14101. r->failures++;
  14102. String message ("!!! Test ");
  14103. message << (r->failures + r->passes) << " failed";
  14104. if (failureMessage.isNotEmpty())
  14105. message << ": " << failureMessage;
  14106. r->messages.add (message);
  14107. logMessage (message);
  14108. }
  14109. resultsUpdated();
  14110. if (assertOnFailure) { jassertfalse }
  14111. }
  14112. END_JUCE_NAMESPACE
  14113. /*** End of inlined file: juce_UnitTest.cpp ***/
  14114. #endif
  14115. #if JUCE_BUILD_MISC
  14116. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14117. BEGIN_JUCE_NAMESPACE
  14118. class ValueTree::SetPropertyAction : public UndoableAction
  14119. {
  14120. public:
  14121. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14122. const var& newValue_, const var& oldValue_,
  14123. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14124. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14125. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14126. {
  14127. }
  14128. bool perform()
  14129. {
  14130. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14131. if (isDeletingProperty)
  14132. target->removeProperty (name, 0);
  14133. else
  14134. target->setProperty (name, newValue, 0);
  14135. return true;
  14136. }
  14137. bool undo()
  14138. {
  14139. if (isAddingNewProperty)
  14140. target->removeProperty (name, 0);
  14141. else
  14142. target->setProperty (name, oldValue, 0);
  14143. return true;
  14144. }
  14145. int getSizeInUnits()
  14146. {
  14147. return (int) sizeof (*this); //xxx should be more accurate
  14148. }
  14149. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14150. {
  14151. if (! (isAddingNewProperty || isDeletingProperty))
  14152. {
  14153. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14154. if (next != 0 && next->target == target && next->name == name
  14155. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14156. {
  14157. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14158. }
  14159. }
  14160. return 0;
  14161. }
  14162. private:
  14163. const SharedObjectPtr target;
  14164. const Identifier name;
  14165. const var newValue;
  14166. var oldValue;
  14167. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14168. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction);
  14169. };
  14170. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14171. {
  14172. public:
  14173. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14174. const SharedObjectPtr& newChild_)
  14175. : target (target_),
  14176. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14177. childIndex (childIndex_),
  14178. isDeleting (newChild_ == 0)
  14179. {
  14180. jassert (child != 0);
  14181. }
  14182. bool perform()
  14183. {
  14184. if (isDeleting)
  14185. target->removeChild (childIndex, 0);
  14186. else
  14187. target->addChild (child, childIndex, 0);
  14188. return true;
  14189. }
  14190. bool undo()
  14191. {
  14192. if (isDeleting)
  14193. {
  14194. target->addChild (child, childIndex, 0);
  14195. }
  14196. else
  14197. {
  14198. // If you hit this, it seems that your object's state is getting confused - probably
  14199. // because you've interleaved some undoable and non-undoable operations?
  14200. jassert (childIndex < target->children.size());
  14201. target->removeChild (childIndex, 0);
  14202. }
  14203. return true;
  14204. }
  14205. int getSizeInUnits()
  14206. {
  14207. return (int) sizeof (*this); //xxx should be more accurate
  14208. }
  14209. private:
  14210. const SharedObjectPtr target, child;
  14211. const int childIndex;
  14212. const bool isDeleting;
  14213. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction);
  14214. };
  14215. class ValueTree::MoveChildAction : public UndoableAction
  14216. {
  14217. public:
  14218. MoveChildAction (const SharedObjectPtr& parent_,
  14219. const int startIndex_, const int endIndex_)
  14220. : parent (parent_),
  14221. startIndex (startIndex_),
  14222. endIndex (endIndex_)
  14223. {
  14224. }
  14225. bool perform()
  14226. {
  14227. parent->moveChild (startIndex, endIndex, 0);
  14228. return true;
  14229. }
  14230. bool undo()
  14231. {
  14232. parent->moveChild (endIndex, startIndex, 0);
  14233. return true;
  14234. }
  14235. int getSizeInUnits()
  14236. {
  14237. return (int) sizeof (*this); //xxx should be more accurate
  14238. }
  14239. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14240. {
  14241. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14242. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14243. return new MoveChildAction (parent, startIndex, next->endIndex);
  14244. return 0;
  14245. }
  14246. private:
  14247. const SharedObjectPtr parent;
  14248. const int startIndex, endIndex;
  14249. JUCE_DECLARE_NON_COPYABLE (MoveChildAction);
  14250. };
  14251. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14252. : type (type_), parent (0)
  14253. {
  14254. }
  14255. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14256. : type (other.type), properties (other.properties), parent (0)
  14257. {
  14258. for (int i = 0; i < other.children.size(); ++i)
  14259. {
  14260. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14261. child->parent = this;
  14262. children.add (child);
  14263. }
  14264. }
  14265. ValueTree::SharedObject::~SharedObject()
  14266. {
  14267. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14268. for (int i = children.size(); --i >= 0;)
  14269. {
  14270. const SharedObjectPtr c (children.getUnchecked(i));
  14271. c->parent = 0;
  14272. children.remove (i);
  14273. c->sendParentChangeMessage();
  14274. }
  14275. }
  14276. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14277. {
  14278. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14279. {
  14280. ValueTree* const v = valueTreesWithListeners[i];
  14281. if (v != 0)
  14282. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14283. }
  14284. }
  14285. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14286. {
  14287. ValueTree tree (this);
  14288. ValueTree::SharedObject* t = this;
  14289. while (t != 0)
  14290. {
  14291. t->sendPropertyChangeMessage (tree, property);
  14292. t = t->parent;
  14293. }
  14294. }
  14295. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14296. {
  14297. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14298. {
  14299. ValueTree* const v = valueTreesWithListeners[i];
  14300. if (v != 0)
  14301. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14302. }
  14303. }
  14304. void ValueTree::SharedObject::sendChildChangeMessage()
  14305. {
  14306. ValueTree tree (this);
  14307. ValueTree::SharedObject* t = this;
  14308. while (t != 0)
  14309. {
  14310. t->sendChildChangeMessage (tree);
  14311. t = t->parent;
  14312. }
  14313. }
  14314. void ValueTree::SharedObject::sendParentChangeMessage()
  14315. {
  14316. ValueTree tree (this);
  14317. int i;
  14318. for (i = children.size(); --i >= 0;)
  14319. {
  14320. SharedObject* const t = children[i];
  14321. if (t != 0)
  14322. t->sendParentChangeMessage();
  14323. }
  14324. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14325. {
  14326. ValueTree* const v = valueTreesWithListeners[i];
  14327. if (v != 0)
  14328. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14329. }
  14330. }
  14331. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14332. {
  14333. return properties [name];
  14334. }
  14335. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14336. {
  14337. return properties.getWithDefault (name, defaultReturnValue);
  14338. }
  14339. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14340. {
  14341. if (undoManager == 0)
  14342. {
  14343. if (properties.set (name, newValue))
  14344. sendPropertyChangeMessage (name);
  14345. }
  14346. else
  14347. {
  14348. var* const existingValue = properties.getVarPointer (name);
  14349. if (existingValue != 0)
  14350. {
  14351. if (*existingValue != newValue)
  14352. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14353. }
  14354. else
  14355. {
  14356. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14357. }
  14358. }
  14359. }
  14360. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14361. {
  14362. return properties.contains (name);
  14363. }
  14364. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14365. {
  14366. if (undoManager == 0)
  14367. {
  14368. if (properties.remove (name))
  14369. sendPropertyChangeMessage (name);
  14370. }
  14371. else
  14372. {
  14373. if (properties.contains (name))
  14374. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14375. }
  14376. }
  14377. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14378. {
  14379. if (undoManager == 0)
  14380. {
  14381. while (properties.size() > 0)
  14382. {
  14383. const Identifier name (properties.getName (properties.size() - 1));
  14384. properties.remove (name);
  14385. sendPropertyChangeMessage (name);
  14386. }
  14387. }
  14388. else
  14389. {
  14390. for (int i = properties.size(); --i >= 0;)
  14391. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14392. }
  14393. }
  14394. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14395. {
  14396. for (int i = 0; i < children.size(); ++i)
  14397. if (children.getUnchecked(i)->type == typeToMatch)
  14398. return ValueTree (children.getUnchecked(i).getObject());
  14399. return ValueTree::invalid;
  14400. }
  14401. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14402. {
  14403. for (int i = 0; i < children.size(); ++i)
  14404. if (children.getUnchecked(i)->type == typeToMatch)
  14405. return ValueTree (children.getUnchecked(i).getObject());
  14406. SharedObject* const newObject = new SharedObject (typeToMatch);
  14407. addChild (newObject, -1, undoManager);
  14408. return ValueTree (newObject);
  14409. }
  14410. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14411. {
  14412. for (int i = 0; i < children.size(); ++i)
  14413. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14414. return ValueTree (children.getUnchecked(i).getObject());
  14415. return ValueTree::invalid;
  14416. }
  14417. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14418. {
  14419. const SharedObject* p = parent;
  14420. while (p != 0)
  14421. {
  14422. if (p == possibleParent)
  14423. return true;
  14424. p = p->parent;
  14425. }
  14426. return false;
  14427. }
  14428. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14429. {
  14430. return children.indexOf (child.object);
  14431. }
  14432. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14433. {
  14434. if (child != 0 && child->parent != this)
  14435. {
  14436. if (child != this && ! isAChildOf (child))
  14437. {
  14438. // You should always make sure that a child is removed from its previous parent before
  14439. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14440. // undomanager should be used when removing it from its current parent..
  14441. jassert (child->parent == 0);
  14442. if (child->parent != 0)
  14443. {
  14444. jassert (child->parent->children.indexOf (child) >= 0);
  14445. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14446. }
  14447. if (undoManager == 0)
  14448. {
  14449. children.insert (index, child);
  14450. child->parent = this;
  14451. sendChildChangeMessage();
  14452. child->sendParentChangeMessage();
  14453. }
  14454. else
  14455. {
  14456. if (index < 0)
  14457. index = children.size();
  14458. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14459. }
  14460. }
  14461. else
  14462. {
  14463. // You're attempting to create a recursive loop! A node
  14464. // can't be a child of one of its own children!
  14465. jassertfalse;
  14466. }
  14467. }
  14468. }
  14469. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14470. {
  14471. const SharedObjectPtr child (children [childIndex]);
  14472. if (child != 0)
  14473. {
  14474. if (undoManager == 0)
  14475. {
  14476. children.remove (childIndex);
  14477. child->parent = 0;
  14478. sendChildChangeMessage();
  14479. child->sendParentChangeMessage();
  14480. }
  14481. else
  14482. {
  14483. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14484. }
  14485. }
  14486. }
  14487. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14488. {
  14489. while (children.size() > 0)
  14490. removeChild (children.size() - 1, undoManager);
  14491. }
  14492. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14493. {
  14494. // The source index must be a valid index!
  14495. jassert (isPositiveAndBelow (currentIndex, children.size()));
  14496. if (currentIndex != newIndex
  14497. && isPositiveAndBelow (currentIndex, children.size()))
  14498. {
  14499. if (undoManager == 0)
  14500. {
  14501. children.move (currentIndex, newIndex);
  14502. sendChildChangeMessage();
  14503. }
  14504. else
  14505. {
  14506. if (! isPositiveAndBelow (newIndex, children.size()))
  14507. newIndex = children.size() - 1;
  14508. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14509. }
  14510. }
  14511. }
  14512. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14513. {
  14514. jassert (newOrder.size() == children.size());
  14515. if (undoManager == 0)
  14516. {
  14517. children = newOrder;
  14518. sendChildChangeMessage();
  14519. }
  14520. else
  14521. {
  14522. for (int i = 0; i < children.size(); ++i)
  14523. {
  14524. if (children.getUnchecked(i) != newOrder.getUnchecked(i))
  14525. {
  14526. jassert (children.contains (newOrder.getUnchecked(i)));
  14527. moveChild (children.indexOf (newOrder.getUnchecked(i)), i, undoManager);
  14528. }
  14529. }
  14530. }
  14531. }
  14532. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14533. {
  14534. if (type != other.type
  14535. || properties.size() != other.properties.size()
  14536. || children.size() != other.children.size()
  14537. || properties != other.properties)
  14538. return false;
  14539. for (int i = 0; i < children.size(); ++i)
  14540. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14541. return false;
  14542. return true;
  14543. }
  14544. ValueTree::ValueTree() throw()
  14545. : object (0)
  14546. {
  14547. }
  14548. const ValueTree ValueTree::invalid;
  14549. ValueTree::ValueTree (const Identifier& type_)
  14550. : object (new ValueTree::SharedObject (type_))
  14551. {
  14552. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14553. }
  14554. ValueTree::ValueTree (SharedObject* const object_)
  14555. : object (object_)
  14556. {
  14557. }
  14558. ValueTree::ValueTree (const ValueTree& other)
  14559. : object (other.object)
  14560. {
  14561. }
  14562. ValueTree& ValueTree::operator= (const ValueTree& other)
  14563. {
  14564. if (listeners.size() > 0)
  14565. {
  14566. if (object != 0)
  14567. object->valueTreesWithListeners.removeValue (this);
  14568. if (other.object != 0)
  14569. other.object->valueTreesWithListeners.add (this);
  14570. }
  14571. object = other.object;
  14572. return *this;
  14573. }
  14574. ValueTree::~ValueTree()
  14575. {
  14576. if (listeners.size() > 0 && object != 0)
  14577. object->valueTreesWithListeners.removeValue (this);
  14578. }
  14579. bool ValueTree::operator== (const ValueTree& other) const throw()
  14580. {
  14581. return object == other.object;
  14582. }
  14583. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14584. {
  14585. return object != other.object;
  14586. }
  14587. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14588. {
  14589. return object == other.object
  14590. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14591. }
  14592. ValueTree ValueTree::createCopy() const
  14593. {
  14594. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14595. }
  14596. bool ValueTree::hasType (const Identifier& typeName) const
  14597. {
  14598. return object != 0 && object->type == typeName;
  14599. }
  14600. const Identifier ValueTree::getType() const
  14601. {
  14602. return object != 0 ? object->type : Identifier();
  14603. }
  14604. ValueTree ValueTree::getParent() const
  14605. {
  14606. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14607. }
  14608. ValueTree ValueTree::getSibling (const int delta) const
  14609. {
  14610. if (object == 0 || object->parent == 0)
  14611. return invalid;
  14612. const int index = object->parent->indexOf (*this) + delta;
  14613. return ValueTree (object->parent->children [index].getObject());
  14614. }
  14615. const var& ValueTree::operator[] (const Identifier& name) const
  14616. {
  14617. return object == 0 ? var::null : object->getProperty (name);
  14618. }
  14619. const var& ValueTree::getProperty (const Identifier& name) const
  14620. {
  14621. return object == 0 ? var::null : object->getProperty (name);
  14622. }
  14623. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14624. {
  14625. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14626. }
  14627. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14628. {
  14629. jassert (name.toString().isNotEmpty());
  14630. if (object != 0 && name.toString().isNotEmpty())
  14631. object->setProperty (name, newValue, undoManager);
  14632. }
  14633. bool ValueTree::hasProperty (const Identifier& name) const
  14634. {
  14635. return object != 0 && object->hasProperty (name);
  14636. }
  14637. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14638. {
  14639. if (object != 0)
  14640. object->removeProperty (name, undoManager);
  14641. }
  14642. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14643. {
  14644. if (object != 0)
  14645. object->removeAllProperties (undoManager);
  14646. }
  14647. int ValueTree::getNumProperties() const
  14648. {
  14649. return object == 0 ? 0 : object->properties.size();
  14650. }
  14651. const Identifier ValueTree::getPropertyName (const int index) const
  14652. {
  14653. return object == 0 ? Identifier()
  14654. : object->properties.getName (index);
  14655. }
  14656. class ValueTreePropertyValueSource : public Value::ValueSource,
  14657. public ValueTree::Listener
  14658. {
  14659. public:
  14660. ValueTreePropertyValueSource (const ValueTree& tree_,
  14661. const Identifier& property_,
  14662. UndoManager* const undoManager_)
  14663. : tree (tree_),
  14664. property (property_),
  14665. undoManager (undoManager_)
  14666. {
  14667. tree.addListener (this);
  14668. }
  14669. ~ValueTreePropertyValueSource()
  14670. {
  14671. tree.removeListener (this);
  14672. }
  14673. const var getValue() const
  14674. {
  14675. return tree [property];
  14676. }
  14677. void setValue (const var& newValue)
  14678. {
  14679. tree.setProperty (property, newValue, undoManager);
  14680. }
  14681. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14682. {
  14683. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14684. sendChangeMessage (false);
  14685. }
  14686. void valueTreeChildrenChanged (ValueTree&) {}
  14687. void valueTreeParentChanged (ValueTree&) {}
  14688. private:
  14689. ValueTree tree;
  14690. const Identifier property;
  14691. UndoManager* const undoManager;
  14692. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14693. };
  14694. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14695. {
  14696. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14697. }
  14698. int ValueTree::getNumChildren() const
  14699. {
  14700. return object == 0 ? 0 : object->children.size();
  14701. }
  14702. ValueTree ValueTree::getChild (int index) const
  14703. {
  14704. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14705. }
  14706. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14707. {
  14708. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14709. }
  14710. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14711. {
  14712. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14713. }
  14714. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14715. {
  14716. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14717. }
  14718. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14719. {
  14720. return object != 0 && object->isAChildOf (possibleParent.object);
  14721. }
  14722. int ValueTree::indexOf (const ValueTree& child) const
  14723. {
  14724. return object != 0 ? object->indexOf (child) : -1;
  14725. }
  14726. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14727. {
  14728. if (object != 0)
  14729. object->addChild (child.object, index, undoManager);
  14730. }
  14731. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14732. {
  14733. if (object != 0)
  14734. object->removeChild (childIndex, undoManager);
  14735. }
  14736. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14737. {
  14738. if (object != 0)
  14739. object->removeChild (object->children.indexOf (child.object), undoManager);
  14740. }
  14741. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14742. {
  14743. if (object != 0)
  14744. object->removeAllChildren (undoManager);
  14745. }
  14746. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14747. {
  14748. if (object != 0)
  14749. object->moveChild (currentIndex, newIndex, undoManager);
  14750. }
  14751. void ValueTree::addListener (Listener* listener)
  14752. {
  14753. if (listener != 0)
  14754. {
  14755. if (listeners.size() == 0 && object != 0)
  14756. object->valueTreesWithListeners.add (this);
  14757. listeners.add (listener);
  14758. }
  14759. }
  14760. void ValueTree::removeListener (Listener* listener)
  14761. {
  14762. listeners.remove (listener);
  14763. if (listeners.size() == 0 && object != 0)
  14764. object->valueTreesWithListeners.removeValue (this);
  14765. }
  14766. XmlElement* ValueTree::SharedObject::createXml() const
  14767. {
  14768. XmlElement* const xml = new XmlElement (type.toString());
  14769. properties.copyToXmlAttributes (*xml);
  14770. for (int i = 0; i < children.size(); ++i)
  14771. xml->addChildElement (children.getUnchecked(i)->createXml());
  14772. return xml;
  14773. }
  14774. XmlElement* ValueTree::createXml() const
  14775. {
  14776. return object != 0 ? object->createXml() : 0;
  14777. }
  14778. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14779. {
  14780. ValueTree v (xml.getTagName());
  14781. v.object->properties.setFromXmlAttributes (xml);
  14782. forEachXmlChildElement (xml, e)
  14783. v.addChild (fromXml (*e), -1, 0);
  14784. return v;
  14785. }
  14786. void ValueTree::writeToStream (OutputStream& output)
  14787. {
  14788. output.writeString (getType().toString());
  14789. const int numProps = getNumProperties();
  14790. output.writeCompressedInt (numProps);
  14791. int i;
  14792. for (i = 0; i < numProps; ++i)
  14793. {
  14794. const Identifier name (getPropertyName(i));
  14795. output.writeString (name.toString());
  14796. getProperty(name).writeToStream (output);
  14797. }
  14798. const int numChildren = getNumChildren();
  14799. output.writeCompressedInt (numChildren);
  14800. for (i = 0; i < numChildren; ++i)
  14801. getChild (i).writeToStream (output);
  14802. }
  14803. ValueTree ValueTree::readFromStream (InputStream& input)
  14804. {
  14805. const String type (input.readString());
  14806. if (type.isEmpty())
  14807. return ValueTree::invalid;
  14808. ValueTree v (type);
  14809. const int numProps = input.readCompressedInt();
  14810. if (numProps < 0)
  14811. {
  14812. jassertfalse; // trying to read corrupted data!
  14813. return v;
  14814. }
  14815. int i;
  14816. for (i = 0; i < numProps; ++i)
  14817. {
  14818. const String name (input.readString());
  14819. jassert (name.isNotEmpty());
  14820. const var value (var::readFromStream (input));
  14821. v.object->properties.set (name, value);
  14822. }
  14823. const int numChildren = input.readCompressedInt();
  14824. for (i = 0; i < numChildren; ++i)
  14825. {
  14826. ValueTree child (readFromStream (input));
  14827. v.object->children.add (child.object);
  14828. child.object->parent = v.object;
  14829. }
  14830. return v;
  14831. }
  14832. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14833. {
  14834. MemoryInputStream in (data, numBytes, false);
  14835. return readFromStream (in);
  14836. }
  14837. END_JUCE_NAMESPACE
  14838. /*** End of inlined file: juce_ValueTree.cpp ***/
  14839. /*** Start of inlined file: juce_Value.cpp ***/
  14840. BEGIN_JUCE_NAMESPACE
  14841. Value::ValueSource::ValueSource()
  14842. {
  14843. }
  14844. Value::ValueSource::~ValueSource()
  14845. {
  14846. }
  14847. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14848. {
  14849. if (synchronous)
  14850. {
  14851. for (int i = valuesWithListeners.size(); --i >= 0;)
  14852. {
  14853. Value* const v = valuesWithListeners[i];
  14854. if (v != 0)
  14855. v->callListeners();
  14856. }
  14857. }
  14858. else
  14859. {
  14860. triggerAsyncUpdate();
  14861. }
  14862. }
  14863. void Value::ValueSource::handleAsyncUpdate()
  14864. {
  14865. sendChangeMessage (true);
  14866. }
  14867. class SimpleValueSource : public Value::ValueSource
  14868. {
  14869. public:
  14870. SimpleValueSource()
  14871. {
  14872. }
  14873. SimpleValueSource (const var& initialValue)
  14874. : value (initialValue)
  14875. {
  14876. }
  14877. ~SimpleValueSource()
  14878. {
  14879. }
  14880. const var getValue() const
  14881. {
  14882. return value;
  14883. }
  14884. void setValue (const var& newValue)
  14885. {
  14886. if (newValue != value)
  14887. {
  14888. value = newValue;
  14889. sendChangeMessage (false);
  14890. }
  14891. }
  14892. private:
  14893. var value;
  14894. JUCE_DECLARE_NON_COPYABLE (SimpleValueSource);
  14895. };
  14896. Value::Value()
  14897. : value (new SimpleValueSource())
  14898. {
  14899. }
  14900. Value::Value (ValueSource* const value_)
  14901. : value (value_)
  14902. {
  14903. jassert (value_ != 0);
  14904. }
  14905. Value::Value (const var& initialValue)
  14906. : value (new SimpleValueSource (initialValue))
  14907. {
  14908. }
  14909. Value::Value (const Value& other)
  14910. : value (other.value)
  14911. {
  14912. }
  14913. Value& Value::operator= (const Value& other)
  14914. {
  14915. value = other.value;
  14916. return *this;
  14917. }
  14918. Value::~Value()
  14919. {
  14920. if (listeners.size() > 0)
  14921. value->valuesWithListeners.removeValue (this);
  14922. }
  14923. const var Value::getValue() const
  14924. {
  14925. return value->getValue();
  14926. }
  14927. Value::operator const var() const
  14928. {
  14929. return getValue();
  14930. }
  14931. void Value::setValue (const var& newValue)
  14932. {
  14933. value->setValue (newValue);
  14934. }
  14935. const String Value::toString() const
  14936. {
  14937. return value->getValue().toString();
  14938. }
  14939. Value& Value::operator= (const var& newValue)
  14940. {
  14941. value->setValue (newValue);
  14942. return *this;
  14943. }
  14944. void Value::referTo (const Value& valueToReferTo)
  14945. {
  14946. if (valueToReferTo.value != value)
  14947. {
  14948. if (listeners.size() > 0)
  14949. {
  14950. value->valuesWithListeners.removeValue (this);
  14951. valueToReferTo.value->valuesWithListeners.add (this);
  14952. }
  14953. value = valueToReferTo.value;
  14954. callListeners();
  14955. }
  14956. }
  14957. bool Value::refersToSameSourceAs (const Value& other) const
  14958. {
  14959. return value == other.value;
  14960. }
  14961. bool Value::operator== (const Value& other) const
  14962. {
  14963. return value == other.value || value->getValue() == other.getValue();
  14964. }
  14965. bool Value::operator!= (const Value& other) const
  14966. {
  14967. return value != other.value && value->getValue() != other.getValue();
  14968. }
  14969. void Value::addListener (ValueListener* const listener)
  14970. {
  14971. if (listener != 0)
  14972. {
  14973. if (listeners.size() == 0)
  14974. value->valuesWithListeners.add (this);
  14975. listeners.add (listener);
  14976. }
  14977. }
  14978. void Value::removeListener (ValueListener* const listener)
  14979. {
  14980. listeners.remove (listener);
  14981. if (listeners.size() == 0)
  14982. value->valuesWithListeners.removeValue (this);
  14983. }
  14984. void Value::callListeners()
  14985. {
  14986. Value v (*this); // (create a copy in case this gets deleted by a callback)
  14987. listeners.call (&ValueListener::valueChanged, v);
  14988. }
  14989. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  14990. {
  14991. return stream << value.toString();
  14992. }
  14993. END_JUCE_NAMESPACE
  14994. /*** End of inlined file: juce_Value.cpp ***/
  14995. /*** Start of inlined file: juce_Application.cpp ***/
  14996. BEGIN_JUCE_NAMESPACE
  14997. #if JUCE_MAC
  14998. extern void juce_initialiseMacMainMenu();
  14999. #endif
  15000. JUCEApplication::JUCEApplication()
  15001. : appReturnValue (0),
  15002. stillInitialising (true)
  15003. {
  15004. jassert (isStandaloneApp() && appInstance == 0);
  15005. appInstance = this;
  15006. }
  15007. JUCEApplication::~JUCEApplication()
  15008. {
  15009. if (appLock != 0)
  15010. {
  15011. appLock->exit();
  15012. appLock = 0;
  15013. }
  15014. jassert (appInstance == this);
  15015. appInstance = 0;
  15016. }
  15017. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15018. JUCEApplication* JUCEApplication::appInstance = 0;
  15019. bool JUCEApplication::moreThanOneInstanceAllowed()
  15020. {
  15021. return true;
  15022. }
  15023. void JUCEApplication::anotherInstanceStarted (const String&)
  15024. {
  15025. }
  15026. void JUCEApplication::systemRequestedQuit()
  15027. {
  15028. quit();
  15029. }
  15030. void JUCEApplication::quit()
  15031. {
  15032. MessageManager::getInstance()->stopDispatchLoop();
  15033. }
  15034. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15035. {
  15036. appReturnValue = newReturnValue;
  15037. }
  15038. void JUCEApplication::actionListenerCallback (const String& message)
  15039. {
  15040. if (message.startsWith (getApplicationName() + "/"))
  15041. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15042. }
  15043. void JUCEApplication::unhandledException (const std::exception*,
  15044. const String&,
  15045. const int)
  15046. {
  15047. jassertfalse;
  15048. }
  15049. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15050. const char* const sourceFile,
  15051. const int lineNumber)
  15052. {
  15053. if (appInstance != 0)
  15054. appInstance->unhandledException (e, sourceFile, lineNumber);
  15055. }
  15056. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15057. {
  15058. return 0;
  15059. }
  15060. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15061. {
  15062. commands.add (StandardApplicationCommandIDs::quit);
  15063. }
  15064. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15065. {
  15066. if (commandID == StandardApplicationCommandIDs::quit)
  15067. {
  15068. result.setInfo (TRANS("Quit"),
  15069. TRANS("Quits the application"),
  15070. "Application",
  15071. 0);
  15072. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15073. }
  15074. }
  15075. bool JUCEApplication::perform (const InvocationInfo& info)
  15076. {
  15077. if (info.commandID == StandardApplicationCommandIDs::quit)
  15078. {
  15079. systemRequestedQuit();
  15080. return true;
  15081. }
  15082. return false;
  15083. }
  15084. bool JUCEApplication::initialiseApp (const String& commandLine)
  15085. {
  15086. commandLineParameters = commandLine.trim();
  15087. #if ! JUCE_IOS
  15088. jassert (appLock == 0); // initialiseApp must only be called once!
  15089. if (! moreThanOneInstanceAllowed())
  15090. {
  15091. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15092. if (! appLock->enter(0))
  15093. {
  15094. appLock = 0;
  15095. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15096. DBG ("Another instance is running - quitting...");
  15097. return false;
  15098. }
  15099. }
  15100. #endif
  15101. // let the app do its setting-up..
  15102. initialise (commandLineParameters);
  15103. #if JUCE_MAC
  15104. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15105. #endif
  15106. // register for broadcast new app messages
  15107. MessageManager::getInstance()->registerBroadcastListener (this);
  15108. stillInitialising = false;
  15109. return true;
  15110. }
  15111. int JUCEApplication::shutdownApp()
  15112. {
  15113. jassert (appInstance == this);
  15114. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15115. JUCE_TRY
  15116. {
  15117. // give the app a chance to clean up..
  15118. shutdown();
  15119. }
  15120. JUCE_CATCH_EXCEPTION
  15121. return getApplicationReturnValue();
  15122. }
  15123. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15124. void JUCEApplication::appWillTerminateByForce()
  15125. {
  15126. {
  15127. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15128. if (app != 0)
  15129. app->shutdownApp();
  15130. }
  15131. shutdownJuce_GUI();
  15132. }
  15133. int JUCEApplication::main (const String& commandLine)
  15134. {
  15135. ScopedJuceInitialiser_GUI libraryInitialiser;
  15136. jassert (createInstance != 0);
  15137. int returnCode = 0;
  15138. {
  15139. const ScopedPointer<JUCEApplication> app (createInstance());
  15140. if (! app->initialiseApp (commandLine))
  15141. return 0;
  15142. JUCE_TRY
  15143. {
  15144. // loop until a quit message is received..
  15145. MessageManager::getInstance()->runDispatchLoop();
  15146. }
  15147. JUCE_CATCH_EXCEPTION
  15148. returnCode = app->shutdownApp();
  15149. }
  15150. return returnCode;
  15151. }
  15152. #if JUCE_IOS
  15153. extern int juce_iOSMain (int argc, const char* argv[]);
  15154. #endif
  15155. #if ! JUCE_WINDOWS
  15156. extern const char* juce_Argv0;
  15157. #endif
  15158. int JUCEApplication::main (int argc, const char* argv[])
  15159. {
  15160. JUCE_AUTORELEASEPOOL
  15161. #if ! JUCE_WINDOWS
  15162. jassert (createInstance != 0);
  15163. juce_Argv0 = argv[0];
  15164. #endif
  15165. #if JUCE_IOS
  15166. return juce_iOSMain (argc, argv);
  15167. #else
  15168. String cmd;
  15169. for (int i = 1; i < argc; ++i)
  15170. cmd << argv[i] << ' ';
  15171. return JUCEApplication::main (cmd);
  15172. #endif
  15173. }
  15174. END_JUCE_NAMESPACE
  15175. /*** End of inlined file: juce_Application.cpp ***/
  15176. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15177. BEGIN_JUCE_NAMESPACE
  15178. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15179. : commandID (commandID_),
  15180. flags (0)
  15181. {
  15182. }
  15183. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15184. const String& description_,
  15185. const String& categoryName_,
  15186. const int flags_) throw()
  15187. {
  15188. shortName = shortName_;
  15189. description = description_;
  15190. categoryName = categoryName_;
  15191. flags = flags_;
  15192. }
  15193. void ApplicationCommandInfo::setActive (const bool b) throw()
  15194. {
  15195. if (b)
  15196. flags &= ~isDisabled;
  15197. else
  15198. flags |= isDisabled;
  15199. }
  15200. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15201. {
  15202. if (b)
  15203. flags |= isTicked;
  15204. else
  15205. flags &= ~isTicked;
  15206. }
  15207. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15208. {
  15209. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15210. }
  15211. END_JUCE_NAMESPACE
  15212. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15213. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15214. BEGIN_JUCE_NAMESPACE
  15215. ApplicationCommandManager::ApplicationCommandManager()
  15216. : firstTarget (0)
  15217. {
  15218. keyMappings = new KeyPressMappingSet (this);
  15219. Desktop::getInstance().addFocusChangeListener (this);
  15220. }
  15221. ApplicationCommandManager::~ApplicationCommandManager()
  15222. {
  15223. Desktop::getInstance().removeFocusChangeListener (this);
  15224. keyMappings = 0;
  15225. }
  15226. void ApplicationCommandManager::clearCommands()
  15227. {
  15228. commands.clear();
  15229. keyMappings->clearAllKeyPresses();
  15230. triggerAsyncUpdate();
  15231. }
  15232. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15233. {
  15234. // zero isn't a valid command ID!
  15235. jassert (newCommand.commandID != 0);
  15236. // the name isn't optional!
  15237. jassert (newCommand.shortName.isNotEmpty());
  15238. if (getCommandForID (newCommand.commandID) == 0)
  15239. {
  15240. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15241. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15242. commands.add (newInfo);
  15243. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15244. triggerAsyncUpdate();
  15245. }
  15246. else
  15247. {
  15248. // trying to re-register the same command with different parameters?
  15249. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15250. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15251. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15252. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15253. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15254. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15255. }
  15256. }
  15257. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15258. {
  15259. if (target != 0)
  15260. {
  15261. Array <CommandID> commandIDs;
  15262. target->getAllCommands (commandIDs);
  15263. for (int i = 0; i < commandIDs.size(); ++i)
  15264. {
  15265. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15266. target->getCommandInfo (info.commandID, info);
  15267. registerCommand (info);
  15268. }
  15269. }
  15270. }
  15271. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15272. {
  15273. for (int i = commands.size(); --i >= 0;)
  15274. {
  15275. if (commands.getUnchecked (i)->commandID == commandID)
  15276. {
  15277. commands.remove (i);
  15278. triggerAsyncUpdate();
  15279. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15280. for (int j = keys.size(); --j >= 0;)
  15281. keyMappings->removeKeyPress (keys.getReference (j));
  15282. }
  15283. }
  15284. }
  15285. void ApplicationCommandManager::commandStatusChanged()
  15286. {
  15287. triggerAsyncUpdate();
  15288. }
  15289. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15290. {
  15291. for (int i = commands.size(); --i >= 0;)
  15292. if (commands.getUnchecked(i)->commandID == commandID)
  15293. return commands.getUnchecked(i);
  15294. return 0;
  15295. }
  15296. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15297. {
  15298. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15299. return (ci != 0) ? ci->shortName : String::empty;
  15300. }
  15301. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15302. {
  15303. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15304. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15305. : String::empty;
  15306. }
  15307. const StringArray ApplicationCommandManager::getCommandCategories() const
  15308. {
  15309. StringArray s;
  15310. for (int i = 0; i < commands.size(); ++i)
  15311. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15312. return s;
  15313. }
  15314. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15315. {
  15316. Array <CommandID> results;
  15317. for (int i = 0; i < commands.size(); ++i)
  15318. if (commands.getUnchecked(i)->categoryName == categoryName)
  15319. results.add (commands.getUnchecked(i)->commandID);
  15320. return results;
  15321. }
  15322. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15323. {
  15324. ApplicationCommandTarget::InvocationInfo info (commandID);
  15325. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15326. return invoke (info, asynchronously);
  15327. }
  15328. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15329. {
  15330. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15331. // manager first..
  15332. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15333. ApplicationCommandInfo commandInfo (0);
  15334. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15335. if (target == 0)
  15336. return false;
  15337. ApplicationCommandTarget::InvocationInfo info (info_);
  15338. info.commandFlags = commandInfo.flags;
  15339. sendListenerInvokeCallback (info);
  15340. const bool ok = target->invoke (info, asynchronously);
  15341. commandStatusChanged();
  15342. return ok;
  15343. }
  15344. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15345. {
  15346. return firstTarget != 0 ? firstTarget
  15347. : findDefaultComponentTarget();
  15348. }
  15349. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15350. {
  15351. firstTarget = newTarget;
  15352. }
  15353. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15354. ApplicationCommandInfo& upToDateInfo)
  15355. {
  15356. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15357. if (target == 0)
  15358. target = JUCEApplication::getInstance();
  15359. if (target != 0)
  15360. target = target->getTargetForCommand (commandID);
  15361. if (target != 0)
  15362. target->getCommandInfo (commandID, upToDateInfo);
  15363. return target;
  15364. }
  15365. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15366. {
  15367. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15368. if (target == 0 && c != 0)
  15369. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15370. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15371. return target;
  15372. }
  15373. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15374. {
  15375. Component* c = Component::getCurrentlyFocusedComponent();
  15376. if (c == 0)
  15377. {
  15378. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15379. if (activeWindow != 0)
  15380. {
  15381. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15382. if (c == 0)
  15383. c = activeWindow;
  15384. }
  15385. }
  15386. if (c == 0 && Process::isForegroundProcess())
  15387. {
  15388. // getting a bit desperate now - try all desktop comps..
  15389. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15390. {
  15391. ApplicationCommandTarget* const target
  15392. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15393. ->getPeer()->getLastFocusedSubcomponent());
  15394. if (target != 0)
  15395. return target;
  15396. }
  15397. }
  15398. if (c != 0)
  15399. {
  15400. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15401. // if we're focused on a ResizableWindow, chances are that it's the content
  15402. // component that really should get the event. And if not, the event will
  15403. // still be passed up to the top level window anyway, so let's send it to the
  15404. // content comp.
  15405. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15406. c = resizableWindow->getContentComponent();
  15407. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15408. if (target != 0)
  15409. return target;
  15410. }
  15411. return JUCEApplication::getInstance();
  15412. }
  15413. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15414. {
  15415. listeners.add (listener);
  15416. }
  15417. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15418. {
  15419. listeners.remove (listener);
  15420. }
  15421. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15422. {
  15423. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15424. }
  15425. void ApplicationCommandManager::handleAsyncUpdate()
  15426. {
  15427. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15428. }
  15429. void ApplicationCommandManager::globalFocusChanged (Component*)
  15430. {
  15431. commandStatusChanged();
  15432. }
  15433. END_JUCE_NAMESPACE
  15434. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15435. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15436. BEGIN_JUCE_NAMESPACE
  15437. ApplicationCommandTarget::ApplicationCommandTarget()
  15438. {
  15439. }
  15440. ApplicationCommandTarget::~ApplicationCommandTarget()
  15441. {
  15442. messageInvoker = 0;
  15443. }
  15444. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15445. {
  15446. if (isCommandActive (info.commandID))
  15447. {
  15448. if (async)
  15449. {
  15450. if (messageInvoker == 0)
  15451. messageInvoker = new CommandTargetMessageInvoker (this);
  15452. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15453. return true;
  15454. }
  15455. else
  15456. {
  15457. const bool success = perform (info);
  15458. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15459. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15460. // returns the command's info.
  15461. return success;
  15462. }
  15463. }
  15464. return false;
  15465. }
  15466. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15467. {
  15468. Component* c = dynamic_cast <Component*> (this);
  15469. if (c != 0)
  15470. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15471. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15472. return 0;
  15473. }
  15474. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15475. {
  15476. ApplicationCommandTarget* target = this;
  15477. int depth = 0;
  15478. while (target != 0)
  15479. {
  15480. Array <CommandID> commandIDs;
  15481. target->getAllCommands (commandIDs);
  15482. if (commandIDs.contains (commandID))
  15483. return target;
  15484. target = target->getNextCommandTarget();
  15485. ++depth;
  15486. jassert (depth < 100); // could be a recursive command chain??
  15487. jassert (target != this); // definitely a recursive command chain!
  15488. if (depth > 100 || target == this)
  15489. break;
  15490. }
  15491. if (target == 0)
  15492. {
  15493. target = JUCEApplication::getInstance();
  15494. if (target != 0)
  15495. {
  15496. Array <CommandID> commandIDs;
  15497. target->getAllCommands (commandIDs);
  15498. if (commandIDs.contains (commandID))
  15499. return target;
  15500. }
  15501. }
  15502. return 0;
  15503. }
  15504. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15505. {
  15506. ApplicationCommandInfo info (commandID);
  15507. info.flags = ApplicationCommandInfo::isDisabled;
  15508. getCommandInfo (commandID, info);
  15509. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15510. }
  15511. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15512. {
  15513. ApplicationCommandTarget* target = this;
  15514. int depth = 0;
  15515. while (target != 0)
  15516. {
  15517. if (target->tryToInvoke (info, async))
  15518. return true;
  15519. target = target->getNextCommandTarget();
  15520. ++depth;
  15521. jassert (depth < 100); // could be a recursive command chain??
  15522. jassert (target != this); // definitely a recursive command chain!
  15523. if (depth > 100 || target == this)
  15524. break;
  15525. }
  15526. if (target == 0)
  15527. {
  15528. target = JUCEApplication::getInstance();
  15529. if (target != 0)
  15530. return target->tryToInvoke (info, async);
  15531. }
  15532. return false;
  15533. }
  15534. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15535. {
  15536. ApplicationCommandTarget::InvocationInfo info (commandID);
  15537. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15538. return invoke (info, asynchronously);
  15539. }
  15540. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15541. : commandID (commandID_),
  15542. commandFlags (0),
  15543. invocationMethod (direct),
  15544. originatingComponent (0),
  15545. isKeyDown (false),
  15546. millisecsSinceKeyPressed (0)
  15547. {
  15548. }
  15549. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15550. : owner (owner_)
  15551. {
  15552. }
  15553. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15554. {
  15555. }
  15556. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15557. {
  15558. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15559. owner->tryToInvoke (*info, false);
  15560. }
  15561. END_JUCE_NAMESPACE
  15562. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15563. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15564. BEGIN_JUCE_NAMESPACE
  15565. juce_ImplementSingleton (ApplicationProperties)
  15566. ApplicationProperties::ApplicationProperties()
  15567. : msBeforeSaving (3000),
  15568. options (PropertiesFile::storeAsBinary),
  15569. commonSettingsAreReadOnly (0),
  15570. processLock (0)
  15571. {
  15572. }
  15573. ApplicationProperties::~ApplicationProperties()
  15574. {
  15575. closeFiles();
  15576. clearSingletonInstance();
  15577. }
  15578. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15579. const String& fileNameSuffix,
  15580. const String& folderName_,
  15581. const int millisecondsBeforeSaving,
  15582. const int propertiesFileOptions,
  15583. InterProcessLock* processLock_)
  15584. {
  15585. appName = applicationName;
  15586. fileSuffix = fileNameSuffix;
  15587. folderName = folderName_;
  15588. msBeforeSaving = millisecondsBeforeSaving;
  15589. options = propertiesFileOptions;
  15590. processLock = processLock_;
  15591. }
  15592. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15593. const bool testCommonSettings,
  15594. const bool showWarningDialogOnFailure)
  15595. {
  15596. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15597. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15598. if (! (userOk && commonOk))
  15599. {
  15600. if (showWarningDialogOnFailure)
  15601. {
  15602. String filenames;
  15603. if (userProps != 0 && ! userOk)
  15604. filenames << '\n' << userProps->getFile().getFullPathName();
  15605. if (commonProps != 0 && ! commonOk)
  15606. filenames << '\n' << commonProps->getFile().getFullPathName();
  15607. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15608. appName + TRANS(" - Unable to save settings"),
  15609. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15610. + appName + TRANS(" needs to be able to write to the following files:\n")
  15611. + filenames
  15612. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15613. }
  15614. return false;
  15615. }
  15616. return true;
  15617. }
  15618. void ApplicationProperties::openFiles()
  15619. {
  15620. // You need to call setStorageParameters() before trying to get hold of the
  15621. // properties!
  15622. jassert (appName.isNotEmpty());
  15623. if (appName.isNotEmpty())
  15624. {
  15625. if (userProps == 0)
  15626. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15627. false, msBeforeSaving, options, processLock);
  15628. if (commonProps == 0)
  15629. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15630. true, msBeforeSaving, options, processLock);
  15631. userProps->setFallbackPropertySet (commonProps);
  15632. }
  15633. }
  15634. PropertiesFile* ApplicationProperties::getUserSettings()
  15635. {
  15636. if (userProps == 0)
  15637. openFiles();
  15638. return userProps;
  15639. }
  15640. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15641. {
  15642. if (commonProps == 0)
  15643. openFiles();
  15644. if (returnUserPropsIfReadOnly)
  15645. {
  15646. if (commonSettingsAreReadOnly == 0)
  15647. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15648. if (commonSettingsAreReadOnly > 0)
  15649. return userProps;
  15650. }
  15651. return commonProps;
  15652. }
  15653. bool ApplicationProperties::saveIfNeeded()
  15654. {
  15655. return (userProps == 0 || userProps->saveIfNeeded())
  15656. && (commonProps == 0 || commonProps->saveIfNeeded());
  15657. }
  15658. void ApplicationProperties::closeFiles()
  15659. {
  15660. userProps = 0;
  15661. commonProps = 0;
  15662. }
  15663. END_JUCE_NAMESPACE
  15664. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15665. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15666. BEGIN_JUCE_NAMESPACE
  15667. namespace PropertyFileConstants
  15668. {
  15669. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15670. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15671. static const char* const fileTag = "PROPERTIES";
  15672. static const char* const valueTag = "VALUE";
  15673. static const char* const nameAttribute = "name";
  15674. static const char* const valueAttribute = "val";
  15675. }
  15676. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15677. const int options_, InterProcessLock* const processLock_)
  15678. : PropertySet (ignoreCaseOfKeyNames),
  15679. file (f),
  15680. timerInterval (millisecondsBeforeSaving),
  15681. options (options_),
  15682. loadedOk (false),
  15683. needsWriting (false),
  15684. processLock (processLock_)
  15685. {
  15686. // You need to correctly specify just one storage format for the file
  15687. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15688. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15689. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15690. ProcessScopedLock pl (createProcessLock());
  15691. if (pl != 0 && ! pl->isLocked())
  15692. return; // locking failure..
  15693. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15694. if (fileStream != 0)
  15695. {
  15696. int magicNumber = fileStream->readInt();
  15697. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15698. {
  15699. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15700. magicNumber = PropertyFileConstants::magicNumber;
  15701. }
  15702. if (magicNumber == PropertyFileConstants::magicNumber)
  15703. {
  15704. loadedOk = true;
  15705. BufferedInputStream in (fileStream.release(), 2048, true);
  15706. int numValues = in.readInt();
  15707. while (--numValues >= 0 && ! in.isExhausted())
  15708. {
  15709. const String key (in.readString());
  15710. const String value (in.readString());
  15711. jassert (key.isNotEmpty());
  15712. if (key.isNotEmpty())
  15713. getAllProperties().set (key, value);
  15714. }
  15715. }
  15716. else
  15717. {
  15718. // Not a binary props file - let's see if it's XML..
  15719. fileStream = 0;
  15720. XmlDocument parser (f);
  15721. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15722. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15723. {
  15724. doc = parser.getDocumentElement();
  15725. if (doc != 0)
  15726. {
  15727. loadedOk = true;
  15728. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15729. {
  15730. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15731. if (name.isNotEmpty())
  15732. {
  15733. getAllProperties().set (name,
  15734. e->getFirstChildElement() != 0
  15735. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15736. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15737. }
  15738. }
  15739. }
  15740. else
  15741. {
  15742. // must be a pretty broken XML file we're trying to parse here,
  15743. // or a sign that this object needs an InterProcessLock,
  15744. // or just a failure reading the file. This last reason is why
  15745. // we don't jassertfalse here.
  15746. }
  15747. }
  15748. }
  15749. }
  15750. else
  15751. {
  15752. loadedOk = ! f.exists();
  15753. }
  15754. }
  15755. PropertiesFile::~PropertiesFile()
  15756. {
  15757. if (! saveIfNeeded())
  15758. jassertfalse;
  15759. }
  15760. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15761. {
  15762. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15763. }
  15764. bool PropertiesFile::saveIfNeeded()
  15765. {
  15766. const ScopedLock sl (getLock());
  15767. return (! needsWriting) || save();
  15768. }
  15769. bool PropertiesFile::needsToBeSaved() const
  15770. {
  15771. const ScopedLock sl (getLock());
  15772. return needsWriting;
  15773. }
  15774. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15775. {
  15776. const ScopedLock sl (getLock());
  15777. needsWriting = needsToBeSaved_;
  15778. }
  15779. bool PropertiesFile::save()
  15780. {
  15781. const ScopedLock sl (getLock());
  15782. stopTimer();
  15783. if (file == File::nonexistent
  15784. || file.isDirectory()
  15785. || ! file.getParentDirectory().createDirectory())
  15786. return false;
  15787. if ((options & storeAsXML) != 0)
  15788. {
  15789. XmlElement doc (PropertyFileConstants::fileTag);
  15790. for (int i = 0; i < getAllProperties().size(); ++i)
  15791. {
  15792. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15793. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15794. // if the value seems to contain xml, store it as such..
  15795. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  15796. if (childElement != 0)
  15797. e->addChildElement (childElement);
  15798. else
  15799. e->setAttribute (PropertyFileConstants::valueAttribute,
  15800. getAllProperties().getAllValues() [i]);
  15801. }
  15802. ProcessScopedLock pl (createProcessLock());
  15803. if (pl != 0 && ! pl->isLocked())
  15804. return false; // locking failure..
  15805. if (doc.writeToFile (file, String::empty))
  15806. {
  15807. needsWriting = false;
  15808. return true;
  15809. }
  15810. }
  15811. else
  15812. {
  15813. ProcessScopedLock pl (createProcessLock());
  15814. if (pl != 0 && ! pl->isLocked())
  15815. return false; // locking failure..
  15816. TemporaryFile tempFile (file);
  15817. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15818. if (out != 0)
  15819. {
  15820. if ((options & storeAsCompressedBinary) != 0)
  15821. {
  15822. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15823. out->flush();
  15824. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15825. }
  15826. else
  15827. {
  15828. // have you set up the storage option flags correctly?
  15829. jassert ((options & storeAsBinary) != 0);
  15830. out->writeInt (PropertyFileConstants::magicNumber);
  15831. }
  15832. const int numProperties = getAllProperties().size();
  15833. out->writeInt (numProperties);
  15834. for (int i = 0; i < numProperties; ++i)
  15835. {
  15836. out->writeString (getAllProperties().getAllKeys() [i]);
  15837. out->writeString (getAllProperties().getAllValues() [i]);
  15838. }
  15839. out = 0;
  15840. if (tempFile.overwriteTargetFileWithTemporary())
  15841. {
  15842. needsWriting = false;
  15843. return true;
  15844. }
  15845. }
  15846. }
  15847. return false;
  15848. }
  15849. void PropertiesFile::timerCallback()
  15850. {
  15851. saveIfNeeded();
  15852. }
  15853. void PropertiesFile::propertyChanged()
  15854. {
  15855. sendChangeMessage();
  15856. needsWriting = true;
  15857. if (timerInterval > 0)
  15858. startTimer (timerInterval);
  15859. else if (timerInterval == 0)
  15860. saveIfNeeded();
  15861. }
  15862. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15863. const String& fileNameSuffix,
  15864. const String& folderName,
  15865. const bool commonToAllUsers)
  15866. {
  15867. // mustn't have illegal characters in this name..
  15868. jassert (applicationName == File::createLegalFileName (applicationName));
  15869. #if JUCE_MAC || JUCE_IOS
  15870. File dir (commonToAllUsers ? "/Library/Preferences"
  15871. : "~/Library/Preferences");
  15872. if (folderName.isNotEmpty())
  15873. dir = dir.getChildFile (folderName);
  15874. #endif
  15875. #ifdef JUCE_LINUX
  15876. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15877. + (folderName.isNotEmpty() ? folderName
  15878. : ("." + applicationName)));
  15879. #endif
  15880. #if JUCE_WINDOWS
  15881. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15882. : File::userApplicationDataDirectory));
  15883. if (dir == File::nonexistent)
  15884. return File::nonexistent;
  15885. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15886. : applicationName);
  15887. #endif
  15888. return dir.getChildFile (applicationName)
  15889. .withFileExtension (fileNameSuffix);
  15890. }
  15891. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15892. const String& fileNameSuffix,
  15893. const String& folderName,
  15894. const bool commonToAllUsers,
  15895. const int millisecondsBeforeSaving,
  15896. const int propertiesFileOptions,
  15897. InterProcessLock* processLock_)
  15898. {
  15899. const File file (getDefaultAppSettingsFile (applicationName,
  15900. fileNameSuffix,
  15901. folderName,
  15902. commonToAllUsers));
  15903. jassert (file != File::nonexistent);
  15904. if (file == File::nonexistent)
  15905. return 0;
  15906. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15907. }
  15908. END_JUCE_NAMESPACE
  15909. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15910. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15911. BEGIN_JUCE_NAMESPACE
  15912. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15913. const String& fileWildcard_,
  15914. const String& openFileDialogTitle_,
  15915. const String& saveFileDialogTitle_)
  15916. : changedSinceSave (false),
  15917. fileExtension (fileExtension_),
  15918. fileWildcard (fileWildcard_),
  15919. openFileDialogTitle (openFileDialogTitle_),
  15920. saveFileDialogTitle (saveFileDialogTitle_)
  15921. {
  15922. }
  15923. FileBasedDocument::~FileBasedDocument()
  15924. {
  15925. }
  15926. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15927. {
  15928. if (changedSinceSave != hasChanged)
  15929. {
  15930. changedSinceSave = hasChanged;
  15931. sendChangeMessage();
  15932. }
  15933. }
  15934. void FileBasedDocument::changed()
  15935. {
  15936. changedSinceSave = true;
  15937. sendChangeMessage();
  15938. }
  15939. void FileBasedDocument::setFile (const File& newFile)
  15940. {
  15941. if (documentFile != newFile)
  15942. {
  15943. documentFile = newFile;
  15944. changed();
  15945. }
  15946. }
  15947. bool FileBasedDocument::loadFrom (const File& newFile,
  15948. const bool showMessageOnFailure)
  15949. {
  15950. MouseCursor::showWaitCursor();
  15951. const File oldFile (documentFile);
  15952. documentFile = newFile;
  15953. String error;
  15954. if (newFile.existsAsFile())
  15955. {
  15956. error = loadDocument (newFile);
  15957. if (error.isEmpty())
  15958. {
  15959. setChangedFlag (false);
  15960. MouseCursor::hideWaitCursor();
  15961. setLastDocumentOpened (newFile);
  15962. return true;
  15963. }
  15964. }
  15965. else
  15966. {
  15967. error = "The file doesn't exist";
  15968. }
  15969. documentFile = oldFile;
  15970. MouseCursor::hideWaitCursor();
  15971. if (showMessageOnFailure)
  15972. {
  15973. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15974. TRANS("Failed to open file..."),
  15975. TRANS("There was an error while trying to load the file:\n\n")
  15976. + newFile.getFullPathName()
  15977. + "\n\n"
  15978. + error);
  15979. }
  15980. return false;
  15981. }
  15982. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  15983. {
  15984. FileChooser fc (openFileDialogTitle,
  15985. getLastDocumentOpened(),
  15986. fileWildcard);
  15987. if (fc.browseForFileToOpen())
  15988. return loadFrom (fc.getResult(), showMessageOnFailure);
  15989. return false;
  15990. }
  15991. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  15992. const bool showMessageOnFailure)
  15993. {
  15994. return saveAs (documentFile,
  15995. false,
  15996. askUserForFileIfNotSpecified,
  15997. showMessageOnFailure);
  15998. }
  15999. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16000. const bool warnAboutOverwritingExistingFiles,
  16001. const bool askUserForFileIfNotSpecified,
  16002. const bool showMessageOnFailure)
  16003. {
  16004. if (newFile == File::nonexistent)
  16005. {
  16006. if (askUserForFileIfNotSpecified)
  16007. {
  16008. return saveAsInteractive (true);
  16009. }
  16010. else
  16011. {
  16012. // can't save to an unspecified file
  16013. jassertfalse;
  16014. return failedToWriteToFile;
  16015. }
  16016. }
  16017. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16018. {
  16019. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16020. TRANS("File already exists"),
  16021. TRANS("There's already a file called:\n\n")
  16022. + newFile.getFullPathName()
  16023. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16024. TRANS("overwrite"),
  16025. TRANS("cancel")))
  16026. {
  16027. return userCancelledSave;
  16028. }
  16029. }
  16030. MouseCursor::showWaitCursor();
  16031. const File oldFile (documentFile);
  16032. documentFile = newFile;
  16033. String error (saveDocument (newFile));
  16034. if (error.isEmpty())
  16035. {
  16036. setChangedFlag (false);
  16037. MouseCursor::hideWaitCursor();
  16038. return savedOk;
  16039. }
  16040. documentFile = oldFile;
  16041. MouseCursor::hideWaitCursor();
  16042. if (showMessageOnFailure)
  16043. {
  16044. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16045. TRANS("Error writing to file..."),
  16046. TRANS("An error occurred while trying to save \"")
  16047. + getDocumentTitle()
  16048. + TRANS("\" to the file:\n\n")
  16049. + newFile.getFullPathName()
  16050. + "\n\n"
  16051. + error);
  16052. }
  16053. return failedToWriteToFile;
  16054. }
  16055. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16056. {
  16057. if (! hasChangedSinceSaved())
  16058. return savedOk;
  16059. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16060. TRANS("Closing document..."),
  16061. TRANS("Do you want to save the changes to \"")
  16062. + getDocumentTitle() + "\"?",
  16063. TRANS("save"),
  16064. TRANS("discard changes"),
  16065. TRANS("cancel"));
  16066. if (r == 1)
  16067. {
  16068. // save changes
  16069. return save (true, true);
  16070. }
  16071. else if (r == 2)
  16072. {
  16073. // discard changes
  16074. return savedOk;
  16075. }
  16076. return userCancelledSave;
  16077. }
  16078. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16079. {
  16080. File f;
  16081. if (documentFile.existsAsFile())
  16082. f = documentFile;
  16083. else
  16084. f = getLastDocumentOpened();
  16085. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16086. if (legalFilename.isEmpty())
  16087. legalFilename = "unnamed";
  16088. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16089. f = f.getSiblingFile (legalFilename);
  16090. else
  16091. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16092. f = f.withFileExtension (fileExtension)
  16093. .getNonexistentSibling (true);
  16094. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16095. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16096. {
  16097. File chosen (fc.getResult());
  16098. if (chosen.getFileExtension().isEmpty())
  16099. {
  16100. chosen = chosen.withFileExtension (fileExtension);
  16101. if (chosen.exists())
  16102. {
  16103. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16104. TRANS("File already exists"),
  16105. TRANS("There's already a file called:")
  16106. + "\n\n" + chosen.getFullPathName()
  16107. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16108. TRANS("overwrite"),
  16109. TRANS("cancel")))
  16110. {
  16111. return userCancelledSave;
  16112. }
  16113. }
  16114. }
  16115. setLastDocumentOpened (chosen);
  16116. return saveAs (chosen, false, false, true);
  16117. }
  16118. return userCancelledSave;
  16119. }
  16120. END_JUCE_NAMESPACE
  16121. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16122. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16123. BEGIN_JUCE_NAMESPACE
  16124. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16125. : maxNumberOfItems (10)
  16126. {
  16127. }
  16128. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16129. {
  16130. }
  16131. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16132. {
  16133. maxNumberOfItems = jmax (1, newMaxNumber);
  16134. while (getNumFiles() > maxNumberOfItems)
  16135. files.remove (getNumFiles() - 1);
  16136. }
  16137. int RecentlyOpenedFilesList::getNumFiles() const
  16138. {
  16139. return files.size();
  16140. }
  16141. const File RecentlyOpenedFilesList::getFile (const int index) const
  16142. {
  16143. return File (files [index]);
  16144. }
  16145. void RecentlyOpenedFilesList::clear()
  16146. {
  16147. files.clear();
  16148. }
  16149. void RecentlyOpenedFilesList::addFile (const File& file)
  16150. {
  16151. const String path (file.getFullPathName());
  16152. files.removeString (path, true);
  16153. files.insert (0, path);
  16154. setMaxNumberOfItems (maxNumberOfItems);
  16155. }
  16156. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16157. {
  16158. for (int i = getNumFiles(); --i >= 0;)
  16159. if (! getFile(i).exists())
  16160. files.remove (i);
  16161. }
  16162. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16163. const int baseItemId,
  16164. const bool showFullPaths,
  16165. const bool dontAddNonExistentFiles,
  16166. const File** filesToAvoid)
  16167. {
  16168. int num = 0;
  16169. for (int i = 0; i < getNumFiles(); ++i)
  16170. {
  16171. const File f (getFile(i));
  16172. if ((! dontAddNonExistentFiles) || f.exists())
  16173. {
  16174. bool needsAvoiding = false;
  16175. if (filesToAvoid != 0)
  16176. {
  16177. const File** avoid = filesToAvoid;
  16178. while (*avoid != 0)
  16179. {
  16180. if (f == **avoid)
  16181. {
  16182. needsAvoiding = true;
  16183. break;
  16184. }
  16185. ++avoid;
  16186. }
  16187. }
  16188. if (! needsAvoiding)
  16189. {
  16190. menuToAddTo.addItem (baseItemId + i,
  16191. showFullPaths ? f.getFullPathName()
  16192. : f.getFileName());
  16193. ++num;
  16194. }
  16195. }
  16196. }
  16197. return num;
  16198. }
  16199. const String RecentlyOpenedFilesList::toString() const
  16200. {
  16201. return files.joinIntoString ("\n");
  16202. }
  16203. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16204. {
  16205. clear();
  16206. files.addLines (stringifiedVersion);
  16207. setMaxNumberOfItems (maxNumberOfItems);
  16208. }
  16209. END_JUCE_NAMESPACE
  16210. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16211. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16212. BEGIN_JUCE_NAMESPACE
  16213. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16214. const int minimumTransactions)
  16215. : totalUnitsStored (0),
  16216. nextIndex (0),
  16217. newTransaction (true),
  16218. reentrancyCheck (false)
  16219. {
  16220. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16221. minimumTransactions);
  16222. }
  16223. UndoManager::~UndoManager()
  16224. {
  16225. clearUndoHistory();
  16226. }
  16227. void UndoManager::clearUndoHistory()
  16228. {
  16229. transactions.clear();
  16230. transactionNames.clear();
  16231. totalUnitsStored = 0;
  16232. nextIndex = 0;
  16233. sendChangeMessage();
  16234. }
  16235. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16236. {
  16237. return totalUnitsStored;
  16238. }
  16239. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16240. const int minimumTransactions)
  16241. {
  16242. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16243. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16244. }
  16245. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16246. {
  16247. if (command_ != 0)
  16248. {
  16249. ScopedPointer<UndoableAction> command (command_);
  16250. if (actionName.isNotEmpty())
  16251. currentTransactionName = actionName;
  16252. if (reentrancyCheck)
  16253. {
  16254. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16255. // undo() methods, or else these actions won't actually get done.
  16256. return false;
  16257. }
  16258. else if (command->perform())
  16259. {
  16260. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16261. if (commandSet != 0 && ! newTransaction)
  16262. {
  16263. UndoableAction* lastAction = commandSet->getLast();
  16264. if (lastAction != 0)
  16265. {
  16266. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16267. if (coalescedAction != 0)
  16268. {
  16269. command = coalescedAction;
  16270. totalUnitsStored -= lastAction->getSizeInUnits();
  16271. commandSet->removeLast();
  16272. }
  16273. }
  16274. }
  16275. else
  16276. {
  16277. commandSet = new OwnedArray<UndoableAction>();
  16278. transactions.insert (nextIndex, commandSet);
  16279. transactionNames.insert (nextIndex, currentTransactionName);
  16280. ++nextIndex;
  16281. }
  16282. totalUnitsStored += command->getSizeInUnits();
  16283. commandSet->add (command.release());
  16284. newTransaction = false;
  16285. while (nextIndex < transactions.size())
  16286. {
  16287. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16288. for (int i = lastSet->size(); --i >= 0;)
  16289. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16290. transactions.removeLast();
  16291. transactionNames.remove (transactionNames.size() - 1);
  16292. }
  16293. while (nextIndex > 0
  16294. && totalUnitsStored > maxNumUnitsToKeep
  16295. && transactions.size() > minimumTransactionsToKeep)
  16296. {
  16297. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16298. for (int i = firstSet->size(); --i >= 0;)
  16299. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16300. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16301. transactions.remove (0);
  16302. transactionNames.remove (0);
  16303. --nextIndex;
  16304. }
  16305. sendChangeMessage();
  16306. return true;
  16307. }
  16308. }
  16309. return false;
  16310. }
  16311. void UndoManager::beginNewTransaction (const String& actionName)
  16312. {
  16313. newTransaction = true;
  16314. currentTransactionName = actionName;
  16315. }
  16316. void UndoManager::setCurrentTransactionName (const String& newName)
  16317. {
  16318. currentTransactionName = newName;
  16319. }
  16320. bool UndoManager::canUndo() const
  16321. {
  16322. return nextIndex > 0;
  16323. }
  16324. bool UndoManager::canRedo() const
  16325. {
  16326. return nextIndex < transactions.size();
  16327. }
  16328. const String UndoManager::getUndoDescription() const
  16329. {
  16330. return transactionNames [nextIndex - 1];
  16331. }
  16332. const String UndoManager::getRedoDescription() const
  16333. {
  16334. return transactionNames [nextIndex];
  16335. }
  16336. bool UndoManager::undo()
  16337. {
  16338. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16339. if (commandSet == 0)
  16340. return false;
  16341. reentrancyCheck = true;
  16342. bool failed = false;
  16343. for (int i = commandSet->size(); --i >= 0;)
  16344. {
  16345. if (! commandSet->getUnchecked(i)->undo())
  16346. {
  16347. jassertfalse;
  16348. failed = true;
  16349. break;
  16350. }
  16351. }
  16352. reentrancyCheck = false;
  16353. if (failed)
  16354. clearUndoHistory();
  16355. else
  16356. --nextIndex;
  16357. beginNewTransaction();
  16358. sendChangeMessage();
  16359. return true;
  16360. }
  16361. bool UndoManager::redo()
  16362. {
  16363. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16364. if (commandSet == 0)
  16365. return false;
  16366. reentrancyCheck = true;
  16367. bool failed = false;
  16368. for (int i = 0; i < commandSet->size(); ++i)
  16369. {
  16370. if (! commandSet->getUnchecked(i)->perform())
  16371. {
  16372. jassertfalse;
  16373. failed = true;
  16374. break;
  16375. }
  16376. }
  16377. reentrancyCheck = false;
  16378. if (failed)
  16379. clearUndoHistory();
  16380. else
  16381. ++nextIndex;
  16382. beginNewTransaction();
  16383. sendChangeMessage();
  16384. return true;
  16385. }
  16386. bool UndoManager::undoCurrentTransactionOnly()
  16387. {
  16388. return newTransaction ? false : undo();
  16389. }
  16390. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16391. {
  16392. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16393. if (commandSet != 0 && ! newTransaction)
  16394. {
  16395. for (int i = 0; i < commandSet->size(); ++i)
  16396. actionsFound.add (commandSet->getUnchecked(i));
  16397. }
  16398. }
  16399. int UndoManager::getNumActionsInCurrentTransaction() const
  16400. {
  16401. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16402. if (commandSet != 0 && ! newTransaction)
  16403. return commandSet->size();
  16404. return 0;
  16405. }
  16406. END_JUCE_NAMESPACE
  16407. /*** End of inlined file: juce_UndoManager.cpp ***/
  16408. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16409. BEGIN_JUCE_NAMESPACE
  16410. static const char* const aiffFormatName = "AIFF file";
  16411. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16412. class AiffAudioFormatReader : public AudioFormatReader
  16413. {
  16414. public:
  16415. int bytesPerFrame;
  16416. int64 dataChunkStart;
  16417. bool littleEndian;
  16418. AiffAudioFormatReader (InputStream* in)
  16419. : AudioFormatReader (in, TRANS (aiffFormatName))
  16420. {
  16421. if (input->readInt() == chunkName ("FORM"))
  16422. {
  16423. const int len = input->readIntBigEndian();
  16424. const int64 end = input->getPosition() + len;
  16425. const int nextType = input->readInt();
  16426. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16427. {
  16428. bool hasGotVer = false;
  16429. bool hasGotData = false;
  16430. bool hasGotType = false;
  16431. while (input->getPosition() < end)
  16432. {
  16433. const int type = input->readInt();
  16434. const uint32 length = (uint32) input->readIntBigEndian();
  16435. const int64 chunkEnd = input->getPosition() + length;
  16436. if (type == chunkName ("FVER"))
  16437. {
  16438. hasGotVer = true;
  16439. const int ver = input->readIntBigEndian();
  16440. if (ver != 0 && ver != (int) 0xa2805140)
  16441. break;
  16442. }
  16443. else if (type == chunkName ("COMM"))
  16444. {
  16445. hasGotType = true;
  16446. numChannels = (unsigned int) input->readShortBigEndian();
  16447. lengthInSamples = input->readIntBigEndian();
  16448. bitsPerSample = input->readShortBigEndian();
  16449. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16450. unsigned char sampleRateBytes[10];
  16451. input->read (sampleRateBytes, 10);
  16452. const int byte0 = sampleRateBytes[0];
  16453. if ((byte0 & 0x80) != 0
  16454. || byte0 <= 0x3F || byte0 > 0x40
  16455. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16456. break;
  16457. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16458. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16459. sampleRate = (int) sampRate;
  16460. if (length <= 18)
  16461. {
  16462. // some types don't have a chunk large enough to include a compression
  16463. // type, so assume it's just big-endian pcm
  16464. littleEndian = false;
  16465. }
  16466. else
  16467. {
  16468. const int compType = input->readInt();
  16469. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16470. {
  16471. littleEndian = false;
  16472. }
  16473. else if (compType == chunkName ("sowt"))
  16474. {
  16475. littleEndian = true;
  16476. }
  16477. else
  16478. {
  16479. sampleRate = 0;
  16480. break;
  16481. }
  16482. }
  16483. }
  16484. else if (type == chunkName ("SSND"))
  16485. {
  16486. hasGotData = true;
  16487. const int offset = input->readIntBigEndian();
  16488. dataChunkStart = input->getPosition() + 4 + offset;
  16489. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16490. }
  16491. else if ((hasGotVer && hasGotData && hasGotType)
  16492. || chunkEnd < input->getPosition()
  16493. || input->isExhausted())
  16494. {
  16495. break;
  16496. }
  16497. input->setPosition (chunkEnd);
  16498. }
  16499. }
  16500. }
  16501. }
  16502. ~AiffAudioFormatReader()
  16503. {
  16504. }
  16505. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16506. int64 startSampleInFile, int numSamples)
  16507. {
  16508. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16509. if (samplesAvailable < numSamples)
  16510. {
  16511. for (int i = numDestChannels; --i >= 0;)
  16512. if (destSamples[i] != 0)
  16513. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16514. numSamples = (int) samplesAvailable;
  16515. }
  16516. if (numSamples <= 0)
  16517. return true;
  16518. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16519. while (numSamples > 0)
  16520. {
  16521. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16522. char tempBuffer [tempBufSize];
  16523. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16524. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16525. if (bytesRead < numThisTime * bytesPerFrame)
  16526. {
  16527. jassert (bytesRead >= 0);
  16528. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16529. }
  16530. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16531. if (littleEndian)
  16532. {
  16533. switch (bitsPerSample)
  16534. {
  16535. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16536. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16537. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16538. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16539. default: jassertfalse; break;
  16540. }
  16541. }
  16542. else
  16543. {
  16544. switch (bitsPerSample)
  16545. {
  16546. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16547. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16548. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16549. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16550. default: jassertfalse; break;
  16551. }
  16552. }
  16553. startOffsetInDestBuffer += numThisTime;
  16554. numSamples -= numThisTime;
  16555. }
  16556. return true;
  16557. }
  16558. private:
  16559. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16560. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  16561. };
  16562. class AiffAudioFormatWriter : public AudioFormatWriter
  16563. {
  16564. public:
  16565. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16566. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16567. lengthInSamples (0),
  16568. bytesWritten (0),
  16569. writeFailed (false)
  16570. {
  16571. headerPosition = out->getPosition();
  16572. writeHeader();
  16573. }
  16574. ~AiffAudioFormatWriter()
  16575. {
  16576. if ((bytesWritten & 1) != 0)
  16577. output->writeByte (0);
  16578. writeHeader();
  16579. }
  16580. bool write (const int** data, int numSamples)
  16581. {
  16582. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16583. if (writeFailed)
  16584. return false;
  16585. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16586. tempBlock.ensureSize (bytes, false);
  16587. switch (bitsPerSample)
  16588. {
  16589. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16590. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16591. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16592. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16593. default: jassertfalse; break;
  16594. }
  16595. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16596. || ! output->write (tempBlock.getData(), bytes))
  16597. {
  16598. // failed to write to disk, so let's try writing the header.
  16599. // If it's just run out of disk space, then if it does manage
  16600. // to write the header, we'll still have a useable file..
  16601. writeHeader();
  16602. writeFailed = true;
  16603. return false;
  16604. }
  16605. else
  16606. {
  16607. bytesWritten += bytes;
  16608. lengthInSamples += numSamples;
  16609. return true;
  16610. }
  16611. }
  16612. private:
  16613. MemoryBlock tempBlock;
  16614. uint32 lengthInSamples, bytesWritten;
  16615. int64 headerPosition;
  16616. bool writeFailed;
  16617. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16618. void writeHeader()
  16619. {
  16620. const bool couldSeekOk = output->setPosition (headerPosition);
  16621. (void) couldSeekOk;
  16622. // if this fails, you've given it an output stream that can't seek! It needs
  16623. // to be able to seek back to write the header
  16624. jassert (couldSeekOk);
  16625. const int headerLen = 54;
  16626. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16627. audioBytes += (audioBytes & 1);
  16628. output->writeInt (chunkName ("FORM"));
  16629. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16630. output->writeInt (chunkName ("AIFF"));
  16631. output->writeInt (chunkName ("COMM"));
  16632. output->writeIntBigEndian (18);
  16633. output->writeShortBigEndian ((short) numChannels);
  16634. output->writeIntBigEndian (lengthInSamples);
  16635. output->writeShortBigEndian ((short) bitsPerSample);
  16636. uint8 sampleRateBytes[10];
  16637. zeromem (sampleRateBytes, 10);
  16638. if (sampleRate <= 1)
  16639. {
  16640. sampleRateBytes[0] = 0x3f;
  16641. sampleRateBytes[1] = 0xff;
  16642. sampleRateBytes[2] = 0x80;
  16643. }
  16644. else
  16645. {
  16646. int mask = 0x40000000;
  16647. sampleRateBytes[0] = 0x40;
  16648. if (sampleRate >= mask)
  16649. {
  16650. jassertfalse;
  16651. sampleRateBytes[1] = 0x1d;
  16652. }
  16653. else
  16654. {
  16655. int n = (int) sampleRate;
  16656. int i;
  16657. for (i = 0; i <= 32 ; ++i)
  16658. {
  16659. if ((n & mask) != 0)
  16660. break;
  16661. mask >>= 1;
  16662. }
  16663. n = n << (i + 1);
  16664. sampleRateBytes[1] = (uint8) (29 - i);
  16665. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16666. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16667. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16668. sampleRateBytes[5] = (uint8) (n & 0xff);
  16669. }
  16670. }
  16671. output->write (sampleRateBytes, 10);
  16672. output->writeInt (chunkName ("SSND"));
  16673. output->writeIntBigEndian (audioBytes + 8);
  16674. output->writeInt (0);
  16675. output->writeInt (0);
  16676. jassert (output->getPosition() == headerLen);
  16677. }
  16678. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  16679. };
  16680. AiffAudioFormat::AiffAudioFormat()
  16681. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16682. {
  16683. }
  16684. AiffAudioFormat::~AiffAudioFormat()
  16685. {
  16686. }
  16687. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16688. {
  16689. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16690. return Array <int> (rates);
  16691. }
  16692. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16693. {
  16694. const int depths[] = { 8, 16, 24, 0 };
  16695. return Array <int> (depths);
  16696. }
  16697. bool AiffAudioFormat::canDoStereo() { return true; }
  16698. bool AiffAudioFormat::canDoMono() { return true; }
  16699. #if JUCE_MAC
  16700. bool AiffAudioFormat::canHandleFile (const File& f)
  16701. {
  16702. if (AudioFormat::canHandleFile (f))
  16703. return true;
  16704. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16705. return type == 'AIFF' || type == 'AIFC'
  16706. || type == 'aiff' || type == 'aifc';
  16707. }
  16708. #endif
  16709. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16710. {
  16711. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16712. if (w->sampleRate != 0)
  16713. return w.release();
  16714. if (! deleteStreamIfOpeningFails)
  16715. w->input = 0;
  16716. return 0;
  16717. }
  16718. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16719. double sampleRate,
  16720. unsigned int numberOfChannels,
  16721. int bitsPerSample,
  16722. const StringPairArray& /*metadataValues*/,
  16723. int /*qualityOptionIndex*/)
  16724. {
  16725. if (getPossibleBitDepths().contains (bitsPerSample))
  16726. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16727. return 0;
  16728. }
  16729. END_JUCE_NAMESPACE
  16730. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16731. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16732. BEGIN_JUCE_NAMESPACE
  16733. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16734. : formatName (name),
  16735. fileExtensions (extensions)
  16736. {
  16737. }
  16738. AudioFormat::~AudioFormat()
  16739. {
  16740. }
  16741. bool AudioFormat::canHandleFile (const File& f)
  16742. {
  16743. for (int i = 0; i < fileExtensions.size(); ++i)
  16744. if (f.hasFileExtension (fileExtensions[i]))
  16745. return true;
  16746. return false;
  16747. }
  16748. const String& AudioFormat::getFormatName() const { return formatName; }
  16749. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16750. bool AudioFormat::isCompressed() { return false; }
  16751. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16752. END_JUCE_NAMESPACE
  16753. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16754. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16755. BEGIN_JUCE_NAMESPACE
  16756. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16757. const String& formatName_)
  16758. : sampleRate (0),
  16759. bitsPerSample (0),
  16760. lengthInSamples (0),
  16761. numChannels (0),
  16762. usesFloatingPointData (false),
  16763. input (in),
  16764. formatName (formatName_)
  16765. {
  16766. }
  16767. AudioFormatReader::~AudioFormatReader()
  16768. {
  16769. delete input;
  16770. }
  16771. bool AudioFormatReader::read (int* const* destSamples,
  16772. int numDestChannels,
  16773. int64 startSampleInSource,
  16774. int numSamplesToRead,
  16775. const bool fillLeftoverChannelsWithCopies)
  16776. {
  16777. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16778. int startOffsetInDestBuffer = 0;
  16779. if (startSampleInSource < 0)
  16780. {
  16781. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16782. for (int i = numDestChannels; --i >= 0;)
  16783. if (destSamples[i] != 0)
  16784. zeromem (destSamples[i], sizeof (int) * silence);
  16785. startOffsetInDestBuffer += silence;
  16786. numSamplesToRead -= silence;
  16787. startSampleInSource = 0;
  16788. }
  16789. if (numSamplesToRead <= 0)
  16790. return true;
  16791. if (! readSamples (const_cast<int**> (destSamples),
  16792. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16793. startSampleInSource, numSamplesToRead))
  16794. return false;
  16795. if (numDestChannels > (int) numChannels)
  16796. {
  16797. if (fillLeftoverChannelsWithCopies)
  16798. {
  16799. int* lastFullChannel = destSamples[0];
  16800. for (int i = (int) numChannels; --i > 0;)
  16801. {
  16802. if (destSamples[i] != 0)
  16803. {
  16804. lastFullChannel = destSamples[i];
  16805. break;
  16806. }
  16807. }
  16808. if (lastFullChannel != 0)
  16809. for (int i = numChannels; i < numDestChannels; ++i)
  16810. if (destSamples[i] != 0)
  16811. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16812. }
  16813. else
  16814. {
  16815. for (int i = numChannels; i < numDestChannels; ++i)
  16816. if (destSamples[i] != 0)
  16817. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16818. }
  16819. }
  16820. return true;
  16821. }
  16822. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16823. int64 numSamples,
  16824. float& lowestLeft, float& highestLeft,
  16825. float& lowestRight, float& highestRight)
  16826. {
  16827. if (numSamples <= 0)
  16828. {
  16829. lowestLeft = 0;
  16830. lowestRight = 0;
  16831. highestLeft = 0;
  16832. highestRight = 0;
  16833. return;
  16834. }
  16835. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16836. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16837. int* tempBuffer[3];
  16838. tempBuffer[0] = tempSpace.getData();
  16839. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16840. tempBuffer[2] = 0;
  16841. if (usesFloatingPointData)
  16842. {
  16843. float lmin = 1.0e6f;
  16844. float lmax = -lmin;
  16845. float rmin = lmin;
  16846. float rmax = lmax;
  16847. while (numSamples > 0)
  16848. {
  16849. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16850. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  16851. numSamples -= numToDo;
  16852. startSampleInFile += numToDo;
  16853. float bufMin, bufMax;
  16854. findMinAndMax (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufMin, bufMax);
  16855. lmin = jmin (lmin, bufMin);
  16856. lmax = jmax (lmax, bufMax);
  16857. if (numChannels > 1)
  16858. {
  16859. findMinAndMax (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufMin, bufMax);
  16860. rmin = jmin (rmin, bufMin);
  16861. rmax = jmax (rmax, bufMax);
  16862. }
  16863. }
  16864. if (numChannels <= 1)
  16865. {
  16866. rmax = lmax;
  16867. rmin = lmin;
  16868. }
  16869. lowestLeft = lmin;
  16870. highestLeft = lmax;
  16871. lowestRight = rmin;
  16872. highestRight = rmax;
  16873. }
  16874. else
  16875. {
  16876. int lmax = std::numeric_limits<int>::min();
  16877. int lmin = std::numeric_limits<int>::max();
  16878. int rmax = std::numeric_limits<int>::min();
  16879. int rmin = std::numeric_limits<int>::max();
  16880. while (numSamples > 0)
  16881. {
  16882. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16883. if (! read (tempBuffer, 2, startSampleInFile, numToDo, false))
  16884. break;
  16885. numSamples -= numToDo;
  16886. startSampleInFile += numToDo;
  16887. for (int j = numChannels; --j >= 0;)
  16888. {
  16889. int bufMin, bufMax;
  16890. findMinAndMax (tempBuffer[j], numToDo, bufMin, bufMax);
  16891. if (j == 0)
  16892. {
  16893. lmax = jmax (lmax, bufMax);
  16894. lmin = jmin (lmin, bufMin);
  16895. }
  16896. else
  16897. {
  16898. rmax = jmax (rmax, bufMax);
  16899. rmin = jmin (rmin, bufMin);
  16900. }
  16901. }
  16902. }
  16903. if (numChannels <= 1)
  16904. {
  16905. rmax = lmax;
  16906. rmin = lmin;
  16907. }
  16908. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16909. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16910. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16911. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16912. }
  16913. }
  16914. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16915. int64 numSamplesToSearch,
  16916. const double magnitudeRangeMinimum,
  16917. const double magnitudeRangeMaximum,
  16918. const int minimumConsecutiveSamples)
  16919. {
  16920. if (numSamplesToSearch == 0)
  16921. return -1;
  16922. const int bufferSize = 4096;
  16923. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16924. int* tempBuffer[3];
  16925. tempBuffer[0] = tempSpace.getData();
  16926. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16927. tempBuffer[2] = 0;
  16928. int consecutive = 0;
  16929. int64 firstMatchPos = -1;
  16930. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16931. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16932. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16933. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16934. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16935. while (numSamplesToSearch != 0)
  16936. {
  16937. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16938. int64 bufferStart = startSample;
  16939. if (numSamplesToSearch < 0)
  16940. bufferStart -= numThisTime;
  16941. if (bufferStart >= (int) lengthInSamples)
  16942. break;
  16943. read (tempBuffer, 2, bufferStart, numThisTime, false);
  16944. int num = numThisTime;
  16945. while (--num >= 0)
  16946. {
  16947. if (numSamplesToSearch < 0)
  16948. --startSample;
  16949. bool matches = false;
  16950. const int index = (int) (startSample - bufferStart);
  16951. if (usesFloatingPointData)
  16952. {
  16953. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16954. if (sample1 >= magnitudeRangeMinimum
  16955. && sample1 <= magnitudeRangeMaximum)
  16956. {
  16957. matches = true;
  16958. }
  16959. else if (numChannels > 1)
  16960. {
  16961. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16962. matches = (sample2 >= magnitudeRangeMinimum
  16963. && sample2 <= magnitudeRangeMaximum);
  16964. }
  16965. }
  16966. else
  16967. {
  16968. const int sample1 = abs (tempBuffer[0] [index]);
  16969. if (sample1 >= intMagnitudeRangeMinimum
  16970. && sample1 <= intMagnitudeRangeMaximum)
  16971. {
  16972. matches = true;
  16973. }
  16974. else if (numChannels > 1)
  16975. {
  16976. const int sample2 = abs (tempBuffer[1][index]);
  16977. matches = (sample2 >= intMagnitudeRangeMinimum
  16978. && sample2 <= intMagnitudeRangeMaximum);
  16979. }
  16980. }
  16981. if (matches)
  16982. {
  16983. if (firstMatchPos < 0)
  16984. firstMatchPos = startSample;
  16985. if (++consecutive >= minimumConsecutiveSamples)
  16986. {
  16987. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16988. return -1;
  16989. return firstMatchPos;
  16990. }
  16991. }
  16992. else
  16993. {
  16994. consecutive = 0;
  16995. firstMatchPos = -1;
  16996. }
  16997. if (numSamplesToSearch > 0)
  16998. ++startSample;
  16999. }
  17000. if (numSamplesToSearch > 0)
  17001. numSamplesToSearch -= numThisTime;
  17002. else
  17003. numSamplesToSearch += numThisTime;
  17004. }
  17005. return -1;
  17006. }
  17007. END_JUCE_NAMESPACE
  17008. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17009. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17010. BEGIN_JUCE_NAMESPACE
  17011. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17012. const String& formatName_,
  17013. const double rate,
  17014. const unsigned int numChannels_,
  17015. const unsigned int bitsPerSample_)
  17016. : sampleRate (rate),
  17017. numChannels (numChannels_),
  17018. bitsPerSample (bitsPerSample_),
  17019. usesFloatingPointData (false),
  17020. output (out),
  17021. formatName (formatName_)
  17022. {
  17023. }
  17024. AudioFormatWriter::~AudioFormatWriter()
  17025. {
  17026. delete output;
  17027. }
  17028. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17029. int64 startSample,
  17030. int64 numSamplesToRead)
  17031. {
  17032. const int bufferSize = 16384;
  17033. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17034. int* buffers [128];
  17035. zerostruct (buffers);
  17036. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17037. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17038. if (numSamplesToRead < 0)
  17039. numSamplesToRead = reader.lengthInSamples;
  17040. while (numSamplesToRead > 0)
  17041. {
  17042. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17043. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17044. return false;
  17045. if (reader.usesFloatingPointData != isFloatingPoint())
  17046. {
  17047. int** bufferChan = buffers;
  17048. while (*bufferChan != 0)
  17049. {
  17050. int* b = *bufferChan++;
  17051. if (isFloatingPoint())
  17052. {
  17053. // int -> float
  17054. const double factor = 1.0 / std::numeric_limits<int>::max();
  17055. for (int i = 0; i < numToDo; ++i)
  17056. ((float*) b)[i] = (float) (factor * b[i]);
  17057. }
  17058. else
  17059. {
  17060. // float -> int
  17061. for (int i = 0; i < numToDo; ++i)
  17062. {
  17063. const double samp = *(const float*) b;
  17064. if (samp <= -1.0)
  17065. *b++ = std::numeric_limits<int>::min();
  17066. else if (samp >= 1.0)
  17067. *b++ = std::numeric_limits<int>::max();
  17068. else
  17069. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17070. }
  17071. }
  17072. }
  17073. }
  17074. if (! write (const_cast<const int**> (buffers), numToDo))
  17075. return false;
  17076. numSamplesToRead -= numToDo;
  17077. startSample += numToDo;
  17078. }
  17079. return true;
  17080. }
  17081. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17082. {
  17083. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17084. while (numSamplesToRead > 0)
  17085. {
  17086. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17087. AudioSourceChannelInfo info;
  17088. info.buffer = &tempBuffer;
  17089. info.startSample = 0;
  17090. info.numSamples = numToDo;
  17091. info.clearActiveBufferRegion();
  17092. source.getNextAudioBlock (info);
  17093. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17094. return false;
  17095. numSamplesToRead -= numToDo;
  17096. }
  17097. return true;
  17098. }
  17099. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17100. {
  17101. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17102. if (numSamples <= 0)
  17103. return true;
  17104. HeapBlock<int> tempBuffer;
  17105. HeapBlock<int*> chans (numChannels + 1);
  17106. chans [numChannels] = 0;
  17107. if (isFloatingPoint())
  17108. {
  17109. for (int i = numChannels; --i >= 0;)
  17110. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17111. }
  17112. else
  17113. {
  17114. tempBuffer.malloc (numSamples * numChannels);
  17115. for (unsigned int i = 0; i < numChannels; ++i)
  17116. {
  17117. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17118. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17119. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17120. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17121. destData.convertSamples (sourceData, numSamples);
  17122. }
  17123. }
  17124. return write ((const int**) chans.getData(), numSamples);
  17125. }
  17126. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17127. public AbstractFifo
  17128. {
  17129. public:
  17130. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize_)
  17131. : AbstractFifo (bufferSize_),
  17132. buffer (numChannels, bufferSize_),
  17133. timeSliceThread (timeSliceThread_),
  17134. writer (writer_),
  17135. thumbnailToUpdate (0),
  17136. samplesWritten (0),
  17137. isRunning (true)
  17138. {
  17139. timeSliceThread.addTimeSliceClient (this);
  17140. }
  17141. ~Buffer()
  17142. {
  17143. isRunning = false;
  17144. timeSliceThread.removeTimeSliceClient (this);
  17145. while (useTimeSlice())
  17146. {}
  17147. }
  17148. bool write (const float** data, int numSamples)
  17149. {
  17150. if (numSamples <= 0 || ! isRunning)
  17151. return true;
  17152. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17153. int start1, size1, start2, size2;
  17154. prepareToWrite (numSamples, start1, size1, start2, size2);
  17155. if (size1 + size2 < numSamples)
  17156. return false;
  17157. for (int i = buffer.getNumChannels(); --i >= 0;)
  17158. {
  17159. buffer.copyFrom (i, start1, data[i], size1);
  17160. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17161. }
  17162. finishedWrite (size1 + size2);
  17163. timeSliceThread.notify();
  17164. return true;
  17165. }
  17166. bool useTimeSlice()
  17167. {
  17168. const int numToDo = getTotalSize() / 4;
  17169. int start1, size1, start2, size2;
  17170. prepareToRead (numToDo, start1, size1, start2, size2);
  17171. if (size1 <= 0)
  17172. return false;
  17173. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17174. const ScopedLock sl (thumbnailLock);
  17175. if (thumbnailToUpdate != 0)
  17176. thumbnailToUpdate->addBlock (samplesWritten, buffer, start1, size1);
  17177. samplesWritten += size1;
  17178. if (size2 > 0)
  17179. {
  17180. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17181. if (thumbnailToUpdate != 0)
  17182. thumbnailToUpdate->addBlock (samplesWritten, buffer, start2, size2);
  17183. samplesWritten += size2;
  17184. }
  17185. finishedRead (size1 + size2);
  17186. return true;
  17187. }
  17188. void setThumbnail (AudioThumbnail* thumb)
  17189. {
  17190. if (thumb != 0)
  17191. thumb->reset (buffer.getNumChannels(), writer->getSampleRate(), 0);
  17192. const ScopedLock sl (thumbnailLock);
  17193. thumbnailToUpdate = thumb;
  17194. samplesWritten = 0;
  17195. }
  17196. private:
  17197. AudioSampleBuffer buffer;
  17198. TimeSliceThread& timeSliceThread;
  17199. ScopedPointer<AudioFormatWriter> writer;
  17200. CriticalSection thumbnailLock;
  17201. AudioThumbnail* thumbnailToUpdate;
  17202. int64 samplesWritten;
  17203. volatile bool isRunning;
  17204. JUCE_DECLARE_NON_COPYABLE (Buffer);
  17205. };
  17206. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17207. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17208. {
  17209. }
  17210. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17211. {
  17212. }
  17213. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17214. {
  17215. return buffer->write (data, numSamples);
  17216. }
  17217. void AudioFormatWriter::ThreadedWriter::setThumbnailToUpdate (AudioThumbnail* thumb)
  17218. {
  17219. buffer->setThumbnail (thumb);
  17220. }
  17221. END_JUCE_NAMESPACE
  17222. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17223. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17224. BEGIN_JUCE_NAMESPACE
  17225. AudioFormatManager::AudioFormatManager()
  17226. : defaultFormatIndex (0)
  17227. {
  17228. }
  17229. AudioFormatManager::~AudioFormatManager()
  17230. {
  17231. }
  17232. void AudioFormatManager::registerFormat (AudioFormat* newFormat, const bool makeThisTheDefaultFormat)
  17233. {
  17234. jassert (newFormat != 0);
  17235. if (newFormat != 0)
  17236. {
  17237. #if JUCE_DEBUG
  17238. for (int i = getNumKnownFormats(); --i >= 0;)
  17239. {
  17240. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17241. {
  17242. jassertfalse; // trying to add the same format twice!
  17243. }
  17244. }
  17245. #endif
  17246. if (makeThisTheDefaultFormat)
  17247. defaultFormatIndex = getNumKnownFormats();
  17248. knownFormats.add (newFormat);
  17249. }
  17250. }
  17251. void AudioFormatManager::registerBasicFormats()
  17252. {
  17253. #if JUCE_MAC
  17254. registerFormat (new AiffAudioFormat(), true);
  17255. registerFormat (new WavAudioFormat(), false);
  17256. #else
  17257. registerFormat (new WavAudioFormat(), true);
  17258. registerFormat (new AiffAudioFormat(), false);
  17259. #endif
  17260. #if JUCE_USE_FLAC
  17261. registerFormat (new FlacAudioFormat(), false);
  17262. #endif
  17263. #if JUCE_USE_OGGVORBIS
  17264. registerFormat (new OggVorbisAudioFormat(), false);
  17265. #endif
  17266. }
  17267. void AudioFormatManager::clearFormats()
  17268. {
  17269. knownFormats.clear();
  17270. defaultFormatIndex = 0;
  17271. }
  17272. int AudioFormatManager::getNumKnownFormats() const
  17273. {
  17274. return knownFormats.size();
  17275. }
  17276. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17277. {
  17278. return knownFormats [index];
  17279. }
  17280. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17281. {
  17282. return getKnownFormat (defaultFormatIndex);
  17283. }
  17284. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17285. {
  17286. String e (fileExtension);
  17287. if (! e.startsWithChar ('.'))
  17288. e = "." + e;
  17289. for (int i = 0; i < getNumKnownFormats(); ++i)
  17290. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17291. return getKnownFormat(i);
  17292. return 0;
  17293. }
  17294. const String AudioFormatManager::getWildcardForAllFormats() const
  17295. {
  17296. StringArray allExtensions;
  17297. int i;
  17298. for (i = 0; i < getNumKnownFormats(); ++i)
  17299. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17300. allExtensions.trim();
  17301. allExtensions.removeEmptyStrings();
  17302. String s;
  17303. for (i = 0; i < allExtensions.size(); ++i)
  17304. {
  17305. s << '*';
  17306. if (! allExtensions[i].startsWithChar ('.'))
  17307. s << '.';
  17308. s << allExtensions[i];
  17309. if (i < allExtensions.size() - 1)
  17310. s << ';';
  17311. }
  17312. return s;
  17313. }
  17314. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17315. {
  17316. // you need to actually register some formats before the manager can
  17317. // use them to open a file!
  17318. jassert (getNumKnownFormats() > 0);
  17319. for (int i = 0; i < getNumKnownFormats(); ++i)
  17320. {
  17321. AudioFormat* const af = getKnownFormat(i);
  17322. if (af->canHandleFile (file))
  17323. {
  17324. InputStream* const in = file.createInputStream();
  17325. if (in != 0)
  17326. {
  17327. AudioFormatReader* const r = af->createReaderFor (in, true);
  17328. if (r != 0)
  17329. return r;
  17330. }
  17331. }
  17332. }
  17333. return 0;
  17334. }
  17335. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17336. {
  17337. // you need to actually register some formats before the manager can
  17338. // use them to open a file!
  17339. jassert (getNumKnownFormats() > 0);
  17340. ScopedPointer <InputStream> in (audioFileStream);
  17341. if (in != 0)
  17342. {
  17343. const int64 originalStreamPos = in->getPosition();
  17344. for (int i = 0; i < getNumKnownFormats(); ++i)
  17345. {
  17346. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17347. if (r != 0)
  17348. {
  17349. in.release();
  17350. return r;
  17351. }
  17352. in->setPosition (originalStreamPos);
  17353. // the stream that is passed-in must be capable of being repositioned so
  17354. // that all the formats can have a go at opening it.
  17355. jassert (in->getPosition() == originalStreamPos);
  17356. }
  17357. }
  17358. return 0;
  17359. }
  17360. END_JUCE_NAMESPACE
  17361. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17362. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17363. BEGIN_JUCE_NAMESPACE
  17364. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17365. const int64 startSample_,
  17366. const int64 length_,
  17367. const bool deleteSourceWhenDeleted_)
  17368. : AudioFormatReader (0, source_->getFormatName()),
  17369. source (source_),
  17370. startSample (startSample_),
  17371. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17372. {
  17373. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17374. sampleRate = source->sampleRate;
  17375. bitsPerSample = source->bitsPerSample;
  17376. lengthInSamples = length;
  17377. numChannels = source->numChannels;
  17378. usesFloatingPointData = source->usesFloatingPointData;
  17379. }
  17380. AudioSubsectionReader::~AudioSubsectionReader()
  17381. {
  17382. if (deleteSourceWhenDeleted)
  17383. delete source;
  17384. }
  17385. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17386. int64 startSampleInFile, int numSamples)
  17387. {
  17388. if (startSampleInFile + numSamples > length)
  17389. {
  17390. for (int i = numDestChannels; --i >= 0;)
  17391. if (destSamples[i] != 0)
  17392. zeromem (destSamples[i], sizeof (int) * numSamples);
  17393. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17394. if (numSamples <= 0)
  17395. return true;
  17396. }
  17397. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17398. startSampleInFile + startSample, numSamples);
  17399. }
  17400. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17401. int64 numSamples,
  17402. float& lowestLeft,
  17403. float& highestLeft,
  17404. float& lowestRight,
  17405. float& highestRight)
  17406. {
  17407. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17408. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17409. source->readMaxLevels (startSampleInFile + startSample,
  17410. numSamples,
  17411. lowestLeft,
  17412. highestLeft,
  17413. lowestRight,
  17414. highestRight);
  17415. }
  17416. END_JUCE_NAMESPACE
  17417. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17418. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17419. BEGIN_JUCE_NAMESPACE
  17420. struct AudioThumbnail::MinMaxValue
  17421. {
  17422. char minValue;
  17423. char maxValue;
  17424. MinMaxValue() : minValue (0), maxValue (0)
  17425. {
  17426. }
  17427. inline void set (const char newMin, const char newMax) throw()
  17428. {
  17429. minValue = newMin;
  17430. maxValue = newMax;
  17431. }
  17432. inline void setFloat (const float newMin, const float newMax) throw()
  17433. {
  17434. minValue = (char) jlimit (-128, 127, roundFloatToInt (newMin * 127.0f));
  17435. maxValue = (char) jlimit (-128, 127, roundFloatToInt (newMax * 127.0f));
  17436. if (maxValue == minValue)
  17437. maxValue = (char) jmin (127, maxValue + 1);
  17438. }
  17439. inline bool isNonZero() const throw()
  17440. {
  17441. return maxValue > minValue;
  17442. }
  17443. inline int getPeak() const throw()
  17444. {
  17445. return jmax (std::abs ((int) minValue),
  17446. std::abs ((int) maxValue));
  17447. }
  17448. inline void read (InputStream& input)
  17449. {
  17450. minValue = input.readByte();
  17451. maxValue = input.readByte();
  17452. }
  17453. inline void write (OutputStream& output)
  17454. {
  17455. output.writeByte (minValue);
  17456. output.writeByte (maxValue);
  17457. }
  17458. };
  17459. class AudioThumbnail::LevelDataSource : public TimeSliceClient,
  17460. public Timer
  17461. {
  17462. public:
  17463. LevelDataSource (AudioThumbnail& owner_, AudioFormatReader* newReader, int64 hash)
  17464. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17465. hashCode (hash), owner (owner_), reader (newReader)
  17466. {
  17467. }
  17468. LevelDataSource (AudioThumbnail& owner_, InputSource* source_)
  17469. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17470. hashCode (source_->hashCode()), owner (owner_), source (source_)
  17471. {
  17472. }
  17473. ~LevelDataSource()
  17474. {
  17475. owner.cache.removeTimeSliceClient (this);
  17476. }
  17477. enum { timeBeforeDeletingReader = 2000 };
  17478. void initialise (int64 numSamplesFinished_)
  17479. {
  17480. const ScopedLock sl (readerLock);
  17481. numSamplesFinished = numSamplesFinished_;
  17482. createReader();
  17483. if (reader != 0)
  17484. {
  17485. lengthInSamples = reader->lengthInSamples;
  17486. numChannels = reader->numChannels;
  17487. sampleRate = reader->sampleRate;
  17488. if (lengthInSamples <= 0)
  17489. reader = 0;
  17490. else if (! isFullyLoaded())
  17491. owner.cache.addTimeSliceClient (this);
  17492. }
  17493. }
  17494. void getLevels (int64 startSample, int numSamples, Array<float>& levels)
  17495. {
  17496. const ScopedLock sl (readerLock);
  17497. createReader();
  17498. if (reader != 0)
  17499. {
  17500. float l[4] = { 0 };
  17501. reader->readMaxLevels (startSample, numSamples, l[0], l[1], l[2], l[3]);
  17502. levels.clearQuick();
  17503. levels.addArray ((const float*) l, 4);
  17504. }
  17505. }
  17506. void releaseResources()
  17507. {
  17508. const ScopedLock sl (readerLock);
  17509. reader = 0;
  17510. }
  17511. bool useTimeSlice()
  17512. {
  17513. if (isFullyLoaded())
  17514. {
  17515. if (reader != 0 && source != 0)
  17516. startTimer (timeBeforeDeletingReader);
  17517. owner.cache.removeTimeSliceClient (this);
  17518. return false;
  17519. }
  17520. stopTimer();
  17521. bool justFinished = false;
  17522. {
  17523. const ScopedLock sl (readerLock);
  17524. createReader();
  17525. if (reader != 0)
  17526. {
  17527. if (! readNextBlock())
  17528. return true;
  17529. justFinished = true;
  17530. }
  17531. }
  17532. if (justFinished)
  17533. owner.cache.storeThumb (owner, hashCode);
  17534. return false;
  17535. }
  17536. void timerCallback()
  17537. {
  17538. stopTimer();
  17539. releaseResources();
  17540. }
  17541. bool isFullyLoaded() const throw()
  17542. {
  17543. return numSamplesFinished >= lengthInSamples;
  17544. }
  17545. inline int sampleToThumbSample (const int64 originalSample) const throw()
  17546. {
  17547. return (int) (originalSample / owner.samplesPerThumbSample);
  17548. }
  17549. int64 lengthInSamples, numSamplesFinished;
  17550. double sampleRate;
  17551. int numChannels;
  17552. int64 hashCode;
  17553. private:
  17554. AudioThumbnail& owner;
  17555. ScopedPointer <InputSource> source;
  17556. ScopedPointer <AudioFormatReader> reader;
  17557. CriticalSection readerLock;
  17558. void createReader()
  17559. {
  17560. if (reader == 0 && source != 0)
  17561. {
  17562. InputStream* audioFileStream = source->createInputStream();
  17563. if (audioFileStream != 0)
  17564. reader = owner.formatManagerToUse.createReaderFor (audioFileStream);
  17565. }
  17566. }
  17567. bool readNextBlock()
  17568. {
  17569. jassert (reader != 0);
  17570. if (! isFullyLoaded())
  17571. {
  17572. const int numToDo = (int) jmin (256 * (int64) owner.samplesPerThumbSample, lengthInSamples - numSamplesFinished);
  17573. if (numToDo > 0)
  17574. {
  17575. int64 startSample = numSamplesFinished;
  17576. const int firstThumbIndex = sampleToThumbSample (startSample);
  17577. const int lastThumbIndex = sampleToThumbSample (startSample + numToDo);
  17578. const int numThumbSamps = lastThumbIndex - firstThumbIndex;
  17579. HeapBlock<MinMaxValue> levelData (numThumbSamps * 2);
  17580. MinMaxValue* levels[2] = { levelData, levelData + numThumbSamps };
  17581. for (int i = 0; i < numThumbSamps; ++i)
  17582. {
  17583. float lowestLeft, highestLeft, lowestRight, highestRight;
  17584. reader->readMaxLevels ((firstThumbIndex + i) * owner.samplesPerThumbSample, owner.samplesPerThumbSample,
  17585. lowestLeft, highestLeft, lowestRight, highestRight);
  17586. levels[0][i].setFloat (lowestLeft, highestLeft);
  17587. levels[1][i].setFloat (lowestRight, highestRight);
  17588. }
  17589. {
  17590. const ScopedUnlock su (readerLock);
  17591. owner.setLevels (levels, firstThumbIndex, 2, numThumbSamps);
  17592. }
  17593. numSamplesFinished += numToDo;
  17594. }
  17595. }
  17596. return isFullyLoaded();
  17597. }
  17598. };
  17599. class AudioThumbnail::ThumbData
  17600. {
  17601. public:
  17602. ThumbData (const int numThumbSamples)
  17603. : peakLevel (-1)
  17604. {
  17605. ensureSize (numThumbSamples);
  17606. }
  17607. inline MinMaxValue* getData (const int thumbSampleIndex) throw()
  17608. {
  17609. jassert (thumbSampleIndex < data.size());
  17610. return data.getRawDataPointer() + thumbSampleIndex;
  17611. }
  17612. int getSize() const throw()
  17613. {
  17614. return data.size();
  17615. }
  17616. void getMinMax (int startSample, int endSample, MinMaxValue& result) throw()
  17617. {
  17618. if (startSample >= 0)
  17619. {
  17620. endSample = jmin (endSample, data.size() - 1);
  17621. char mx = -128;
  17622. char mn = 127;
  17623. while (startSample <= endSample)
  17624. {
  17625. const MinMaxValue& v = data.getReference (startSample);
  17626. if (v.minValue < mn) mn = v.minValue;
  17627. if (v.maxValue > mx) mx = v.maxValue;
  17628. ++startSample;
  17629. }
  17630. if (mn <= mx)
  17631. {
  17632. result.set (mn, mx);
  17633. return;
  17634. }
  17635. }
  17636. result.set (1, 0);
  17637. }
  17638. void write (const MinMaxValue* const source, const int startIndex, const int numValues)
  17639. {
  17640. resetPeak();
  17641. if (startIndex + numValues > data.size())
  17642. ensureSize (startIndex + numValues);
  17643. MinMaxValue* const dest = getData (startIndex);
  17644. for (int i = 0; i < numValues; ++i)
  17645. dest[i] = source[i];
  17646. }
  17647. void resetPeak()
  17648. {
  17649. peakLevel = -1;
  17650. }
  17651. int getPeak()
  17652. {
  17653. if (peakLevel < 0)
  17654. {
  17655. for (int i = 0; i < data.size(); ++i)
  17656. {
  17657. const int peak = data[i].getPeak();
  17658. if (peak > peakLevel)
  17659. peakLevel = peak;
  17660. }
  17661. }
  17662. return peakLevel;
  17663. }
  17664. private:
  17665. Array <MinMaxValue> data;
  17666. int peakLevel;
  17667. void ensureSize (const int thumbSamples)
  17668. {
  17669. const int extraNeeded = thumbSamples - data.size();
  17670. if (extraNeeded > 0)
  17671. data.insertMultiple (-1, MinMaxValue(), extraNeeded);
  17672. }
  17673. };
  17674. class AudioThumbnail::CachedWindow
  17675. {
  17676. public:
  17677. CachedWindow()
  17678. : cachedStart (0), cachedTimePerPixel (0),
  17679. numChannelsCached (0), numSamplesCached (0),
  17680. cacheNeedsRefilling (true)
  17681. {
  17682. }
  17683. void invalidate()
  17684. {
  17685. cacheNeedsRefilling = true;
  17686. }
  17687. void drawChannel (Graphics& g, const Rectangle<int>& area,
  17688. const double startTime, const double endTime,
  17689. const int channelNum, const float verticalZoomFactor,
  17690. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17691. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17692. {
  17693. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  17694. numChannels, samplesPerThumbSample, levelData, channels);
  17695. if (isPositiveAndBelow (channelNum, numChannelsCached))
  17696. {
  17697. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  17698. if (! clip.isEmpty())
  17699. {
  17700. const float topY = (float) area.getY();
  17701. const float bottomY = (float) area.getBottom();
  17702. const float midY = (topY + bottomY) * 0.5f;
  17703. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  17704. const MinMaxValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  17705. int x = clip.getX();
  17706. for (int w = clip.getWidth(); --w >= 0;)
  17707. {
  17708. if (cacheData->isNonZero())
  17709. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  17710. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  17711. ++x;
  17712. ++cacheData;
  17713. }
  17714. }
  17715. }
  17716. }
  17717. private:
  17718. Array <MinMaxValue> data;
  17719. double cachedStart, cachedTimePerPixel;
  17720. int numChannelsCached, numSamplesCached;
  17721. bool cacheNeedsRefilling;
  17722. void refillCache (const int numSamples, double startTime, const double endTime,
  17723. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17724. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17725. {
  17726. const double timePerPixel = (endTime - startTime) / numSamples;
  17727. if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0)
  17728. {
  17729. invalidate();
  17730. return;
  17731. }
  17732. if (numSamples == numSamplesCached
  17733. && numChannelsCached == numChannels
  17734. && startTime == cachedStart
  17735. && timePerPixel == cachedTimePerPixel
  17736. && ! cacheNeedsRefilling)
  17737. {
  17738. return;
  17739. }
  17740. numSamplesCached = numSamples;
  17741. numChannelsCached = numChannels;
  17742. cachedStart = startTime;
  17743. cachedTimePerPixel = timePerPixel;
  17744. cacheNeedsRefilling = false;
  17745. ensureSize (numSamples);
  17746. if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != 0)
  17747. {
  17748. int sample = roundToInt (startTime * sampleRate);
  17749. Array<float> levels;
  17750. int i;
  17751. for (i = 0; i < numSamples; ++i)
  17752. {
  17753. const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate);
  17754. if (sample >= 0)
  17755. {
  17756. if (sample >= levelData->lengthInSamples)
  17757. break;
  17758. levelData->getLevels (sample, jmax (1, nextSample - sample), levels);
  17759. const int numChans = jmin (levels.size() / 2, numChannelsCached);
  17760. for (int chan = 0; chan < numChans; ++chan)
  17761. getData (chan, i)->setFloat (levels.getUnchecked (chan * 2),
  17762. levels.getUnchecked (chan * 2 + 1));
  17763. }
  17764. startTime += timePerPixel;
  17765. sample = nextSample;
  17766. }
  17767. numSamplesCached = i;
  17768. }
  17769. else
  17770. {
  17771. jassert (channels.size() == numChannelsCached);
  17772. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17773. {
  17774. ThumbData* channelData = channels.getUnchecked (channelNum);
  17775. MinMaxValue* cacheData = getData (channelNum, 0);
  17776. const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample;
  17777. startTime = cachedStart;
  17778. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17779. for (int i = numSamples; --i >= 0;)
  17780. {
  17781. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17782. channelData->getMinMax (sample, nextSample, *cacheData);
  17783. ++cacheData;
  17784. startTime += timePerPixel;
  17785. sample = nextSample;
  17786. }
  17787. }
  17788. }
  17789. }
  17790. MinMaxValue* getData (const int channelNum, const int cacheIndex) throw()
  17791. {
  17792. jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));
  17793. return data.getRawDataPointer() + channelNum * numSamplesCached
  17794. + cacheIndex;
  17795. }
  17796. void ensureSize (const int numSamples)
  17797. {
  17798. const int itemsRequired = numSamples * numChannelsCached;
  17799. if (data.size() < itemsRequired)
  17800. data.insertMultiple (-1, MinMaxValue(), itemsRequired - data.size());
  17801. }
  17802. };
  17803. AudioThumbnail::AudioThumbnail (const int originalSamplesPerThumbnailSample,
  17804. AudioFormatManager& formatManagerToUse_,
  17805. AudioThumbnailCache& cacheToUse)
  17806. : formatManagerToUse (formatManagerToUse_),
  17807. cache (cacheToUse),
  17808. window (new CachedWindow()),
  17809. samplesPerThumbSample (originalSamplesPerThumbnailSample),
  17810. totalSamples (0),
  17811. numChannels (0),
  17812. sampleRate (0)
  17813. {
  17814. }
  17815. AudioThumbnail::~AudioThumbnail()
  17816. {
  17817. clear();
  17818. }
  17819. void AudioThumbnail::clear()
  17820. {
  17821. source = 0;
  17822. const ScopedLock sl (lock);
  17823. window->invalidate();
  17824. channels.clear();
  17825. totalSamples = numSamplesFinished = 0;
  17826. numChannels = 0;
  17827. sampleRate = 0;
  17828. sendChangeMessage();
  17829. }
  17830. void AudioThumbnail::reset (int newNumChannels, double newSampleRate, int64 totalSamplesInSource)
  17831. {
  17832. clear();
  17833. numChannels = newNumChannels;
  17834. sampleRate = newSampleRate;
  17835. totalSamples = totalSamplesInSource;
  17836. createChannels (1 + (int) (totalSamplesInSource / samplesPerThumbSample));
  17837. }
  17838. void AudioThumbnail::createChannels (const int length)
  17839. {
  17840. while (channels.size() < numChannels)
  17841. channels.add (new ThumbData (length));
  17842. }
  17843. void AudioThumbnail::loadFrom (InputStream& input)
  17844. {
  17845. clear();
  17846. if (input.readByte() != 'j' || input.readByte() != 'a' || input.readByte() != 't' || input.readByte() != 'm')
  17847. return;
  17848. samplesPerThumbSample = input.readInt();
  17849. totalSamples = input.readInt64(); // Total number of source samples.
  17850. numSamplesFinished = input.readInt64(); // Number of valid source samples that have been read into the thumbnail.
  17851. int32 numThumbnailSamples = input.readInt(); // Number of samples in the thumbnail data.
  17852. numChannels = input.readInt(); // Number of audio channels.
  17853. sampleRate = input.readInt(); // Source sample rate.
  17854. input.skipNextBytes (16); // reserved area
  17855. createChannels (numThumbnailSamples);
  17856. for (int i = 0; i < numThumbnailSamples; ++i)
  17857. for (int chan = 0; chan < numChannels; ++chan)
  17858. channels.getUnchecked(chan)->getData(i)->read (input);
  17859. }
  17860. void AudioThumbnail::saveTo (OutputStream& output) const
  17861. {
  17862. const ScopedLock sl (lock);
  17863. const int numThumbnailSamples = channels.size() == 0 ? 0 : channels.getUnchecked(0)->getSize();
  17864. output.write ("jatm", 4);
  17865. output.writeInt (samplesPerThumbSample);
  17866. output.writeInt64 (totalSamples);
  17867. output.writeInt64 (numSamplesFinished);
  17868. output.writeInt (numThumbnailSamples);
  17869. output.writeInt (numChannels);
  17870. output.writeInt ((int) sampleRate);
  17871. output.writeInt64 (0);
  17872. output.writeInt64 (0);
  17873. for (int i = 0; i < numThumbnailSamples; ++i)
  17874. for (int chan = 0; chan < numChannels; ++chan)
  17875. channels.getUnchecked(chan)->getData(i)->write (output);
  17876. }
  17877. bool AudioThumbnail::setDataSource (LevelDataSource* newSource)
  17878. {
  17879. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  17880. numSamplesFinished = 0;
  17881. if (cache.loadThumb (*this, newSource->hashCode) && isFullyLoaded())
  17882. {
  17883. source = newSource; // (make sure this isn't done before loadThumb is called)
  17884. source->lengthInSamples = totalSamples;
  17885. source->sampleRate = sampleRate;
  17886. source->numChannels = numChannels;
  17887. source->numSamplesFinished = numSamplesFinished;
  17888. }
  17889. else
  17890. {
  17891. source = newSource; // (make sure this isn't done before loadThumb is called)
  17892. const ScopedLock sl (lock);
  17893. source->initialise (numSamplesFinished);
  17894. totalSamples = source->lengthInSamples;
  17895. sampleRate = source->sampleRate;
  17896. numChannels = source->numChannels;
  17897. createChannels (1 + (int) (totalSamples / samplesPerThumbSample));
  17898. }
  17899. return sampleRate > 0 && totalSamples > 0;
  17900. }
  17901. bool AudioThumbnail::setSource (InputSource* const newSource)
  17902. {
  17903. clear();
  17904. return newSource != 0 && setDataSource (new LevelDataSource (*this, newSource));
  17905. }
  17906. void AudioThumbnail::setReader (AudioFormatReader* newReader, int64 hash)
  17907. {
  17908. clear();
  17909. if (newReader != 0)
  17910. setDataSource (new LevelDataSource (*this, newReader, hash));
  17911. }
  17912. int64 AudioThumbnail::getHashCode() const
  17913. {
  17914. return source == 0 ? 0 : source->hashCode;
  17915. }
  17916. void AudioThumbnail::addBlock (const int64 startSample, const AudioSampleBuffer& incoming,
  17917. int startOffsetInBuffer, int numSamples)
  17918. {
  17919. jassert (startSample >= 0);
  17920. const int firstThumbIndex = (int) (startSample / samplesPerThumbSample);
  17921. const int lastThumbIndex = (int) ((startSample + numSamples + (samplesPerThumbSample - 1)) / samplesPerThumbSample);
  17922. const int numToDo = lastThumbIndex - firstThumbIndex;
  17923. if (numToDo > 0)
  17924. {
  17925. const int numChans = jmin (channels.size(), incoming.getNumChannels());
  17926. const HeapBlock<MinMaxValue> thumbData (numToDo * numChans);
  17927. const HeapBlock<MinMaxValue*> thumbChannels (numChans);
  17928. for (int chan = 0; chan < numChans; ++chan)
  17929. {
  17930. const float* const sourceData = incoming.getSampleData (chan, startOffsetInBuffer);
  17931. MinMaxValue* const dest = thumbData + numToDo * chan;
  17932. thumbChannels [chan] = dest;
  17933. for (int i = 0; i < numToDo; ++i)
  17934. {
  17935. float low, high;
  17936. const int start = i * samplesPerThumbSample;
  17937. findMinAndMax (sourceData + start, jmin (samplesPerThumbSample, numSamples - start), low, high);
  17938. dest[i].setFloat (low, high);
  17939. }
  17940. }
  17941. setLevels (thumbChannels, firstThumbIndex, numChans, numToDo);
  17942. }
  17943. }
  17944. void AudioThumbnail::setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues)
  17945. {
  17946. const ScopedLock sl (lock);
  17947. for (int i = jmin (numChans, channels.size()); --i >= 0;)
  17948. channels.getUnchecked(i)->write (values[i], thumbIndex, numValues);
  17949. numSamplesFinished = jmax (numSamplesFinished, (thumbIndex + numValues) * (int64) samplesPerThumbSample);
  17950. totalSamples = jmax (numSamplesFinished, totalSamples);
  17951. window->invalidate();
  17952. sendChangeMessage();
  17953. }
  17954. int AudioThumbnail::getNumChannels() const throw()
  17955. {
  17956. return numChannels;
  17957. }
  17958. double AudioThumbnail::getTotalLength() const throw()
  17959. {
  17960. return totalSamples / sampleRate;
  17961. }
  17962. bool AudioThumbnail::isFullyLoaded() const throw()
  17963. {
  17964. return numSamplesFinished >= totalSamples - samplesPerThumbSample;
  17965. }
  17966. int64 AudioThumbnail::getNumSamplesFinished() const throw()
  17967. {
  17968. return numSamplesFinished;
  17969. }
  17970. float AudioThumbnail::getApproximatePeak() const
  17971. {
  17972. int peak = 0;
  17973. for (int i = channels.size(); --i >= 0;)
  17974. peak = jmax (peak, channels.getUnchecked(i)->getPeak());
  17975. return jlimit (0, 127, peak) / 127.0f;
  17976. }
  17977. void AudioThumbnail::drawChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  17978. double endTime, int channelNum, float verticalZoomFactor)
  17979. {
  17980. const ScopedLock sl (lock);
  17981. window->drawChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor,
  17982. sampleRate, numChannels, samplesPerThumbSample, source, channels);
  17983. }
  17984. void AudioThumbnail::drawChannels (Graphics& g, const Rectangle<int>& area, double startTimeSeconds,
  17985. double endTimeSeconds, float verticalZoomFactor)
  17986. {
  17987. for (int i = 0; i < numChannels; ++i)
  17988. {
  17989. const int y1 = roundToInt ((i * area.getHeight()) / numChannels);
  17990. const int y2 = roundToInt (((i + 1) * area.getHeight()) / numChannels);
  17991. drawChannel (g, Rectangle<int> (area.getX(), area.getY() + y1, area.getWidth(), y2 - y1),
  17992. startTimeSeconds, endTimeSeconds, i, verticalZoomFactor);
  17993. }
  17994. }
  17995. END_JUCE_NAMESPACE
  17996. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  17997. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  17998. BEGIN_JUCE_NAMESPACE
  17999. struct ThumbnailCacheEntry
  18000. {
  18001. int64 hash;
  18002. uint32 lastUsed;
  18003. MemoryBlock data;
  18004. JUCE_LEAK_DETECTOR (ThumbnailCacheEntry);
  18005. };
  18006. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18007. : TimeSliceThread ("thumb cache"),
  18008. maxNumThumbsToStore (maxNumThumbsToStore_)
  18009. {
  18010. startThread (2);
  18011. }
  18012. AudioThumbnailCache::~AudioThumbnailCache()
  18013. {
  18014. }
  18015. ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
  18016. {
  18017. for (int i = thumbs.size(); --i >= 0;)
  18018. if (thumbs.getUnchecked(i)->hash == hash)
  18019. return thumbs.getUnchecked(i);
  18020. return 0;
  18021. }
  18022. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18023. {
  18024. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  18025. if (te != 0)
  18026. {
  18027. te->lastUsed = Time::getMillisecondCounter();
  18028. MemoryInputStream in (te->data, false);
  18029. thumb.loadFrom (in);
  18030. return true;
  18031. }
  18032. return false;
  18033. }
  18034. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18035. const int64 hashCode)
  18036. {
  18037. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  18038. if (te == 0)
  18039. {
  18040. te = new ThumbnailCacheEntry();
  18041. te->hash = hashCode;
  18042. if (thumbs.size() < maxNumThumbsToStore)
  18043. {
  18044. thumbs.add (te);
  18045. }
  18046. else
  18047. {
  18048. int oldest = 0;
  18049. uint32 oldestTime = Time::getMillisecondCounter() + 1;
  18050. for (int i = thumbs.size(); --i >= 0;)
  18051. {
  18052. if (thumbs.getUnchecked(i)->lastUsed < oldestTime)
  18053. {
  18054. oldest = i;
  18055. oldestTime = thumbs.getUnchecked(i)->lastUsed;
  18056. }
  18057. }
  18058. thumbs.set (oldest, te);
  18059. }
  18060. }
  18061. te->lastUsed = Time::getMillisecondCounter();
  18062. MemoryOutputStream out (te->data, false);
  18063. thumb.saveTo (out);
  18064. }
  18065. void AudioThumbnailCache::clear()
  18066. {
  18067. thumbs.clear();
  18068. }
  18069. END_JUCE_NAMESPACE
  18070. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18071. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18072. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18073. #if ! JUCE_WINDOWS
  18074. #include <QuickTime/Movies.h>
  18075. #include <QuickTime/QTML.h>
  18076. #include <QuickTime/QuickTimeComponents.h>
  18077. #include <QuickTime/MediaHandlers.h>
  18078. #include <QuickTime/ImageCodec.h>
  18079. #else
  18080. #if JUCE_MSVC
  18081. #pragma warning (push)
  18082. #pragma warning (disable : 4100)
  18083. #endif
  18084. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18085. add its header directory to your include path.
  18086. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18087. flag in juce_Config.h
  18088. */
  18089. #include <Movies.h>
  18090. #include <QTML.h>
  18091. #include <QuickTimeComponents.h>
  18092. #include <MediaHandlers.h>
  18093. #include <ImageCodec.h>
  18094. #if JUCE_MSVC
  18095. #pragma warning (pop)
  18096. #endif
  18097. #endif
  18098. BEGIN_JUCE_NAMESPACE
  18099. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18100. static const char* const quickTimeFormatName = "QuickTime file";
  18101. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18102. class QTAudioReader : public AudioFormatReader
  18103. {
  18104. public:
  18105. QTAudioReader (InputStream* const input_, const int trackNum_)
  18106. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18107. ok (false),
  18108. movie (0),
  18109. trackNum (trackNum_),
  18110. lastSampleRead (0),
  18111. lastThreadId (0),
  18112. extractor (0),
  18113. dataHandle (0)
  18114. {
  18115. JUCE_AUTORELEASEPOOL
  18116. bufferList.calloc (256, 1);
  18117. #if JUCE_WINDOWS
  18118. if (InitializeQTML (0) != noErr)
  18119. return;
  18120. #endif
  18121. if (EnterMovies() != noErr)
  18122. return;
  18123. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18124. if (! opened)
  18125. return;
  18126. {
  18127. const int numTracks = GetMovieTrackCount (movie);
  18128. int trackCount = 0;
  18129. for (int i = 1; i <= numTracks; ++i)
  18130. {
  18131. track = GetMovieIndTrack (movie, i);
  18132. media = GetTrackMedia (track);
  18133. OSType mediaType;
  18134. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18135. if (mediaType == SoundMediaType
  18136. && trackCount++ == trackNum_)
  18137. {
  18138. ok = true;
  18139. break;
  18140. }
  18141. }
  18142. }
  18143. if (! ok)
  18144. return;
  18145. ok = false;
  18146. lengthInSamples = GetMediaDecodeDuration (media);
  18147. usesFloatingPointData = false;
  18148. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18149. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18150. / GetMediaTimeScale (media);
  18151. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18152. unsigned long output_layout_size;
  18153. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18154. kQTPropertyClass_MovieAudioExtraction_Audio,
  18155. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18156. 0, &output_layout_size, 0);
  18157. if (err != noErr)
  18158. return;
  18159. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18160. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18161. err = MovieAudioExtractionGetProperty (extractor,
  18162. kQTPropertyClass_MovieAudioExtraction_Audio,
  18163. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18164. output_layout_size, qt_audio_channel_layout, 0);
  18165. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18166. err = MovieAudioExtractionSetProperty (extractor,
  18167. kQTPropertyClass_MovieAudioExtraction_Audio,
  18168. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18169. output_layout_size,
  18170. qt_audio_channel_layout);
  18171. err = MovieAudioExtractionGetProperty (extractor,
  18172. kQTPropertyClass_MovieAudioExtraction_Audio,
  18173. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18174. sizeof (inputStreamDesc),
  18175. &inputStreamDesc, 0);
  18176. if (err != noErr)
  18177. return;
  18178. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18179. | kAudioFormatFlagIsPacked
  18180. | kAudioFormatFlagsNativeEndian;
  18181. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18182. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18183. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18184. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18185. err = MovieAudioExtractionSetProperty (extractor,
  18186. kQTPropertyClass_MovieAudioExtraction_Audio,
  18187. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18188. sizeof (inputStreamDesc),
  18189. &inputStreamDesc);
  18190. if (err != noErr)
  18191. return;
  18192. Boolean allChannelsDiscrete = false;
  18193. err = MovieAudioExtractionSetProperty (extractor,
  18194. kQTPropertyClass_MovieAudioExtraction_Movie,
  18195. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18196. sizeof (allChannelsDiscrete),
  18197. &allChannelsDiscrete);
  18198. if (err != noErr)
  18199. return;
  18200. bufferList->mNumberBuffers = 1;
  18201. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18202. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18203. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18204. bufferList->mBuffers[0].mData = dataBuffer;
  18205. sampleRate = inputStreamDesc.mSampleRate;
  18206. bitsPerSample = 16;
  18207. numChannels = inputStreamDesc.mChannelsPerFrame;
  18208. detachThread();
  18209. ok = true;
  18210. }
  18211. ~QTAudioReader()
  18212. {
  18213. JUCE_AUTORELEASEPOOL
  18214. checkThreadIsAttached();
  18215. if (dataHandle != 0)
  18216. DisposeHandle (dataHandle);
  18217. if (extractor != 0)
  18218. {
  18219. MovieAudioExtractionEnd (extractor);
  18220. extractor = 0;
  18221. }
  18222. DisposeMovie (movie);
  18223. #if JUCE_MAC
  18224. ExitMoviesOnThread ();
  18225. #endif
  18226. }
  18227. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18228. int64 startSampleInFile, int numSamples)
  18229. {
  18230. JUCE_AUTORELEASEPOOL
  18231. checkThreadIsAttached();
  18232. bool ok = true;
  18233. while (numSamples > 0)
  18234. {
  18235. if (lastSampleRead != startSampleInFile)
  18236. {
  18237. TimeRecord time;
  18238. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18239. time.base = 0;
  18240. time.value.hi = 0;
  18241. time.value.lo = (UInt32) startSampleInFile;
  18242. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18243. kQTPropertyClass_MovieAudioExtraction_Movie,
  18244. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18245. sizeof (time), &time);
  18246. if (err != noErr)
  18247. {
  18248. ok = false;
  18249. break;
  18250. }
  18251. }
  18252. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18253. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18254. UInt32 outFlags = 0;
  18255. UInt32 actualNumFrames = framesToDo;
  18256. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18257. if (err != noErr)
  18258. {
  18259. ok = false;
  18260. break;
  18261. }
  18262. lastSampleRead = startSampleInFile + actualNumFrames;
  18263. const int samplesReceived = actualNumFrames;
  18264. for (int j = numDestChannels; --j >= 0;)
  18265. {
  18266. if (destSamples[j] != 0)
  18267. {
  18268. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18269. for (int i = 0; i < samplesReceived; ++i)
  18270. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18271. }
  18272. }
  18273. startOffsetInDestBuffer += samplesReceived;
  18274. startSampleInFile += samplesReceived;
  18275. numSamples -= samplesReceived;
  18276. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18277. {
  18278. for (int j = numDestChannels; --j >= 0;)
  18279. if (destSamples[j] != 0)
  18280. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18281. break;
  18282. }
  18283. }
  18284. detachThread();
  18285. return ok;
  18286. }
  18287. bool ok;
  18288. private:
  18289. Movie movie;
  18290. Media media;
  18291. Track track;
  18292. const int trackNum;
  18293. double trackUnitsPerFrame;
  18294. int samplesPerFrame;
  18295. int64 lastSampleRead;
  18296. Thread::ThreadID lastThreadId;
  18297. MovieAudioExtractionRef extractor;
  18298. AudioStreamBasicDescription inputStreamDesc;
  18299. HeapBlock <AudioBufferList> bufferList;
  18300. HeapBlock <char> dataBuffer;
  18301. Handle dataHandle;
  18302. void checkThreadIsAttached()
  18303. {
  18304. #if JUCE_MAC
  18305. if (Thread::getCurrentThreadId() != lastThreadId)
  18306. EnterMoviesOnThread (0);
  18307. AttachMovieToCurrentThread (movie);
  18308. #endif
  18309. }
  18310. void detachThread()
  18311. {
  18312. #if JUCE_MAC
  18313. DetachMovieFromCurrentThread (movie);
  18314. #endif
  18315. }
  18316. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QTAudioReader);
  18317. };
  18318. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18319. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18320. {
  18321. }
  18322. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18323. {
  18324. }
  18325. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18326. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18327. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18328. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18329. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18330. const bool deleteStreamIfOpeningFails)
  18331. {
  18332. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18333. if (r->ok)
  18334. return r.release();
  18335. if (! deleteStreamIfOpeningFails)
  18336. r->input = 0;
  18337. return 0;
  18338. }
  18339. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18340. double /*sampleRateToUse*/,
  18341. unsigned int /*numberOfChannels*/,
  18342. int /*bitsPerSample*/,
  18343. const StringPairArray& /*metadataValues*/,
  18344. int /*qualityOptionIndex*/)
  18345. {
  18346. jassertfalse; // not yet implemented!
  18347. return 0;
  18348. }
  18349. END_JUCE_NAMESPACE
  18350. #endif
  18351. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18352. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18353. BEGIN_JUCE_NAMESPACE
  18354. static const char* const wavFormatName = "WAV file";
  18355. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18356. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18357. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18358. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18359. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18360. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18361. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18362. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18363. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18364. const String& originator,
  18365. const String& originatorRef,
  18366. const Time& date,
  18367. const int64 timeReferenceSamples,
  18368. const String& codingHistory)
  18369. {
  18370. StringPairArray m;
  18371. m.set (bwavDescription, description);
  18372. m.set (bwavOriginator, originator);
  18373. m.set (bwavOriginatorRef, originatorRef);
  18374. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18375. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18376. m.set (bwavTimeReference, String (timeReferenceSamples));
  18377. m.set (bwavCodingHistory, codingHistory);
  18378. return m;
  18379. }
  18380. #if JUCE_MSVC
  18381. #pragma pack (push, 1)
  18382. #define PACKED
  18383. #elif JUCE_GCC
  18384. #define PACKED __attribute__((packed))
  18385. #else
  18386. #define PACKED
  18387. #endif
  18388. struct BWAVChunk
  18389. {
  18390. char description [256];
  18391. char originator [32];
  18392. char originatorRef [32];
  18393. char originationDate [10];
  18394. char originationTime [8];
  18395. uint32 timeRefLow;
  18396. uint32 timeRefHigh;
  18397. uint16 version;
  18398. uint8 umid[64];
  18399. uint8 reserved[190];
  18400. char codingHistory[1];
  18401. void copyTo (StringPairArray& values) const
  18402. {
  18403. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18404. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18405. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18406. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18407. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18408. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18409. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18410. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18411. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18412. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18413. }
  18414. static MemoryBlock createFrom (const StringPairArray& values)
  18415. {
  18416. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18417. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18418. data.fillWith (0);
  18419. BWAVChunk* b = (BWAVChunk*) data.getData();
  18420. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18421. // as they get called in the right order..
  18422. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18423. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18424. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18425. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18426. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18427. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18428. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18429. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18430. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18431. if (b->description[0] != 0
  18432. || b->originator[0] != 0
  18433. || b->originationDate[0] != 0
  18434. || b->originationTime[0] != 0
  18435. || b->codingHistory[0] != 0
  18436. || time != 0)
  18437. {
  18438. return data;
  18439. }
  18440. return MemoryBlock();
  18441. }
  18442. } PACKED;
  18443. struct SMPLChunk
  18444. {
  18445. struct SampleLoop
  18446. {
  18447. uint32 identifier;
  18448. uint32 type;
  18449. uint32 start;
  18450. uint32 end;
  18451. uint32 fraction;
  18452. uint32 playCount;
  18453. } PACKED;
  18454. uint32 manufacturer;
  18455. uint32 product;
  18456. uint32 samplePeriod;
  18457. uint32 midiUnityNote;
  18458. uint32 midiPitchFraction;
  18459. uint32 smpteFormat;
  18460. uint32 smpteOffset;
  18461. uint32 numSampleLoops;
  18462. uint32 samplerData;
  18463. SampleLoop loops[1];
  18464. void copyTo (StringPairArray& values, const int totalSize) const
  18465. {
  18466. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18467. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18468. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18469. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18470. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18471. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18472. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18473. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18474. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18475. for (uint32 i = 0; i < numSampleLoops; ++i)
  18476. {
  18477. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18478. break;
  18479. const String prefix ("Loop" + String(i));
  18480. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18481. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18482. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18483. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18484. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18485. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18486. }
  18487. }
  18488. static MemoryBlock createFrom (const StringPairArray& values)
  18489. {
  18490. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18491. if (numLoops <= 0)
  18492. return MemoryBlock();
  18493. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18494. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18495. data.fillWith (0);
  18496. SMPLChunk* s = (SMPLChunk*) data.getData();
  18497. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18498. // as they get called in the right order..
  18499. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18500. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18501. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18502. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18503. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18504. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18505. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18506. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18507. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18508. for (int i = 0; i < numLoops; ++i)
  18509. {
  18510. const String prefix ("Loop" + String(i));
  18511. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18512. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18513. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18514. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18515. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18516. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18517. }
  18518. return data;
  18519. }
  18520. } PACKED;
  18521. struct ExtensibleWavSubFormat
  18522. {
  18523. uint32 data1;
  18524. uint16 data2;
  18525. uint16 data3;
  18526. uint8 data4[8];
  18527. } PACKED;
  18528. #if JUCE_MSVC
  18529. #pragma pack (pop)
  18530. #endif
  18531. #undef PACKED
  18532. class WavAudioFormatReader : public AudioFormatReader
  18533. {
  18534. public:
  18535. WavAudioFormatReader (InputStream* const in)
  18536. : AudioFormatReader (in, TRANS (wavFormatName)),
  18537. bwavChunkStart (0),
  18538. bwavSize (0),
  18539. dataLength (0)
  18540. {
  18541. if (input->readInt() == chunkName ("RIFF"))
  18542. {
  18543. const uint32 len = (uint32) input->readInt();
  18544. const int64 end = input->getPosition() + len;
  18545. bool hasGotType = false;
  18546. bool hasGotData = false;
  18547. if (input->readInt() == chunkName ("WAVE"))
  18548. {
  18549. while (input->getPosition() < end
  18550. && ! input->isExhausted())
  18551. {
  18552. const int chunkType = input->readInt();
  18553. uint32 length = (uint32) input->readInt();
  18554. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18555. if (chunkType == chunkName ("fmt "))
  18556. {
  18557. // read the format chunk
  18558. const unsigned short format = input->readShort();
  18559. const short numChans = input->readShort();
  18560. sampleRate = input->readInt();
  18561. const int bytesPerSec = input->readInt();
  18562. numChannels = numChans;
  18563. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18564. bitsPerSample = 8 * bytesPerFrame / numChans;
  18565. if (format == 3)
  18566. {
  18567. usesFloatingPointData = true;
  18568. }
  18569. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18570. {
  18571. if (length < 40) // too short
  18572. {
  18573. bytesPerFrame = 0;
  18574. }
  18575. else
  18576. {
  18577. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18578. ExtensibleWavSubFormat subFormat;
  18579. subFormat.data1 = input->readInt();
  18580. subFormat.data2 = input->readShort();
  18581. subFormat.data3 = input->readShort();
  18582. input->read (subFormat.data4, sizeof (subFormat.data4));
  18583. const ExtensibleWavSubFormat pcmFormat
  18584. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18585. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18586. {
  18587. const ExtensibleWavSubFormat ambisonicFormat
  18588. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18589. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18590. bytesPerFrame = 0;
  18591. }
  18592. }
  18593. }
  18594. else if (format != 1)
  18595. {
  18596. bytesPerFrame = 0;
  18597. }
  18598. hasGotType = true;
  18599. }
  18600. else if (chunkType == chunkName ("data"))
  18601. {
  18602. // get the data chunk's position
  18603. dataLength = length;
  18604. dataChunkStart = input->getPosition();
  18605. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18606. hasGotData = true;
  18607. }
  18608. else if (chunkType == chunkName ("bext"))
  18609. {
  18610. bwavChunkStart = input->getPosition();
  18611. bwavSize = length;
  18612. // Broadcast-wav extension chunk..
  18613. HeapBlock <BWAVChunk> bwav;
  18614. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18615. input->read (bwav, length);
  18616. bwav->copyTo (metadataValues);
  18617. }
  18618. else if (chunkType == chunkName ("smpl"))
  18619. {
  18620. HeapBlock <SMPLChunk> smpl;
  18621. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18622. input->read (smpl, length);
  18623. smpl->copyTo (metadataValues, length);
  18624. }
  18625. else if (chunkEnd <= input->getPosition())
  18626. {
  18627. break;
  18628. }
  18629. input->setPosition (chunkEnd);
  18630. }
  18631. }
  18632. }
  18633. }
  18634. ~WavAudioFormatReader()
  18635. {
  18636. }
  18637. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18638. int64 startSampleInFile, int numSamples)
  18639. {
  18640. jassert (destSamples != 0);
  18641. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18642. if (samplesAvailable < numSamples)
  18643. {
  18644. for (int i = numDestChannels; --i >= 0;)
  18645. if (destSamples[i] != 0)
  18646. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18647. numSamples = (int) samplesAvailable;
  18648. }
  18649. if (numSamples <= 0)
  18650. return true;
  18651. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18652. while (numSamples > 0)
  18653. {
  18654. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18655. char tempBuffer [tempBufSize];
  18656. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18657. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18658. if (bytesRead < numThisTime * bytesPerFrame)
  18659. {
  18660. jassert (bytesRead >= 0);
  18661. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18662. }
  18663. switch (bitsPerSample)
  18664. {
  18665. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18666. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18667. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18668. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18669. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18670. default: jassertfalse; break;
  18671. }
  18672. startOffsetInDestBuffer += numThisTime;
  18673. numSamples -= numThisTime;
  18674. }
  18675. return true;
  18676. }
  18677. int64 bwavChunkStart, bwavSize;
  18678. private:
  18679. ScopedPointer<AudioData::Converter> converter;
  18680. int bytesPerFrame;
  18681. int64 dataChunkStart, dataLength;
  18682. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18683. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  18684. };
  18685. class WavAudioFormatWriter : public AudioFormatWriter
  18686. {
  18687. public:
  18688. WavAudioFormatWriter (OutputStream* const out,
  18689. const double sampleRate_,
  18690. const unsigned int numChannels_,
  18691. const int bits,
  18692. const StringPairArray& metadataValues)
  18693. : AudioFormatWriter (out,
  18694. TRANS (wavFormatName),
  18695. sampleRate_,
  18696. numChannels_,
  18697. bits),
  18698. lengthInSamples (0),
  18699. bytesWritten (0),
  18700. writeFailed (false)
  18701. {
  18702. if (metadataValues.size() > 0)
  18703. {
  18704. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18705. smplChunk = SMPLChunk::createFrom (metadataValues);
  18706. }
  18707. headerPosition = out->getPosition();
  18708. writeHeader();
  18709. }
  18710. ~WavAudioFormatWriter()
  18711. {
  18712. writeHeader();
  18713. }
  18714. bool write (const int** data, int numSamples)
  18715. {
  18716. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18717. if (writeFailed)
  18718. return false;
  18719. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18720. tempBlock.ensureSize (bytes, false);
  18721. switch (bitsPerSample)
  18722. {
  18723. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18724. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18725. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18726. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18727. default: jassertfalse; break;
  18728. }
  18729. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18730. || ! output->write (tempBlock.getData(), bytes))
  18731. {
  18732. // failed to write to disk, so let's try writing the header.
  18733. // If it's just run out of disk space, then if it does manage
  18734. // to write the header, we'll still have a useable file..
  18735. writeHeader();
  18736. writeFailed = true;
  18737. return false;
  18738. }
  18739. else
  18740. {
  18741. bytesWritten += bytes;
  18742. lengthInSamples += numSamples;
  18743. return true;
  18744. }
  18745. }
  18746. private:
  18747. ScopedPointer<AudioData::Converter> converter;
  18748. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18749. uint32 lengthInSamples, bytesWritten;
  18750. int64 headerPosition;
  18751. bool writeFailed;
  18752. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18753. void writeHeader()
  18754. {
  18755. const bool seekedOk = output->setPosition (headerPosition);
  18756. (void) seekedOk;
  18757. // if this fails, you've given it an output stream that can't seek! It needs
  18758. // to be able to seek back to write the header
  18759. jassert (seekedOk);
  18760. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18761. output->writeInt (chunkName ("RIFF"));
  18762. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18763. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18764. output->writeInt (chunkName ("WAVE"));
  18765. output->writeInt (chunkName ("fmt "));
  18766. output->writeInt (16);
  18767. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18768. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18769. output->writeShort ((short) numChannels);
  18770. output->writeInt ((int) sampleRate);
  18771. output->writeInt (bytesPerFrame * (int) sampleRate);
  18772. output->writeShort ((short) bytesPerFrame);
  18773. output->writeShort ((short) bitsPerSample);
  18774. if (bwavChunk.getSize() > 0)
  18775. {
  18776. output->writeInt (chunkName ("bext"));
  18777. output->writeInt ((int) bwavChunk.getSize());
  18778. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18779. }
  18780. if (smplChunk.getSize() > 0)
  18781. {
  18782. output->writeInt (chunkName ("smpl"));
  18783. output->writeInt ((int) smplChunk.getSize());
  18784. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18785. }
  18786. output->writeInt (chunkName ("data"));
  18787. output->writeInt (lengthInSamples * bytesPerFrame);
  18788. usesFloatingPointData = (bitsPerSample == 32);
  18789. }
  18790. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  18791. };
  18792. WavAudioFormat::WavAudioFormat()
  18793. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18794. {
  18795. }
  18796. WavAudioFormat::~WavAudioFormat()
  18797. {
  18798. }
  18799. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18800. {
  18801. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18802. return Array <int> (rates);
  18803. }
  18804. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18805. {
  18806. const int depths[] = { 8, 16, 24, 32, 0 };
  18807. return Array <int> (depths);
  18808. }
  18809. bool WavAudioFormat::canDoStereo() { return true; }
  18810. bool WavAudioFormat::canDoMono() { return true; }
  18811. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18812. const bool deleteStreamIfOpeningFails)
  18813. {
  18814. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18815. if (r->sampleRate != 0)
  18816. return r.release();
  18817. if (! deleteStreamIfOpeningFails)
  18818. r->input = 0;
  18819. return 0;
  18820. }
  18821. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18822. double sampleRate,
  18823. unsigned int numChannels,
  18824. int bitsPerSample,
  18825. const StringPairArray& metadataValues,
  18826. int /*qualityOptionIndex*/)
  18827. {
  18828. if (getPossibleBitDepths().contains (bitsPerSample))
  18829. {
  18830. return new WavAudioFormatWriter (out,
  18831. sampleRate,
  18832. numChannels,
  18833. bitsPerSample,
  18834. metadataValues);
  18835. }
  18836. return 0;
  18837. }
  18838. namespace
  18839. {
  18840. bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18841. {
  18842. TemporaryFile tempFile (file);
  18843. WavAudioFormat wav;
  18844. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18845. if (reader != 0)
  18846. {
  18847. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18848. if (outStream != 0)
  18849. {
  18850. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18851. reader->numChannels, reader->bitsPerSample,
  18852. metadata, 0));
  18853. if (writer != 0)
  18854. {
  18855. outStream.release();
  18856. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18857. writer = 0;
  18858. reader = 0;
  18859. return ok && tempFile.overwriteTargetFileWithTemporary();
  18860. }
  18861. }
  18862. }
  18863. return false;
  18864. }
  18865. }
  18866. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18867. {
  18868. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18869. if (reader != 0)
  18870. {
  18871. const int64 bwavPos = reader->bwavChunkStart;
  18872. const int64 bwavSize = reader->bwavSize;
  18873. reader = 0;
  18874. if (bwavSize > 0)
  18875. {
  18876. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18877. if (chunk.getSize() <= (size_t) bwavSize)
  18878. {
  18879. // the new one will fit in the space available, so write it directly..
  18880. const int64 oldSize = wavFile.getSize();
  18881. {
  18882. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18883. out->setPosition (bwavPos);
  18884. out->write (chunk.getData(), (int) chunk.getSize());
  18885. out->setPosition (oldSize);
  18886. }
  18887. jassert (wavFile.getSize() == oldSize);
  18888. return true;
  18889. }
  18890. }
  18891. }
  18892. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18893. }
  18894. END_JUCE_NAMESPACE
  18895. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18896. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18897. #if JUCE_USE_CDREADER
  18898. BEGIN_JUCE_NAMESPACE
  18899. int AudioCDReader::getNumTracks() const
  18900. {
  18901. return trackStartSamples.size() - 1;
  18902. }
  18903. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18904. {
  18905. return trackStartSamples [trackNum];
  18906. }
  18907. const Array<int>& AudioCDReader::getTrackOffsets() const
  18908. {
  18909. return trackStartSamples;
  18910. }
  18911. int AudioCDReader::getCDDBId()
  18912. {
  18913. int checksum = 0;
  18914. const int numTracks = getNumTracks();
  18915. for (int i = 0; i < numTracks; ++i)
  18916. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18917. checksum += offset % 10;
  18918. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18919. // CCLLLLTT: checksum, length, tracks
  18920. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18921. }
  18922. END_JUCE_NAMESPACE
  18923. #endif
  18924. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18925. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18926. BEGIN_JUCE_NAMESPACE
  18927. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18928. const bool deleteReaderWhenThisIsDeleted)
  18929. : reader (reader_),
  18930. deleteReader (deleteReaderWhenThisIsDeleted),
  18931. nextPlayPos (0),
  18932. looping (false)
  18933. {
  18934. jassert (reader != 0);
  18935. }
  18936. AudioFormatReaderSource::~AudioFormatReaderSource()
  18937. {
  18938. releaseResources();
  18939. if (deleteReader)
  18940. delete reader;
  18941. }
  18942. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18943. {
  18944. nextPlayPos = newPosition;
  18945. }
  18946. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18947. {
  18948. looping = shouldLoop;
  18949. }
  18950. int AudioFormatReaderSource::getNextReadPosition() const
  18951. {
  18952. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18953. : nextPlayPos;
  18954. }
  18955. int AudioFormatReaderSource::getTotalLength() const
  18956. {
  18957. return (int) reader->lengthInSamples;
  18958. }
  18959. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18960. double /*sampleRate*/)
  18961. {
  18962. }
  18963. void AudioFormatReaderSource::releaseResources()
  18964. {
  18965. }
  18966. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18967. {
  18968. if (info.numSamples > 0)
  18969. {
  18970. const int start = nextPlayPos;
  18971. if (looping)
  18972. {
  18973. const int newStart = start % (int) reader->lengthInSamples;
  18974. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18975. if (newEnd > newStart)
  18976. {
  18977. info.buffer->readFromAudioReader (reader,
  18978. info.startSample,
  18979. newEnd - newStart,
  18980. newStart,
  18981. true, true);
  18982. }
  18983. else
  18984. {
  18985. const int endSamps = (int) reader->lengthInSamples - newStart;
  18986. info.buffer->readFromAudioReader (reader,
  18987. info.startSample,
  18988. endSamps,
  18989. newStart,
  18990. true, true);
  18991. info.buffer->readFromAudioReader (reader,
  18992. info.startSample + endSamps,
  18993. newEnd,
  18994. 0,
  18995. true, true);
  18996. }
  18997. nextPlayPos = newEnd;
  18998. }
  18999. else
  19000. {
  19001. info.buffer->readFromAudioReader (reader,
  19002. info.startSample,
  19003. info.numSamples,
  19004. start,
  19005. true, true);
  19006. nextPlayPos += info.numSamples;
  19007. }
  19008. }
  19009. }
  19010. END_JUCE_NAMESPACE
  19011. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19012. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19013. BEGIN_JUCE_NAMESPACE
  19014. AudioSourcePlayer::AudioSourcePlayer()
  19015. : source (0),
  19016. sampleRate (0),
  19017. bufferSize (0),
  19018. tempBuffer (2, 8),
  19019. lastGain (1.0f),
  19020. gain (1.0f)
  19021. {
  19022. }
  19023. AudioSourcePlayer::~AudioSourcePlayer()
  19024. {
  19025. setSource (0);
  19026. }
  19027. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19028. {
  19029. if (source != newSource)
  19030. {
  19031. AudioSource* const oldSource = source;
  19032. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19033. newSource->prepareToPlay (bufferSize, sampleRate);
  19034. {
  19035. const ScopedLock sl (readLock);
  19036. source = newSource;
  19037. }
  19038. if (oldSource != 0)
  19039. oldSource->releaseResources();
  19040. }
  19041. }
  19042. void AudioSourcePlayer::setGain (const float newGain) throw()
  19043. {
  19044. gain = newGain;
  19045. }
  19046. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19047. int totalNumInputChannels,
  19048. float** outputChannelData,
  19049. int totalNumOutputChannels,
  19050. int numSamples)
  19051. {
  19052. // these should have been prepared by audioDeviceAboutToStart()...
  19053. jassert (sampleRate > 0 && bufferSize > 0);
  19054. const ScopedLock sl (readLock);
  19055. if (source != 0)
  19056. {
  19057. AudioSourceChannelInfo info;
  19058. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19059. // messy stuff needed to compact the channels down into an array
  19060. // of non-zero pointers..
  19061. for (i = 0; i < totalNumInputChannels; ++i)
  19062. {
  19063. if (inputChannelData[i] != 0)
  19064. {
  19065. inputChans [numInputs++] = inputChannelData[i];
  19066. if (numInputs >= numElementsInArray (inputChans))
  19067. break;
  19068. }
  19069. }
  19070. for (i = 0; i < totalNumOutputChannels; ++i)
  19071. {
  19072. if (outputChannelData[i] != 0)
  19073. {
  19074. outputChans [numOutputs++] = outputChannelData[i];
  19075. if (numOutputs >= numElementsInArray (outputChans))
  19076. break;
  19077. }
  19078. }
  19079. if (numInputs > numOutputs)
  19080. {
  19081. // if there aren't enough output channels for the number of
  19082. // inputs, we need to create some temporary extra ones (can't
  19083. // use the input data in case it gets written to)
  19084. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19085. false, false, true);
  19086. for (i = 0; i < numOutputs; ++i)
  19087. {
  19088. channels[numActiveChans] = outputChans[i];
  19089. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19090. ++numActiveChans;
  19091. }
  19092. for (i = numOutputs; i < numInputs; ++i)
  19093. {
  19094. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19095. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19096. ++numActiveChans;
  19097. }
  19098. }
  19099. else
  19100. {
  19101. for (i = 0; i < numInputs; ++i)
  19102. {
  19103. channels[numActiveChans] = outputChans[i];
  19104. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19105. ++numActiveChans;
  19106. }
  19107. for (i = numInputs; i < numOutputs; ++i)
  19108. {
  19109. channels[numActiveChans] = outputChans[i];
  19110. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19111. ++numActiveChans;
  19112. }
  19113. }
  19114. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19115. info.buffer = &buffer;
  19116. info.startSample = 0;
  19117. info.numSamples = numSamples;
  19118. source->getNextAudioBlock (info);
  19119. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19120. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19121. lastGain = gain;
  19122. }
  19123. else
  19124. {
  19125. for (int i = 0; i < totalNumOutputChannels; ++i)
  19126. if (outputChannelData[i] != 0)
  19127. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19128. }
  19129. }
  19130. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19131. {
  19132. sampleRate = device->getCurrentSampleRate();
  19133. bufferSize = device->getCurrentBufferSizeSamples();
  19134. zeromem (channels, sizeof (channels));
  19135. if (source != 0)
  19136. source->prepareToPlay (bufferSize, sampleRate);
  19137. }
  19138. void AudioSourcePlayer::audioDeviceStopped()
  19139. {
  19140. if (source != 0)
  19141. source->releaseResources();
  19142. sampleRate = 0.0;
  19143. bufferSize = 0;
  19144. tempBuffer.setSize (2, 8);
  19145. }
  19146. END_JUCE_NAMESPACE
  19147. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19148. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19149. BEGIN_JUCE_NAMESPACE
  19150. AudioTransportSource::AudioTransportSource()
  19151. : source (0),
  19152. resamplerSource (0),
  19153. bufferingSource (0),
  19154. positionableSource (0),
  19155. masterSource (0),
  19156. gain (1.0f),
  19157. lastGain (1.0f),
  19158. playing (false),
  19159. stopped (true),
  19160. sampleRate (44100.0),
  19161. sourceSampleRate (0.0),
  19162. blockSize (128),
  19163. readAheadBufferSize (0),
  19164. isPrepared (false),
  19165. inputStreamEOF (false)
  19166. {
  19167. }
  19168. AudioTransportSource::~AudioTransportSource()
  19169. {
  19170. setSource (0);
  19171. releaseResources();
  19172. }
  19173. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19174. int readAheadBufferSize_,
  19175. double sourceSampleRateToCorrectFor)
  19176. {
  19177. if (source == newSource)
  19178. {
  19179. if (source == 0)
  19180. return;
  19181. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19182. }
  19183. readAheadBufferSize = readAheadBufferSize_;
  19184. sourceSampleRate = sourceSampleRateToCorrectFor;
  19185. ResamplingAudioSource* newResamplerSource = 0;
  19186. BufferingAudioSource* newBufferingSource = 0;
  19187. PositionableAudioSource* newPositionableSource = 0;
  19188. AudioSource* newMasterSource = 0;
  19189. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19190. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19191. AudioSource* oldMasterSource = masterSource;
  19192. if (newSource != 0)
  19193. {
  19194. newPositionableSource = newSource;
  19195. if (readAheadBufferSize_ > 0)
  19196. newPositionableSource = newBufferingSource
  19197. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19198. newPositionableSource->setNextReadPosition (0);
  19199. if (sourceSampleRateToCorrectFor != 0)
  19200. newMasterSource = newResamplerSource
  19201. = new ResamplingAudioSource (newPositionableSource, false);
  19202. else
  19203. newMasterSource = newPositionableSource;
  19204. if (isPrepared)
  19205. {
  19206. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19207. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19208. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19209. }
  19210. }
  19211. {
  19212. const ScopedLock sl (callbackLock);
  19213. source = newSource;
  19214. resamplerSource = newResamplerSource;
  19215. bufferingSource = newBufferingSource;
  19216. masterSource = newMasterSource;
  19217. positionableSource = newPositionableSource;
  19218. playing = false;
  19219. }
  19220. if (oldMasterSource != 0)
  19221. oldMasterSource->releaseResources();
  19222. }
  19223. void AudioTransportSource::start()
  19224. {
  19225. if ((! playing) && masterSource != 0)
  19226. {
  19227. {
  19228. const ScopedLock sl (callbackLock);
  19229. playing = true;
  19230. stopped = false;
  19231. inputStreamEOF = false;
  19232. }
  19233. sendChangeMessage();
  19234. }
  19235. }
  19236. void AudioTransportSource::stop()
  19237. {
  19238. if (playing)
  19239. {
  19240. {
  19241. const ScopedLock sl (callbackLock);
  19242. playing = false;
  19243. }
  19244. int n = 500;
  19245. while (--n >= 0 && ! stopped)
  19246. Thread::sleep (2);
  19247. sendChangeMessage();
  19248. }
  19249. }
  19250. void AudioTransportSource::setPosition (double newPosition)
  19251. {
  19252. if (sampleRate > 0.0)
  19253. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19254. }
  19255. double AudioTransportSource::getCurrentPosition() const
  19256. {
  19257. if (sampleRate > 0.0)
  19258. return getNextReadPosition() / sampleRate;
  19259. else
  19260. return 0.0;
  19261. }
  19262. double AudioTransportSource::getLengthInSeconds() const
  19263. {
  19264. return getTotalLength() / sampleRate;
  19265. }
  19266. void AudioTransportSource::setNextReadPosition (int newPosition)
  19267. {
  19268. if (positionableSource != 0)
  19269. {
  19270. if (sampleRate > 0 && sourceSampleRate > 0)
  19271. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19272. positionableSource->setNextReadPosition (newPosition);
  19273. }
  19274. }
  19275. int AudioTransportSource::getNextReadPosition() const
  19276. {
  19277. if (positionableSource != 0)
  19278. {
  19279. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19280. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19281. }
  19282. return 0;
  19283. }
  19284. int AudioTransportSource::getTotalLength() const
  19285. {
  19286. const ScopedLock sl (callbackLock);
  19287. if (positionableSource != 0)
  19288. {
  19289. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19290. return roundToInt (positionableSource->getTotalLength() * ratio);
  19291. }
  19292. return 0;
  19293. }
  19294. bool AudioTransportSource::isLooping() const
  19295. {
  19296. const ScopedLock sl (callbackLock);
  19297. return positionableSource != 0
  19298. && positionableSource->isLooping();
  19299. }
  19300. void AudioTransportSource::setGain (const float newGain) throw()
  19301. {
  19302. gain = newGain;
  19303. }
  19304. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19305. double sampleRate_)
  19306. {
  19307. const ScopedLock sl (callbackLock);
  19308. sampleRate = sampleRate_;
  19309. blockSize = samplesPerBlockExpected;
  19310. if (masterSource != 0)
  19311. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19312. if (resamplerSource != 0 && sourceSampleRate != 0)
  19313. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19314. isPrepared = true;
  19315. }
  19316. void AudioTransportSource::releaseResources()
  19317. {
  19318. const ScopedLock sl (callbackLock);
  19319. if (masterSource != 0)
  19320. masterSource->releaseResources();
  19321. isPrepared = false;
  19322. }
  19323. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19324. {
  19325. const ScopedLock sl (callbackLock);
  19326. inputStreamEOF = false;
  19327. if (masterSource != 0 && ! stopped)
  19328. {
  19329. masterSource->getNextAudioBlock (info);
  19330. if (! playing)
  19331. {
  19332. // just stopped playing, so fade out the last block..
  19333. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19334. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19335. if (info.numSamples > 256)
  19336. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19337. }
  19338. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19339. && ! positionableSource->isLooping())
  19340. {
  19341. playing = false;
  19342. inputStreamEOF = true;
  19343. sendChangeMessage();
  19344. }
  19345. stopped = ! playing;
  19346. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19347. {
  19348. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19349. lastGain, gain);
  19350. }
  19351. }
  19352. else
  19353. {
  19354. info.clearActiveBufferRegion();
  19355. stopped = true;
  19356. }
  19357. lastGain = gain;
  19358. }
  19359. END_JUCE_NAMESPACE
  19360. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19361. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19362. BEGIN_JUCE_NAMESPACE
  19363. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19364. public Thread,
  19365. private Timer
  19366. {
  19367. public:
  19368. SharedBufferingAudioSourceThread()
  19369. : Thread ("Audio Buffer")
  19370. {
  19371. }
  19372. ~SharedBufferingAudioSourceThread()
  19373. {
  19374. stopThread (10000);
  19375. clearSingletonInstance();
  19376. }
  19377. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19378. void addSource (BufferingAudioSource* source)
  19379. {
  19380. const ScopedLock sl (lock);
  19381. if (! sources.contains (source))
  19382. {
  19383. sources.add (source);
  19384. startThread();
  19385. stopTimer();
  19386. }
  19387. notify();
  19388. }
  19389. void removeSource (BufferingAudioSource* source)
  19390. {
  19391. const ScopedLock sl (lock);
  19392. sources.removeValue (source);
  19393. if (sources.size() == 0)
  19394. startTimer (5000);
  19395. }
  19396. private:
  19397. Array <BufferingAudioSource*> sources;
  19398. CriticalSection lock;
  19399. void run()
  19400. {
  19401. while (! threadShouldExit())
  19402. {
  19403. bool busy = false;
  19404. for (int i = sources.size(); --i >= 0;)
  19405. {
  19406. if (threadShouldExit())
  19407. return;
  19408. const ScopedLock sl (lock);
  19409. BufferingAudioSource* const b = sources[i];
  19410. if (b != 0 && b->readNextBufferChunk())
  19411. busy = true;
  19412. }
  19413. if (! busy)
  19414. wait (500);
  19415. }
  19416. }
  19417. void timerCallback()
  19418. {
  19419. stopTimer();
  19420. if (sources.size() == 0)
  19421. deleteInstance();
  19422. }
  19423. JUCE_DECLARE_NON_COPYABLE (SharedBufferingAudioSourceThread);
  19424. };
  19425. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19426. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19427. const bool deleteSourceWhenDeleted_,
  19428. int numberOfSamplesToBuffer_)
  19429. : source (source_),
  19430. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19431. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19432. buffer (2, 0),
  19433. bufferValidStart (0),
  19434. bufferValidEnd (0),
  19435. nextPlayPos (0),
  19436. wasSourceLooping (false)
  19437. {
  19438. jassert (source_ != 0);
  19439. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19440. // not using a larger buffer..
  19441. }
  19442. BufferingAudioSource::~BufferingAudioSource()
  19443. {
  19444. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19445. if (thread != 0)
  19446. thread->removeSource (this);
  19447. if (deleteSourceWhenDeleted)
  19448. delete source;
  19449. }
  19450. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19451. {
  19452. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19453. sampleRate = sampleRate_;
  19454. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19455. buffer.clear();
  19456. bufferValidStart = 0;
  19457. bufferValidEnd = 0;
  19458. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19459. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19460. buffer.getNumSamples() / 2))
  19461. {
  19462. SharedBufferingAudioSourceThread::getInstance()->notify();
  19463. Thread::sleep (5);
  19464. }
  19465. }
  19466. void BufferingAudioSource::releaseResources()
  19467. {
  19468. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19469. if (thread != 0)
  19470. thread->removeSource (this);
  19471. buffer.setSize (2, 0);
  19472. source->releaseResources();
  19473. }
  19474. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19475. {
  19476. const ScopedLock sl (bufferStartPosLock);
  19477. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19478. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19479. if (validStart == validEnd)
  19480. {
  19481. // total cache miss
  19482. info.clearActiveBufferRegion();
  19483. }
  19484. else
  19485. {
  19486. if (validStart > 0)
  19487. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19488. if (validEnd < info.numSamples)
  19489. info.buffer->clear (info.startSample + validEnd,
  19490. info.numSamples - validEnd); // partial cache miss at end
  19491. if (validStart < validEnd)
  19492. {
  19493. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19494. {
  19495. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19496. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19497. if (startBufferIndex < endBufferIndex)
  19498. {
  19499. info.buffer->copyFrom (chan, info.startSample + validStart,
  19500. buffer,
  19501. chan, startBufferIndex,
  19502. validEnd - validStart);
  19503. }
  19504. else
  19505. {
  19506. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19507. info.buffer->copyFrom (chan, info.startSample + validStart,
  19508. buffer,
  19509. chan, startBufferIndex,
  19510. initialSize);
  19511. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19512. buffer,
  19513. chan, 0,
  19514. (validEnd - validStart) - initialSize);
  19515. }
  19516. }
  19517. }
  19518. nextPlayPos += info.numSamples;
  19519. if (source->isLooping() && nextPlayPos > 0)
  19520. nextPlayPos %= source->getTotalLength();
  19521. }
  19522. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19523. if (thread != 0)
  19524. thread->notify();
  19525. }
  19526. int BufferingAudioSource::getNextReadPosition() const
  19527. {
  19528. return (source->isLooping() && nextPlayPos > 0)
  19529. ? nextPlayPos % source->getTotalLength()
  19530. : nextPlayPos;
  19531. }
  19532. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19533. {
  19534. const ScopedLock sl (bufferStartPosLock);
  19535. nextPlayPos = newPosition;
  19536. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19537. if (thread != 0)
  19538. thread->notify();
  19539. }
  19540. bool BufferingAudioSource::readNextBufferChunk()
  19541. {
  19542. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19543. {
  19544. const ScopedLock sl (bufferStartPosLock);
  19545. if (wasSourceLooping != isLooping())
  19546. {
  19547. wasSourceLooping = isLooping();
  19548. bufferValidStart = 0;
  19549. bufferValidEnd = 0;
  19550. }
  19551. newBVS = jmax (0, nextPlayPos);
  19552. newBVE = newBVS + buffer.getNumSamples() - 4;
  19553. sectionToReadStart = 0;
  19554. sectionToReadEnd = 0;
  19555. const int maxChunkSize = 2048;
  19556. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19557. {
  19558. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19559. sectionToReadStart = newBVS;
  19560. sectionToReadEnd = newBVE;
  19561. bufferValidStart = 0;
  19562. bufferValidEnd = 0;
  19563. }
  19564. else if (abs (newBVS - bufferValidStart) > 512
  19565. || abs (newBVE - bufferValidEnd) > 512)
  19566. {
  19567. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19568. sectionToReadStart = bufferValidEnd;
  19569. sectionToReadEnd = newBVE;
  19570. bufferValidStart = newBVS;
  19571. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19572. }
  19573. }
  19574. if (sectionToReadStart != sectionToReadEnd)
  19575. {
  19576. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19577. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19578. if (bufferIndexStart < bufferIndexEnd)
  19579. {
  19580. readBufferSection (sectionToReadStart,
  19581. sectionToReadEnd - sectionToReadStart,
  19582. bufferIndexStart);
  19583. }
  19584. else
  19585. {
  19586. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19587. readBufferSection (sectionToReadStart,
  19588. initialSize,
  19589. bufferIndexStart);
  19590. readBufferSection (sectionToReadStart + initialSize,
  19591. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19592. 0);
  19593. }
  19594. const ScopedLock sl2 (bufferStartPosLock);
  19595. bufferValidStart = newBVS;
  19596. bufferValidEnd = newBVE;
  19597. return true;
  19598. }
  19599. else
  19600. {
  19601. return false;
  19602. }
  19603. }
  19604. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19605. {
  19606. if (source->getNextReadPosition() != start)
  19607. source->setNextReadPosition (start);
  19608. AudioSourceChannelInfo info;
  19609. info.buffer = &buffer;
  19610. info.startSample = bufferOffset;
  19611. info.numSamples = length;
  19612. source->getNextAudioBlock (info);
  19613. }
  19614. END_JUCE_NAMESPACE
  19615. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19616. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19617. BEGIN_JUCE_NAMESPACE
  19618. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19619. const bool deleteSourceWhenDeleted_)
  19620. : requiredNumberOfChannels (2),
  19621. source (source_),
  19622. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19623. buffer (2, 16)
  19624. {
  19625. remappedInfo.buffer = &buffer;
  19626. remappedInfo.startSample = 0;
  19627. }
  19628. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19629. {
  19630. if (deleteSourceWhenDeleted)
  19631. delete source;
  19632. }
  19633. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19634. {
  19635. const ScopedLock sl (lock);
  19636. requiredNumberOfChannels = requiredNumberOfChannels_;
  19637. }
  19638. void ChannelRemappingAudioSource::clearAllMappings()
  19639. {
  19640. const ScopedLock sl (lock);
  19641. remappedInputs.clear();
  19642. remappedOutputs.clear();
  19643. }
  19644. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19645. {
  19646. const ScopedLock sl (lock);
  19647. while (remappedInputs.size() < destIndex)
  19648. remappedInputs.add (-1);
  19649. remappedInputs.set (destIndex, sourceIndex);
  19650. }
  19651. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19652. {
  19653. const ScopedLock sl (lock);
  19654. while (remappedOutputs.size() < sourceIndex)
  19655. remappedOutputs.add (-1);
  19656. remappedOutputs.set (sourceIndex, destIndex);
  19657. }
  19658. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19659. {
  19660. const ScopedLock sl (lock);
  19661. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19662. return remappedInputs.getUnchecked (inputChannelIndex);
  19663. return -1;
  19664. }
  19665. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19666. {
  19667. const ScopedLock sl (lock);
  19668. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19669. return remappedOutputs .getUnchecked (outputChannelIndex);
  19670. return -1;
  19671. }
  19672. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19673. {
  19674. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19675. }
  19676. void ChannelRemappingAudioSource::releaseResources()
  19677. {
  19678. source->releaseResources();
  19679. }
  19680. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19681. {
  19682. const ScopedLock sl (lock);
  19683. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19684. const int numChans = bufferToFill.buffer->getNumChannels();
  19685. int i;
  19686. for (i = 0; i < buffer.getNumChannels(); ++i)
  19687. {
  19688. const int remappedChan = getRemappedInputChannel (i);
  19689. if (remappedChan >= 0 && remappedChan < numChans)
  19690. {
  19691. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19692. remappedChan,
  19693. bufferToFill.startSample,
  19694. bufferToFill.numSamples);
  19695. }
  19696. else
  19697. {
  19698. buffer.clear (i, 0, bufferToFill.numSamples);
  19699. }
  19700. }
  19701. remappedInfo.numSamples = bufferToFill.numSamples;
  19702. source->getNextAudioBlock (remappedInfo);
  19703. bufferToFill.clearActiveBufferRegion();
  19704. for (i = 0; i < requiredNumberOfChannels; ++i)
  19705. {
  19706. const int remappedChan = getRemappedOutputChannel (i);
  19707. if (remappedChan >= 0 && remappedChan < numChans)
  19708. {
  19709. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19710. buffer, i, 0, bufferToFill.numSamples);
  19711. }
  19712. }
  19713. }
  19714. XmlElement* ChannelRemappingAudioSource::createXml() const
  19715. {
  19716. XmlElement* e = new XmlElement ("MAPPINGS");
  19717. String ins, outs;
  19718. int i;
  19719. const ScopedLock sl (lock);
  19720. for (i = 0; i < remappedInputs.size(); ++i)
  19721. ins << remappedInputs.getUnchecked(i) << ' ';
  19722. for (i = 0; i < remappedOutputs.size(); ++i)
  19723. outs << remappedOutputs.getUnchecked(i) << ' ';
  19724. e->setAttribute ("inputs", ins.trimEnd());
  19725. e->setAttribute ("outputs", outs.trimEnd());
  19726. return e;
  19727. }
  19728. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19729. {
  19730. if (e.hasTagName ("MAPPINGS"))
  19731. {
  19732. const ScopedLock sl (lock);
  19733. clearAllMappings();
  19734. StringArray ins, outs;
  19735. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19736. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19737. int i;
  19738. for (i = 0; i < ins.size(); ++i)
  19739. remappedInputs.add (ins[i].getIntValue());
  19740. for (i = 0; i < outs.size(); ++i)
  19741. remappedOutputs.add (outs[i].getIntValue());
  19742. }
  19743. }
  19744. END_JUCE_NAMESPACE
  19745. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19746. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19747. BEGIN_JUCE_NAMESPACE
  19748. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19749. const bool deleteInputWhenDeleted_)
  19750. : input (inputSource),
  19751. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19752. {
  19753. jassert (inputSource != 0);
  19754. for (int i = 2; --i >= 0;)
  19755. iirFilters.add (new IIRFilter());
  19756. }
  19757. IIRFilterAudioSource::~IIRFilterAudioSource()
  19758. {
  19759. if (deleteInputWhenDeleted)
  19760. delete input;
  19761. }
  19762. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19763. {
  19764. for (int i = iirFilters.size(); --i >= 0;)
  19765. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19766. }
  19767. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19768. {
  19769. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19770. for (int i = iirFilters.size(); --i >= 0;)
  19771. iirFilters.getUnchecked(i)->reset();
  19772. }
  19773. void IIRFilterAudioSource::releaseResources()
  19774. {
  19775. input->releaseResources();
  19776. }
  19777. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19778. {
  19779. input->getNextAudioBlock (bufferToFill);
  19780. const int numChannels = bufferToFill.buffer->getNumChannels();
  19781. while (numChannels > iirFilters.size())
  19782. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19783. for (int i = 0; i < numChannels; ++i)
  19784. iirFilters.getUnchecked(i)
  19785. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19786. bufferToFill.numSamples);
  19787. }
  19788. END_JUCE_NAMESPACE
  19789. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19790. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19791. BEGIN_JUCE_NAMESPACE
  19792. MixerAudioSource::MixerAudioSource()
  19793. : tempBuffer (2, 0),
  19794. currentSampleRate (0.0),
  19795. bufferSizeExpected (0)
  19796. {
  19797. }
  19798. MixerAudioSource::~MixerAudioSource()
  19799. {
  19800. removeAllInputs();
  19801. }
  19802. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19803. {
  19804. if (input != 0 && ! inputs.contains (input))
  19805. {
  19806. double localRate;
  19807. int localBufferSize;
  19808. {
  19809. const ScopedLock sl (lock);
  19810. localRate = currentSampleRate;
  19811. localBufferSize = bufferSizeExpected;
  19812. }
  19813. if (localRate != 0.0)
  19814. input->prepareToPlay (localBufferSize, localRate);
  19815. const ScopedLock sl (lock);
  19816. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19817. inputs.add (input);
  19818. }
  19819. }
  19820. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19821. {
  19822. if (input != 0)
  19823. {
  19824. int index;
  19825. {
  19826. const ScopedLock sl (lock);
  19827. index = inputs.indexOf (input);
  19828. if (index >= 0)
  19829. {
  19830. inputsToDelete.shiftBits (index, 1);
  19831. inputs.remove (index);
  19832. }
  19833. }
  19834. if (index >= 0)
  19835. {
  19836. input->releaseResources();
  19837. if (deleteInput)
  19838. delete input;
  19839. }
  19840. }
  19841. }
  19842. void MixerAudioSource::removeAllInputs()
  19843. {
  19844. OwnedArray<AudioSource> toDelete;
  19845. {
  19846. const ScopedLock sl (lock);
  19847. for (int i = inputs.size(); --i >= 0;)
  19848. if (inputsToDelete[i])
  19849. toDelete.add (inputs.getUnchecked(i));
  19850. }
  19851. }
  19852. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19853. {
  19854. tempBuffer.setSize (2, samplesPerBlockExpected);
  19855. const ScopedLock sl (lock);
  19856. currentSampleRate = sampleRate;
  19857. bufferSizeExpected = samplesPerBlockExpected;
  19858. for (int i = inputs.size(); --i >= 0;)
  19859. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19860. }
  19861. void MixerAudioSource::releaseResources()
  19862. {
  19863. const ScopedLock sl (lock);
  19864. for (int i = inputs.size(); --i >= 0;)
  19865. inputs.getUnchecked(i)->releaseResources();
  19866. tempBuffer.setSize (2, 0);
  19867. currentSampleRate = 0;
  19868. bufferSizeExpected = 0;
  19869. }
  19870. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19871. {
  19872. const ScopedLock sl (lock);
  19873. if (inputs.size() > 0)
  19874. {
  19875. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19876. if (inputs.size() > 1)
  19877. {
  19878. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19879. info.buffer->getNumSamples());
  19880. AudioSourceChannelInfo info2;
  19881. info2.buffer = &tempBuffer;
  19882. info2.numSamples = info.numSamples;
  19883. info2.startSample = 0;
  19884. for (int i = 1; i < inputs.size(); ++i)
  19885. {
  19886. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19887. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19888. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19889. }
  19890. }
  19891. }
  19892. else
  19893. {
  19894. info.clearActiveBufferRegion();
  19895. }
  19896. }
  19897. END_JUCE_NAMESPACE
  19898. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19899. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19900. BEGIN_JUCE_NAMESPACE
  19901. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19902. const bool deleteInputWhenDeleted_,
  19903. const int numChannels_)
  19904. : input (inputSource),
  19905. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19906. ratio (1.0),
  19907. lastRatio (1.0),
  19908. buffer (numChannels_, 0),
  19909. sampsInBuffer (0),
  19910. numChannels (numChannels_)
  19911. {
  19912. jassert (input != 0);
  19913. }
  19914. ResamplingAudioSource::~ResamplingAudioSource()
  19915. {
  19916. if (deleteInputWhenDeleted)
  19917. delete input;
  19918. }
  19919. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19920. {
  19921. jassert (samplesInPerOutputSample > 0);
  19922. const ScopedLock sl (ratioLock);
  19923. ratio = jmax (0.0, samplesInPerOutputSample);
  19924. }
  19925. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19926. double sampleRate)
  19927. {
  19928. const ScopedLock sl (ratioLock);
  19929. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19930. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19931. buffer.clear();
  19932. sampsInBuffer = 0;
  19933. bufferPos = 0;
  19934. subSampleOffset = 0.0;
  19935. filterStates.calloc (numChannels);
  19936. srcBuffers.calloc (numChannels);
  19937. destBuffers.calloc (numChannels);
  19938. createLowPass (ratio);
  19939. resetFilters();
  19940. }
  19941. void ResamplingAudioSource::releaseResources()
  19942. {
  19943. input->releaseResources();
  19944. buffer.setSize (numChannels, 0);
  19945. }
  19946. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19947. {
  19948. double localRatio;
  19949. {
  19950. const ScopedLock sl (ratioLock);
  19951. localRatio = ratio;
  19952. }
  19953. if (lastRatio != localRatio)
  19954. {
  19955. createLowPass (localRatio);
  19956. lastRatio = localRatio;
  19957. }
  19958. const int sampsNeeded = roundToInt (info.numSamples * localRatio) + 2;
  19959. int bufferSize = buffer.getNumSamples();
  19960. if (bufferSize < sampsNeeded + 8)
  19961. {
  19962. bufferPos %= bufferSize;
  19963. bufferSize = sampsNeeded + 32;
  19964. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19965. }
  19966. bufferPos %= bufferSize;
  19967. int endOfBufferPos = bufferPos + sampsInBuffer;
  19968. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19969. while (sampsNeeded > sampsInBuffer)
  19970. {
  19971. endOfBufferPos %= bufferSize;
  19972. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19973. bufferSize - endOfBufferPos);
  19974. AudioSourceChannelInfo readInfo;
  19975. readInfo.buffer = &buffer;
  19976. readInfo.numSamples = numToDo;
  19977. readInfo.startSample = endOfBufferPos;
  19978. input->getNextAudioBlock (readInfo);
  19979. if (localRatio > 1.0001)
  19980. {
  19981. // for down-sampling, pre-apply the filter..
  19982. for (int i = channelsToProcess; --i >= 0;)
  19983. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19984. }
  19985. sampsInBuffer += numToDo;
  19986. endOfBufferPos += numToDo;
  19987. }
  19988. for (int channel = 0; channel < channelsToProcess; ++channel)
  19989. {
  19990. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19991. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19992. }
  19993. int nextPos = (bufferPos + 1) % bufferSize;
  19994. for (int m = info.numSamples; --m >= 0;)
  19995. {
  19996. const float alpha = (float) subSampleOffset;
  19997. const float invAlpha = 1.0f - alpha;
  19998. for (int channel = 0; channel < channelsToProcess; ++channel)
  19999. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20000. subSampleOffset += localRatio;
  20001. jassert (sampsInBuffer > 0);
  20002. while (subSampleOffset >= 1.0)
  20003. {
  20004. if (++bufferPos >= bufferSize)
  20005. bufferPos = 0;
  20006. --sampsInBuffer;
  20007. nextPos = (bufferPos + 1) % bufferSize;
  20008. subSampleOffset -= 1.0;
  20009. }
  20010. }
  20011. if (localRatio < 0.9999)
  20012. {
  20013. // for up-sampling, apply the filter after transposing..
  20014. for (int i = channelsToProcess; --i >= 0;)
  20015. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20016. }
  20017. else if (localRatio <= 1.0001)
  20018. {
  20019. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20020. for (int i = channelsToProcess; --i >= 0;)
  20021. {
  20022. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20023. FilterState& fs = filterStates[i];
  20024. if (info.numSamples > 1)
  20025. {
  20026. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20027. }
  20028. else
  20029. {
  20030. fs.y2 = fs.y1;
  20031. fs.x2 = fs.x1;
  20032. }
  20033. fs.y1 = fs.x1 = *endOfBuffer;
  20034. }
  20035. }
  20036. jassert (sampsInBuffer >= 0);
  20037. }
  20038. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20039. {
  20040. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20041. : 0.5 * frequencyRatio;
  20042. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  20043. const double nSquared = n * n;
  20044. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20045. setFilterCoefficients (c1,
  20046. c1 * 2.0f,
  20047. c1,
  20048. 1.0,
  20049. c1 * 2.0 * (1.0 - nSquared),
  20050. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20051. }
  20052. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20053. {
  20054. const double a = 1.0 / c4;
  20055. c1 *= a;
  20056. c2 *= a;
  20057. c3 *= a;
  20058. c5 *= a;
  20059. c6 *= a;
  20060. coefficients[0] = c1;
  20061. coefficients[1] = c2;
  20062. coefficients[2] = c3;
  20063. coefficients[3] = c4;
  20064. coefficients[4] = c5;
  20065. coefficients[5] = c6;
  20066. }
  20067. void ResamplingAudioSource::resetFilters()
  20068. {
  20069. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20070. }
  20071. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20072. {
  20073. while (--num >= 0)
  20074. {
  20075. const double in = *samples;
  20076. double out = coefficients[0] * in
  20077. + coefficients[1] * fs.x1
  20078. + coefficients[2] * fs.x2
  20079. - coefficients[4] * fs.y1
  20080. - coefficients[5] * fs.y2;
  20081. #if JUCE_INTEL
  20082. if (! (out < -1.0e-8 || out > 1.0e-8))
  20083. out = 0;
  20084. #endif
  20085. fs.x2 = fs.x1;
  20086. fs.x1 = in;
  20087. fs.y2 = fs.y1;
  20088. fs.y1 = out;
  20089. *samples++ = (float) out;
  20090. }
  20091. }
  20092. END_JUCE_NAMESPACE
  20093. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20094. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20095. BEGIN_JUCE_NAMESPACE
  20096. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20097. : frequency (1000.0),
  20098. sampleRate (44100.0),
  20099. currentPhase (0.0),
  20100. phasePerSample (0.0),
  20101. amplitude (0.5f)
  20102. {
  20103. }
  20104. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20105. {
  20106. }
  20107. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20108. {
  20109. amplitude = newAmplitude;
  20110. }
  20111. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20112. {
  20113. frequency = newFrequencyHz;
  20114. phasePerSample = 0.0;
  20115. }
  20116. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20117. double sampleRate_)
  20118. {
  20119. currentPhase = 0.0;
  20120. phasePerSample = 0.0;
  20121. sampleRate = sampleRate_;
  20122. }
  20123. void ToneGeneratorAudioSource::releaseResources()
  20124. {
  20125. }
  20126. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20127. {
  20128. if (phasePerSample == 0.0)
  20129. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20130. for (int i = 0; i < info.numSamples; ++i)
  20131. {
  20132. const float sample = amplitude * (float) std::sin (currentPhase);
  20133. currentPhase += phasePerSample;
  20134. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20135. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20136. }
  20137. }
  20138. END_JUCE_NAMESPACE
  20139. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20140. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20141. BEGIN_JUCE_NAMESPACE
  20142. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20143. : sampleRate (0),
  20144. bufferSize (0),
  20145. useDefaultInputChannels (true),
  20146. useDefaultOutputChannels (true)
  20147. {
  20148. }
  20149. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20150. {
  20151. return outputDeviceName == other.outputDeviceName
  20152. && inputDeviceName == other.inputDeviceName
  20153. && sampleRate == other.sampleRate
  20154. && bufferSize == other.bufferSize
  20155. && inputChannels == other.inputChannels
  20156. && useDefaultInputChannels == other.useDefaultInputChannels
  20157. && outputChannels == other.outputChannels
  20158. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20159. }
  20160. AudioDeviceManager::AudioDeviceManager()
  20161. : currentAudioDevice (0),
  20162. numInputChansNeeded (0),
  20163. numOutputChansNeeded (2),
  20164. listNeedsScanning (true),
  20165. useInputNames (false),
  20166. inputLevelMeasurementEnabledCount (0),
  20167. inputLevel (0),
  20168. tempBuffer (2, 2),
  20169. defaultMidiOutput (0),
  20170. cpuUsageMs (0),
  20171. timeToCpuScale (0)
  20172. {
  20173. callbackHandler.owner = this;
  20174. }
  20175. AudioDeviceManager::~AudioDeviceManager()
  20176. {
  20177. currentAudioDevice = 0;
  20178. defaultMidiOutput = 0;
  20179. }
  20180. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20181. {
  20182. if (availableDeviceTypes.size() == 0)
  20183. {
  20184. createAudioDeviceTypes (availableDeviceTypes);
  20185. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20186. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20187. if (availableDeviceTypes.size() > 0)
  20188. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20189. }
  20190. }
  20191. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20192. {
  20193. scanDevicesIfNeeded();
  20194. return availableDeviceTypes;
  20195. }
  20196. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20197. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20198. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20199. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20200. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20201. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20202. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20203. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20204. {
  20205. (void) list; // (to avoid 'unused param' warnings)
  20206. #if JUCE_WINDOWS
  20207. #if JUCE_WASAPI
  20208. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20209. list.add (juce_createAudioIODeviceType_WASAPI());
  20210. #endif
  20211. #if JUCE_DIRECTSOUND
  20212. list.add (juce_createAudioIODeviceType_DirectSound());
  20213. #endif
  20214. #if JUCE_ASIO
  20215. list.add (juce_createAudioIODeviceType_ASIO());
  20216. #endif
  20217. #endif
  20218. #if JUCE_MAC
  20219. list.add (juce_createAudioIODeviceType_CoreAudio());
  20220. #endif
  20221. #if JUCE_IOS
  20222. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20223. #endif
  20224. #if JUCE_LINUX && JUCE_ALSA
  20225. list.add (juce_createAudioIODeviceType_ALSA());
  20226. #endif
  20227. #if JUCE_LINUX && JUCE_JACK
  20228. list.add (juce_createAudioIODeviceType_JACK());
  20229. #endif
  20230. }
  20231. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20232. const int numOutputChannelsNeeded,
  20233. const XmlElement* const e,
  20234. const bool selectDefaultDeviceOnFailure,
  20235. const String& preferredDefaultDeviceName,
  20236. const AudioDeviceSetup* preferredSetupOptions)
  20237. {
  20238. scanDevicesIfNeeded();
  20239. numInputChansNeeded = numInputChannelsNeeded;
  20240. numOutputChansNeeded = numOutputChannelsNeeded;
  20241. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20242. {
  20243. lastExplicitSettings = new XmlElement (*e);
  20244. String error;
  20245. AudioDeviceSetup setup;
  20246. if (preferredSetupOptions != 0)
  20247. setup = *preferredSetupOptions;
  20248. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20249. {
  20250. setup.inputDeviceName = setup.outputDeviceName
  20251. = e->getStringAttribute ("audioDeviceName");
  20252. }
  20253. else
  20254. {
  20255. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20256. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20257. }
  20258. currentDeviceType = e->getStringAttribute ("deviceType");
  20259. if (currentDeviceType.isEmpty())
  20260. {
  20261. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20262. if (type != 0)
  20263. currentDeviceType = type->getTypeName();
  20264. else if (availableDeviceTypes.size() > 0)
  20265. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20266. }
  20267. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20268. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20269. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20270. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20271. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20272. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20273. error = setAudioDeviceSetup (setup, true);
  20274. midiInsFromXml.clear();
  20275. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20276. midiInsFromXml.add (c->getStringAttribute ("name"));
  20277. const StringArray allMidiIns (MidiInput::getDevices());
  20278. for (int i = allMidiIns.size(); --i >= 0;)
  20279. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20280. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20281. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20282. false, preferredDefaultDeviceName);
  20283. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20284. return error;
  20285. }
  20286. else
  20287. {
  20288. AudioDeviceSetup setup;
  20289. if (preferredSetupOptions != 0)
  20290. {
  20291. setup = *preferredSetupOptions;
  20292. }
  20293. else if (preferredDefaultDeviceName.isNotEmpty())
  20294. {
  20295. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20296. {
  20297. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20298. StringArray outs (type->getDeviceNames (false));
  20299. int i;
  20300. for (i = 0; i < outs.size(); ++i)
  20301. {
  20302. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20303. {
  20304. setup.outputDeviceName = outs[i];
  20305. break;
  20306. }
  20307. }
  20308. StringArray ins (type->getDeviceNames (true));
  20309. for (i = 0; i < ins.size(); ++i)
  20310. {
  20311. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20312. {
  20313. setup.inputDeviceName = ins[i];
  20314. break;
  20315. }
  20316. }
  20317. }
  20318. }
  20319. insertDefaultDeviceNames (setup);
  20320. return setAudioDeviceSetup (setup, false);
  20321. }
  20322. }
  20323. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20324. {
  20325. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20326. if (type != 0)
  20327. {
  20328. if (setup.outputDeviceName.isEmpty())
  20329. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20330. if (setup.inputDeviceName.isEmpty())
  20331. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20332. }
  20333. }
  20334. XmlElement* AudioDeviceManager::createStateXml() const
  20335. {
  20336. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20337. }
  20338. void AudioDeviceManager::scanDevicesIfNeeded()
  20339. {
  20340. if (listNeedsScanning)
  20341. {
  20342. listNeedsScanning = false;
  20343. createDeviceTypesIfNeeded();
  20344. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20345. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20346. }
  20347. }
  20348. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20349. {
  20350. scanDevicesIfNeeded();
  20351. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20352. {
  20353. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20354. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20355. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20356. {
  20357. return type;
  20358. }
  20359. }
  20360. return 0;
  20361. }
  20362. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20363. {
  20364. setup = currentSetup;
  20365. }
  20366. void AudioDeviceManager::deleteCurrentDevice()
  20367. {
  20368. currentAudioDevice = 0;
  20369. currentSetup.inputDeviceName = String::empty;
  20370. currentSetup.outputDeviceName = String::empty;
  20371. }
  20372. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20373. const bool treatAsChosenDevice)
  20374. {
  20375. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20376. {
  20377. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20378. && currentDeviceType != type)
  20379. {
  20380. currentDeviceType = type;
  20381. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20382. insertDefaultDeviceNames (s);
  20383. setAudioDeviceSetup (s, treatAsChosenDevice);
  20384. sendChangeMessage();
  20385. break;
  20386. }
  20387. }
  20388. }
  20389. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20390. {
  20391. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20392. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20393. return availableDeviceTypes[i];
  20394. return availableDeviceTypes[0];
  20395. }
  20396. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20397. const bool treatAsChosenDevice)
  20398. {
  20399. jassert (&newSetup != &currentSetup); // this will have no effect
  20400. if (newSetup == currentSetup && currentAudioDevice != 0)
  20401. return String::empty;
  20402. if (! (newSetup == currentSetup))
  20403. sendChangeMessage();
  20404. stopDevice();
  20405. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20406. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20407. String error;
  20408. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20409. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20410. {
  20411. deleteCurrentDevice();
  20412. if (treatAsChosenDevice)
  20413. updateXml();
  20414. return String::empty;
  20415. }
  20416. if (currentSetup.inputDeviceName != newInputDeviceName
  20417. || currentSetup.outputDeviceName != newOutputDeviceName
  20418. || currentAudioDevice == 0)
  20419. {
  20420. deleteCurrentDevice();
  20421. scanDevicesIfNeeded();
  20422. if (newOutputDeviceName.isNotEmpty()
  20423. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20424. {
  20425. return "No such device: " + newOutputDeviceName;
  20426. }
  20427. if (newInputDeviceName.isNotEmpty()
  20428. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20429. {
  20430. return "No such device: " + newInputDeviceName;
  20431. }
  20432. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20433. if (currentAudioDevice == 0)
  20434. 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!";
  20435. else
  20436. error = currentAudioDevice->getLastError();
  20437. if (error.isNotEmpty())
  20438. {
  20439. deleteCurrentDevice();
  20440. return error;
  20441. }
  20442. if (newSetup.useDefaultInputChannels)
  20443. {
  20444. inputChannels.clear();
  20445. inputChannels.setRange (0, numInputChansNeeded, true);
  20446. }
  20447. if (newSetup.useDefaultOutputChannels)
  20448. {
  20449. outputChannels.clear();
  20450. outputChannels.setRange (0, numOutputChansNeeded, true);
  20451. }
  20452. if (newInputDeviceName.isEmpty())
  20453. inputChannels.clear();
  20454. if (newOutputDeviceName.isEmpty())
  20455. outputChannels.clear();
  20456. }
  20457. if (! newSetup.useDefaultInputChannels)
  20458. inputChannels = newSetup.inputChannels;
  20459. if (! newSetup.useDefaultOutputChannels)
  20460. outputChannels = newSetup.outputChannels;
  20461. currentSetup = newSetup;
  20462. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20463. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20464. error = currentAudioDevice->open (inputChannels,
  20465. outputChannels,
  20466. currentSetup.sampleRate,
  20467. currentSetup.bufferSize);
  20468. if (error.isEmpty())
  20469. {
  20470. currentDeviceType = currentAudioDevice->getTypeName();
  20471. currentAudioDevice->start (&callbackHandler);
  20472. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20473. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20474. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20475. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20476. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20477. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20478. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20479. if (treatAsChosenDevice)
  20480. updateXml();
  20481. }
  20482. else
  20483. {
  20484. deleteCurrentDevice();
  20485. }
  20486. return error;
  20487. }
  20488. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20489. {
  20490. jassert (currentAudioDevice != 0);
  20491. if (rate > 0)
  20492. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20493. if (currentAudioDevice->getSampleRate (i) == rate)
  20494. return rate;
  20495. double lowestAbove44 = 0.0;
  20496. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20497. {
  20498. const double sr = currentAudioDevice->getSampleRate (i);
  20499. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20500. lowestAbove44 = sr;
  20501. }
  20502. if (lowestAbove44 > 0.0)
  20503. return lowestAbove44;
  20504. return currentAudioDevice->getSampleRate (0);
  20505. }
  20506. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20507. {
  20508. jassert (currentAudioDevice != 0);
  20509. if (bufferSize > 0)
  20510. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20511. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20512. return bufferSize;
  20513. return currentAudioDevice->getDefaultBufferSize();
  20514. }
  20515. void AudioDeviceManager::stopDevice()
  20516. {
  20517. if (currentAudioDevice != 0)
  20518. currentAudioDevice->stop();
  20519. testSound = 0;
  20520. }
  20521. void AudioDeviceManager::closeAudioDevice()
  20522. {
  20523. stopDevice();
  20524. currentAudioDevice = 0;
  20525. }
  20526. void AudioDeviceManager::restartLastAudioDevice()
  20527. {
  20528. if (currentAudioDevice == 0)
  20529. {
  20530. if (currentSetup.inputDeviceName.isEmpty()
  20531. && currentSetup.outputDeviceName.isEmpty())
  20532. {
  20533. // This method will only reload the last device that was running
  20534. // before closeAudioDevice() was called - you need to actually open
  20535. // one first, with setAudioDevice().
  20536. jassertfalse;
  20537. return;
  20538. }
  20539. AudioDeviceSetup s (currentSetup);
  20540. setAudioDeviceSetup (s, false);
  20541. }
  20542. }
  20543. void AudioDeviceManager::updateXml()
  20544. {
  20545. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20546. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20547. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20548. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20549. if (currentAudioDevice != 0)
  20550. {
  20551. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20552. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20553. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20554. if (! currentSetup.useDefaultInputChannels)
  20555. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20556. if (! currentSetup.useDefaultOutputChannels)
  20557. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20558. }
  20559. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20560. {
  20561. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20562. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20563. }
  20564. if (midiInsFromXml.size() > 0)
  20565. {
  20566. // Add any midi devices that have been enabled before, but which aren't currently
  20567. // open because the device has been disconnected.
  20568. const StringArray availableMidiDevices (MidiInput::getDevices());
  20569. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20570. {
  20571. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20572. {
  20573. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20574. m->setAttribute ("name", midiInsFromXml[i]);
  20575. }
  20576. }
  20577. }
  20578. if (defaultMidiOutputName.isNotEmpty())
  20579. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20580. }
  20581. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20582. {
  20583. {
  20584. const ScopedLock sl (audioCallbackLock);
  20585. if (callbacks.contains (newCallback))
  20586. return;
  20587. }
  20588. if (currentAudioDevice != 0 && newCallback != 0)
  20589. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20590. const ScopedLock sl (audioCallbackLock);
  20591. callbacks.add (newCallback);
  20592. }
  20593. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  20594. {
  20595. if (callbackToRemove != 0)
  20596. {
  20597. bool needsDeinitialising = currentAudioDevice != 0;
  20598. {
  20599. const ScopedLock sl (audioCallbackLock);
  20600. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  20601. callbacks.removeValue (callbackToRemove);
  20602. }
  20603. if (needsDeinitialising)
  20604. callbackToRemove->audioDeviceStopped();
  20605. }
  20606. }
  20607. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20608. int numInputChannels,
  20609. float** outputChannelData,
  20610. int numOutputChannels,
  20611. int numSamples)
  20612. {
  20613. const ScopedLock sl (audioCallbackLock);
  20614. if (inputLevelMeasurementEnabledCount > 0)
  20615. {
  20616. for (int j = 0; j < numSamples; ++j)
  20617. {
  20618. float s = 0;
  20619. for (int i = 0; i < numInputChannels; ++i)
  20620. s += std::abs (inputChannelData[i][j]);
  20621. s /= numInputChannels;
  20622. const double decayFactor = 0.99992;
  20623. if (s > inputLevel)
  20624. inputLevel = s;
  20625. else if (inputLevel > 0.001f)
  20626. inputLevel *= decayFactor;
  20627. else
  20628. inputLevel = 0;
  20629. }
  20630. }
  20631. if (callbacks.size() > 0)
  20632. {
  20633. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20634. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20635. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20636. outputChannelData, numOutputChannels, numSamples);
  20637. float** const tempChans = tempBuffer.getArrayOfChannels();
  20638. for (int i = callbacks.size(); --i > 0;)
  20639. {
  20640. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20641. tempChans, numOutputChannels, numSamples);
  20642. for (int chan = 0; chan < numOutputChannels; ++chan)
  20643. {
  20644. const float* const src = tempChans [chan];
  20645. float* const dst = outputChannelData [chan];
  20646. if (src != 0 && dst != 0)
  20647. for (int j = 0; j < numSamples; ++j)
  20648. dst[j] += src[j];
  20649. }
  20650. }
  20651. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20652. const double filterAmount = 0.2;
  20653. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20654. }
  20655. else
  20656. {
  20657. for (int i = 0; i < numOutputChannels; ++i)
  20658. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20659. }
  20660. if (testSound != 0)
  20661. {
  20662. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20663. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20664. for (int i = 0; i < numOutputChannels; ++i)
  20665. for (int j = 0; j < numSamps; ++j)
  20666. outputChannelData [i][j] += src[j];
  20667. testSoundPosition += numSamps;
  20668. if (testSoundPosition >= testSound->getNumSamples())
  20669. testSound = 0;
  20670. }
  20671. }
  20672. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20673. {
  20674. cpuUsageMs = 0;
  20675. const double sampleRate = device->getCurrentSampleRate();
  20676. const int blockSize = device->getCurrentBufferSizeSamples();
  20677. if (sampleRate > 0.0 && blockSize > 0)
  20678. {
  20679. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20680. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20681. }
  20682. {
  20683. const ScopedLock sl (audioCallbackLock);
  20684. for (int i = callbacks.size(); --i >= 0;)
  20685. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20686. }
  20687. sendChangeMessage();
  20688. }
  20689. void AudioDeviceManager::audioDeviceStoppedInt()
  20690. {
  20691. cpuUsageMs = 0;
  20692. timeToCpuScale = 0;
  20693. sendChangeMessage();
  20694. const ScopedLock sl (audioCallbackLock);
  20695. for (int i = callbacks.size(); --i >= 0;)
  20696. callbacks.getUnchecked(i)->audioDeviceStopped();
  20697. }
  20698. double AudioDeviceManager::getCpuUsage() const
  20699. {
  20700. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20701. }
  20702. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20703. const bool enabled)
  20704. {
  20705. if (enabled != isMidiInputEnabled (name))
  20706. {
  20707. if (enabled)
  20708. {
  20709. const int index = MidiInput::getDevices().indexOf (name);
  20710. if (index >= 0)
  20711. {
  20712. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20713. if (min != 0)
  20714. {
  20715. enabledMidiInputs.add (min);
  20716. min->start();
  20717. }
  20718. }
  20719. }
  20720. else
  20721. {
  20722. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20723. if (enabledMidiInputs[i]->getName() == name)
  20724. enabledMidiInputs.remove (i);
  20725. }
  20726. updateXml();
  20727. sendChangeMessage();
  20728. }
  20729. }
  20730. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20731. {
  20732. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20733. if (enabledMidiInputs[i]->getName() == name)
  20734. return true;
  20735. return false;
  20736. }
  20737. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20738. MidiInputCallback* callbackToAdd)
  20739. {
  20740. removeMidiInputCallback (name, callbackToAdd);
  20741. if (name.isEmpty())
  20742. {
  20743. midiCallbacks.add (callbackToAdd);
  20744. midiCallbackDevices.add (0);
  20745. }
  20746. else
  20747. {
  20748. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20749. {
  20750. if (enabledMidiInputs[i]->getName() == name)
  20751. {
  20752. const ScopedLock sl (midiCallbackLock);
  20753. midiCallbacks.add (callbackToAdd);
  20754. midiCallbackDevices.add (enabledMidiInputs[i]);
  20755. break;
  20756. }
  20757. }
  20758. }
  20759. }
  20760. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* /*callback*/)
  20761. {
  20762. const ScopedLock sl (midiCallbackLock);
  20763. for (int i = midiCallbacks.size(); --i >= 0;)
  20764. {
  20765. String devName;
  20766. if (midiCallbackDevices.getUnchecked(i) != 0)
  20767. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20768. if (devName == name)
  20769. {
  20770. midiCallbacks.remove (i);
  20771. midiCallbackDevices.remove (i);
  20772. }
  20773. }
  20774. }
  20775. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20776. const MidiMessage& message)
  20777. {
  20778. if (! message.isActiveSense())
  20779. {
  20780. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20781. const ScopedLock sl (midiCallbackLock);
  20782. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20783. {
  20784. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20785. if (md == source || (md == 0 && isDefaultSource))
  20786. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20787. }
  20788. }
  20789. }
  20790. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20791. {
  20792. if (defaultMidiOutputName != deviceName)
  20793. {
  20794. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20795. {
  20796. const ScopedLock sl (audioCallbackLock);
  20797. oldCallbacks = callbacks;
  20798. callbacks.clear();
  20799. }
  20800. if (currentAudioDevice != 0)
  20801. for (int i = oldCallbacks.size(); --i >= 0;)
  20802. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20803. defaultMidiOutput = 0;
  20804. defaultMidiOutputName = deviceName;
  20805. if (deviceName.isNotEmpty())
  20806. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20807. if (currentAudioDevice != 0)
  20808. for (int i = oldCallbacks.size(); --i >= 0;)
  20809. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20810. {
  20811. const ScopedLock sl (audioCallbackLock);
  20812. callbacks = oldCallbacks;
  20813. }
  20814. updateXml();
  20815. sendChangeMessage();
  20816. }
  20817. }
  20818. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20819. int numInputChannels,
  20820. float** outputChannelData,
  20821. int numOutputChannels,
  20822. int numSamples)
  20823. {
  20824. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20825. }
  20826. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20827. {
  20828. owner->audioDeviceAboutToStartInt (device);
  20829. }
  20830. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20831. {
  20832. owner->audioDeviceStoppedInt();
  20833. }
  20834. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20835. {
  20836. owner->handleIncomingMidiMessageInt (source, message);
  20837. }
  20838. void AudioDeviceManager::playTestSound()
  20839. {
  20840. { // cunningly nested to swap, unlock and delete in that order.
  20841. ScopedPointer <AudioSampleBuffer> oldSound;
  20842. {
  20843. const ScopedLock sl (audioCallbackLock);
  20844. oldSound = testSound;
  20845. }
  20846. }
  20847. testSoundPosition = 0;
  20848. if (currentAudioDevice != 0)
  20849. {
  20850. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20851. const int soundLength = (int) sampleRate;
  20852. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20853. float* samples = newSound->getSampleData (0);
  20854. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20855. const float amplitude = 0.5f;
  20856. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20857. for (int i = 0; i < soundLength; ++i)
  20858. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20859. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20860. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20861. const ScopedLock sl (audioCallbackLock);
  20862. testSound = newSound;
  20863. }
  20864. }
  20865. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20866. {
  20867. const ScopedLock sl (audioCallbackLock);
  20868. if (enableMeasurement)
  20869. ++inputLevelMeasurementEnabledCount;
  20870. else
  20871. --inputLevelMeasurementEnabledCount;
  20872. inputLevel = 0;
  20873. }
  20874. double AudioDeviceManager::getCurrentInputLevel() const
  20875. {
  20876. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20877. return inputLevel;
  20878. }
  20879. END_JUCE_NAMESPACE
  20880. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20881. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20882. BEGIN_JUCE_NAMESPACE
  20883. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20884. : name (deviceName),
  20885. typeName (typeName_)
  20886. {
  20887. }
  20888. AudioIODevice::~AudioIODevice()
  20889. {
  20890. }
  20891. bool AudioIODevice::hasControlPanel() const
  20892. {
  20893. return false;
  20894. }
  20895. bool AudioIODevice::showControlPanel()
  20896. {
  20897. jassertfalse; // this should only be called for devices which return true from
  20898. // their hasControlPanel() method.
  20899. return false;
  20900. }
  20901. END_JUCE_NAMESPACE
  20902. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20903. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20904. BEGIN_JUCE_NAMESPACE
  20905. AudioIODeviceType::AudioIODeviceType (const String& name)
  20906. : typeName (name)
  20907. {
  20908. }
  20909. AudioIODeviceType::~AudioIODeviceType()
  20910. {
  20911. }
  20912. END_JUCE_NAMESPACE
  20913. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20914. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20915. BEGIN_JUCE_NAMESPACE
  20916. MidiOutput::MidiOutput()
  20917. : Thread ("midi out"),
  20918. internal (0),
  20919. firstMessage (0)
  20920. {
  20921. }
  20922. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20923. const double sampleNumber)
  20924. : message (data, len, sampleNumber)
  20925. {
  20926. }
  20927. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20928. const double millisecondCounterToStartAt,
  20929. double samplesPerSecondForBuffer)
  20930. {
  20931. // You've got to call startBackgroundThread() for this to actually work..
  20932. jassert (isThreadRunning());
  20933. // this needs to be a value in the future - RTFM for this method!
  20934. jassert (millisecondCounterToStartAt > 0);
  20935. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20936. MidiBuffer::Iterator i (buffer);
  20937. const uint8* data;
  20938. int len, time;
  20939. while (i.getNextEvent (data, len, time))
  20940. {
  20941. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20942. PendingMessage* const m
  20943. = new PendingMessage (data, len, eventTime);
  20944. const ScopedLock sl (lock);
  20945. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20946. {
  20947. m->next = firstMessage;
  20948. firstMessage = m;
  20949. }
  20950. else
  20951. {
  20952. PendingMessage* mm = firstMessage;
  20953. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20954. mm = mm->next;
  20955. m->next = mm->next;
  20956. mm->next = m;
  20957. }
  20958. }
  20959. notify();
  20960. }
  20961. void MidiOutput::clearAllPendingMessages()
  20962. {
  20963. const ScopedLock sl (lock);
  20964. while (firstMessage != 0)
  20965. {
  20966. PendingMessage* const m = firstMessage;
  20967. firstMessage = firstMessage->next;
  20968. delete m;
  20969. }
  20970. }
  20971. void MidiOutput::startBackgroundThread()
  20972. {
  20973. startThread (9);
  20974. }
  20975. void MidiOutput::stopBackgroundThread()
  20976. {
  20977. stopThread (5000);
  20978. }
  20979. void MidiOutput::run()
  20980. {
  20981. while (! threadShouldExit())
  20982. {
  20983. uint32 now = Time::getMillisecondCounter();
  20984. uint32 eventTime = 0;
  20985. uint32 timeToWait = 500;
  20986. PendingMessage* message;
  20987. {
  20988. const ScopedLock sl (lock);
  20989. message = firstMessage;
  20990. if (message != 0)
  20991. {
  20992. eventTime = roundToInt (message->message.getTimeStamp());
  20993. if (eventTime > now + 20)
  20994. {
  20995. timeToWait = eventTime - (now + 20);
  20996. message = 0;
  20997. }
  20998. else
  20999. {
  21000. firstMessage = message->next;
  21001. }
  21002. }
  21003. }
  21004. if (message != 0)
  21005. {
  21006. if (eventTime > now)
  21007. {
  21008. Time::waitForMillisecondCounter (eventTime);
  21009. if (threadShouldExit())
  21010. break;
  21011. }
  21012. if (eventTime > now - 200)
  21013. sendMessageNow (message->message);
  21014. delete message;
  21015. }
  21016. else
  21017. {
  21018. jassert (timeToWait < 1000 * 30);
  21019. wait (timeToWait);
  21020. }
  21021. }
  21022. clearAllPendingMessages();
  21023. }
  21024. END_JUCE_NAMESPACE
  21025. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21026. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21027. BEGIN_JUCE_NAMESPACE
  21028. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21029. {
  21030. const double maxVal = (double) 0x7fff;
  21031. char* intData = static_cast <char*> (dest);
  21032. if (dest != (void*) source || destBytesPerSample <= 4)
  21033. {
  21034. for (int i = 0; i < numSamples; ++i)
  21035. {
  21036. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21037. intData += destBytesPerSample;
  21038. }
  21039. }
  21040. else
  21041. {
  21042. intData += destBytesPerSample * numSamples;
  21043. for (int i = numSamples; --i >= 0;)
  21044. {
  21045. intData -= destBytesPerSample;
  21046. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21047. }
  21048. }
  21049. }
  21050. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21051. {
  21052. const double maxVal = (double) 0x7fff;
  21053. char* intData = static_cast <char*> (dest);
  21054. if (dest != (void*) source || destBytesPerSample <= 4)
  21055. {
  21056. for (int i = 0; i < numSamples; ++i)
  21057. {
  21058. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21059. intData += destBytesPerSample;
  21060. }
  21061. }
  21062. else
  21063. {
  21064. intData += destBytesPerSample * numSamples;
  21065. for (int i = numSamples; --i >= 0;)
  21066. {
  21067. intData -= destBytesPerSample;
  21068. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21069. }
  21070. }
  21071. }
  21072. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21073. {
  21074. const double maxVal = (double) 0x7fffff;
  21075. char* intData = static_cast <char*> (dest);
  21076. if (dest != (void*) source || destBytesPerSample <= 4)
  21077. {
  21078. for (int i = 0; i < numSamples; ++i)
  21079. {
  21080. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21081. intData += destBytesPerSample;
  21082. }
  21083. }
  21084. else
  21085. {
  21086. intData += destBytesPerSample * numSamples;
  21087. for (int i = numSamples; --i >= 0;)
  21088. {
  21089. intData -= destBytesPerSample;
  21090. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21091. }
  21092. }
  21093. }
  21094. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21095. {
  21096. const double maxVal = (double) 0x7fffff;
  21097. char* intData = static_cast <char*> (dest);
  21098. if (dest != (void*) source || destBytesPerSample <= 4)
  21099. {
  21100. for (int i = 0; i < numSamples; ++i)
  21101. {
  21102. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21103. intData += destBytesPerSample;
  21104. }
  21105. }
  21106. else
  21107. {
  21108. intData += destBytesPerSample * numSamples;
  21109. for (int i = numSamples; --i >= 0;)
  21110. {
  21111. intData -= destBytesPerSample;
  21112. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21113. }
  21114. }
  21115. }
  21116. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21117. {
  21118. const double maxVal = (double) 0x7fffffff;
  21119. char* intData = static_cast <char*> (dest);
  21120. if (dest != (void*) source || destBytesPerSample <= 4)
  21121. {
  21122. for (int i = 0; i < numSamples; ++i)
  21123. {
  21124. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21125. intData += destBytesPerSample;
  21126. }
  21127. }
  21128. else
  21129. {
  21130. intData += destBytesPerSample * numSamples;
  21131. for (int i = numSamples; --i >= 0;)
  21132. {
  21133. intData -= destBytesPerSample;
  21134. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21135. }
  21136. }
  21137. }
  21138. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21139. {
  21140. const double maxVal = (double) 0x7fffffff;
  21141. char* intData = static_cast <char*> (dest);
  21142. if (dest != (void*) source || destBytesPerSample <= 4)
  21143. {
  21144. for (int i = 0; i < numSamples; ++i)
  21145. {
  21146. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21147. intData += destBytesPerSample;
  21148. }
  21149. }
  21150. else
  21151. {
  21152. intData += destBytesPerSample * numSamples;
  21153. for (int i = numSamples; --i >= 0;)
  21154. {
  21155. intData -= destBytesPerSample;
  21156. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21157. }
  21158. }
  21159. }
  21160. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21161. {
  21162. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21163. char* d = static_cast <char*> (dest);
  21164. for (int i = 0; i < numSamples; ++i)
  21165. {
  21166. *(float*) d = source[i];
  21167. #if JUCE_BIG_ENDIAN
  21168. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21169. #endif
  21170. d += destBytesPerSample;
  21171. }
  21172. }
  21173. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21174. {
  21175. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21176. char* d = static_cast <char*> (dest);
  21177. for (int i = 0; i < numSamples; ++i)
  21178. {
  21179. *(float*) d = source[i];
  21180. #if JUCE_LITTLE_ENDIAN
  21181. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21182. #endif
  21183. d += destBytesPerSample;
  21184. }
  21185. }
  21186. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21187. {
  21188. const float scale = 1.0f / 0x7fff;
  21189. const char* intData = static_cast <const char*> (source);
  21190. if (source != (void*) dest || srcBytesPerSample >= 4)
  21191. {
  21192. for (int i = 0; i < numSamples; ++i)
  21193. {
  21194. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21195. intData += srcBytesPerSample;
  21196. }
  21197. }
  21198. else
  21199. {
  21200. intData += srcBytesPerSample * numSamples;
  21201. for (int i = numSamples; --i >= 0;)
  21202. {
  21203. intData -= srcBytesPerSample;
  21204. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21205. }
  21206. }
  21207. }
  21208. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21209. {
  21210. const float scale = 1.0f / 0x7fff;
  21211. const char* intData = static_cast <const char*> (source);
  21212. if (source != (void*) dest || srcBytesPerSample >= 4)
  21213. {
  21214. for (int i = 0; i < numSamples; ++i)
  21215. {
  21216. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21217. intData += srcBytesPerSample;
  21218. }
  21219. }
  21220. else
  21221. {
  21222. intData += srcBytesPerSample * numSamples;
  21223. for (int i = numSamples; --i >= 0;)
  21224. {
  21225. intData -= srcBytesPerSample;
  21226. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21227. }
  21228. }
  21229. }
  21230. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21231. {
  21232. const float scale = 1.0f / 0x7fffff;
  21233. const char* intData = static_cast <const char*> (source);
  21234. if (source != (void*) dest || srcBytesPerSample >= 4)
  21235. {
  21236. for (int i = 0; i < numSamples; ++i)
  21237. {
  21238. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21239. intData += srcBytesPerSample;
  21240. }
  21241. }
  21242. else
  21243. {
  21244. intData += srcBytesPerSample * numSamples;
  21245. for (int i = numSamples; --i >= 0;)
  21246. {
  21247. intData -= srcBytesPerSample;
  21248. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21249. }
  21250. }
  21251. }
  21252. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21253. {
  21254. const float scale = 1.0f / 0x7fffff;
  21255. const char* intData = static_cast <const char*> (source);
  21256. if (source != (void*) dest || srcBytesPerSample >= 4)
  21257. {
  21258. for (int i = 0; i < numSamples; ++i)
  21259. {
  21260. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21261. intData += srcBytesPerSample;
  21262. }
  21263. }
  21264. else
  21265. {
  21266. intData += srcBytesPerSample * numSamples;
  21267. for (int i = numSamples; --i >= 0;)
  21268. {
  21269. intData -= srcBytesPerSample;
  21270. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21271. }
  21272. }
  21273. }
  21274. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21275. {
  21276. const float scale = 1.0f / 0x7fffffff;
  21277. const char* intData = static_cast <const char*> (source);
  21278. if (source != (void*) dest || srcBytesPerSample >= 4)
  21279. {
  21280. for (int i = 0; i < numSamples; ++i)
  21281. {
  21282. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21283. intData += srcBytesPerSample;
  21284. }
  21285. }
  21286. else
  21287. {
  21288. intData += srcBytesPerSample * numSamples;
  21289. for (int i = numSamples; --i >= 0;)
  21290. {
  21291. intData -= srcBytesPerSample;
  21292. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21293. }
  21294. }
  21295. }
  21296. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21297. {
  21298. const float scale = 1.0f / 0x7fffffff;
  21299. const char* intData = static_cast <const char*> (source);
  21300. if (source != (void*) dest || srcBytesPerSample >= 4)
  21301. {
  21302. for (int i = 0; i < numSamples; ++i)
  21303. {
  21304. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21305. intData += srcBytesPerSample;
  21306. }
  21307. }
  21308. else
  21309. {
  21310. intData += srcBytesPerSample * numSamples;
  21311. for (int i = numSamples; --i >= 0;)
  21312. {
  21313. intData -= srcBytesPerSample;
  21314. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21315. }
  21316. }
  21317. }
  21318. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21319. {
  21320. const char* s = static_cast <const char*> (source);
  21321. for (int i = 0; i < numSamples; ++i)
  21322. {
  21323. dest[i] = *(float*)s;
  21324. #if JUCE_BIG_ENDIAN
  21325. uint32* const d = (uint32*) (dest + i);
  21326. *d = ByteOrder::swap (*d);
  21327. #endif
  21328. s += srcBytesPerSample;
  21329. }
  21330. }
  21331. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21332. {
  21333. const char* s = static_cast <const char*> (source);
  21334. for (int i = 0; i < numSamples; ++i)
  21335. {
  21336. dest[i] = *(float*)s;
  21337. #if JUCE_LITTLE_ENDIAN
  21338. uint32* const d = (uint32*) (dest + i);
  21339. *d = ByteOrder::swap (*d);
  21340. #endif
  21341. s += srcBytesPerSample;
  21342. }
  21343. }
  21344. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21345. const float* const source,
  21346. void* const dest,
  21347. const int numSamples)
  21348. {
  21349. switch (destFormat)
  21350. {
  21351. case int16LE:
  21352. convertFloatToInt16LE (source, dest, numSamples);
  21353. break;
  21354. case int16BE:
  21355. convertFloatToInt16BE (source, dest, numSamples);
  21356. break;
  21357. case int24LE:
  21358. convertFloatToInt24LE (source, dest, numSamples);
  21359. break;
  21360. case int24BE:
  21361. convertFloatToInt24BE (source, dest, numSamples);
  21362. break;
  21363. case int32LE:
  21364. convertFloatToInt32LE (source, dest, numSamples);
  21365. break;
  21366. case int32BE:
  21367. convertFloatToInt32BE (source, dest, numSamples);
  21368. break;
  21369. case float32LE:
  21370. convertFloatToFloat32LE (source, dest, numSamples);
  21371. break;
  21372. case float32BE:
  21373. convertFloatToFloat32BE (source, dest, numSamples);
  21374. break;
  21375. default:
  21376. jassertfalse;
  21377. break;
  21378. }
  21379. }
  21380. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21381. const void* const source,
  21382. float* const dest,
  21383. const int numSamples)
  21384. {
  21385. switch (sourceFormat)
  21386. {
  21387. case int16LE:
  21388. convertInt16LEToFloat (source, dest, numSamples);
  21389. break;
  21390. case int16BE:
  21391. convertInt16BEToFloat (source, dest, numSamples);
  21392. break;
  21393. case int24LE:
  21394. convertInt24LEToFloat (source, dest, numSamples);
  21395. break;
  21396. case int24BE:
  21397. convertInt24BEToFloat (source, dest, numSamples);
  21398. break;
  21399. case int32LE:
  21400. convertInt32LEToFloat (source, dest, numSamples);
  21401. break;
  21402. case int32BE:
  21403. convertInt32BEToFloat (source, dest, numSamples);
  21404. break;
  21405. case float32LE:
  21406. convertFloat32LEToFloat (source, dest, numSamples);
  21407. break;
  21408. case float32BE:
  21409. convertFloat32BEToFloat (source, dest, numSamples);
  21410. break;
  21411. default:
  21412. jassertfalse;
  21413. break;
  21414. }
  21415. }
  21416. void AudioDataConverters::interleaveSamples (const float** const source,
  21417. float* const dest,
  21418. const int numSamples,
  21419. const int numChannels)
  21420. {
  21421. for (int chan = 0; chan < numChannels; ++chan)
  21422. {
  21423. int i = chan;
  21424. const float* src = source [chan];
  21425. for (int j = 0; j < numSamples; ++j)
  21426. {
  21427. dest [i] = src [j];
  21428. i += numChannels;
  21429. }
  21430. }
  21431. }
  21432. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21433. float** const dest,
  21434. const int numSamples,
  21435. const int numChannels)
  21436. {
  21437. for (int chan = 0; chan < numChannels; ++chan)
  21438. {
  21439. int i = chan;
  21440. float* dst = dest [chan];
  21441. for (int j = 0; j < numSamples; ++j)
  21442. {
  21443. dst [j] = source [i];
  21444. i += numChannels;
  21445. }
  21446. }
  21447. }
  21448. #if JUCE_UNIT_TESTS
  21449. class AudioConversionTests : public UnitTest
  21450. {
  21451. public:
  21452. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21453. template <class F1, class E1, class F2, class E2>
  21454. struct Test5
  21455. {
  21456. static void test (UnitTest& unitTest)
  21457. {
  21458. test (unitTest, false);
  21459. test (unitTest, true);
  21460. }
  21461. static void test (UnitTest& unitTest, bool inPlace)
  21462. {
  21463. const int numSamples = 2048;
  21464. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21465. {
  21466. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21467. bool clippingFailed = false;
  21468. for (int i = 0; i < numSamples / 2; ++i)
  21469. {
  21470. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21471. if (! d.isFloatingPoint())
  21472. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21473. ++d;
  21474. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21475. ++d;
  21476. }
  21477. unitTest.expect (! clippingFailed);
  21478. }
  21479. // convert data from the source to dest format..
  21480. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21481. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21482. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21483. // ..and back again..
  21484. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21485. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21486. if (! inPlace)
  21487. zerostruct (reversed);
  21488. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21489. {
  21490. int biggestDiff = 0;
  21491. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21492. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21493. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21494. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21495. for (int i = 0; i < numSamples; ++i)
  21496. {
  21497. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21498. ++d1;
  21499. ++d2;
  21500. }
  21501. unitTest.expect (biggestDiff <= errorMargin);
  21502. }
  21503. }
  21504. };
  21505. template <class F1, class E1, class FormatType>
  21506. struct Test3
  21507. {
  21508. static void test (UnitTest& unitTest)
  21509. {
  21510. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21511. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21512. }
  21513. };
  21514. template <class FormatType, class Endianness>
  21515. struct Test2
  21516. {
  21517. static void test (UnitTest& unitTest)
  21518. {
  21519. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21520. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21521. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21522. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21523. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21524. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21525. }
  21526. };
  21527. template <class FormatType>
  21528. struct Test1
  21529. {
  21530. static void test (UnitTest& unitTest)
  21531. {
  21532. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21533. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21534. }
  21535. };
  21536. void runTest()
  21537. {
  21538. beginTest ("Round-trip conversion");
  21539. Test1 <AudioData::Int8>::test (*this);
  21540. Test1 <AudioData::Int16>::test (*this);
  21541. Test1 <AudioData::Int24>::test (*this);
  21542. Test1 <AudioData::Int32>::test (*this);
  21543. Test1 <AudioData::Float32>::test (*this);
  21544. }
  21545. };
  21546. static AudioConversionTests audioConversionUnitTests;
  21547. #endif
  21548. END_JUCE_NAMESPACE
  21549. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21550. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21551. BEGIN_JUCE_NAMESPACE
  21552. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21553. const int numSamples) throw()
  21554. : numChannels (numChannels_),
  21555. size (numSamples)
  21556. {
  21557. jassert (numSamples >= 0);
  21558. jassert (numChannels_ > 0);
  21559. allocateData();
  21560. }
  21561. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21562. : numChannels (other.numChannels),
  21563. size (other.size)
  21564. {
  21565. allocateData();
  21566. const size_t numBytes = size * sizeof (float);
  21567. for (int i = 0; i < numChannels; ++i)
  21568. memcpy (channels[i], other.channels[i], numBytes);
  21569. }
  21570. void AudioSampleBuffer::allocateData()
  21571. {
  21572. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21573. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21574. allocatedData.malloc (allocatedBytes);
  21575. channels = reinterpret_cast <float**> (allocatedData.getData());
  21576. float* chan = (float*) (allocatedData + channelListSize);
  21577. for (int i = 0; i < numChannels; ++i)
  21578. {
  21579. channels[i] = chan;
  21580. chan += size;
  21581. }
  21582. channels [numChannels] = 0;
  21583. }
  21584. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21585. const int numChannels_,
  21586. const int numSamples) throw()
  21587. : numChannels (numChannels_),
  21588. size (numSamples),
  21589. allocatedBytes (0)
  21590. {
  21591. jassert (numChannels_ > 0);
  21592. allocateChannels (dataToReferTo);
  21593. }
  21594. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21595. const int newNumChannels,
  21596. const int newNumSamples) throw()
  21597. {
  21598. jassert (newNumChannels > 0);
  21599. allocatedBytes = 0;
  21600. allocatedData.free();
  21601. numChannels = newNumChannels;
  21602. size = newNumSamples;
  21603. allocateChannels (dataToReferTo);
  21604. }
  21605. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21606. {
  21607. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21608. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21609. {
  21610. channels = static_cast <float**> (preallocatedChannelSpace);
  21611. }
  21612. else
  21613. {
  21614. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21615. channels = reinterpret_cast <float**> (allocatedData.getData());
  21616. }
  21617. for (int i = 0; i < numChannels; ++i)
  21618. {
  21619. // you have to pass in the same number of valid pointers as numChannels
  21620. jassert (dataToReferTo[i] != 0);
  21621. channels[i] = dataToReferTo[i];
  21622. }
  21623. channels [numChannels] = 0;
  21624. }
  21625. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21626. {
  21627. if (this != &other)
  21628. {
  21629. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21630. const size_t numBytes = size * sizeof (float);
  21631. for (int i = 0; i < numChannels; ++i)
  21632. memcpy (channels[i], other.channels[i], numBytes);
  21633. }
  21634. return *this;
  21635. }
  21636. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21637. {
  21638. }
  21639. void AudioSampleBuffer::setSize (const int newNumChannels,
  21640. const int newNumSamples,
  21641. const bool keepExistingContent,
  21642. const bool clearExtraSpace,
  21643. const bool avoidReallocating) throw()
  21644. {
  21645. jassert (newNumChannels > 0);
  21646. if (newNumSamples != size || newNumChannels != numChannels)
  21647. {
  21648. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21649. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21650. if (keepExistingContent)
  21651. {
  21652. HeapBlock <char> newData;
  21653. newData.allocate (newTotalBytes, clearExtraSpace);
  21654. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21655. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21656. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21657. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21658. for (int i = 0; i < numChansToCopy; ++i)
  21659. {
  21660. memcpy (newChan, channels[i], numBytesToCopy);
  21661. newChannels[i] = newChan;
  21662. newChan += newNumSamples;
  21663. }
  21664. allocatedData.swapWith (newData);
  21665. allocatedBytes = (int) newTotalBytes;
  21666. channels = newChannels;
  21667. }
  21668. else
  21669. {
  21670. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21671. {
  21672. if (clearExtraSpace)
  21673. zeromem (allocatedData, newTotalBytes);
  21674. }
  21675. else
  21676. {
  21677. allocatedBytes = newTotalBytes;
  21678. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21679. channels = reinterpret_cast <float**> (allocatedData.getData());
  21680. }
  21681. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21682. for (int i = 0; i < newNumChannels; ++i)
  21683. {
  21684. channels[i] = chan;
  21685. chan += newNumSamples;
  21686. }
  21687. }
  21688. channels [newNumChannels] = 0;
  21689. size = newNumSamples;
  21690. numChannels = newNumChannels;
  21691. }
  21692. }
  21693. void AudioSampleBuffer::clear() throw()
  21694. {
  21695. for (int i = 0; i < numChannels; ++i)
  21696. zeromem (channels[i], size * sizeof (float));
  21697. }
  21698. void AudioSampleBuffer::clear (const int startSample,
  21699. const int numSamples) throw()
  21700. {
  21701. jassert (startSample >= 0 && startSample + numSamples <= size);
  21702. for (int i = 0; i < numChannels; ++i)
  21703. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21704. }
  21705. void AudioSampleBuffer::clear (const int channel,
  21706. const int startSample,
  21707. const int numSamples) throw()
  21708. {
  21709. jassert (isPositiveAndBelow (channel, numChannels));
  21710. jassert (startSample >= 0 && startSample + numSamples <= size);
  21711. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21712. }
  21713. void AudioSampleBuffer::applyGain (const int channel,
  21714. const int startSample,
  21715. int numSamples,
  21716. const float gain) throw()
  21717. {
  21718. jassert (isPositiveAndBelow (channel, numChannels));
  21719. jassert (startSample >= 0 && startSample + numSamples <= size);
  21720. if (gain != 1.0f)
  21721. {
  21722. float* d = channels [channel] + startSample;
  21723. if (gain == 0.0f)
  21724. {
  21725. zeromem (d, sizeof (float) * numSamples);
  21726. }
  21727. else
  21728. {
  21729. while (--numSamples >= 0)
  21730. *d++ *= gain;
  21731. }
  21732. }
  21733. }
  21734. void AudioSampleBuffer::applyGainRamp (const int channel,
  21735. const int startSample,
  21736. int numSamples,
  21737. float startGain,
  21738. float endGain) throw()
  21739. {
  21740. if (startGain == endGain)
  21741. {
  21742. applyGain (channel, startSample, numSamples, startGain);
  21743. }
  21744. else
  21745. {
  21746. jassert (isPositiveAndBelow (channel, numChannels));
  21747. jassert (startSample >= 0 && startSample + numSamples <= size);
  21748. const float increment = (endGain - startGain) / numSamples;
  21749. float* d = channels [channel] + startSample;
  21750. while (--numSamples >= 0)
  21751. {
  21752. *d++ *= startGain;
  21753. startGain += increment;
  21754. }
  21755. }
  21756. }
  21757. void AudioSampleBuffer::applyGain (const int startSample,
  21758. const int numSamples,
  21759. const float gain) throw()
  21760. {
  21761. for (int i = 0; i < numChannels; ++i)
  21762. applyGain (i, startSample, numSamples, gain);
  21763. }
  21764. void AudioSampleBuffer::addFrom (const int destChannel,
  21765. const int destStartSample,
  21766. const AudioSampleBuffer& source,
  21767. const int sourceChannel,
  21768. const int sourceStartSample,
  21769. int numSamples,
  21770. const float gain) throw()
  21771. {
  21772. jassert (&source != this || sourceChannel != destChannel);
  21773. jassert (isPositiveAndBelow (destChannel, numChannels));
  21774. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21775. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21776. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21777. if (gain != 0.0f && numSamples > 0)
  21778. {
  21779. float* d = channels [destChannel] + destStartSample;
  21780. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21781. if (gain != 1.0f)
  21782. {
  21783. while (--numSamples >= 0)
  21784. *d++ += gain * *s++;
  21785. }
  21786. else
  21787. {
  21788. while (--numSamples >= 0)
  21789. *d++ += *s++;
  21790. }
  21791. }
  21792. }
  21793. void AudioSampleBuffer::addFrom (const int destChannel,
  21794. const int destStartSample,
  21795. const float* source,
  21796. int numSamples,
  21797. const float gain) throw()
  21798. {
  21799. jassert (isPositiveAndBelow (destChannel, numChannels));
  21800. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21801. jassert (source != 0);
  21802. if (gain != 0.0f && numSamples > 0)
  21803. {
  21804. float* d = channels [destChannel] + destStartSample;
  21805. if (gain != 1.0f)
  21806. {
  21807. while (--numSamples >= 0)
  21808. *d++ += gain * *source++;
  21809. }
  21810. else
  21811. {
  21812. while (--numSamples >= 0)
  21813. *d++ += *source++;
  21814. }
  21815. }
  21816. }
  21817. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21818. const int destStartSample,
  21819. const float* source,
  21820. int numSamples,
  21821. float startGain,
  21822. const float endGain) throw()
  21823. {
  21824. jassert (isPositiveAndBelow (destChannel, numChannels));
  21825. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21826. jassert (source != 0);
  21827. if (startGain == endGain)
  21828. {
  21829. addFrom (destChannel,
  21830. destStartSample,
  21831. source,
  21832. numSamples,
  21833. startGain);
  21834. }
  21835. else
  21836. {
  21837. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21838. {
  21839. const float increment = (endGain - startGain) / numSamples;
  21840. float* d = channels [destChannel] + destStartSample;
  21841. while (--numSamples >= 0)
  21842. {
  21843. *d++ += startGain * *source++;
  21844. startGain += increment;
  21845. }
  21846. }
  21847. }
  21848. }
  21849. void AudioSampleBuffer::copyFrom (const int destChannel,
  21850. const int destStartSample,
  21851. const AudioSampleBuffer& source,
  21852. const int sourceChannel,
  21853. const int sourceStartSample,
  21854. int numSamples) throw()
  21855. {
  21856. jassert (&source != this || sourceChannel != destChannel);
  21857. jassert (isPositiveAndBelow (destChannel, numChannels));
  21858. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21859. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21860. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21861. if (numSamples > 0)
  21862. {
  21863. memcpy (channels [destChannel] + destStartSample,
  21864. source.channels [sourceChannel] + sourceStartSample,
  21865. sizeof (float) * numSamples);
  21866. }
  21867. }
  21868. void AudioSampleBuffer::copyFrom (const int destChannel,
  21869. const int destStartSample,
  21870. const float* source,
  21871. int numSamples) throw()
  21872. {
  21873. jassert (isPositiveAndBelow (destChannel, numChannels));
  21874. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21875. jassert (source != 0);
  21876. if (numSamples > 0)
  21877. {
  21878. memcpy (channels [destChannel] + destStartSample,
  21879. source,
  21880. sizeof (float) * numSamples);
  21881. }
  21882. }
  21883. void AudioSampleBuffer::copyFrom (const int destChannel,
  21884. const int destStartSample,
  21885. const float* source,
  21886. int numSamples,
  21887. const float gain) throw()
  21888. {
  21889. jassert (isPositiveAndBelow (destChannel, numChannels));
  21890. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21891. jassert (source != 0);
  21892. if (numSamples > 0)
  21893. {
  21894. float* d = channels [destChannel] + destStartSample;
  21895. if (gain != 1.0f)
  21896. {
  21897. if (gain == 0)
  21898. {
  21899. zeromem (d, sizeof (float) * numSamples);
  21900. }
  21901. else
  21902. {
  21903. while (--numSamples >= 0)
  21904. *d++ = gain * *source++;
  21905. }
  21906. }
  21907. else
  21908. {
  21909. memcpy (d, source, sizeof (float) * numSamples);
  21910. }
  21911. }
  21912. }
  21913. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21914. const int destStartSample,
  21915. const float* source,
  21916. int numSamples,
  21917. float startGain,
  21918. float endGain) throw()
  21919. {
  21920. jassert (isPositiveAndBelow (destChannel, numChannels));
  21921. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21922. jassert (source != 0);
  21923. if (startGain == endGain)
  21924. {
  21925. copyFrom (destChannel,
  21926. destStartSample,
  21927. source,
  21928. numSamples,
  21929. startGain);
  21930. }
  21931. else
  21932. {
  21933. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21934. {
  21935. const float increment = (endGain - startGain) / numSamples;
  21936. float* d = channels [destChannel] + destStartSample;
  21937. while (--numSamples >= 0)
  21938. {
  21939. *d++ = startGain * *source++;
  21940. startGain += increment;
  21941. }
  21942. }
  21943. }
  21944. }
  21945. void AudioSampleBuffer::findMinMax (const int channel,
  21946. const int startSample,
  21947. int numSamples,
  21948. float& minVal,
  21949. float& maxVal) const throw()
  21950. {
  21951. jassert (isPositiveAndBelow (channel, numChannels));
  21952. jassert (startSample >= 0 && startSample + numSamples <= size);
  21953. findMinAndMax (channels [channel] + startSample, numSamples, minVal, maxVal);
  21954. }
  21955. float AudioSampleBuffer::getMagnitude (const int channel,
  21956. const int startSample,
  21957. const int numSamples) const throw()
  21958. {
  21959. jassert (isPositiveAndBelow (channel, numChannels));
  21960. jassert (startSample >= 0 && startSample + numSamples <= size);
  21961. float mn, mx;
  21962. findMinMax (channel, startSample, numSamples, mn, mx);
  21963. return jmax (mn, -mn, mx, -mx);
  21964. }
  21965. float AudioSampleBuffer::getMagnitude (const int startSample,
  21966. const int numSamples) const throw()
  21967. {
  21968. float mag = 0.0f;
  21969. for (int i = 0; i < numChannels; ++i)
  21970. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21971. return mag;
  21972. }
  21973. float AudioSampleBuffer::getRMSLevel (const int channel,
  21974. const int startSample,
  21975. const int numSamples) const throw()
  21976. {
  21977. jassert (isPositiveAndBelow (channel, numChannels));
  21978. jassert (startSample >= 0 && startSample + numSamples <= size);
  21979. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21980. return 0.0f;
  21981. const float* const data = channels [channel] + startSample;
  21982. double sum = 0.0;
  21983. for (int i = 0; i < numSamples; ++i)
  21984. {
  21985. const float sample = data [i];
  21986. sum += sample * sample;
  21987. }
  21988. return (float) std::sqrt (sum / numSamples);
  21989. }
  21990. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21991. const int startSample,
  21992. const int numSamples,
  21993. const int readerStartSample,
  21994. const bool useLeftChan,
  21995. const bool useRightChan)
  21996. {
  21997. jassert (reader != 0);
  21998. jassert (startSample >= 0 && startSample + numSamples <= size);
  21999. if (numSamples > 0)
  22000. {
  22001. int* chans[3];
  22002. if (useLeftChan == useRightChan)
  22003. {
  22004. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22005. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22006. }
  22007. else if (useLeftChan || (reader->numChannels == 1))
  22008. {
  22009. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22010. chans[1] = 0;
  22011. }
  22012. else if (useRightChan)
  22013. {
  22014. chans[0] = 0;
  22015. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22016. }
  22017. chans[2] = 0;
  22018. reader->read (chans, 2, readerStartSample, numSamples, true);
  22019. if (! reader->usesFloatingPointData)
  22020. {
  22021. for (int j = 0; j < 2; ++j)
  22022. {
  22023. float* const d = reinterpret_cast <float*> (chans[j]);
  22024. if (d != 0)
  22025. {
  22026. const float multiplier = 1.0f / 0x7fffffff;
  22027. for (int i = 0; i < numSamples; ++i)
  22028. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22029. }
  22030. }
  22031. }
  22032. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22033. {
  22034. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22035. memcpy (getSampleData (1, startSample),
  22036. getSampleData (0, startSample),
  22037. sizeof (float) * numSamples);
  22038. }
  22039. }
  22040. }
  22041. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22042. const int startSample,
  22043. const int numSamples) const
  22044. {
  22045. jassert (writer != 0);
  22046. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22047. }
  22048. END_JUCE_NAMESPACE
  22049. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22050. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22051. BEGIN_JUCE_NAMESPACE
  22052. IIRFilter::IIRFilter()
  22053. : active (false)
  22054. {
  22055. reset();
  22056. }
  22057. IIRFilter::IIRFilter (const IIRFilter& other)
  22058. : active (other.active)
  22059. {
  22060. const ScopedLock sl (other.processLock);
  22061. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22062. reset();
  22063. }
  22064. IIRFilter::~IIRFilter()
  22065. {
  22066. }
  22067. void IIRFilter::reset() throw()
  22068. {
  22069. const ScopedLock sl (processLock);
  22070. x1 = 0;
  22071. x2 = 0;
  22072. y1 = 0;
  22073. y2 = 0;
  22074. }
  22075. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22076. {
  22077. float out = coefficients[0] * in
  22078. + coefficients[1] * x1
  22079. + coefficients[2] * x2
  22080. - coefficients[4] * y1
  22081. - coefficients[5] * y2;
  22082. #if JUCE_INTEL
  22083. if (! (out < -1.0e-8 || out > 1.0e-8))
  22084. out = 0;
  22085. #endif
  22086. x2 = x1;
  22087. x1 = in;
  22088. y2 = y1;
  22089. y1 = out;
  22090. return out;
  22091. }
  22092. void IIRFilter::processSamples (float* const samples,
  22093. const int numSamples) throw()
  22094. {
  22095. const ScopedLock sl (processLock);
  22096. if (active)
  22097. {
  22098. for (int i = 0; i < numSamples; ++i)
  22099. {
  22100. const float in = samples[i];
  22101. float out = coefficients[0] * in
  22102. + coefficients[1] * x1
  22103. + coefficients[2] * x2
  22104. - coefficients[4] * y1
  22105. - coefficients[5] * y2;
  22106. #if JUCE_INTEL
  22107. if (! (out < -1.0e-8 || out > 1.0e-8))
  22108. out = 0;
  22109. #endif
  22110. x2 = x1;
  22111. x1 = in;
  22112. y2 = y1;
  22113. y1 = out;
  22114. samples[i] = out;
  22115. }
  22116. }
  22117. }
  22118. void IIRFilter::makeLowPass (const double sampleRate,
  22119. const double frequency) throw()
  22120. {
  22121. jassert (sampleRate > 0);
  22122. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22123. const double nSquared = n * n;
  22124. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22125. setCoefficients (c1,
  22126. c1 * 2.0f,
  22127. c1,
  22128. 1.0,
  22129. c1 * 2.0 * (1.0 - nSquared),
  22130. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22131. }
  22132. void IIRFilter::makeHighPass (const double sampleRate,
  22133. const double frequency) throw()
  22134. {
  22135. const double n = tan (double_Pi * frequency / sampleRate);
  22136. const double nSquared = n * n;
  22137. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22138. setCoefficients (c1,
  22139. c1 * -2.0f,
  22140. c1,
  22141. 1.0,
  22142. c1 * 2.0 * (nSquared - 1.0),
  22143. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22144. }
  22145. void IIRFilter::makeLowShelf (const double sampleRate,
  22146. const double cutOffFrequency,
  22147. const double Q,
  22148. const float gainFactor) throw()
  22149. {
  22150. jassert (sampleRate > 0);
  22151. jassert (Q > 0);
  22152. const double A = jmax (0.0f, gainFactor);
  22153. const double aminus1 = A - 1.0;
  22154. const double aplus1 = A + 1.0;
  22155. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22156. const double coso = std::cos (omega);
  22157. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22158. const double aminus1TimesCoso = aminus1 * coso;
  22159. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22160. A * 2.0 * (aminus1 - aplus1 * coso),
  22161. A * (aplus1 - aminus1TimesCoso - beta),
  22162. aplus1 + aminus1TimesCoso + beta,
  22163. -2.0 * (aminus1 + aplus1 * coso),
  22164. aplus1 + aminus1TimesCoso - beta);
  22165. }
  22166. void IIRFilter::makeHighShelf (const double sampleRate,
  22167. const double cutOffFrequency,
  22168. const double Q,
  22169. const float gainFactor) throw()
  22170. {
  22171. jassert (sampleRate > 0);
  22172. jassert (Q > 0);
  22173. const double A = jmax (0.0f, gainFactor);
  22174. const double aminus1 = A - 1.0;
  22175. const double aplus1 = A + 1.0;
  22176. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22177. const double coso = std::cos (omega);
  22178. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22179. const double aminus1TimesCoso = aminus1 * coso;
  22180. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22181. A * -2.0 * (aminus1 + aplus1 * coso),
  22182. A * (aplus1 + aminus1TimesCoso - beta),
  22183. aplus1 - aminus1TimesCoso + beta,
  22184. 2.0 * (aminus1 - aplus1 * coso),
  22185. aplus1 - aminus1TimesCoso - beta);
  22186. }
  22187. void IIRFilter::makeBandPass (const double sampleRate,
  22188. const double centreFrequency,
  22189. const double Q,
  22190. const float gainFactor) throw()
  22191. {
  22192. jassert (sampleRate > 0);
  22193. jassert (Q > 0);
  22194. const double A = jmax (0.0f, gainFactor);
  22195. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22196. const double alpha = 0.5 * std::sin (omega) / Q;
  22197. const double c2 = -2.0 * std::cos (omega);
  22198. const double alphaTimesA = alpha * A;
  22199. const double alphaOverA = alpha / A;
  22200. setCoefficients (1.0 + alphaTimesA,
  22201. c2,
  22202. 1.0 - alphaTimesA,
  22203. 1.0 + alphaOverA,
  22204. c2,
  22205. 1.0 - alphaOverA);
  22206. }
  22207. void IIRFilter::makeInactive() throw()
  22208. {
  22209. const ScopedLock sl (processLock);
  22210. active = false;
  22211. }
  22212. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22213. {
  22214. const ScopedLock sl (processLock);
  22215. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22216. active = other.active;
  22217. }
  22218. void IIRFilter::setCoefficients (double c1,
  22219. double c2,
  22220. double c3,
  22221. double c4,
  22222. double c5,
  22223. double c6) throw()
  22224. {
  22225. const double a = 1.0 / c4;
  22226. c1 *= a;
  22227. c2 *= a;
  22228. c3 *= a;
  22229. c5 *= a;
  22230. c6 *= a;
  22231. const ScopedLock sl (processLock);
  22232. coefficients[0] = (float) c1;
  22233. coefficients[1] = (float) c2;
  22234. coefficients[2] = (float) c3;
  22235. coefficients[3] = (float) c4;
  22236. coefficients[4] = (float) c5;
  22237. coefficients[5] = (float) c6;
  22238. active = true;
  22239. }
  22240. END_JUCE_NAMESPACE
  22241. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22242. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22243. BEGIN_JUCE_NAMESPACE
  22244. MidiBuffer::MidiBuffer() throw()
  22245. : bytesUsed (0)
  22246. {
  22247. }
  22248. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22249. : bytesUsed (0)
  22250. {
  22251. addEvent (message, 0);
  22252. }
  22253. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22254. : data (other.data),
  22255. bytesUsed (other.bytesUsed)
  22256. {
  22257. }
  22258. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22259. {
  22260. bytesUsed = other.bytesUsed;
  22261. data = other.data;
  22262. return *this;
  22263. }
  22264. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22265. {
  22266. data.swapWith (other.data);
  22267. swapVariables <int> (bytesUsed, other.bytesUsed);
  22268. }
  22269. MidiBuffer::~MidiBuffer()
  22270. {
  22271. }
  22272. inline uint8* MidiBuffer::getData() const throw()
  22273. {
  22274. return static_cast <uint8*> (data.getData());
  22275. }
  22276. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22277. {
  22278. return *static_cast <const int*> (d);
  22279. }
  22280. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22281. {
  22282. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22283. }
  22284. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22285. {
  22286. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22287. }
  22288. void MidiBuffer::clear() throw()
  22289. {
  22290. bytesUsed = 0;
  22291. }
  22292. void MidiBuffer::clear (const int startSample, const int numSamples)
  22293. {
  22294. uint8* const start = findEventAfter (getData(), startSample - 1);
  22295. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22296. if (end > start)
  22297. {
  22298. const int bytesToMove = bytesUsed - (int) (end - getData());
  22299. if (bytesToMove > 0)
  22300. memmove (start, end, bytesToMove);
  22301. bytesUsed -= (int) (end - start);
  22302. }
  22303. }
  22304. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22305. {
  22306. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22307. }
  22308. namespace MidiBufferHelpers
  22309. {
  22310. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22311. {
  22312. unsigned int byte = (unsigned int) *data;
  22313. int size = 0;
  22314. if (byte == 0xf0 || byte == 0xf7)
  22315. {
  22316. const uint8* d = data + 1;
  22317. while (d < data + maxBytes)
  22318. if (*d++ == 0xf7)
  22319. break;
  22320. size = (int) (d - data);
  22321. }
  22322. else if (byte == 0xff)
  22323. {
  22324. int n;
  22325. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22326. size = jmin (maxBytes, n + 2 + bytesLeft);
  22327. }
  22328. else if (byte >= 0x80)
  22329. {
  22330. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22331. }
  22332. return size;
  22333. }
  22334. }
  22335. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22336. {
  22337. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22338. if (numBytes > 0)
  22339. {
  22340. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22341. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22342. uint8* d = findEventAfter (getData(), sampleNumber);
  22343. const int bytesToMove = bytesUsed - (int) (d - getData());
  22344. if (bytesToMove > 0)
  22345. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22346. *reinterpret_cast <int*> (d) = sampleNumber;
  22347. d += sizeof (int);
  22348. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22349. d += sizeof (uint16);
  22350. memcpy (d, newData, numBytes);
  22351. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22352. }
  22353. }
  22354. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22355. const int startSample,
  22356. const int numSamples,
  22357. const int sampleDeltaToAdd)
  22358. {
  22359. Iterator i (otherBuffer);
  22360. i.setNextSamplePosition (startSample);
  22361. const uint8* eventData;
  22362. int eventSize, position;
  22363. while (i.getNextEvent (eventData, eventSize, position)
  22364. && (position < startSample + numSamples || numSamples < 0))
  22365. {
  22366. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22367. }
  22368. }
  22369. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22370. {
  22371. data.ensureSize (minimumNumBytes);
  22372. }
  22373. bool MidiBuffer::isEmpty() const throw()
  22374. {
  22375. return bytesUsed == 0;
  22376. }
  22377. int MidiBuffer::getNumEvents() const throw()
  22378. {
  22379. int n = 0;
  22380. const uint8* d = getData();
  22381. const uint8* const end = d + bytesUsed;
  22382. while (d < end)
  22383. {
  22384. d += getEventTotalSize (d);
  22385. ++n;
  22386. }
  22387. return n;
  22388. }
  22389. int MidiBuffer::getFirstEventTime() const throw()
  22390. {
  22391. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22392. }
  22393. int MidiBuffer::getLastEventTime() const throw()
  22394. {
  22395. if (bytesUsed == 0)
  22396. return 0;
  22397. const uint8* d = getData();
  22398. const uint8* const endData = d + bytesUsed;
  22399. for (;;)
  22400. {
  22401. const uint8* const nextOne = d + getEventTotalSize (d);
  22402. if (nextOne >= endData)
  22403. return getEventTime (d);
  22404. d = nextOne;
  22405. }
  22406. }
  22407. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22408. {
  22409. const uint8* const endData = getData() + bytesUsed;
  22410. while (d < endData && getEventTime (d) <= samplePosition)
  22411. d += getEventTotalSize (d);
  22412. return d;
  22413. }
  22414. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22415. : buffer (buffer_),
  22416. data (buffer_.getData())
  22417. {
  22418. }
  22419. MidiBuffer::Iterator::~Iterator() throw()
  22420. {
  22421. }
  22422. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22423. {
  22424. data = buffer.getData();
  22425. const uint8* dataEnd = data + buffer.bytesUsed;
  22426. while (data < dataEnd && getEventTime (data) < samplePosition)
  22427. data += getEventTotalSize (data);
  22428. }
  22429. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22430. {
  22431. if (data >= buffer.getData() + buffer.bytesUsed)
  22432. return false;
  22433. samplePosition = getEventTime (data);
  22434. numBytes = getEventDataSize (data);
  22435. data += sizeof (int) + sizeof (uint16);
  22436. midiData = data;
  22437. data += numBytes;
  22438. return true;
  22439. }
  22440. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22441. {
  22442. if (data >= buffer.getData() + buffer.bytesUsed)
  22443. return false;
  22444. samplePosition = getEventTime (data);
  22445. const int numBytes = getEventDataSize (data);
  22446. data += sizeof (int) + sizeof (uint16);
  22447. result = MidiMessage (data, numBytes, samplePosition);
  22448. data += numBytes;
  22449. return true;
  22450. }
  22451. END_JUCE_NAMESPACE
  22452. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22453. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22454. BEGIN_JUCE_NAMESPACE
  22455. namespace MidiFileHelpers
  22456. {
  22457. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22458. {
  22459. unsigned int buffer = v & 0x7F;
  22460. while ((v >>= 7) != 0)
  22461. {
  22462. buffer <<= 8;
  22463. buffer |= ((v & 0x7F) | 0x80);
  22464. }
  22465. for (;;)
  22466. {
  22467. out.writeByte ((char) buffer);
  22468. if (buffer & 0x80)
  22469. buffer >>= 8;
  22470. else
  22471. break;
  22472. }
  22473. }
  22474. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22475. {
  22476. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22477. data += 4;
  22478. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22479. {
  22480. bool ok = false;
  22481. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22482. {
  22483. for (int i = 0; i < 8; ++i)
  22484. {
  22485. ch = ByteOrder::bigEndianInt (data);
  22486. data += 4;
  22487. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22488. {
  22489. ok = true;
  22490. break;
  22491. }
  22492. }
  22493. }
  22494. if (! ok)
  22495. return false;
  22496. }
  22497. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22498. data += 4;
  22499. fileType = (short) ByteOrder::bigEndianShort (data);
  22500. data += 2;
  22501. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22502. data += 2;
  22503. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22504. data += 2;
  22505. bytesRemaining -= 6;
  22506. data += bytesRemaining;
  22507. return true;
  22508. }
  22509. double convertTicksToSeconds (const double time,
  22510. const MidiMessageSequence& tempoEvents,
  22511. const int timeFormat)
  22512. {
  22513. if (timeFormat > 0)
  22514. {
  22515. int numer = 4, denom = 4;
  22516. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22517. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22518. double secsPerTick = 0.5 * tickLen;
  22519. const int numEvents = tempoEvents.getNumEvents();
  22520. for (int i = 0; i < numEvents; ++i)
  22521. {
  22522. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22523. if (time <= m.getTimeStamp())
  22524. break;
  22525. if (timeFormat > 0)
  22526. {
  22527. correctedTempoTime = correctedTempoTime
  22528. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22529. }
  22530. else
  22531. {
  22532. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22533. }
  22534. tempoTime = m.getTimeStamp();
  22535. if (m.isTempoMetaEvent())
  22536. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22537. else if (m.isTimeSignatureMetaEvent())
  22538. m.getTimeSignatureInfo (numer, denom);
  22539. while (i + 1 < numEvents)
  22540. {
  22541. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22542. if (m2.getTimeStamp() == tempoTime)
  22543. {
  22544. ++i;
  22545. if (m2.isTempoMetaEvent())
  22546. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22547. else if (m2.isTimeSignatureMetaEvent())
  22548. m2.getTimeSignatureInfo (numer, denom);
  22549. }
  22550. else
  22551. {
  22552. break;
  22553. }
  22554. }
  22555. }
  22556. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22557. }
  22558. else
  22559. {
  22560. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22561. }
  22562. }
  22563. // a comparator that puts all the note-offs before note-ons that have the same time
  22564. struct Sorter
  22565. {
  22566. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22567. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22568. {
  22569. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22570. if (diff == 0)
  22571. {
  22572. if (first->message.isNoteOff() && second->message.isNoteOn())
  22573. return -1;
  22574. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22575. return 1;
  22576. else
  22577. return 0;
  22578. }
  22579. else
  22580. {
  22581. return (diff > 0) ? 1 : -1;
  22582. }
  22583. }
  22584. };
  22585. }
  22586. MidiFile::MidiFile()
  22587. : timeFormat ((short) (unsigned short) 0xe728)
  22588. {
  22589. }
  22590. MidiFile::~MidiFile()
  22591. {
  22592. clear();
  22593. }
  22594. void MidiFile::clear()
  22595. {
  22596. tracks.clear();
  22597. }
  22598. int MidiFile::getNumTracks() const throw()
  22599. {
  22600. return tracks.size();
  22601. }
  22602. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22603. {
  22604. return tracks [index];
  22605. }
  22606. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22607. {
  22608. tracks.add (new MidiMessageSequence (trackSequence));
  22609. }
  22610. short MidiFile::getTimeFormat() const throw()
  22611. {
  22612. return timeFormat;
  22613. }
  22614. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22615. {
  22616. timeFormat = (short) ticks;
  22617. }
  22618. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22619. const int subframeResolution) throw()
  22620. {
  22621. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22622. }
  22623. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22624. {
  22625. for (int i = tracks.size(); --i >= 0;)
  22626. {
  22627. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22628. for (int j = 0; j < numEvents; ++j)
  22629. {
  22630. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22631. if (m.isTempoMetaEvent())
  22632. tempoChangeEvents.addEvent (m);
  22633. }
  22634. }
  22635. }
  22636. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22637. {
  22638. for (int i = tracks.size(); --i >= 0;)
  22639. {
  22640. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22641. for (int j = 0; j < numEvents; ++j)
  22642. {
  22643. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22644. if (m.isTimeSignatureMetaEvent())
  22645. timeSigEvents.addEvent (m);
  22646. }
  22647. }
  22648. }
  22649. double MidiFile::getLastTimestamp() const
  22650. {
  22651. double t = 0.0;
  22652. for (int i = tracks.size(); --i >= 0;)
  22653. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22654. return t;
  22655. }
  22656. bool MidiFile::readFrom (InputStream& sourceStream)
  22657. {
  22658. clear();
  22659. MemoryBlock data;
  22660. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22661. // (put a sanity-check on the file size, as midi files are generally small)
  22662. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22663. {
  22664. size_t size = data.getSize();
  22665. const uint8* d = static_cast <const uint8*> (data.getData());
  22666. short fileType, expectedTracks;
  22667. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22668. {
  22669. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22670. int track = 0;
  22671. while (size > 0 && track < expectedTracks)
  22672. {
  22673. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22674. d += 4;
  22675. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22676. d += 4;
  22677. if (chunkSize <= 0)
  22678. break;
  22679. if (size < 0)
  22680. return false;
  22681. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22682. {
  22683. readNextTrack (d, chunkSize);
  22684. }
  22685. size -= chunkSize + 8;
  22686. d += chunkSize;
  22687. ++track;
  22688. }
  22689. return true;
  22690. }
  22691. }
  22692. return false;
  22693. }
  22694. void MidiFile::readNextTrack (const uint8* data, int size)
  22695. {
  22696. double time = 0;
  22697. char lastStatusByte = 0;
  22698. MidiMessageSequence result;
  22699. while (size > 0)
  22700. {
  22701. int bytesUsed;
  22702. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22703. data += bytesUsed;
  22704. size -= bytesUsed;
  22705. time += delay;
  22706. int messSize = 0;
  22707. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22708. if (messSize <= 0)
  22709. break;
  22710. size -= messSize;
  22711. data += messSize;
  22712. result.addEvent (mm);
  22713. const char firstByte = *(mm.getRawData());
  22714. if ((firstByte & 0xf0) != 0xf0)
  22715. lastStatusByte = firstByte;
  22716. }
  22717. // use a sort that puts all the note-offs before note-ons that have the same time
  22718. MidiFileHelpers::Sorter sorter;
  22719. result.list.sort (sorter, true);
  22720. result.updateMatchedPairs();
  22721. addTrack (result);
  22722. }
  22723. void MidiFile::convertTimestampTicksToSeconds()
  22724. {
  22725. MidiMessageSequence tempoEvents;
  22726. findAllTempoEvents (tempoEvents);
  22727. findAllTimeSigEvents (tempoEvents);
  22728. for (int i = 0; i < tracks.size(); ++i)
  22729. {
  22730. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22731. for (int j = ms.getNumEvents(); --j >= 0;)
  22732. {
  22733. MidiMessage& m = ms.getEventPointer(j)->message;
  22734. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22735. tempoEvents,
  22736. timeFormat));
  22737. }
  22738. }
  22739. }
  22740. bool MidiFile::writeTo (OutputStream& out)
  22741. {
  22742. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22743. out.writeIntBigEndian (6);
  22744. out.writeShortBigEndian (1); // type
  22745. out.writeShortBigEndian ((short) tracks.size());
  22746. out.writeShortBigEndian (timeFormat);
  22747. for (int i = 0; i < tracks.size(); ++i)
  22748. writeTrack (out, i);
  22749. out.flush();
  22750. return true;
  22751. }
  22752. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22753. {
  22754. MemoryOutputStream out;
  22755. const MidiMessageSequence& ms = *tracks[trackNum];
  22756. int lastTick = 0;
  22757. char lastStatusByte = 0;
  22758. for (int i = 0; i < ms.getNumEvents(); ++i)
  22759. {
  22760. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22761. const int tick = roundToInt (mm.getTimeStamp());
  22762. const int delta = jmax (0, tick - lastTick);
  22763. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22764. lastTick = tick;
  22765. const char statusByte = *(mm.getRawData());
  22766. if ((statusByte == lastStatusByte)
  22767. && ((statusByte & 0xf0) != 0xf0)
  22768. && i > 0
  22769. && mm.getRawDataSize() > 1)
  22770. {
  22771. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22772. }
  22773. else
  22774. {
  22775. out.write (mm.getRawData(), mm.getRawDataSize());
  22776. }
  22777. lastStatusByte = statusByte;
  22778. }
  22779. out.writeByte (0);
  22780. const MidiMessage m (MidiMessage::endOfTrack());
  22781. out.write (m.getRawData(),
  22782. m.getRawDataSize());
  22783. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22784. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22785. mainOut.write (out.getData(), (int) out.getDataSize());
  22786. }
  22787. END_JUCE_NAMESPACE
  22788. /*** End of inlined file: juce_MidiFile.cpp ***/
  22789. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22790. BEGIN_JUCE_NAMESPACE
  22791. MidiKeyboardState::MidiKeyboardState()
  22792. {
  22793. zerostruct (noteStates);
  22794. }
  22795. MidiKeyboardState::~MidiKeyboardState()
  22796. {
  22797. }
  22798. void MidiKeyboardState::reset()
  22799. {
  22800. const ScopedLock sl (lock);
  22801. zerostruct (noteStates);
  22802. eventsToAdd.clear();
  22803. }
  22804. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22805. {
  22806. jassert (midiChannel >= 0 && midiChannel <= 16);
  22807. return isPositiveAndBelow (n, (int) 128)
  22808. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22809. }
  22810. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22811. {
  22812. return isPositiveAndBelow (n, (int) 128)
  22813. && (noteStates[n] & midiChannelMask) != 0;
  22814. }
  22815. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22816. {
  22817. jassert (midiChannel >= 0 && midiChannel <= 16);
  22818. jassert (isPositiveAndBelow (midiNoteNumber, (int) 128));
  22819. const ScopedLock sl (lock);
  22820. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22821. {
  22822. const int timeNow = (int) Time::getMillisecondCounter();
  22823. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22824. eventsToAdd.clear (0, timeNow - 500);
  22825. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22826. }
  22827. }
  22828. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22829. {
  22830. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22831. {
  22832. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22833. for (int i = listeners.size(); --i >= 0;)
  22834. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22835. }
  22836. }
  22837. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22838. {
  22839. const ScopedLock sl (lock);
  22840. if (isNoteOn (midiChannel, midiNoteNumber))
  22841. {
  22842. const int timeNow = (int) Time::getMillisecondCounter();
  22843. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22844. eventsToAdd.clear (0, timeNow - 500);
  22845. noteOffInternal (midiChannel, midiNoteNumber);
  22846. }
  22847. }
  22848. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22849. {
  22850. if (isNoteOn (midiChannel, midiNoteNumber))
  22851. {
  22852. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22853. for (int i = listeners.size(); --i >= 0;)
  22854. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22855. }
  22856. }
  22857. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22858. {
  22859. const ScopedLock sl (lock);
  22860. if (midiChannel <= 0)
  22861. {
  22862. for (int i = 1; i <= 16; ++i)
  22863. allNotesOff (i);
  22864. }
  22865. else
  22866. {
  22867. for (int i = 0; i < 128; ++i)
  22868. noteOff (midiChannel, i);
  22869. }
  22870. }
  22871. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22872. {
  22873. if (message.isNoteOn())
  22874. {
  22875. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22876. }
  22877. else if (message.isNoteOff())
  22878. {
  22879. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22880. }
  22881. else if (message.isAllNotesOff())
  22882. {
  22883. for (int i = 0; i < 128; ++i)
  22884. noteOffInternal (message.getChannel(), i);
  22885. }
  22886. }
  22887. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22888. const int startSample,
  22889. const int numSamples,
  22890. const bool injectIndirectEvents)
  22891. {
  22892. MidiBuffer::Iterator i (buffer);
  22893. MidiMessage message (0xf4, 0.0);
  22894. int time;
  22895. const ScopedLock sl (lock);
  22896. while (i.getNextEvent (message, time))
  22897. processNextMidiEvent (message);
  22898. if (injectIndirectEvents)
  22899. {
  22900. MidiBuffer::Iterator i2 (eventsToAdd);
  22901. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22902. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22903. while (i2.getNextEvent (message, time))
  22904. {
  22905. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22906. buffer.addEvent (message, startSample + pos);
  22907. }
  22908. }
  22909. eventsToAdd.clear();
  22910. }
  22911. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22912. {
  22913. const ScopedLock sl (lock);
  22914. listeners.addIfNotAlreadyThere (listener);
  22915. }
  22916. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22917. {
  22918. const ScopedLock sl (lock);
  22919. listeners.removeValue (listener);
  22920. }
  22921. END_JUCE_NAMESPACE
  22922. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22923. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22924. BEGIN_JUCE_NAMESPACE
  22925. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22926. {
  22927. numBytesUsed = 0;
  22928. int v = 0;
  22929. int i;
  22930. do
  22931. {
  22932. i = (int) *data++;
  22933. if (++numBytesUsed > 6)
  22934. break;
  22935. v = (v << 7) + (i & 0x7f);
  22936. } while (i & 0x80);
  22937. return v;
  22938. }
  22939. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22940. {
  22941. // this method only works for valid starting bytes of a short midi message
  22942. jassert (firstByte >= 0x80 && firstByte != 0xf0 && firstByte != 0xf7);
  22943. static const char messageLengths[] =
  22944. {
  22945. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22946. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22947. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22948. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22949. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22950. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22951. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22952. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22953. };
  22954. return messageLengths [firstByte & 0x7f];
  22955. }
  22956. MidiMessage::MidiMessage() throw()
  22957. : timeStamp (0),
  22958. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22959. size (2)
  22960. {
  22961. data[0] = 0xf0;
  22962. data[1] = 0xf7;
  22963. }
  22964. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22965. : timeStamp (t),
  22966. size (dataSize)
  22967. {
  22968. jassert (dataSize > 0);
  22969. if (dataSize <= 4)
  22970. data = static_cast<uint8*> (preallocatedData.asBytes);
  22971. else
  22972. data = new uint8 [dataSize];
  22973. memcpy (data, d, dataSize);
  22974. // check that the length matches the data..
  22975. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22976. }
  22977. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22978. : timeStamp (t),
  22979. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22980. size (1)
  22981. {
  22982. data[0] = (uint8) byte1;
  22983. // check that the length matches the data..
  22984. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22985. }
  22986. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22987. : timeStamp (t),
  22988. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22989. size (2)
  22990. {
  22991. data[0] = (uint8) byte1;
  22992. data[1] = (uint8) byte2;
  22993. // check that the length matches the data..
  22994. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22995. }
  22996. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22997. : timeStamp (t),
  22998. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22999. size (3)
  23000. {
  23001. data[0] = (uint8) byte1;
  23002. data[1] = (uint8) byte2;
  23003. data[2] = (uint8) byte3;
  23004. // check that the length matches the data..
  23005. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23006. }
  23007. MidiMessage::MidiMessage (const MidiMessage& other)
  23008. : timeStamp (other.timeStamp),
  23009. size (other.size)
  23010. {
  23011. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23012. {
  23013. data = new uint8 [size];
  23014. memcpy (data, other.data, size);
  23015. }
  23016. else
  23017. {
  23018. data = static_cast<uint8*> (preallocatedData.asBytes);
  23019. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23020. }
  23021. }
  23022. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23023. : timeStamp (newTimeStamp),
  23024. size (other.size)
  23025. {
  23026. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23027. {
  23028. data = new uint8 [size];
  23029. memcpy (data, other.data, size);
  23030. }
  23031. else
  23032. {
  23033. data = static_cast<uint8*> (preallocatedData.asBytes);
  23034. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23035. }
  23036. }
  23037. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23038. : timeStamp (t),
  23039. data (static_cast<uint8*> (preallocatedData.asBytes))
  23040. {
  23041. const uint8* src = static_cast <const uint8*> (src_);
  23042. unsigned int byte = (unsigned int) *src;
  23043. if (byte < 0x80)
  23044. {
  23045. byte = (unsigned int) (uint8) lastStatusByte;
  23046. numBytesUsed = -1;
  23047. }
  23048. else
  23049. {
  23050. numBytesUsed = 0;
  23051. --sz;
  23052. ++src;
  23053. }
  23054. if (byte >= 0x80)
  23055. {
  23056. if (byte == 0xf0)
  23057. {
  23058. const uint8* d = src;
  23059. bool haveReadAllLengthBytes = false;
  23060. while (d < src + sz)
  23061. {
  23062. if (*d >= 0x80)
  23063. {
  23064. if (*d == 0xf7)
  23065. {
  23066. ++d; // include the trailing 0xf7 when we hit it
  23067. break;
  23068. }
  23069. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  23070. break; // bytes, assume it's the end of the sysex
  23071. ++d;
  23072. continue;
  23073. }
  23074. haveReadAllLengthBytes = true;
  23075. ++d;
  23076. }
  23077. size = 1 + (int) (d - src);
  23078. data = new uint8 [size];
  23079. *data = (uint8) byte;
  23080. memcpy (data + 1, src, size - 1);
  23081. }
  23082. else if (byte == 0xff)
  23083. {
  23084. int n;
  23085. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23086. size = jmin (sz + 1, n + 2 + bytesLeft);
  23087. data = new uint8 [size];
  23088. *data = (uint8) byte;
  23089. memcpy (data + 1, src, size - 1);
  23090. }
  23091. else
  23092. {
  23093. preallocatedData.asInt32 = 0;
  23094. size = getMessageLengthFromFirstByte ((uint8) byte);
  23095. data[0] = (uint8) byte;
  23096. if (size > 1)
  23097. {
  23098. data[1] = src[0];
  23099. if (size > 2)
  23100. data[2] = src[1];
  23101. }
  23102. }
  23103. numBytesUsed += size;
  23104. }
  23105. else
  23106. {
  23107. preallocatedData.asInt32 = 0;
  23108. size = 0;
  23109. }
  23110. }
  23111. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23112. {
  23113. if (this != &other)
  23114. {
  23115. timeStamp = other.timeStamp;
  23116. size = other.size;
  23117. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23118. delete[] data;
  23119. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23120. {
  23121. data = new uint8 [size];
  23122. memcpy (data, other.data, size);
  23123. }
  23124. else
  23125. {
  23126. data = static_cast<uint8*> (preallocatedData.asBytes);
  23127. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23128. }
  23129. }
  23130. return *this;
  23131. }
  23132. MidiMessage::~MidiMessage()
  23133. {
  23134. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23135. delete[] data;
  23136. }
  23137. int MidiMessage::getChannel() const throw()
  23138. {
  23139. if ((data[0] & 0xf0) != 0xf0)
  23140. return (data[0] & 0xf) + 1;
  23141. else
  23142. return 0;
  23143. }
  23144. bool MidiMessage::isForChannel (const int channel) const throw()
  23145. {
  23146. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23147. return ((data[0] & 0xf) == channel - 1)
  23148. && ((data[0] & 0xf0) != 0xf0);
  23149. }
  23150. void MidiMessage::setChannel (const int channel) throw()
  23151. {
  23152. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23153. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23154. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  23155. | (uint8)(channel - 1));
  23156. }
  23157. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23158. {
  23159. return ((data[0] & 0xf0) == 0x90)
  23160. && (returnTrueForVelocity0 || data[2] != 0);
  23161. }
  23162. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23163. {
  23164. return ((data[0] & 0xf0) == 0x80)
  23165. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23166. }
  23167. bool MidiMessage::isNoteOnOrOff() const throw()
  23168. {
  23169. const int d = data[0] & 0xf0;
  23170. return (d == 0x90) || (d == 0x80);
  23171. }
  23172. int MidiMessage::getNoteNumber() const throw()
  23173. {
  23174. return data[1];
  23175. }
  23176. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23177. {
  23178. if (isNoteOnOrOff())
  23179. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23180. }
  23181. uint8 MidiMessage::getVelocity() const throw()
  23182. {
  23183. if (isNoteOnOrOff())
  23184. return data[2];
  23185. else
  23186. return 0;
  23187. }
  23188. float MidiMessage::getFloatVelocity() const throw()
  23189. {
  23190. return getVelocity() * (1.0f / 127.0f);
  23191. }
  23192. void MidiMessage::setVelocity (const float newVelocity) throw()
  23193. {
  23194. if (isNoteOnOrOff())
  23195. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23196. }
  23197. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23198. {
  23199. if (isNoteOnOrOff())
  23200. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23201. }
  23202. bool MidiMessage::isAftertouch() const throw()
  23203. {
  23204. return (data[0] & 0xf0) == 0xa0;
  23205. }
  23206. int MidiMessage::getAfterTouchValue() const throw()
  23207. {
  23208. return data[2];
  23209. }
  23210. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23211. const int noteNum,
  23212. const int aftertouchValue) throw()
  23213. {
  23214. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23215. jassert (isPositiveAndBelow (noteNum, (int) 128));
  23216. jassert (isPositiveAndBelow (aftertouchValue, (int) 128));
  23217. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23218. noteNum & 0x7f,
  23219. aftertouchValue & 0x7f);
  23220. }
  23221. bool MidiMessage::isChannelPressure() const throw()
  23222. {
  23223. return (data[0] & 0xf0) == 0xd0;
  23224. }
  23225. int MidiMessage::getChannelPressureValue() const throw()
  23226. {
  23227. jassert (isChannelPressure());
  23228. return data[1];
  23229. }
  23230. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23231. const int pressure) throw()
  23232. {
  23233. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23234. jassert (isPositiveAndBelow (pressure, (int) 128));
  23235. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23236. pressure & 0x7f);
  23237. }
  23238. bool MidiMessage::isProgramChange() const throw()
  23239. {
  23240. return (data[0] & 0xf0) == 0xc0;
  23241. }
  23242. int MidiMessage::getProgramChangeNumber() const throw()
  23243. {
  23244. return data[1];
  23245. }
  23246. const MidiMessage MidiMessage::programChange (const int channel,
  23247. const int programNumber) throw()
  23248. {
  23249. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23250. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23251. programNumber & 0x7f);
  23252. }
  23253. bool MidiMessage::isPitchWheel() const throw()
  23254. {
  23255. return (data[0] & 0xf0) == 0xe0;
  23256. }
  23257. int MidiMessage::getPitchWheelValue() const throw()
  23258. {
  23259. return data[1] | (data[2] << 7);
  23260. }
  23261. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23262. const int position) throw()
  23263. {
  23264. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23265. jassert (isPositiveAndBelow (position, (int) 0x4000));
  23266. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23267. position & 127,
  23268. (position >> 7) & 127);
  23269. }
  23270. bool MidiMessage::isController() const throw()
  23271. {
  23272. return (data[0] & 0xf0) == 0xb0;
  23273. }
  23274. int MidiMessage::getControllerNumber() const throw()
  23275. {
  23276. jassert (isController());
  23277. return data[1];
  23278. }
  23279. int MidiMessage::getControllerValue() const throw()
  23280. {
  23281. jassert (isController());
  23282. return data[2];
  23283. }
  23284. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23285. const int controllerType,
  23286. const int value) throw()
  23287. {
  23288. // the channel must be between 1 and 16 inclusive
  23289. jassert (channel > 0 && channel <= 16);
  23290. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23291. controllerType & 127,
  23292. value & 127);
  23293. }
  23294. const MidiMessage MidiMessage::noteOn (const int channel,
  23295. const int noteNumber,
  23296. const float velocity) throw()
  23297. {
  23298. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23299. }
  23300. const MidiMessage MidiMessage::noteOn (const int channel,
  23301. const int noteNumber,
  23302. const uint8 velocity) throw()
  23303. {
  23304. jassert (channel > 0 && channel <= 16);
  23305. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23306. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23307. noteNumber & 127,
  23308. jlimit (0, 127, roundToInt (velocity)));
  23309. }
  23310. const MidiMessage MidiMessage::noteOff (const int channel,
  23311. const int noteNumber) throw()
  23312. {
  23313. jassert (channel > 0 && channel <= 16);
  23314. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23315. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23316. }
  23317. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23318. {
  23319. return controllerEvent (channel, 123, 0);
  23320. }
  23321. bool MidiMessage::isAllNotesOff() const throw()
  23322. {
  23323. return (data[0] & 0xf0) == 0xb0 && data[1] == 123;
  23324. }
  23325. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23326. {
  23327. return controllerEvent (channel, 120, 0);
  23328. }
  23329. bool MidiMessage::isAllSoundOff() const throw()
  23330. {
  23331. return (data[0] & 0xf0) == 0xb0 && data[1] == 120;
  23332. }
  23333. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23334. {
  23335. return controllerEvent (channel, 121, 0);
  23336. }
  23337. const MidiMessage MidiMessage::masterVolume (const float volume)
  23338. {
  23339. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23340. uint8 buf[8];
  23341. buf[0] = 0xf0;
  23342. buf[1] = 0x7f;
  23343. buf[2] = 0x7f;
  23344. buf[3] = 0x04;
  23345. buf[4] = 0x01;
  23346. buf[5] = (uint8) (vol & 0x7f);
  23347. buf[6] = (uint8) (vol >> 7);
  23348. buf[7] = 0xf7;
  23349. return MidiMessage (buf, 8);
  23350. }
  23351. bool MidiMessage::isSysEx() const throw()
  23352. {
  23353. return *data == 0xf0;
  23354. }
  23355. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23356. {
  23357. MemoryBlock mm (dataSize + 2);
  23358. uint8* const m = static_cast <uint8*> (mm.getData());
  23359. m[0] = 0xf0;
  23360. memcpy (m + 1, sysexData, dataSize);
  23361. m[dataSize + 1] = 0xf7;
  23362. return MidiMessage (m, dataSize + 2);
  23363. }
  23364. const uint8* MidiMessage::getSysExData() const throw()
  23365. {
  23366. return isSysEx() ? getRawData() + 1 : 0;
  23367. }
  23368. int MidiMessage::getSysExDataSize() const throw()
  23369. {
  23370. return isSysEx() ? size - 2 : 0;
  23371. }
  23372. bool MidiMessage::isMetaEvent() const throw()
  23373. {
  23374. return *data == 0xff;
  23375. }
  23376. bool MidiMessage::isActiveSense() const throw()
  23377. {
  23378. return *data == 0xfe;
  23379. }
  23380. int MidiMessage::getMetaEventType() const throw()
  23381. {
  23382. return *data != 0xff ? -1 : data[1];
  23383. }
  23384. int MidiMessage::getMetaEventLength() const throw()
  23385. {
  23386. if (*data == 0xff)
  23387. {
  23388. int n;
  23389. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23390. }
  23391. return 0;
  23392. }
  23393. const uint8* MidiMessage::getMetaEventData() const throw()
  23394. {
  23395. int n;
  23396. const uint8* d = data + 2;
  23397. readVariableLengthVal (d, n);
  23398. return d + n;
  23399. }
  23400. bool MidiMessage::isTrackMetaEvent() const throw()
  23401. {
  23402. return getMetaEventType() == 0;
  23403. }
  23404. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23405. {
  23406. return getMetaEventType() == 47;
  23407. }
  23408. bool MidiMessage::isTextMetaEvent() const throw()
  23409. {
  23410. const int t = getMetaEventType();
  23411. return t > 0 && t < 16;
  23412. }
  23413. const String MidiMessage::getTextFromTextMetaEvent() const
  23414. {
  23415. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23416. }
  23417. bool MidiMessage::isTrackNameEvent() const throw()
  23418. {
  23419. return (data[1] == 3) && (*data == 0xff);
  23420. }
  23421. bool MidiMessage::isTempoMetaEvent() const throw()
  23422. {
  23423. return (data[1] == 81) && (*data == 0xff);
  23424. }
  23425. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23426. {
  23427. return (data[1] == 0x20) && (*data == 0xff) && (data[2] == 1);
  23428. }
  23429. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23430. {
  23431. return data[3] + 1;
  23432. }
  23433. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23434. {
  23435. if (! isTempoMetaEvent())
  23436. return 0.0;
  23437. const uint8* const d = getMetaEventData();
  23438. return (((unsigned int) d[0] << 16)
  23439. | ((unsigned int) d[1] << 8)
  23440. | d[2])
  23441. / 1000000.0;
  23442. }
  23443. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23444. {
  23445. if (timeFormat > 0)
  23446. {
  23447. if (! isTempoMetaEvent())
  23448. return 0.5 / timeFormat;
  23449. return getTempoSecondsPerQuarterNote() / timeFormat;
  23450. }
  23451. else
  23452. {
  23453. const int frameCode = (-timeFormat) >> 8;
  23454. double framesPerSecond;
  23455. switch (frameCode)
  23456. {
  23457. case 24: framesPerSecond = 24.0; break;
  23458. case 25: framesPerSecond = 25.0; break;
  23459. case 29: framesPerSecond = 29.97; break;
  23460. case 30: framesPerSecond = 30.0; break;
  23461. default: framesPerSecond = 30.0; break;
  23462. }
  23463. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23464. }
  23465. }
  23466. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23467. {
  23468. uint8 d[8];
  23469. d[0] = 0xff;
  23470. d[1] = 81;
  23471. d[2] = 3;
  23472. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23473. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23474. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23475. return MidiMessage (d, 6, 0.0);
  23476. }
  23477. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23478. {
  23479. return (data[1] == 0x58) && (*data == (uint8) 0xff);
  23480. }
  23481. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23482. {
  23483. if (isTimeSignatureMetaEvent())
  23484. {
  23485. const uint8* const d = getMetaEventData();
  23486. numerator = d[0];
  23487. denominator = 1 << d[1];
  23488. }
  23489. else
  23490. {
  23491. numerator = 4;
  23492. denominator = 4;
  23493. }
  23494. }
  23495. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23496. {
  23497. uint8 d[8];
  23498. d[0] = 0xff;
  23499. d[1] = 0x58;
  23500. d[2] = 0x04;
  23501. d[3] = (uint8) numerator;
  23502. int n = 1;
  23503. int powerOfTwo = 0;
  23504. while (n < denominator)
  23505. {
  23506. n <<= 1;
  23507. ++powerOfTwo;
  23508. }
  23509. d[4] = (uint8) powerOfTwo;
  23510. d[5] = 0x01;
  23511. d[6] = 96;
  23512. return MidiMessage (d, 7, 0.0);
  23513. }
  23514. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23515. {
  23516. uint8 d[8];
  23517. d[0] = 0xff;
  23518. d[1] = 0x20;
  23519. d[2] = 0x01;
  23520. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23521. return MidiMessage (d, 4, 0.0);
  23522. }
  23523. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23524. {
  23525. return getMetaEventType() == 89;
  23526. }
  23527. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23528. {
  23529. return (int) *getMetaEventData();
  23530. }
  23531. const MidiMessage MidiMessage::endOfTrack() throw()
  23532. {
  23533. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23534. }
  23535. bool MidiMessage::isSongPositionPointer() const throw()
  23536. {
  23537. return *data == 0xf2;
  23538. }
  23539. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23540. {
  23541. return data[1] | (data[2] << 7);
  23542. }
  23543. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23544. {
  23545. return MidiMessage (0xf2,
  23546. positionInMidiBeats & 127,
  23547. (positionInMidiBeats >> 7) & 127);
  23548. }
  23549. bool MidiMessage::isMidiStart() const throw()
  23550. {
  23551. return *data == 0xfa;
  23552. }
  23553. const MidiMessage MidiMessage::midiStart() throw()
  23554. {
  23555. return MidiMessage (0xfa);
  23556. }
  23557. bool MidiMessage::isMidiContinue() const throw()
  23558. {
  23559. return *data == 0xfb;
  23560. }
  23561. const MidiMessage MidiMessage::midiContinue() throw()
  23562. {
  23563. return MidiMessage (0xfb);
  23564. }
  23565. bool MidiMessage::isMidiStop() const throw()
  23566. {
  23567. return *data == 0xfc;
  23568. }
  23569. const MidiMessage MidiMessage::midiStop() throw()
  23570. {
  23571. return MidiMessage (0xfc);
  23572. }
  23573. bool MidiMessage::isMidiClock() const throw()
  23574. {
  23575. return *data == 0xf8;
  23576. }
  23577. const MidiMessage MidiMessage::midiClock() throw()
  23578. {
  23579. return MidiMessage (0xf8);
  23580. }
  23581. bool MidiMessage::isQuarterFrame() const throw()
  23582. {
  23583. return *data == 0xf1;
  23584. }
  23585. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23586. {
  23587. return ((int) data[1]) >> 4;
  23588. }
  23589. int MidiMessage::getQuarterFrameValue() const throw()
  23590. {
  23591. return ((int) data[1]) & 0x0f;
  23592. }
  23593. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23594. const int value) throw()
  23595. {
  23596. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23597. }
  23598. bool MidiMessage::isFullFrame() const throw()
  23599. {
  23600. return data[0] == 0xf0
  23601. && data[1] == 0x7f
  23602. && size >= 10
  23603. && data[3] == 0x01
  23604. && data[4] == 0x01;
  23605. }
  23606. void MidiMessage::getFullFrameParameters (int& hours,
  23607. int& minutes,
  23608. int& seconds,
  23609. int& frames,
  23610. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23611. {
  23612. jassert (isFullFrame());
  23613. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23614. hours = data[5] & 0x1f;
  23615. minutes = data[6];
  23616. seconds = data[7];
  23617. frames = data[8];
  23618. }
  23619. const MidiMessage MidiMessage::fullFrame (const int hours,
  23620. const int minutes,
  23621. const int seconds,
  23622. const int frames,
  23623. MidiMessage::SmpteTimecodeType timecodeType)
  23624. {
  23625. uint8 d[10];
  23626. d[0] = 0xf0;
  23627. d[1] = 0x7f;
  23628. d[2] = 0x7f;
  23629. d[3] = 0x01;
  23630. d[4] = 0x01;
  23631. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23632. d[6] = (uint8) minutes;
  23633. d[7] = (uint8) seconds;
  23634. d[8] = (uint8) frames;
  23635. d[9] = 0xf7;
  23636. return MidiMessage (d, 10, 0.0);
  23637. }
  23638. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23639. {
  23640. return data[0] == 0xf0
  23641. && data[1] == 0x7f
  23642. && data[3] == 0x06
  23643. && size > 5;
  23644. }
  23645. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23646. {
  23647. jassert (isMidiMachineControlMessage());
  23648. return (MidiMachineControlCommand) data[4];
  23649. }
  23650. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23651. {
  23652. uint8 d[6];
  23653. d[0] = 0xf0;
  23654. d[1] = 0x7f;
  23655. d[2] = 0x00;
  23656. d[3] = 0x06;
  23657. d[4] = (uint8) command;
  23658. d[5] = 0xf7;
  23659. return MidiMessage (d, 6, 0.0);
  23660. }
  23661. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23662. int& minutes,
  23663. int& seconds,
  23664. int& frames) const throw()
  23665. {
  23666. if (size >= 12
  23667. && data[0] == 0xf0
  23668. && data[1] == 0x7f
  23669. && data[3] == 0x06
  23670. && data[4] == 0x44
  23671. && data[5] == 0x06
  23672. && data[6] == 0x01)
  23673. {
  23674. hours = data[7] % 24; // (that some machines send out hours > 24)
  23675. minutes = data[8];
  23676. seconds = data[9];
  23677. frames = data[10];
  23678. return true;
  23679. }
  23680. return false;
  23681. }
  23682. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23683. int minutes,
  23684. int seconds,
  23685. int frames)
  23686. {
  23687. uint8 d[12];
  23688. d[0] = 0xf0;
  23689. d[1] = 0x7f;
  23690. d[2] = 0x00;
  23691. d[3] = 0x06;
  23692. d[4] = 0x44;
  23693. d[5] = 0x06;
  23694. d[6] = 0x01;
  23695. d[7] = (uint8) hours;
  23696. d[8] = (uint8) minutes;
  23697. d[9] = (uint8) seconds;
  23698. d[10] = (uint8) frames;
  23699. d[11] = 0xf7;
  23700. return MidiMessage (d, 12, 0.0);
  23701. }
  23702. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23703. {
  23704. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23705. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23706. if (isPositiveAndBelow (note, (int) 128))
  23707. {
  23708. String s (useSharps ? sharpNoteNames [note % 12]
  23709. : flatNoteNames [note % 12]);
  23710. if (includeOctaveNumber)
  23711. s << (note / 12 + (octaveNumForMiddleC - 5));
  23712. return s;
  23713. }
  23714. return String::empty;
  23715. }
  23716. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23717. {
  23718. noteNumber -= 12 * 6 + 9; // now 0 = A
  23719. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23720. }
  23721. const String MidiMessage::getGMInstrumentName (const int n)
  23722. {
  23723. const char* names[] =
  23724. {
  23725. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23726. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23727. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23728. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23729. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23730. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23731. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23732. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23733. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23734. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23735. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23736. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23737. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23738. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23739. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23740. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23741. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23742. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23743. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23744. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23745. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23746. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23747. "Applause", "Gunshot"
  23748. };
  23749. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23750. }
  23751. const String MidiMessage::getGMInstrumentBankName (const int n)
  23752. {
  23753. const char* names[] =
  23754. {
  23755. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23756. "Bass", "Strings", "Ensemble", "Brass",
  23757. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23758. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23759. };
  23760. return isPositiveAndBelow (n, (int) 16) ? names[n] : (const char*) 0;
  23761. }
  23762. const String MidiMessage::getRhythmInstrumentName (const int n)
  23763. {
  23764. const char* names[] =
  23765. {
  23766. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23767. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23768. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23769. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23770. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23771. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23772. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23773. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23774. "Mute Triangle", "Open Triangle"
  23775. };
  23776. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23777. }
  23778. const String MidiMessage::getControllerName (const int n)
  23779. {
  23780. const char* names[] =
  23781. {
  23782. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23783. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23784. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23785. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23786. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23787. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23788. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23789. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23790. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23791. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23792. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23793. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23794. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23795. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23796. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23797. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23798. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23799. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23800. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23802. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23803. "Poly Operation"
  23804. };
  23805. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23806. }
  23807. END_JUCE_NAMESPACE
  23808. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23809. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23810. BEGIN_JUCE_NAMESPACE
  23811. MidiMessageCollector::MidiMessageCollector()
  23812. : lastCallbackTime (0),
  23813. sampleRate (44100.0001)
  23814. {
  23815. }
  23816. MidiMessageCollector::~MidiMessageCollector()
  23817. {
  23818. }
  23819. void MidiMessageCollector::reset (const double sampleRate_)
  23820. {
  23821. jassert (sampleRate_ > 0);
  23822. const ScopedLock sl (midiCallbackLock);
  23823. sampleRate = sampleRate_;
  23824. incomingMessages.clear();
  23825. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23826. }
  23827. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23828. {
  23829. // you need to call reset() to set the correct sample rate before using this object
  23830. jassert (sampleRate != 44100.0001);
  23831. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23832. // for details of what the number should be.
  23833. jassert (message.getTimeStamp() != 0);
  23834. const ScopedLock sl (midiCallbackLock);
  23835. const int sampleNumber
  23836. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23837. incomingMessages.addEvent (message, sampleNumber);
  23838. // if the messages don't get used for over a second, we'd better
  23839. // get rid of any old ones to avoid the queue getting too big
  23840. if (sampleNumber > sampleRate)
  23841. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23842. }
  23843. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23844. const int numSamples)
  23845. {
  23846. // you need to call reset() to set the correct sample rate before using this object
  23847. jassert (sampleRate != 44100.0001);
  23848. const double timeNow = Time::getMillisecondCounterHiRes();
  23849. const double msElapsed = timeNow - lastCallbackTime;
  23850. const ScopedLock sl (midiCallbackLock);
  23851. lastCallbackTime = timeNow;
  23852. if (! incomingMessages.isEmpty())
  23853. {
  23854. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23855. int startSample = 0;
  23856. int scale = 1 << 16;
  23857. const uint8* midiData;
  23858. int numBytes, samplePosition;
  23859. MidiBuffer::Iterator iter (incomingMessages);
  23860. if (numSourceSamples > numSamples)
  23861. {
  23862. // if our list of events is longer than the buffer we're being
  23863. // asked for, scale them down to squeeze them all in..
  23864. const int maxBlockLengthToUse = numSamples << 5;
  23865. if (numSourceSamples > maxBlockLengthToUse)
  23866. {
  23867. startSample = numSourceSamples - maxBlockLengthToUse;
  23868. numSourceSamples = maxBlockLengthToUse;
  23869. iter.setNextSamplePosition (startSample);
  23870. }
  23871. scale = (numSamples << 10) / numSourceSamples;
  23872. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23873. {
  23874. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23875. destBuffer.addEvent (midiData, numBytes,
  23876. jlimit (0, numSamples - 1, samplePosition));
  23877. }
  23878. }
  23879. else
  23880. {
  23881. // if our event list is shorter than the number we need, put them
  23882. // towards the end of the buffer
  23883. startSample = numSamples - numSourceSamples;
  23884. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23885. {
  23886. destBuffer.addEvent (midiData, numBytes,
  23887. jlimit (0, numSamples - 1, samplePosition + startSample));
  23888. }
  23889. }
  23890. incomingMessages.clear();
  23891. }
  23892. }
  23893. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23894. {
  23895. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23896. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23897. addMessageToQueue (m);
  23898. }
  23899. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23900. {
  23901. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23902. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23903. addMessageToQueue (m);
  23904. }
  23905. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23906. {
  23907. addMessageToQueue (message);
  23908. }
  23909. END_JUCE_NAMESPACE
  23910. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23911. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23912. BEGIN_JUCE_NAMESPACE
  23913. MidiMessageSequence::MidiMessageSequence()
  23914. {
  23915. }
  23916. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23917. {
  23918. list.ensureStorageAllocated (other.list.size());
  23919. for (int i = 0; i < other.list.size(); ++i)
  23920. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23921. }
  23922. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23923. {
  23924. MidiMessageSequence otherCopy (other);
  23925. swapWith (otherCopy);
  23926. return *this;
  23927. }
  23928. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23929. {
  23930. list.swapWithArray (other.list);
  23931. }
  23932. MidiMessageSequence::~MidiMessageSequence()
  23933. {
  23934. }
  23935. void MidiMessageSequence::clear()
  23936. {
  23937. list.clear();
  23938. }
  23939. int MidiMessageSequence::getNumEvents() const
  23940. {
  23941. return list.size();
  23942. }
  23943. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23944. {
  23945. return list [index];
  23946. }
  23947. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23948. {
  23949. const MidiEventHolder* const meh = list [index];
  23950. if (meh != 0 && meh->noteOffObject != 0)
  23951. return meh->noteOffObject->message.getTimeStamp();
  23952. else
  23953. return 0.0;
  23954. }
  23955. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23956. {
  23957. const MidiEventHolder* const meh = list [index];
  23958. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23959. }
  23960. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23961. {
  23962. return list.indexOf (event);
  23963. }
  23964. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23965. {
  23966. const int numEvents = list.size();
  23967. int i;
  23968. for (i = 0; i < numEvents; ++i)
  23969. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23970. break;
  23971. return i;
  23972. }
  23973. double MidiMessageSequence::getStartTime() const
  23974. {
  23975. if (list.size() > 0)
  23976. return list.getUnchecked(0)->message.getTimeStamp();
  23977. else
  23978. return 0;
  23979. }
  23980. double MidiMessageSequence::getEndTime() const
  23981. {
  23982. if (list.size() > 0)
  23983. return list.getLast()->message.getTimeStamp();
  23984. else
  23985. return 0;
  23986. }
  23987. double MidiMessageSequence::getEventTime (const int index) const
  23988. {
  23989. if (isPositiveAndBelow (index, list.size()))
  23990. return list.getUnchecked (index)->message.getTimeStamp();
  23991. return 0.0;
  23992. }
  23993. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23994. double timeAdjustment)
  23995. {
  23996. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23997. timeAdjustment += newMessage.getTimeStamp();
  23998. newOne->message.setTimeStamp (timeAdjustment);
  23999. int i;
  24000. for (i = list.size(); --i >= 0;)
  24001. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24002. break;
  24003. list.insert (i + 1, newOne);
  24004. }
  24005. void MidiMessageSequence::deleteEvent (const int index,
  24006. const bool deleteMatchingNoteUp)
  24007. {
  24008. if (isPositiveAndBelow (index, list.size()))
  24009. {
  24010. if (deleteMatchingNoteUp)
  24011. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24012. list.remove (index);
  24013. }
  24014. }
  24015. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24016. double timeAdjustment,
  24017. double firstAllowableTime,
  24018. double endOfAllowableDestTimes)
  24019. {
  24020. firstAllowableTime -= timeAdjustment;
  24021. endOfAllowableDestTimes -= timeAdjustment;
  24022. for (int i = 0; i < other.list.size(); ++i)
  24023. {
  24024. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24025. const double t = m.getTimeStamp();
  24026. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24027. {
  24028. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24029. newOne->message.setTimeStamp (timeAdjustment + t);
  24030. list.add (newOne);
  24031. }
  24032. }
  24033. sort();
  24034. }
  24035. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24036. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24037. {
  24038. const double diff = first->message.getTimeStamp()
  24039. - second->message.getTimeStamp();
  24040. return (diff > 0) - (diff < 0);
  24041. }
  24042. void MidiMessageSequence::sort()
  24043. {
  24044. list.sort (*this, true);
  24045. }
  24046. void MidiMessageSequence::updateMatchedPairs()
  24047. {
  24048. for (int i = 0; i < list.size(); ++i)
  24049. {
  24050. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24051. if (m1.isNoteOn())
  24052. {
  24053. list.getUnchecked(i)->noteOffObject = 0;
  24054. const int note = m1.getNoteNumber();
  24055. const int chan = m1.getChannel();
  24056. const int len = list.size();
  24057. for (int j = i + 1; j < len; ++j)
  24058. {
  24059. const MidiMessage& m = list.getUnchecked(j)->message;
  24060. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24061. {
  24062. if (m.isNoteOff())
  24063. {
  24064. list.getUnchecked(i)->noteOffObject = list[j];
  24065. break;
  24066. }
  24067. else if (m.isNoteOn())
  24068. {
  24069. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24070. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24071. list.getUnchecked(i)->noteOffObject = list[j];
  24072. break;
  24073. }
  24074. }
  24075. }
  24076. }
  24077. }
  24078. }
  24079. void MidiMessageSequence::addTimeToMessages (const double delta)
  24080. {
  24081. for (int i = list.size(); --i >= 0;)
  24082. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24083. + delta);
  24084. }
  24085. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24086. MidiMessageSequence& destSequence,
  24087. const bool alsoIncludeMetaEvents) const
  24088. {
  24089. for (int i = 0; i < list.size(); ++i)
  24090. {
  24091. const MidiMessage& mm = list.getUnchecked(i)->message;
  24092. if (mm.isForChannel (channelNumberToExtract)
  24093. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24094. {
  24095. destSequence.addEvent (mm);
  24096. }
  24097. }
  24098. }
  24099. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24100. {
  24101. for (int i = 0; i < list.size(); ++i)
  24102. {
  24103. const MidiMessage& mm = list.getUnchecked(i)->message;
  24104. if (mm.isSysEx())
  24105. destSequence.addEvent (mm);
  24106. }
  24107. }
  24108. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24109. {
  24110. for (int i = list.size(); --i >= 0;)
  24111. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24112. list.remove(i);
  24113. }
  24114. void MidiMessageSequence::deleteSysExMessages()
  24115. {
  24116. for (int i = list.size(); --i >= 0;)
  24117. if (list.getUnchecked(i)->message.isSysEx())
  24118. list.remove(i);
  24119. }
  24120. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24121. const double time,
  24122. OwnedArray<MidiMessage>& dest)
  24123. {
  24124. bool doneProg = false;
  24125. bool donePitchWheel = false;
  24126. Array <int> doneControllers;
  24127. doneControllers.ensureStorageAllocated (32);
  24128. for (int i = list.size(); --i >= 0;)
  24129. {
  24130. const MidiMessage& mm = list.getUnchecked(i)->message;
  24131. if (mm.isForChannel (channelNumber)
  24132. && mm.getTimeStamp() <= time)
  24133. {
  24134. if (mm.isProgramChange())
  24135. {
  24136. if (! doneProg)
  24137. {
  24138. dest.add (new MidiMessage (mm, 0.0));
  24139. doneProg = true;
  24140. }
  24141. }
  24142. else if (mm.isController())
  24143. {
  24144. if (! doneControllers.contains (mm.getControllerNumber()))
  24145. {
  24146. dest.add (new MidiMessage (mm, 0.0));
  24147. doneControllers.add (mm.getControllerNumber());
  24148. }
  24149. }
  24150. else if (mm.isPitchWheel())
  24151. {
  24152. if (! donePitchWheel)
  24153. {
  24154. dest.add (new MidiMessage (mm, 0.0));
  24155. donePitchWheel = true;
  24156. }
  24157. }
  24158. }
  24159. }
  24160. }
  24161. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24162. : message (message_),
  24163. noteOffObject (0)
  24164. {
  24165. }
  24166. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24167. {
  24168. }
  24169. END_JUCE_NAMESPACE
  24170. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24171. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24172. BEGIN_JUCE_NAMESPACE
  24173. AudioPluginFormat::AudioPluginFormat() throw()
  24174. {
  24175. }
  24176. AudioPluginFormat::~AudioPluginFormat()
  24177. {
  24178. }
  24179. END_JUCE_NAMESPACE
  24180. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24181. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24182. BEGIN_JUCE_NAMESPACE
  24183. AudioPluginFormatManager::AudioPluginFormatManager()
  24184. {
  24185. }
  24186. AudioPluginFormatManager::~AudioPluginFormatManager()
  24187. {
  24188. clearSingletonInstance();
  24189. }
  24190. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24191. void AudioPluginFormatManager::addDefaultFormats()
  24192. {
  24193. #if JUCE_DEBUG
  24194. // you should only call this method once!
  24195. for (int i = formats.size(); --i >= 0;)
  24196. {
  24197. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24198. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24199. #endif
  24200. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24201. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24202. #endif
  24203. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24204. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24205. #endif
  24206. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24207. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24208. #endif
  24209. }
  24210. #endif
  24211. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24212. formats.add (new AudioUnitPluginFormat());
  24213. #endif
  24214. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24215. formats.add (new VSTPluginFormat());
  24216. #endif
  24217. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24218. formats.add (new DirectXPluginFormat());
  24219. #endif
  24220. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24221. formats.add (new LADSPAPluginFormat());
  24222. #endif
  24223. }
  24224. int AudioPluginFormatManager::getNumFormats()
  24225. {
  24226. return formats.size();
  24227. }
  24228. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24229. {
  24230. return formats [index];
  24231. }
  24232. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24233. {
  24234. formats.add (format);
  24235. }
  24236. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24237. String& errorMessage) const
  24238. {
  24239. AudioPluginInstance* result = 0;
  24240. for (int i = 0; i < formats.size(); ++i)
  24241. {
  24242. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24243. if (result != 0)
  24244. break;
  24245. }
  24246. if (result == 0)
  24247. {
  24248. if (! doesPluginStillExist (description))
  24249. errorMessage = TRANS ("This plug-in file no longer exists");
  24250. else
  24251. errorMessage = TRANS ("This plug-in failed to load correctly");
  24252. }
  24253. return result;
  24254. }
  24255. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24256. {
  24257. for (int i = 0; i < formats.size(); ++i)
  24258. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24259. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24260. return false;
  24261. }
  24262. END_JUCE_NAMESPACE
  24263. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24264. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24265. #define JUCE_PLUGIN_HOST 1
  24266. BEGIN_JUCE_NAMESPACE
  24267. AudioPluginInstance::AudioPluginInstance()
  24268. {
  24269. }
  24270. AudioPluginInstance::~AudioPluginInstance()
  24271. {
  24272. }
  24273. void* AudioPluginInstance::getPlatformSpecificData()
  24274. {
  24275. return 0;
  24276. }
  24277. END_JUCE_NAMESPACE
  24278. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24279. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24280. BEGIN_JUCE_NAMESPACE
  24281. KnownPluginList::KnownPluginList()
  24282. {
  24283. }
  24284. KnownPluginList::~KnownPluginList()
  24285. {
  24286. }
  24287. void KnownPluginList::clear()
  24288. {
  24289. if (types.size() > 0)
  24290. {
  24291. types.clear();
  24292. sendChangeMessage();
  24293. }
  24294. }
  24295. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24296. {
  24297. for (int i = 0; i < types.size(); ++i)
  24298. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24299. return types.getUnchecked(i);
  24300. return 0;
  24301. }
  24302. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24303. {
  24304. for (int i = 0; i < types.size(); ++i)
  24305. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24306. return types.getUnchecked(i);
  24307. return 0;
  24308. }
  24309. bool KnownPluginList::addType (const PluginDescription& type)
  24310. {
  24311. for (int i = types.size(); --i >= 0;)
  24312. {
  24313. if (types.getUnchecked(i)->isDuplicateOf (type))
  24314. {
  24315. // strange - found a duplicate plugin with different info..
  24316. jassert (types.getUnchecked(i)->name == type.name);
  24317. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24318. *types.getUnchecked(i) = type;
  24319. return false;
  24320. }
  24321. }
  24322. types.add (new PluginDescription (type));
  24323. sendChangeMessage();
  24324. return true;
  24325. }
  24326. void KnownPluginList::removeType (const int index)
  24327. {
  24328. types.remove (index);
  24329. sendChangeMessage();
  24330. }
  24331. namespace
  24332. {
  24333. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24334. {
  24335. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24336. return File (fileOrIdentifier).getLastModificationTime();
  24337. return Time();
  24338. }
  24339. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24340. {
  24341. return t1 != t2 || t1 == Time();
  24342. }
  24343. }
  24344. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24345. {
  24346. if (getTypeForFile (fileOrIdentifier) == 0)
  24347. return false;
  24348. for (int i = types.size(); --i >= 0;)
  24349. {
  24350. const PluginDescription* const d = types.getUnchecked(i);
  24351. if (d->fileOrIdentifier == fileOrIdentifier
  24352. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24353. {
  24354. return false;
  24355. }
  24356. }
  24357. return true;
  24358. }
  24359. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24360. const bool dontRescanIfAlreadyInList,
  24361. OwnedArray <PluginDescription>& typesFound,
  24362. AudioPluginFormat& format)
  24363. {
  24364. bool addedOne = false;
  24365. if (dontRescanIfAlreadyInList
  24366. && getTypeForFile (fileOrIdentifier) != 0)
  24367. {
  24368. bool needsRescanning = false;
  24369. for (int i = types.size(); --i >= 0;)
  24370. {
  24371. const PluginDescription* const d = types.getUnchecked(i);
  24372. if (d->fileOrIdentifier == fileOrIdentifier)
  24373. {
  24374. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24375. needsRescanning = true;
  24376. else
  24377. typesFound.add (new PluginDescription (*d));
  24378. }
  24379. }
  24380. if (! needsRescanning)
  24381. return false;
  24382. }
  24383. OwnedArray <PluginDescription> found;
  24384. format.findAllTypesForFile (found, fileOrIdentifier);
  24385. for (int i = 0; i < found.size(); ++i)
  24386. {
  24387. PluginDescription* const desc = found.getUnchecked(i);
  24388. jassert (desc != 0);
  24389. if (addType (*desc))
  24390. addedOne = true;
  24391. typesFound.add (new PluginDescription (*desc));
  24392. }
  24393. return addedOne;
  24394. }
  24395. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24396. OwnedArray <PluginDescription>& typesFound)
  24397. {
  24398. for (int i = 0; i < files.size(); ++i)
  24399. {
  24400. bool loaded = false;
  24401. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24402. {
  24403. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24404. if (scanAndAddFile (files[i], true, typesFound, *format))
  24405. loaded = true;
  24406. }
  24407. if (! loaded)
  24408. {
  24409. const File f (files[i]);
  24410. if (f.isDirectory())
  24411. {
  24412. StringArray s;
  24413. {
  24414. Array<File> subFiles;
  24415. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24416. for (int j = 0; j < subFiles.size(); ++j)
  24417. s.add (subFiles.getReference(j).getFullPathName());
  24418. }
  24419. scanAndAddDragAndDroppedFiles (s, typesFound);
  24420. }
  24421. }
  24422. }
  24423. }
  24424. class PluginSorter
  24425. {
  24426. public:
  24427. KnownPluginList::SortMethod method;
  24428. PluginSorter() throw() {}
  24429. int compareElements (const PluginDescription* const first,
  24430. const PluginDescription* const second) const
  24431. {
  24432. int diff = 0;
  24433. if (method == KnownPluginList::sortByCategory)
  24434. diff = first->category.compareLexicographically (second->category);
  24435. else if (method == KnownPluginList::sortByManufacturer)
  24436. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24437. else if (method == KnownPluginList::sortByFileSystemLocation)
  24438. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24439. .upToLastOccurrenceOf ("/", false, false)
  24440. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24441. .upToLastOccurrenceOf ("/", false, false));
  24442. if (diff == 0)
  24443. diff = first->name.compareLexicographically (second->name);
  24444. return diff;
  24445. }
  24446. };
  24447. void KnownPluginList::sort (const SortMethod method)
  24448. {
  24449. if (method != defaultOrder)
  24450. {
  24451. PluginSorter sorter;
  24452. sorter.method = method;
  24453. types.sort (sorter, true);
  24454. sendChangeMessage();
  24455. }
  24456. }
  24457. XmlElement* KnownPluginList::createXml() const
  24458. {
  24459. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24460. for (int i = 0; i < types.size(); ++i)
  24461. e->addChildElement (types.getUnchecked(i)->createXml());
  24462. return e;
  24463. }
  24464. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24465. {
  24466. clear();
  24467. if (xml.hasTagName ("KNOWNPLUGINS"))
  24468. {
  24469. forEachXmlChildElement (xml, e)
  24470. {
  24471. PluginDescription info;
  24472. if (info.loadFromXml (*e))
  24473. addType (info);
  24474. }
  24475. }
  24476. }
  24477. const int menuIdBase = 0x324503f4;
  24478. // This is used to turn a bunch of paths into a nested menu structure.
  24479. struct PluginFilesystemTree
  24480. {
  24481. private:
  24482. String folder;
  24483. OwnedArray <PluginFilesystemTree> subFolders;
  24484. Array <PluginDescription*> plugins;
  24485. void addPlugin (PluginDescription* const pd, const String& path)
  24486. {
  24487. if (path.isEmpty())
  24488. {
  24489. plugins.add (pd);
  24490. }
  24491. else
  24492. {
  24493. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24494. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24495. for (int i = subFolders.size(); --i >= 0;)
  24496. {
  24497. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24498. {
  24499. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24500. return;
  24501. }
  24502. }
  24503. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24504. newFolder->folder = firstSubFolder;
  24505. subFolders.add (newFolder);
  24506. newFolder->addPlugin (pd, remainingPath);
  24507. }
  24508. }
  24509. // removes any deeply nested folders that don't contain any actual plugins
  24510. void optimise()
  24511. {
  24512. for (int i = subFolders.size(); --i >= 0;)
  24513. {
  24514. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24515. sub->optimise();
  24516. if (sub->plugins.size() == 0)
  24517. {
  24518. for (int j = 0; j < sub->subFolders.size(); ++j)
  24519. subFolders.add (sub->subFolders.getUnchecked(j));
  24520. sub->subFolders.clear (false);
  24521. subFolders.remove (i);
  24522. }
  24523. }
  24524. }
  24525. public:
  24526. void buildTree (const Array <PluginDescription*>& allPlugins)
  24527. {
  24528. for (int i = 0; i < allPlugins.size(); ++i)
  24529. {
  24530. String path (allPlugins.getUnchecked(i)
  24531. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24532. .upToLastOccurrenceOf ("/", false, false));
  24533. if (path.substring (1, 2) == ":")
  24534. path = path.substring (2);
  24535. addPlugin (allPlugins.getUnchecked(i), path);
  24536. }
  24537. optimise();
  24538. }
  24539. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24540. {
  24541. int i;
  24542. for (i = 0; i < subFolders.size(); ++i)
  24543. {
  24544. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24545. PopupMenu subMenu;
  24546. sub->addToMenu (subMenu, allPlugins);
  24547. #if JUCE_MAC
  24548. // avoid the special AU formatting nonsense on Mac..
  24549. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24550. #else
  24551. m.addSubMenu (sub->folder, subMenu);
  24552. #endif
  24553. }
  24554. for (i = 0; i < plugins.size(); ++i)
  24555. {
  24556. PluginDescription* const plugin = plugins.getUnchecked(i);
  24557. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24558. plugin->name, true, false);
  24559. }
  24560. }
  24561. };
  24562. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24563. {
  24564. Array <PluginDescription*> sorted;
  24565. {
  24566. PluginSorter sorter;
  24567. sorter.method = sortMethod;
  24568. for (int i = 0; i < types.size(); ++i)
  24569. sorted.addSorted (sorter, types.getUnchecked(i));
  24570. }
  24571. if (sortMethod == sortByCategory
  24572. || sortMethod == sortByManufacturer)
  24573. {
  24574. String lastSubMenuName;
  24575. PopupMenu sub;
  24576. for (int i = 0; i < sorted.size(); ++i)
  24577. {
  24578. const PluginDescription* const pd = sorted.getUnchecked(i);
  24579. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24580. : pd->manufacturerName);
  24581. if (! thisSubMenuName.containsNonWhitespaceChars())
  24582. thisSubMenuName = "Other";
  24583. if (thisSubMenuName != lastSubMenuName)
  24584. {
  24585. if (sub.getNumItems() > 0)
  24586. {
  24587. menu.addSubMenu (lastSubMenuName, sub);
  24588. sub.clear();
  24589. }
  24590. lastSubMenuName = thisSubMenuName;
  24591. }
  24592. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24593. }
  24594. if (sub.getNumItems() > 0)
  24595. menu.addSubMenu (lastSubMenuName, sub);
  24596. }
  24597. else if (sortMethod == sortByFileSystemLocation)
  24598. {
  24599. PluginFilesystemTree root;
  24600. root.buildTree (sorted);
  24601. root.addToMenu (menu, types);
  24602. }
  24603. else
  24604. {
  24605. for (int i = 0; i < sorted.size(); ++i)
  24606. {
  24607. const PluginDescription* const pd = sorted.getUnchecked(i);
  24608. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24609. }
  24610. }
  24611. }
  24612. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24613. {
  24614. const int i = menuResultCode - menuIdBase;
  24615. return isPositiveAndBelow (i, types.size()) ? i : -1;
  24616. }
  24617. END_JUCE_NAMESPACE
  24618. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24619. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24620. BEGIN_JUCE_NAMESPACE
  24621. PluginDescription::PluginDescription()
  24622. : uid (0),
  24623. isInstrument (false),
  24624. numInputChannels (0),
  24625. numOutputChannels (0)
  24626. {
  24627. }
  24628. PluginDescription::~PluginDescription()
  24629. {
  24630. }
  24631. PluginDescription::PluginDescription (const PluginDescription& other)
  24632. : name (other.name),
  24633. descriptiveName (other.descriptiveName),
  24634. pluginFormatName (other.pluginFormatName),
  24635. category (other.category),
  24636. manufacturerName (other.manufacturerName),
  24637. version (other.version),
  24638. fileOrIdentifier (other.fileOrIdentifier),
  24639. lastFileModTime (other.lastFileModTime),
  24640. uid (other.uid),
  24641. isInstrument (other.isInstrument),
  24642. numInputChannels (other.numInputChannels),
  24643. numOutputChannels (other.numOutputChannels)
  24644. {
  24645. }
  24646. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24647. {
  24648. name = other.name;
  24649. descriptiveName = other.descriptiveName;
  24650. pluginFormatName = other.pluginFormatName;
  24651. category = other.category;
  24652. manufacturerName = other.manufacturerName;
  24653. version = other.version;
  24654. fileOrIdentifier = other.fileOrIdentifier;
  24655. uid = other.uid;
  24656. isInstrument = other.isInstrument;
  24657. lastFileModTime = other.lastFileModTime;
  24658. numInputChannels = other.numInputChannels;
  24659. numOutputChannels = other.numOutputChannels;
  24660. return *this;
  24661. }
  24662. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24663. {
  24664. return fileOrIdentifier == other.fileOrIdentifier
  24665. && uid == other.uid;
  24666. }
  24667. const String PluginDescription::createIdentifierString() const
  24668. {
  24669. return pluginFormatName
  24670. + "-" + name
  24671. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24672. + "-" + String::toHexString (uid);
  24673. }
  24674. XmlElement* PluginDescription::createXml() const
  24675. {
  24676. XmlElement* const e = new XmlElement ("PLUGIN");
  24677. e->setAttribute ("name", name);
  24678. if (descriptiveName != name)
  24679. e->setAttribute ("descriptiveName", descriptiveName);
  24680. e->setAttribute ("format", pluginFormatName);
  24681. e->setAttribute ("category", category);
  24682. e->setAttribute ("manufacturer", manufacturerName);
  24683. e->setAttribute ("version", version);
  24684. e->setAttribute ("file", fileOrIdentifier);
  24685. e->setAttribute ("uid", String::toHexString (uid));
  24686. e->setAttribute ("isInstrument", isInstrument);
  24687. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24688. e->setAttribute ("numInputs", numInputChannels);
  24689. e->setAttribute ("numOutputs", numOutputChannels);
  24690. return e;
  24691. }
  24692. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24693. {
  24694. if (xml.hasTagName ("PLUGIN"))
  24695. {
  24696. name = xml.getStringAttribute ("name");
  24697. descriptiveName = xml.getStringAttribute ("name", name);
  24698. pluginFormatName = xml.getStringAttribute ("format");
  24699. category = xml.getStringAttribute ("category");
  24700. manufacturerName = xml.getStringAttribute ("manufacturer");
  24701. version = xml.getStringAttribute ("version");
  24702. fileOrIdentifier = xml.getStringAttribute ("file");
  24703. uid = xml.getStringAttribute ("uid").getHexValue32();
  24704. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24705. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24706. numInputChannels = xml.getIntAttribute ("numInputs");
  24707. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24708. return true;
  24709. }
  24710. return false;
  24711. }
  24712. END_JUCE_NAMESPACE
  24713. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24714. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24715. BEGIN_JUCE_NAMESPACE
  24716. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24717. AudioPluginFormat& formatToLookFor,
  24718. FileSearchPath directoriesToSearch,
  24719. const bool recursive,
  24720. const File& deadMansPedalFile_)
  24721. : list (listToAddTo),
  24722. format (formatToLookFor),
  24723. deadMansPedalFile (deadMansPedalFile_),
  24724. nextIndex (0),
  24725. progress (0)
  24726. {
  24727. directoriesToSearch.removeRedundantPaths();
  24728. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24729. // If any plugins have crashed recently when being loaded, move them to the
  24730. // end of the list to give the others a chance to load correctly..
  24731. const StringArray crashedPlugins (getDeadMansPedalFile());
  24732. for (int i = 0; i < crashedPlugins.size(); ++i)
  24733. {
  24734. const String f = crashedPlugins[i];
  24735. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24736. if (f == filesOrIdentifiersToScan[j])
  24737. filesOrIdentifiersToScan.move (j, -1);
  24738. }
  24739. }
  24740. PluginDirectoryScanner::~PluginDirectoryScanner()
  24741. {
  24742. }
  24743. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24744. {
  24745. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24746. }
  24747. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24748. {
  24749. String file (filesOrIdentifiersToScan [nextIndex]);
  24750. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24751. {
  24752. OwnedArray <PluginDescription> typesFound;
  24753. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24754. StringArray crashedPlugins (getDeadMansPedalFile());
  24755. crashedPlugins.removeString (file);
  24756. crashedPlugins.add (file);
  24757. setDeadMansPedalFile (crashedPlugins);
  24758. list.scanAndAddFile (file,
  24759. dontRescanIfAlreadyInList,
  24760. typesFound,
  24761. format);
  24762. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24763. crashedPlugins.removeString (file);
  24764. setDeadMansPedalFile (crashedPlugins);
  24765. if (typesFound.size() == 0)
  24766. failedFiles.add (file);
  24767. }
  24768. return skipNextFile();
  24769. }
  24770. bool PluginDirectoryScanner::skipNextFile()
  24771. {
  24772. if (nextIndex >= filesOrIdentifiersToScan.size())
  24773. return false;
  24774. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24775. return nextIndex < filesOrIdentifiersToScan.size();
  24776. }
  24777. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24778. {
  24779. StringArray lines;
  24780. if (deadMansPedalFile != File::nonexistent)
  24781. {
  24782. lines.addLines (deadMansPedalFile.loadFileAsString());
  24783. lines.removeEmptyStrings();
  24784. }
  24785. return lines;
  24786. }
  24787. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24788. {
  24789. if (deadMansPedalFile != File::nonexistent)
  24790. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24791. }
  24792. END_JUCE_NAMESPACE
  24793. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24794. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24795. BEGIN_JUCE_NAMESPACE
  24796. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24797. const File& deadMansPedalFile_,
  24798. PropertiesFile* const propertiesToUse_)
  24799. : list (listToEdit),
  24800. deadMansPedalFile (deadMansPedalFile_),
  24801. optionsButton ("Options..."),
  24802. propertiesToUse (propertiesToUse_)
  24803. {
  24804. listBox.setModel (this);
  24805. addAndMakeVisible (&listBox);
  24806. addAndMakeVisible (&optionsButton);
  24807. optionsButton.addListener (this);
  24808. optionsButton.setTriggeredOnMouseDown (true);
  24809. setSize (400, 600);
  24810. list.addChangeListener (this);
  24811. changeListenerCallback (0);
  24812. }
  24813. PluginListComponent::~PluginListComponent()
  24814. {
  24815. list.removeChangeListener (this);
  24816. }
  24817. void PluginListComponent::resized()
  24818. {
  24819. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24820. optionsButton.changeWidthToFitText (24);
  24821. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24822. }
  24823. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  24824. {
  24825. listBox.updateContent();
  24826. listBox.repaint();
  24827. }
  24828. int PluginListComponent::getNumRows()
  24829. {
  24830. return list.getNumTypes();
  24831. }
  24832. void PluginListComponent::paintListBoxItem (int row,
  24833. Graphics& g,
  24834. int width, int height,
  24835. bool rowIsSelected)
  24836. {
  24837. if (rowIsSelected)
  24838. g.fillAll (findColour (TextEditor::highlightColourId));
  24839. const PluginDescription* const pd = list.getType (row);
  24840. if (pd != 0)
  24841. {
  24842. GlyphArrangement ga;
  24843. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24844. g.setColour (Colours::black);
  24845. ga.draw (g);
  24846. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24847. String desc;
  24848. desc << pd->pluginFormatName
  24849. << (pd->isInstrument ? " instrument" : " effect")
  24850. << " - "
  24851. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24852. << " / "
  24853. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24854. if (pd->manufacturerName.isNotEmpty())
  24855. desc << " - " << pd->manufacturerName;
  24856. if (pd->version.isNotEmpty())
  24857. desc << " - " << pd->version;
  24858. if (pd->category.isNotEmpty())
  24859. desc << " - category: '" << pd->category << '\'';
  24860. g.setColour (Colours::grey);
  24861. ga.clear();
  24862. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24863. ga.draw (g);
  24864. }
  24865. }
  24866. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24867. {
  24868. list.removeType (lastRowSelected);
  24869. }
  24870. void PluginListComponent::buttonClicked (Button* button)
  24871. {
  24872. if (button == &optionsButton)
  24873. {
  24874. PopupMenu menu;
  24875. menu.addItem (1, TRANS("Clear list"));
  24876. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  24877. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  24878. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24879. menu.addSeparator();
  24880. menu.addItem (2, TRANS("Sort alphabetically"));
  24881. menu.addItem (3, TRANS("Sort by category"));
  24882. menu.addItem (4, TRANS("Sort by manufacturer"));
  24883. menu.addSeparator();
  24884. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24885. {
  24886. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24887. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24888. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24889. }
  24890. const int r = menu.showAt (&optionsButton);
  24891. if (r == 1)
  24892. {
  24893. list.clear();
  24894. }
  24895. else if (r == 2)
  24896. {
  24897. list.sort (KnownPluginList::sortAlphabetically);
  24898. }
  24899. else if (r == 3)
  24900. {
  24901. list.sort (KnownPluginList::sortByCategory);
  24902. }
  24903. else if (r == 4)
  24904. {
  24905. list.sort (KnownPluginList::sortByManufacturer);
  24906. }
  24907. else if (r == 5)
  24908. {
  24909. const SparseSet <int> selected (listBox.getSelectedRows());
  24910. for (int i = list.getNumTypes(); --i >= 0;)
  24911. if (selected.contains (i))
  24912. list.removeType (i);
  24913. }
  24914. else if (r == 6)
  24915. {
  24916. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  24917. if (desc != 0)
  24918. {
  24919. if (File (desc->fileOrIdentifier).existsAsFile())
  24920. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24921. }
  24922. }
  24923. else if (r == 7)
  24924. {
  24925. for (int i = list.getNumTypes(); --i >= 0;)
  24926. {
  24927. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24928. {
  24929. list.removeType (i);
  24930. }
  24931. }
  24932. }
  24933. else if (r != 0)
  24934. {
  24935. typeToScan = r - 10;
  24936. startTimer (1);
  24937. }
  24938. }
  24939. }
  24940. void PluginListComponent::timerCallback()
  24941. {
  24942. stopTimer();
  24943. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24944. }
  24945. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24946. {
  24947. return true;
  24948. }
  24949. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24950. {
  24951. OwnedArray <PluginDescription> typesFound;
  24952. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24953. }
  24954. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24955. {
  24956. if (format == 0)
  24957. return;
  24958. FileSearchPath path (format->getDefaultLocationsToSearch());
  24959. if (propertiesToUse != 0)
  24960. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24961. {
  24962. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24963. FileSearchPathListComponent pathList;
  24964. pathList.setSize (500, 300);
  24965. pathList.setPath (path);
  24966. aw.addCustomComponent (&pathList);
  24967. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24968. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24969. if (aw.runModalLoop() == 0)
  24970. return;
  24971. path = pathList.getPath();
  24972. }
  24973. if (propertiesToUse != 0)
  24974. {
  24975. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24976. propertiesToUse->saveIfNeeded();
  24977. }
  24978. double progress = 0.0;
  24979. AlertWindow aw (TRANS("Scanning for plugins..."),
  24980. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24981. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24982. aw.addProgressBarComponent (progress);
  24983. aw.enterModalState();
  24984. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24985. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24986. for (;;)
  24987. {
  24988. aw.setMessage (TRANS("Testing:\n\n")
  24989. + scanner.getNextPluginFileThatWillBeScanned());
  24990. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24991. if (! scanner.scanNextFile (true))
  24992. break;
  24993. if (! aw.isCurrentlyModal())
  24994. break;
  24995. progress = scanner.getProgress();
  24996. }
  24997. if (scanner.getFailedFiles().size() > 0)
  24998. {
  24999. StringArray shortNames;
  25000. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25001. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25002. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25003. TRANS("Scan complete"),
  25004. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25005. + shortNames.joinIntoString (", "));
  25006. }
  25007. }
  25008. END_JUCE_NAMESPACE
  25009. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25010. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25011. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25012. #include <AudioUnit/AudioUnit.h>
  25013. #include <AudioUnit/AUCocoaUIView.h>
  25014. #include <CoreAudioKit/AUGenericView.h>
  25015. #if JUCE_SUPPORT_CARBON
  25016. #include <AudioToolbox/AudioUnitUtilities.h>
  25017. #include <AudioUnit/AudioUnitCarbonView.h>
  25018. #endif
  25019. BEGIN_JUCE_NAMESPACE
  25020. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25021. #endif
  25022. #if JUCE_MAC
  25023. // Change this to disable logging of various activities
  25024. #ifndef AU_LOGGING
  25025. #define AU_LOGGING 1
  25026. #endif
  25027. #if AU_LOGGING
  25028. #define log(a) Logger::writeToLog(a);
  25029. #else
  25030. #define log(a)
  25031. #endif
  25032. namespace AudioUnitFormatHelpers
  25033. {
  25034. static int insideCallback = 0;
  25035. const String osTypeToString (OSType type)
  25036. {
  25037. char s[4];
  25038. s[0] = (char) (((uint32) type) >> 24);
  25039. s[1] = (char) (((uint32) type) >> 16);
  25040. s[2] = (char) (((uint32) type) >> 8);
  25041. s[3] = (char) ((uint32) type);
  25042. return String (s, 4);
  25043. }
  25044. OSType stringToOSType (const String& s1)
  25045. {
  25046. const String s (s1 + " ");
  25047. return (((OSType) (unsigned char) s[0]) << 24)
  25048. | (((OSType) (unsigned char) s[1]) << 16)
  25049. | (((OSType) (unsigned char) s[2]) << 8)
  25050. | ((OSType) (unsigned char) s[3]);
  25051. }
  25052. static const char* auIdentifierPrefix = "AudioUnit:";
  25053. const String createAUPluginIdentifier (const ComponentDescription& desc)
  25054. {
  25055. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25056. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25057. String s (auIdentifierPrefix);
  25058. if (desc.componentType == kAudioUnitType_MusicDevice)
  25059. s << "Synths/";
  25060. else if (desc.componentType == kAudioUnitType_MusicEffect
  25061. || desc.componentType == kAudioUnitType_Effect)
  25062. s << "Effects/";
  25063. else if (desc.componentType == kAudioUnitType_Generator)
  25064. s << "Generators/";
  25065. else if (desc.componentType == kAudioUnitType_Panner)
  25066. s << "Panners/";
  25067. s << osTypeToString (desc.componentType) << ","
  25068. << osTypeToString (desc.componentSubType) << ","
  25069. << osTypeToString (desc.componentManufacturer);
  25070. return s;
  25071. }
  25072. void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25073. {
  25074. Handle componentNameHandle = NewHandle (sizeof (void*));
  25075. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25076. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25077. {
  25078. ComponentDescription desc;
  25079. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25080. {
  25081. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25082. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25083. if (nameString != 0 && nameString[0] != 0)
  25084. {
  25085. const String all ((const char*) nameString + 1, nameString[0]);
  25086. DBG ("name: "+ all);
  25087. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25088. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25089. }
  25090. if (infoString != 0 && infoString[0] != 0)
  25091. {
  25092. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25093. }
  25094. if (name.isEmpty())
  25095. name = "<Unknown>";
  25096. }
  25097. DisposeHandle (componentNameHandle);
  25098. DisposeHandle (componentInfoHandle);
  25099. }
  25100. }
  25101. bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25102. String& name, String& version, String& manufacturer)
  25103. {
  25104. zerostruct (desc);
  25105. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25106. {
  25107. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25108. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25109. StringArray tokens;
  25110. tokens.addTokens (s, ",", String::empty);
  25111. tokens.trim();
  25112. tokens.removeEmptyStrings();
  25113. if (tokens.size() == 3)
  25114. {
  25115. desc.componentType = stringToOSType (tokens[0]);
  25116. desc.componentSubType = stringToOSType (tokens[1]);
  25117. desc.componentManufacturer = stringToOSType (tokens[2]);
  25118. ComponentRecord* comp = FindNextComponent (0, &desc);
  25119. if (comp != 0)
  25120. {
  25121. getAUDetails (comp, name, manufacturer);
  25122. return true;
  25123. }
  25124. }
  25125. }
  25126. return false;
  25127. }
  25128. }
  25129. class AudioUnitPluginWindowCarbon;
  25130. class AudioUnitPluginWindowCocoa;
  25131. class AudioUnitPluginInstance : public AudioPluginInstance
  25132. {
  25133. public:
  25134. ~AudioUnitPluginInstance();
  25135. void initialise();
  25136. // AudioPluginInstance methods:
  25137. void fillInPluginDescription (PluginDescription& desc) const
  25138. {
  25139. desc.name = pluginName;
  25140. desc.descriptiveName = pluginName;
  25141. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25142. desc.uid = ((int) componentDesc.componentType)
  25143. ^ ((int) componentDesc.componentSubType)
  25144. ^ ((int) componentDesc.componentManufacturer);
  25145. desc.lastFileModTime = Time();
  25146. desc.pluginFormatName = "AudioUnit";
  25147. desc.category = getCategory();
  25148. desc.manufacturerName = manufacturer;
  25149. desc.version = version;
  25150. desc.numInputChannels = getNumInputChannels();
  25151. desc.numOutputChannels = getNumOutputChannels();
  25152. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25153. }
  25154. void* getPlatformSpecificData() { return audioUnit; }
  25155. const String getName() const { return pluginName; }
  25156. bool acceptsMidi() const { return wantsMidiMessages; }
  25157. bool producesMidi() const { return false; }
  25158. // AudioProcessor methods:
  25159. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25160. void releaseResources();
  25161. void processBlock (AudioSampleBuffer& buffer,
  25162. MidiBuffer& midiMessages);
  25163. bool hasEditor() const;
  25164. AudioProcessorEditor* createEditor();
  25165. const String getInputChannelName (int index) const;
  25166. bool isInputChannelStereoPair (int index) const;
  25167. const String getOutputChannelName (int index) const;
  25168. bool isOutputChannelStereoPair (int index) const;
  25169. int getNumParameters();
  25170. float getParameter (int index);
  25171. void setParameter (int index, float newValue);
  25172. const String getParameterName (int index);
  25173. const String getParameterText (int index);
  25174. bool isParameterAutomatable (int index) const;
  25175. int getNumPrograms();
  25176. int getCurrentProgram();
  25177. void setCurrentProgram (int index);
  25178. const String getProgramName (int index);
  25179. void changeProgramName (int index, const String& newName);
  25180. void getStateInformation (MemoryBlock& destData);
  25181. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25182. void setStateInformation (const void* data, int sizeInBytes);
  25183. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25184. private:
  25185. friend class AudioUnitPluginWindowCarbon;
  25186. friend class AudioUnitPluginWindowCocoa;
  25187. friend class AudioUnitPluginFormat;
  25188. ComponentDescription componentDesc;
  25189. String pluginName, manufacturer, version;
  25190. String fileOrIdentifier;
  25191. CriticalSection lock;
  25192. bool wantsMidiMessages, wasPlaying, prepared;
  25193. HeapBlock <AudioBufferList> outputBufferList;
  25194. AudioTimeStamp timeStamp;
  25195. AudioSampleBuffer* currentBuffer;
  25196. AudioUnit audioUnit;
  25197. Array <int> parameterIds;
  25198. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25199. void setPluginCallbacks();
  25200. void getParameterListFromPlugin();
  25201. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25202. const AudioTimeStamp* inTimeStamp,
  25203. UInt32 inBusNumber,
  25204. UInt32 inNumberFrames,
  25205. AudioBufferList* ioData) const;
  25206. static OSStatus renderGetInputCallback (void* inRefCon,
  25207. AudioUnitRenderActionFlags* ioActionFlags,
  25208. const AudioTimeStamp* inTimeStamp,
  25209. UInt32 inBusNumber,
  25210. UInt32 inNumberFrames,
  25211. AudioBufferList* ioData)
  25212. {
  25213. return ((AudioUnitPluginInstance*) inRefCon)
  25214. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25215. }
  25216. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25217. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25218. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25219. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25220. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25221. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25222. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25223. {
  25224. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25225. }
  25226. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25227. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25228. Float64* outCurrentMeasureDownBeat)
  25229. {
  25230. return ((AudioUnitPluginInstance*) inHostUserData)
  25231. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25232. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25233. }
  25234. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25235. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25236. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25237. {
  25238. return ((AudioUnitPluginInstance*) inHostUserData)
  25239. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25240. outCurrentSampleInTimeLine, outIsCycling,
  25241. outCycleStartBeat, outCycleEndBeat);
  25242. }
  25243. void getNumChannels (int& numIns, int& numOuts)
  25244. {
  25245. numIns = 0;
  25246. numOuts = 0;
  25247. AUChannelInfo supportedChannels [128];
  25248. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25249. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25250. 0, supportedChannels, &supportedChannelsSize) == noErr
  25251. && supportedChannelsSize > 0)
  25252. {
  25253. int explicitNumIns = 0;
  25254. int explicitNumOuts = 0;
  25255. int maximumNumIns = 0;
  25256. int maximumNumOuts = 0;
  25257. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25258. {
  25259. const int inChannels = (int) supportedChannels[i].inChannels;
  25260. const int outChannels = (int) supportedChannels[i].outChannels;
  25261. if (inChannels < 0)
  25262. maximumNumIns = jmin (maximumNumIns, inChannels);
  25263. else
  25264. explicitNumIns = jmax (explicitNumIns, inChannels);
  25265. if (outChannels < 0)
  25266. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25267. else
  25268. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25269. }
  25270. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25271. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25272. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25273. {
  25274. numIns = numOuts = 2;
  25275. }
  25276. else
  25277. {
  25278. numIns = explicitNumIns;
  25279. numOuts = explicitNumOuts;
  25280. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25281. numIns = 2;
  25282. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25283. numOuts = 2;
  25284. }
  25285. }
  25286. else
  25287. {
  25288. // (this really means the plugin will take any number of ins/outs as long
  25289. // as they are the same)
  25290. numIns = numOuts = 2;
  25291. }
  25292. }
  25293. const String getCategory() const;
  25294. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25295. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginInstance);
  25296. };
  25297. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25298. : fileOrIdentifier (fileOrIdentifier),
  25299. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25300. currentBuffer (0),
  25301. audioUnit (0)
  25302. {
  25303. using namespace AudioUnitFormatHelpers;
  25304. try
  25305. {
  25306. ++insideCallback;
  25307. log ("Opening AU: " + fileOrIdentifier);
  25308. if (getComponentDescFromFile (fileOrIdentifier))
  25309. {
  25310. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25311. if (comp != 0)
  25312. {
  25313. audioUnit = (AudioUnit) OpenComponent (comp);
  25314. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25315. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25316. }
  25317. }
  25318. --insideCallback;
  25319. }
  25320. catch (...)
  25321. {
  25322. --insideCallback;
  25323. }
  25324. }
  25325. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25326. {
  25327. const ScopedLock sl (lock);
  25328. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25329. if (audioUnit != 0)
  25330. {
  25331. AudioUnitUninitialize (audioUnit);
  25332. CloseComponent (audioUnit);
  25333. audioUnit = 0;
  25334. }
  25335. }
  25336. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25337. {
  25338. zerostruct (componentDesc);
  25339. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25340. return true;
  25341. const File file (fileOrIdentifier);
  25342. if (! file.hasFileExtension (".component"))
  25343. return false;
  25344. const char* const utf8 = fileOrIdentifier.toUTF8();
  25345. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25346. strlen (utf8), file.isDirectory());
  25347. if (url != 0)
  25348. {
  25349. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25350. CFRelease (url);
  25351. if (bundleRef != 0)
  25352. {
  25353. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25354. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25355. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25356. if (pluginName.isEmpty())
  25357. pluginName = file.getFileNameWithoutExtension();
  25358. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25359. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25360. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25361. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25362. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25363. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25364. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25365. UseResFile (resFileId);
  25366. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25367. {
  25368. Handle h = Get1IndResource ('thng', i);
  25369. if (h != 0)
  25370. {
  25371. HLock (h);
  25372. const uint32* const types = (const uint32*) *h;
  25373. if (types[0] == kAudioUnitType_MusicDevice
  25374. || types[0] == kAudioUnitType_MusicEffect
  25375. || types[0] == kAudioUnitType_Effect
  25376. || types[0] == kAudioUnitType_Generator
  25377. || types[0] == kAudioUnitType_Panner)
  25378. {
  25379. componentDesc.componentType = types[0];
  25380. componentDesc.componentSubType = types[1];
  25381. componentDesc.componentManufacturer = types[2];
  25382. break;
  25383. }
  25384. HUnlock (h);
  25385. ReleaseResource (h);
  25386. }
  25387. }
  25388. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25389. CFRelease (bundleRef);
  25390. }
  25391. }
  25392. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25393. }
  25394. void AudioUnitPluginInstance::initialise()
  25395. {
  25396. getParameterListFromPlugin();
  25397. setPluginCallbacks();
  25398. int numIns, numOuts;
  25399. getNumChannels (numIns, numOuts);
  25400. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25401. setLatencySamples (0);
  25402. }
  25403. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25404. {
  25405. parameterIds.clear();
  25406. if (audioUnit != 0)
  25407. {
  25408. UInt32 paramListSize = 0;
  25409. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25410. 0, 0, &paramListSize);
  25411. if (paramListSize > 0)
  25412. {
  25413. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25414. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25415. 0, &parameterIds.getReference(0), &paramListSize);
  25416. }
  25417. }
  25418. }
  25419. void AudioUnitPluginInstance::setPluginCallbacks()
  25420. {
  25421. if (audioUnit != 0)
  25422. {
  25423. {
  25424. AURenderCallbackStruct info;
  25425. zerostruct (info);
  25426. info.inputProcRefCon = this;
  25427. info.inputProc = renderGetInputCallback;
  25428. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25429. 0, &info, sizeof (info));
  25430. }
  25431. {
  25432. HostCallbackInfo info;
  25433. zerostruct (info);
  25434. info.hostUserData = this;
  25435. info.beatAndTempoProc = getBeatAndTempoCallback;
  25436. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25437. info.transportStateProc = getTransportStateCallback;
  25438. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25439. 0, &info, sizeof (info));
  25440. }
  25441. }
  25442. }
  25443. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25444. int samplesPerBlockExpected)
  25445. {
  25446. if (audioUnit != 0)
  25447. {
  25448. releaseResources();
  25449. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25450. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25451. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25452. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25453. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25454. {
  25455. Float64 sr = sampleRate_;
  25456. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25457. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25458. }
  25459. int numIns, numOuts;
  25460. getNumChannels (numIns, numOuts);
  25461. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25462. Float64 latencySecs = 0.0;
  25463. UInt32 latencySize = sizeof (latencySecs);
  25464. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25465. 0, &latencySecs, &latencySize);
  25466. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25467. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25468. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25469. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25470. {
  25471. AudioStreamBasicDescription stream;
  25472. zerostruct (stream);
  25473. stream.mSampleRate = sampleRate_;
  25474. stream.mFormatID = kAudioFormatLinearPCM;
  25475. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25476. stream.mFramesPerPacket = 1;
  25477. stream.mBytesPerPacket = 4;
  25478. stream.mBytesPerFrame = 4;
  25479. stream.mBitsPerChannel = 32;
  25480. stream.mChannelsPerFrame = numIns;
  25481. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25482. 0, &stream, sizeof (stream));
  25483. stream.mChannelsPerFrame = numOuts;
  25484. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25485. 0, &stream, sizeof (stream));
  25486. }
  25487. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25488. outputBufferList->mNumberBuffers = numOuts;
  25489. for (int i = numOuts; --i >= 0;)
  25490. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25491. zerostruct (timeStamp);
  25492. timeStamp.mSampleTime = 0;
  25493. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25494. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25495. currentBuffer = 0;
  25496. wasPlaying = false;
  25497. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25498. }
  25499. }
  25500. void AudioUnitPluginInstance::releaseResources()
  25501. {
  25502. if (prepared)
  25503. {
  25504. AudioUnitUninitialize (audioUnit);
  25505. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25506. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25507. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25508. outputBufferList.free();
  25509. currentBuffer = 0;
  25510. prepared = false;
  25511. }
  25512. }
  25513. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25514. const AudioTimeStamp* inTimeStamp,
  25515. UInt32 inBusNumber,
  25516. UInt32 inNumberFrames,
  25517. AudioBufferList* ioData) const
  25518. {
  25519. if (inBusNumber == 0
  25520. && currentBuffer != 0)
  25521. {
  25522. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25523. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25524. {
  25525. if (i < currentBuffer->getNumChannels())
  25526. {
  25527. memcpy (ioData->mBuffers[i].mData,
  25528. currentBuffer->getSampleData (i, 0),
  25529. sizeof (float) * inNumberFrames);
  25530. }
  25531. else
  25532. {
  25533. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25534. }
  25535. }
  25536. }
  25537. return noErr;
  25538. }
  25539. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25540. MidiBuffer& midiMessages)
  25541. {
  25542. const int numSamples = buffer.getNumSamples();
  25543. if (prepared)
  25544. {
  25545. AudioUnitRenderActionFlags flags = 0;
  25546. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25547. for (int i = getNumOutputChannels(); --i >= 0;)
  25548. {
  25549. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25550. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25551. }
  25552. currentBuffer = &buffer;
  25553. if (wantsMidiMessages)
  25554. {
  25555. const uint8* midiEventData;
  25556. int midiEventSize, midiEventPosition;
  25557. MidiBuffer::Iterator i (midiMessages);
  25558. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25559. {
  25560. if (midiEventSize <= 3)
  25561. MusicDeviceMIDIEvent (audioUnit,
  25562. midiEventData[0], midiEventData[1], midiEventData[2],
  25563. midiEventPosition);
  25564. else
  25565. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25566. }
  25567. midiMessages.clear();
  25568. }
  25569. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25570. 0, numSamples, outputBufferList);
  25571. timeStamp.mSampleTime += numSamples;
  25572. }
  25573. else
  25574. {
  25575. // Plugin not working correctly, so just bypass..
  25576. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25577. buffer.clear (i, 0, buffer.getNumSamples());
  25578. }
  25579. }
  25580. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25581. {
  25582. AudioPlayHead* const ph = getPlayHead();
  25583. AudioPlayHead::CurrentPositionInfo result;
  25584. if (ph != 0 && ph->getCurrentPosition (result))
  25585. {
  25586. if (outCurrentBeat != 0)
  25587. *outCurrentBeat = result.ppqPosition;
  25588. if (outCurrentTempo != 0)
  25589. *outCurrentTempo = result.bpm;
  25590. }
  25591. else
  25592. {
  25593. if (outCurrentBeat != 0)
  25594. *outCurrentBeat = 0;
  25595. if (outCurrentTempo != 0)
  25596. *outCurrentTempo = 120.0;
  25597. }
  25598. return noErr;
  25599. }
  25600. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25601. Float32* outTimeSig_Numerator,
  25602. UInt32* outTimeSig_Denominator,
  25603. Float64* outCurrentMeasureDownBeat) const
  25604. {
  25605. AudioPlayHead* const ph = getPlayHead();
  25606. AudioPlayHead::CurrentPositionInfo result;
  25607. if (ph != 0 && ph->getCurrentPosition (result))
  25608. {
  25609. if (outTimeSig_Numerator != 0)
  25610. *outTimeSig_Numerator = result.timeSigNumerator;
  25611. if (outTimeSig_Denominator != 0)
  25612. *outTimeSig_Denominator = result.timeSigDenominator;
  25613. if (outDeltaSampleOffsetToNextBeat != 0)
  25614. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25615. if (outCurrentMeasureDownBeat != 0)
  25616. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25617. }
  25618. else
  25619. {
  25620. if (outDeltaSampleOffsetToNextBeat != 0)
  25621. *outDeltaSampleOffsetToNextBeat = 0;
  25622. if (outTimeSig_Numerator != 0)
  25623. *outTimeSig_Numerator = 4;
  25624. if (outTimeSig_Denominator != 0)
  25625. *outTimeSig_Denominator = 4;
  25626. if (outCurrentMeasureDownBeat != 0)
  25627. *outCurrentMeasureDownBeat = 0;
  25628. }
  25629. return noErr;
  25630. }
  25631. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25632. Boolean* outTransportStateChanged,
  25633. Float64* outCurrentSampleInTimeLine,
  25634. Boolean* outIsCycling,
  25635. Float64* outCycleStartBeat,
  25636. Float64* outCycleEndBeat)
  25637. {
  25638. AudioPlayHead* const ph = getPlayHead();
  25639. AudioPlayHead::CurrentPositionInfo result;
  25640. if (ph != 0 && ph->getCurrentPosition (result))
  25641. {
  25642. if (outIsPlaying != 0)
  25643. *outIsPlaying = result.isPlaying;
  25644. if (outTransportStateChanged != 0)
  25645. {
  25646. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25647. wasPlaying = result.isPlaying;
  25648. }
  25649. if (outCurrentSampleInTimeLine != 0)
  25650. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25651. if (outIsCycling != 0)
  25652. *outIsCycling = false;
  25653. if (outCycleStartBeat != 0)
  25654. *outCycleStartBeat = 0;
  25655. if (outCycleEndBeat != 0)
  25656. *outCycleEndBeat = 0;
  25657. }
  25658. else
  25659. {
  25660. if (outIsPlaying != 0)
  25661. *outIsPlaying = false;
  25662. if (outTransportStateChanged != 0)
  25663. *outTransportStateChanged = false;
  25664. if (outCurrentSampleInTimeLine != 0)
  25665. *outCurrentSampleInTimeLine = 0;
  25666. if (outIsCycling != 0)
  25667. *outIsCycling = false;
  25668. if (outCycleStartBeat != 0)
  25669. *outCycleStartBeat = 0;
  25670. if (outCycleEndBeat != 0)
  25671. *outCycleEndBeat = 0;
  25672. }
  25673. return noErr;
  25674. }
  25675. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25676. public Timer
  25677. {
  25678. public:
  25679. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25680. : AudioProcessorEditor (&plugin_),
  25681. plugin (plugin_)
  25682. {
  25683. addAndMakeVisible (&wrapper);
  25684. setOpaque (true);
  25685. setVisible (true);
  25686. setSize (100, 100);
  25687. createView (createGenericViewIfNeeded);
  25688. }
  25689. ~AudioUnitPluginWindowCocoa()
  25690. {
  25691. const bool wasValid = isValid();
  25692. wrapper.setView (0);
  25693. if (wasValid)
  25694. plugin.editorBeingDeleted (this);
  25695. }
  25696. bool isValid() const { return wrapper.getView() != 0; }
  25697. void paint (Graphics& g)
  25698. {
  25699. g.fillAll (Colours::white);
  25700. }
  25701. void resized()
  25702. {
  25703. wrapper.setSize (getWidth(), getHeight());
  25704. }
  25705. void timerCallback()
  25706. {
  25707. wrapper.resizeToFitView();
  25708. startTimer (jmin (713, getTimerInterval() + 51));
  25709. }
  25710. void childBoundsChanged (Component* child)
  25711. {
  25712. setSize (wrapper.getWidth(), wrapper.getHeight());
  25713. startTimer (70);
  25714. }
  25715. private:
  25716. AudioUnitPluginInstance& plugin;
  25717. NSViewComponent wrapper;
  25718. bool createView (const bool createGenericViewIfNeeded)
  25719. {
  25720. NSView* pluginView = 0;
  25721. UInt32 dataSize = 0;
  25722. Boolean isWritable = false;
  25723. AudioUnitInitialize (plugin.audioUnit);
  25724. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25725. 0, &dataSize, &isWritable) == noErr
  25726. && dataSize != 0
  25727. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25728. 0, &dataSize, &isWritable) == noErr)
  25729. {
  25730. HeapBlock <AudioUnitCocoaViewInfo> info;
  25731. info.calloc (dataSize, 1);
  25732. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25733. 0, info, &dataSize) == noErr)
  25734. {
  25735. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25736. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25737. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25738. Class viewClass = [viewBundle classNamed: viewClassName];
  25739. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25740. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25741. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25742. {
  25743. id factory = [[[viewClass alloc] init] autorelease];
  25744. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25745. withSize: NSMakeSize (getWidth(), getHeight())];
  25746. }
  25747. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25748. CFRelease (info->mCocoaAUViewClass[i]);
  25749. CFRelease (info->mCocoaAUViewBundleLocation);
  25750. }
  25751. }
  25752. if (createGenericViewIfNeeded && (pluginView == 0))
  25753. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25754. wrapper.setView (pluginView);
  25755. if (pluginView != 0)
  25756. {
  25757. timerCallback();
  25758. startTimer (70);
  25759. }
  25760. return pluginView != 0;
  25761. }
  25762. };
  25763. #if JUCE_SUPPORT_CARBON
  25764. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25765. {
  25766. public:
  25767. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25768. : AudioProcessorEditor (&plugin_),
  25769. plugin (plugin_),
  25770. viewComponent (0)
  25771. {
  25772. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25773. setOpaque (true);
  25774. setVisible (true);
  25775. setSize (400, 300);
  25776. ComponentDescription viewList [16];
  25777. UInt32 viewListSize = sizeof (viewList);
  25778. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25779. 0, &viewList, &viewListSize);
  25780. componentRecord = FindNextComponent (0, &viewList[0]);
  25781. }
  25782. ~AudioUnitPluginWindowCarbon()
  25783. {
  25784. innerWrapper = 0;
  25785. if (isValid())
  25786. plugin.editorBeingDeleted (this);
  25787. }
  25788. bool isValid() const throw() { return componentRecord != 0; }
  25789. void paint (Graphics& g)
  25790. {
  25791. g.fillAll (Colours::black);
  25792. }
  25793. void resized()
  25794. {
  25795. innerWrapper->setSize (getWidth(), getHeight());
  25796. }
  25797. bool keyStateChanged (bool)
  25798. {
  25799. return false;
  25800. }
  25801. bool keyPressed (const KeyPress&)
  25802. {
  25803. return false;
  25804. }
  25805. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25806. AudioUnitCarbonView getViewComponent()
  25807. {
  25808. if (viewComponent == 0 && componentRecord != 0)
  25809. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25810. return viewComponent;
  25811. }
  25812. void closeViewComponent()
  25813. {
  25814. if (viewComponent != 0)
  25815. {
  25816. log ("Closing AU GUI: " + plugin.getName());
  25817. CloseComponent (viewComponent);
  25818. viewComponent = 0;
  25819. }
  25820. }
  25821. private:
  25822. AudioUnitPluginInstance& plugin;
  25823. ComponentRecord* componentRecord;
  25824. AudioUnitCarbonView viewComponent;
  25825. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25826. {
  25827. public:
  25828. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25829. : owner (owner_)
  25830. {
  25831. }
  25832. ~InnerWrapperComponent()
  25833. {
  25834. deleteWindow();
  25835. }
  25836. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25837. {
  25838. log ("Opening AU GUI: " + owner->plugin.getName());
  25839. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25840. if (viewComponent == 0)
  25841. return 0;
  25842. Float32Point pos = { 0, 0 };
  25843. Float32Point size = { 250, 200 };
  25844. HIViewRef pluginView = 0;
  25845. AudioUnitCarbonViewCreate (viewComponent,
  25846. owner->getAudioUnit(),
  25847. windowRef,
  25848. rootView,
  25849. &pos,
  25850. &size,
  25851. (ControlRef*) &pluginView);
  25852. return pluginView;
  25853. }
  25854. void removeView (HIViewRef)
  25855. {
  25856. owner->closeViewComponent();
  25857. }
  25858. private:
  25859. AudioUnitPluginWindowCarbon* const owner;
  25860. };
  25861. friend class InnerWrapperComponent;
  25862. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25863. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginWindowCarbon);
  25864. };
  25865. #endif
  25866. bool AudioUnitPluginInstance::hasEditor() const
  25867. {
  25868. return true;
  25869. }
  25870. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25871. {
  25872. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25873. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25874. w = 0;
  25875. #if JUCE_SUPPORT_CARBON
  25876. if (w == 0)
  25877. {
  25878. w = new AudioUnitPluginWindowCarbon (*this);
  25879. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25880. w = 0;
  25881. }
  25882. #endif
  25883. if (w == 0)
  25884. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25885. return w.release();
  25886. }
  25887. const String AudioUnitPluginInstance::getCategory() const
  25888. {
  25889. const char* result = 0;
  25890. switch (componentDesc.componentType)
  25891. {
  25892. case kAudioUnitType_Effect:
  25893. case kAudioUnitType_MusicEffect: result = "Effect"; break;
  25894. case kAudioUnitType_MusicDevice: result = "Synth"; break;
  25895. case kAudioUnitType_Generator: result = "Generator"; break;
  25896. case kAudioUnitType_Panner: result = "Panner"; break;
  25897. default: break;
  25898. }
  25899. return result;
  25900. }
  25901. int AudioUnitPluginInstance::getNumParameters()
  25902. {
  25903. return parameterIds.size();
  25904. }
  25905. float AudioUnitPluginInstance::getParameter (int index)
  25906. {
  25907. const ScopedLock sl (lock);
  25908. Float32 value = 0.0f;
  25909. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25910. {
  25911. AudioUnitGetParameter (audioUnit,
  25912. (UInt32) parameterIds.getUnchecked (index),
  25913. kAudioUnitScope_Global, 0,
  25914. &value);
  25915. }
  25916. return value;
  25917. }
  25918. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25919. {
  25920. const ScopedLock sl (lock);
  25921. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25922. {
  25923. AudioUnitSetParameter (audioUnit,
  25924. (UInt32) parameterIds.getUnchecked (index),
  25925. kAudioUnitScope_Global, 0,
  25926. newValue, 0);
  25927. }
  25928. }
  25929. const String AudioUnitPluginInstance::getParameterName (int index)
  25930. {
  25931. AudioUnitParameterInfo info;
  25932. zerostruct (info);
  25933. UInt32 sz = sizeof (info);
  25934. String name;
  25935. if (AudioUnitGetProperty (audioUnit,
  25936. kAudioUnitProperty_ParameterInfo,
  25937. kAudioUnitScope_Global,
  25938. parameterIds [index], &info, &sz) == noErr)
  25939. {
  25940. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25941. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25942. else
  25943. name = String (info.name, sizeof (info.name));
  25944. }
  25945. return name;
  25946. }
  25947. const String AudioUnitPluginInstance::getParameterText (int index)
  25948. {
  25949. return String (getParameter (index));
  25950. }
  25951. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25952. {
  25953. AudioUnitParameterInfo info;
  25954. UInt32 sz = sizeof (info);
  25955. if (AudioUnitGetProperty (audioUnit,
  25956. kAudioUnitProperty_ParameterInfo,
  25957. kAudioUnitScope_Global,
  25958. parameterIds [index], &info, &sz) == noErr)
  25959. {
  25960. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25961. }
  25962. return true;
  25963. }
  25964. int AudioUnitPluginInstance::getNumPrograms()
  25965. {
  25966. CFArrayRef presets;
  25967. UInt32 sz = sizeof (CFArrayRef);
  25968. int num = 0;
  25969. if (AudioUnitGetProperty (audioUnit,
  25970. kAudioUnitProperty_FactoryPresets,
  25971. kAudioUnitScope_Global,
  25972. 0, &presets, &sz) == noErr)
  25973. {
  25974. num = (int) CFArrayGetCount (presets);
  25975. CFRelease (presets);
  25976. }
  25977. return num;
  25978. }
  25979. int AudioUnitPluginInstance::getCurrentProgram()
  25980. {
  25981. AUPreset current;
  25982. current.presetNumber = 0;
  25983. UInt32 sz = sizeof (AUPreset);
  25984. AudioUnitGetProperty (audioUnit,
  25985. kAudioUnitProperty_FactoryPresets,
  25986. kAudioUnitScope_Global,
  25987. 0, &current, &sz);
  25988. return current.presetNumber;
  25989. }
  25990. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25991. {
  25992. AUPreset current;
  25993. current.presetNumber = newIndex;
  25994. current.presetName = 0;
  25995. AudioUnitSetProperty (audioUnit,
  25996. kAudioUnitProperty_FactoryPresets,
  25997. kAudioUnitScope_Global,
  25998. 0, &current, sizeof (AUPreset));
  25999. }
  26000. const String AudioUnitPluginInstance::getProgramName (int index)
  26001. {
  26002. String s;
  26003. CFArrayRef presets;
  26004. UInt32 sz = sizeof (CFArrayRef);
  26005. if (AudioUnitGetProperty (audioUnit,
  26006. kAudioUnitProperty_FactoryPresets,
  26007. kAudioUnitScope_Global,
  26008. 0, &presets, &sz) == noErr)
  26009. {
  26010. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26011. {
  26012. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26013. if (p != 0 && p->presetNumber == index)
  26014. {
  26015. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26016. break;
  26017. }
  26018. }
  26019. CFRelease (presets);
  26020. }
  26021. return s;
  26022. }
  26023. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26024. {
  26025. jassertfalse; // xxx not implemented!
  26026. }
  26027. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26028. {
  26029. if (isPositiveAndBelow (index, getNumInputChannels()))
  26030. return "Input " + String (index + 1);
  26031. return String::empty;
  26032. }
  26033. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26034. {
  26035. if (! isPositiveAndBelow (index, getNumInputChannels()))
  26036. return false;
  26037. return true;
  26038. }
  26039. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26040. {
  26041. if (isPositiveAndBelow (index, getNumOutputChannels()))
  26042. return "Output " + String (index + 1);
  26043. return String::empty;
  26044. }
  26045. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26046. {
  26047. if (! isPositiveAndBelow (index, getNumOutputChannels()))
  26048. return false;
  26049. return true;
  26050. }
  26051. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26052. {
  26053. getCurrentProgramStateInformation (destData);
  26054. }
  26055. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26056. {
  26057. CFPropertyListRef propertyList = 0;
  26058. UInt32 sz = sizeof (CFPropertyListRef);
  26059. if (AudioUnitGetProperty (audioUnit,
  26060. kAudioUnitProperty_ClassInfo,
  26061. kAudioUnitScope_Global,
  26062. 0, &propertyList, &sz) == noErr)
  26063. {
  26064. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26065. CFWriteStreamOpen (stream);
  26066. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26067. CFWriteStreamClose (stream);
  26068. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26069. destData.setSize (bytesWritten);
  26070. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26071. CFRelease (data);
  26072. CFRelease (stream);
  26073. CFRelease (propertyList);
  26074. }
  26075. }
  26076. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26077. {
  26078. setCurrentProgramStateInformation (data, sizeInBytes);
  26079. }
  26080. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26081. {
  26082. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26083. (const UInt8*) data,
  26084. sizeInBytes,
  26085. kCFAllocatorNull);
  26086. CFReadStreamOpen (stream);
  26087. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26088. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26089. stream,
  26090. 0,
  26091. kCFPropertyListImmutable,
  26092. &format,
  26093. 0);
  26094. CFRelease (stream);
  26095. if (propertyList != 0)
  26096. AudioUnitSetProperty (audioUnit,
  26097. kAudioUnitProperty_ClassInfo,
  26098. kAudioUnitScope_Global,
  26099. 0, &propertyList, sizeof (propertyList));
  26100. }
  26101. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26102. {
  26103. }
  26104. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26105. {
  26106. }
  26107. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26108. const String& fileOrIdentifier)
  26109. {
  26110. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26111. return;
  26112. PluginDescription desc;
  26113. desc.fileOrIdentifier = fileOrIdentifier;
  26114. desc.uid = 0;
  26115. try
  26116. {
  26117. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26118. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26119. if (auInstance != 0)
  26120. {
  26121. auInstance->fillInPluginDescription (desc);
  26122. results.add (new PluginDescription (desc));
  26123. }
  26124. }
  26125. catch (...)
  26126. {
  26127. // crashed while loading...
  26128. }
  26129. }
  26130. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26131. {
  26132. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26133. {
  26134. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26135. if (result->audioUnit != 0)
  26136. {
  26137. result->initialise();
  26138. return result.release();
  26139. }
  26140. }
  26141. return 0;
  26142. }
  26143. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26144. const bool /*recursive*/)
  26145. {
  26146. StringArray result;
  26147. ComponentRecord* comp = 0;
  26148. ComponentDescription desc;
  26149. zerostruct (desc);
  26150. for (;;)
  26151. {
  26152. zerostruct (desc);
  26153. comp = FindNextComponent (comp, &desc);
  26154. if (comp == 0)
  26155. break;
  26156. GetComponentInfo (comp, &desc, 0, 0, 0);
  26157. if (desc.componentType == kAudioUnitType_MusicDevice
  26158. || desc.componentType == kAudioUnitType_MusicEffect
  26159. || desc.componentType == kAudioUnitType_Effect
  26160. || desc.componentType == kAudioUnitType_Generator
  26161. || desc.componentType == kAudioUnitType_Panner)
  26162. {
  26163. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26164. DBG (s);
  26165. result.add (s);
  26166. }
  26167. }
  26168. return result;
  26169. }
  26170. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26171. {
  26172. ComponentDescription desc;
  26173. String name, version, manufacturer;
  26174. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26175. return FindNextComponent (0, &desc) != 0;
  26176. const File f (fileOrIdentifier);
  26177. return f.hasFileExtension (".component")
  26178. && f.isDirectory();
  26179. }
  26180. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26181. {
  26182. ComponentDescription desc;
  26183. String name, version, manufacturer;
  26184. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26185. if (name.isEmpty())
  26186. name = fileOrIdentifier;
  26187. return name;
  26188. }
  26189. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26190. {
  26191. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26192. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26193. else
  26194. return File (desc.fileOrIdentifier).exists();
  26195. }
  26196. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26197. {
  26198. return FileSearchPath ("/(Default AudioUnit locations)");
  26199. }
  26200. #endif
  26201. END_JUCE_NAMESPACE
  26202. #undef log
  26203. #endif
  26204. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26205. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26206. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26207. #define JUCE_MAC_VST_INCLUDED 1
  26208. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26209. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26210. #if JUCE_WINDOWS
  26211. #undef _WIN32_WINNT
  26212. #define _WIN32_WINNT 0x500
  26213. #undef STRICT
  26214. #define STRICT
  26215. #include <windows.h>
  26216. #include <float.h>
  26217. #pragma warning (disable : 4312 4355)
  26218. #elif JUCE_LINUX
  26219. #include <float.h>
  26220. #include <sys/time.h>
  26221. #include <X11/Xlib.h>
  26222. #include <X11/Xutil.h>
  26223. #include <X11/Xatom.h>
  26224. #undef Font
  26225. #undef KeyPress
  26226. #undef Drawable
  26227. #undef Time
  26228. #else
  26229. #include <Cocoa/Cocoa.h>
  26230. #include <Carbon/Carbon.h>
  26231. #endif
  26232. #if ! (JUCE_MAC && JUCE_64BIT)
  26233. BEGIN_JUCE_NAMESPACE
  26234. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26235. #endif
  26236. #undef PRAGMA_ALIGN_SUPPORTED
  26237. #define VST_FORCE_DEPRECATED 0
  26238. #if JUCE_MSVC
  26239. #pragma warning (push)
  26240. #pragma warning (disable: 4996)
  26241. #endif
  26242. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26243. your include path if you want to add VST support.
  26244. If you're not interested in VSTs, you can disable them by changing the
  26245. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26246. */
  26247. #include <pluginterfaces/vst2.x/aeffectx.h>
  26248. #if JUCE_MSVC
  26249. #pragma warning (pop)
  26250. #endif
  26251. #if JUCE_LINUX
  26252. #define Font JUCE_NAMESPACE::Font
  26253. #define KeyPress JUCE_NAMESPACE::KeyPress
  26254. #define Drawable JUCE_NAMESPACE::Drawable
  26255. #define Time JUCE_NAMESPACE::Time
  26256. #endif
  26257. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26258. #ifdef __aeffect__
  26259. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26260. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26261. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26262. events to the list.
  26263. This is used by both the VST hosting code and the plugin wrapper.
  26264. */
  26265. class VSTMidiEventList
  26266. {
  26267. public:
  26268. VSTMidiEventList()
  26269. : numEventsUsed (0), numEventsAllocated (0)
  26270. {
  26271. }
  26272. ~VSTMidiEventList()
  26273. {
  26274. freeEvents();
  26275. }
  26276. void clear()
  26277. {
  26278. numEventsUsed = 0;
  26279. if (events != 0)
  26280. events->numEvents = 0;
  26281. }
  26282. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26283. {
  26284. ensureSize (numEventsUsed + 1);
  26285. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26286. events->numEvents = ++numEventsUsed;
  26287. if (numBytes <= 4)
  26288. {
  26289. if (e->type == kVstSysExType)
  26290. {
  26291. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26292. e->type = kVstMidiType;
  26293. e->byteSize = sizeof (VstMidiEvent);
  26294. e->noteLength = 0;
  26295. e->noteOffset = 0;
  26296. e->detune = 0;
  26297. e->noteOffVelocity = 0;
  26298. }
  26299. e->deltaFrames = frameOffset;
  26300. memcpy (e->midiData, midiData, numBytes);
  26301. }
  26302. else
  26303. {
  26304. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26305. if (se->type == kVstSysExType)
  26306. delete[] se->sysexDump;
  26307. se->sysexDump = new char [numBytes];
  26308. memcpy (se->sysexDump, midiData, numBytes);
  26309. se->type = kVstSysExType;
  26310. se->byteSize = sizeof (VstMidiSysexEvent);
  26311. se->deltaFrames = frameOffset;
  26312. se->flags = 0;
  26313. se->dumpBytes = numBytes;
  26314. se->resvd1 = 0;
  26315. se->resvd2 = 0;
  26316. }
  26317. }
  26318. // Handy method to pull the events out of an event buffer supplied by the host
  26319. // or plugin.
  26320. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26321. {
  26322. for (int i = 0; i < events->numEvents; ++i)
  26323. {
  26324. const VstEvent* const e = events->events[i];
  26325. if (e != 0)
  26326. {
  26327. if (e->type == kVstMidiType)
  26328. {
  26329. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26330. 4, e->deltaFrames);
  26331. }
  26332. else if (e->type == kVstSysExType)
  26333. {
  26334. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26335. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26336. e->deltaFrames);
  26337. }
  26338. }
  26339. }
  26340. }
  26341. void ensureSize (int numEventsNeeded)
  26342. {
  26343. if (numEventsNeeded > numEventsAllocated)
  26344. {
  26345. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26346. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26347. if (events == 0)
  26348. events.calloc (size, 1);
  26349. else
  26350. events.realloc (size, 1);
  26351. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26352. {
  26353. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26354. (int) sizeof (VstMidiSysexEvent)));
  26355. e->type = kVstMidiType;
  26356. e->byteSize = sizeof (VstMidiEvent);
  26357. events->events[i] = (VstEvent*) e;
  26358. }
  26359. numEventsAllocated = numEventsNeeded;
  26360. }
  26361. }
  26362. void freeEvents()
  26363. {
  26364. if (events != 0)
  26365. {
  26366. for (int i = numEventsAllocated; --i >= 0;)
  26367. {
  26368. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26369. if (e->type == kVstSysExType)
  26370. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26371. juce_free (e);
  26372. }
  26373. events.free();
  26374. numEventsUsed = 0;
  26375. numEventsAllocated = 0;
  26376. }
  26377. }
  26378. HeapBlock <VstEvents> events;
  26379. private:
  26380. int numEventsUsed, numEventsAllocated;
  26381. };
  26382. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26383. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26384. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26385. #if ! JUCE_WINDOWS
  26386. static void _fpreset() {}
  26387. static void _clearfp() {}
  26388. #endif
  26389. extern void juce_callAnyTimersSynchronously();
  26390. const int fxbVersionNum = 1;
  26391. struct fxProgram
  26392. {
  26393. long chunkMagic; // 'CcnK'
  26394. long byteSize; // of this chunk, excl. magic + byteSize
  26395. long fxMagic; // 'FxCk'
  26396. long version;
  26397. long fxID; // fx unique id
  26398. long fxVersion;
  26399. long numParams;
  26400. char prgName[28];
  26401. float params[1]; // variable no. of parameters
  26402. };
  26403. struct fxSet
  26404. {
  26405. long chunkMagic; // 'CcnK'
  26406. long byteSize; // of this chunk, excl. magic + byteSize
  26407. long fxMagic; // 'FxBk'
  26408. long version;
  26409. long fxID; // fx unique id
  26410. long fxVersion;
  26411. long numPrograms;
  26412. char future[128];
  26413. fxProgram programs[1]; // variable no. of programs
  26414. };
  26415. struct fxChunkSet
  26416. {
  26417. long chunkMagic; // 'CcnK'
  26418. long byteSize; // of this chunk, excl. magic + byteSize
  26419. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26420. long version;
  26421. long fxID; // fx unique id
  26422. long fxVersion;
  26423. long numPrograms;
  26424. char future[128];
  26425. long chunkSize;
  26426. char chunk[8]; // variable
  26427. };
  26428. struct fxProgramSet
  26429. {
  26430. long chunkMagic; // 'CcnK'
  26431. long byteSize; // of this chunk, excl. magic + byteSize
  26432. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26433. long version;
  26434. long fxID; // fx unique id
  26435. long fxVersion;
  26436. long numPrograms;
  26437. char name[28];
  26438. long chunkSize;
  26439. char chunk[8]; // variable
  26440. };
  26441. namespace
  26442. {
  26443. long vst_swap (const long x) throw()
  26444. {
  26445. #ifdef JUCE_LITTLE_ENDIAN
  26446. return (long) ByteOrder::swap ((uint32) x);
  26447. #else
  26448. return x;
  26449. #endif
  26450. }
  26451. float vst_swapFloat (const float x) throw()
  26452. {
  26453. #ifdef JUCE_LITTLE_ENDIAN
  26454. union { uint32 asInt; float asFloat; } n;
  26455. n.asFloat = x;
  26456. n.asInt = ByteOrder::swap (n.asInt);
  26457. return n.asFloat;
  26458. #else
  26459. return x;
  26460. #endif
  26461. }
  26462. double getVSTHostTimeNanoseconds()
  26463. {
  26464. #if JUCE_WINDOWS
  26465. return timeGetTime() * 1000000.0;
  26466. #elif JUCE_LINUX
  26467. timeval micro;
  26468. gettimeofday (&micro, 0);
  26469. return micro.tv_usec * 1000.0;
  26470. #elif JUCE_MAC
  26471. UnsignedWide micro;
  26472. Microseconds (&micro);
  26473. return micro.lo * 1000.0;
  26474. #endif
  26475. }
  26476. }
  26477. typedef AEffect* (VSTCALLBACK *MainCall) (audioMasterCallback);
  26478. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26479. static int shellUIDToCreate = 0;
  26480. static int insideVSTCallback = 0;
  26481. class VSTPluginWindow;
  26482. // Change this to disable logging of various VST activities
  26483. #ifndef VST_LOGGING
  26484. #define VST_LOGGING 1
  26485. #endif
  26486. #if VST_LOGGING
  26487. #define log(a) Logger::writeToLog(a);
  26488. #else
  26489. #define log(a)
  26490. #endif
  26491. #if JUCE_MAC && JUCE_PPC
  26492. static void* NewCFMFromMachO (void* const machofp) throw()
  26493. {
  26494. void* result = (void*) new char[8];
  26495. ((void**) result)[0] = machofp;
  26496. ((void**) result)[1] = result;
  26497. return result;
  26498. }
  26499. #endif
  26500. #if JUCE_LINUX
  26501. extern Display* display;
  26502. extern XContext windowHandleXContext;
  26503. typedef void (*EventProcPtr) (XEvent* ev);
  26504. static bool xErrorTriggered;
  26505. namespace
  26506. {
  26507. int temporaryErrorHandler (Display*, XErrorEvent*)
  26508. {
  26509. xErrorTriggered = true;
  26510. return 0;
  26511. }
  26512. int getPropertyFromXWindow (Window handle, Atom atom)
  26513. {
  26514. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26515. xErrorTriggered = false;
  26516. int userSize;
  26517. unsigned long bytes, userCount;
  26518. unsigned char* data;
  26519. Atom userType;
  26520. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26521. &userType, &userSize, &userCount, &bytes, &data);
  26522. XSetErrorHandler (oldErrorHandler);
  26523. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26524. : 0;
  26525. }
  26526. Window getChildWindow (Window windowToCheck)
  26527. {
  26528. Window rootWindow, parentWindow;
  26529. Window* childWindows;
  26530. unsigned int numChildren;
  26531. XQueryTree (display,
  26532. windowToCheck,
  26533. &rootWindow,
  26534. &parentWindow,
  26535. &childWindows,
  26536. &numChildren);
  26537. if (numChildren > 0)
  26538. return childWindows [0];
  26539. return 0;
  26540. }
  26541. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26542. {
  26543. if (e.mods.isLeftButtonDown())
  26544. {
  26545. ev.xbutton.button = Button1;
  26546. ev.xbutton.state |= Button1Mask;
  26547. }
  26548. else if (e.mods.isRightButtonDown())
  26549. {
  26550. ev.xbutton.button = Button3;
  26551. ev.xbutton.state |= Button3Mask;
  26552. }
  26553. else if (e.mods.isMiddleButtonDown())
  26554. {
  26555. ev.xbutton.button = Button2;
  26556. ev.xbutton.state |= Button2Mask;
  26557. }
  26558. }
  26559. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26560. {
  26561. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26562. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26563. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26564. }
  26565. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26566. {
  26567. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26568. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26569. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26570. }
  26571. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26572. {
  26573. if (increment < 0)
  26574. {
  26575. ev.xbutton.button = Button5;
  26576. ev.xbutton.state |= Button5Mask;
  26577. }
  26578. else if (increment > 0)
  26579. {
  26580. ev.xbutton.button = Button4;
  26581. ev.xbutton.state |= Button4Mask;
  26582. }
  26583. }
  26584. }
  26585. #endif
  26586. class ModuleHandle : public ReferenceCountedObject
  26587. {
  26588. public:
  26589. File file;
  26590. MainCall moduleMain;
  26591. String pluginName;
  26592. static Array <ModuleHandle*>& getActiveModules()
  26593. {
  26594. static Array <ModuleHandle*> activeModules;
  26595. return activeModules;
  26596. }
  26597. static ModuleHandle* findOrCreateModule (const File& file)
  26598. {
  26599. for (int i = getActiveModules().size(); --i >= 0;)
  26600. {
  26601. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26602. if (module->file == file)
  26603. return module;
  26604. }
  26605. _fpreset(); // (doesn't do any harm)
  26606. ++insideVSTCallback;
  26607. shellUIDToCreate = 0;
  26608. log ("Attempting to load VST: " + file.getFullPathName());
  26609. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26610. if (! m->open())
  26611. m = 0;
  26612. --insideVSTCallback;
  26613. _fpreset(); // (doesn't do any harm)
  26614. return m.release();
  26615. }
  26616. ModuleHandle (const File& file_)
  26617. : file (file_),
  26618. moduleMain (0),
  26619. #if JUCE_WINDOWS || JUCE_LINUX
  26620. hModule (0)
  26621. #elif JUCE_MAC
  26622. fragId (0),
  26623. resHandle (0),
  26624. bundleRef (0),
  26625. resFileId (0)
  26626. #endif
  26627. {
  26628. getActiveModules().add (this);
  26629. #if JUCE_WINDOWS || JUCE_LINUX
  26630. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26631. #elif JUCE_MAC
  26632. FSRef ref;
  26633. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26634. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26635. #endif
  26636. }
  26637. ~ModuleHandle()
  26638. {
  26639. getActiveModules().removeValue (this);
  26640. close();
  26641. }
  26642. #if JUCE_WINDOWS || JUCE_LINUX
  26643. void* hModule;
  26644. String fullParentDirectoryPathName;
  26645. bool open()
  26646. {
  26647. #if JUCE_WINDOWS
  26648. static bool timePeriodSet = false;
  26649. if (! timePeriodSet)
  26650. {
  26651. timePeriodSet = true;
  26652. timeBeginPeriod (2);
  26653. }
  26654. #endif
  26655. pluginName = file.getFileNameWithoutExtension();
  26656. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26657. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26658. if (moduleMain == 0)
  26659. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26660. return moduleMain != 0;
  26661. }
  26662. void close()
  26663. {
  26664. _fpreset(); // (doesn't do any harm)
  26665. PlatformUtilities::freeDynamicLibrary (hModule);
  26666. }
  26667. void closeEffect (AEffect* eff)
  26668. {
  26669. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26670. }
  26671. #else
  26672. CFragConnectionID fragId;
  26673. Handle resHandle;
  26674. CFBundleRef bundleRef;
  26675. FSSpec parentDirFSSpec;
  26676. short resFileId;
  26677. bool open()
  26678. {
  26679. bool ok = false;
  26680. const String filename (file.getFullPathName());
  26681. if (file.hasFileExtension (".vst"))
  26682. {
  26683. const char* const utf8 = filename.toUTF8();
  26684. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26685. strlen (utf8), file.isDirectory());
  26686. if (url != 0)
  26687. {
  26688. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26689. CFRelease (url);
  26690. if (bundleRef != 0)
  26691. {
  26692. if (CFBundleLoadExecutable (bundleRef))
  26693. {
  26694. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26695. if (moduleMain == 0)
  26696. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26697. if (moduleMain != 0)
  26698. {
  26699. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26700. if (name != 0)
  26701. {
  26702. if (CFGetTypeID (name) == CFStringGetTypeID())
  26703. {
  26704. char buffer[1024];
  26705. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26706. pluginName = buffer;
  26707. }
  26708. }
  26709. if (pluginName.isEmpty())
  26710. pluginName = file.getFileNameWithoutExtension();
  26711. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26712. ok = true;
  26713. }
  26714. }
  26715. if (! ok)
  26716. {
  26717. CFBundleUnloadExecutable (bundleRef);
  26718. CFRelease (bundleRef);
  26719. bundleRef = 0;
  26720. }
  26721. }
  26722. }
  26723. }
  26724. #if JUCE_PPC
  26725. else
  26726. {
  26727. FSRef fn;
  26728. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26729. {
  26730. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26731. if (resFileId != -1)
  26732. {
  26733. const int numEffs = Count1Resources ('aEff');
  26734. for (int i = 0; i < numEffs; ++i)
  26735. {
  26736. resHandle = Get1IndResource ('aEff', i + 1);
  26737. if (resHandle != 0)
  26738. {
  26739. OSType type;
  26740. Str255 name;
  26741. SInt16 id;
  26742. GetResInfo (resHandle, &id, &type, name);
  26743. pluginName = String ((const char*) name + 1, name[0]);
  26744. DetachResource (resHandle);
  26745. HLock (resHandle);
  26746. Ptr ptr;
  26747. Str255 errorText;
  26748. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26749. name, kPrivateCFragCopy,
  26750. &fragId, &ptr, errorText);
  26751. if (err == noErr)
  26752. {
  26753. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26754. ok = true;
  26755. }
  26756. else
  26757. {
  26758. HUnlock (resHandle);
  26759. }
  26760. break;
  26761. }
  26762. }
  26763. if (! ok)
  26764. CloseResFile (resFileId);
  26765. }
  26766. }
  26767. }
  26768. #endif
  26769. return ok;
  26770. }
  26771. void close()
  26772. {
  26773. #if JUCE_PPC
  26774. if (fragId != 0)
  26775. {
  26776. if (moduleMain != 0)
  26777. disposeMachOFromCFM ((void*) moduleMain);
  26778. CloseConnection (&fragId);
  26779. HUnlock (resHandle);
  26780. if (resFileId != 0)
  26781. CloseResFile (resFileId);
  26782. }
  26783. else
  26784. #endif
  26785. if (bundleRef != 0)
  26786. {
  26787. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26788. if (CFGetRetainCount (bundleRef) == 1)
  26789. CFBundleUnloadExecutable (bundleRef);
  26790. if (CFGetRetainCount (bundleRef) > 0)
  26791. CFRelease (bundleRef);
  26792. }
  26793. }
  26794. void closeEffect (AEffect* eff)
  26795. {
  26796. #if JUCE_PPC
  26797. if (fragId != 0)
  26798. {
  26799. Array<void*> thingsToDelete;
  26800. thingsToDelete.add ((void*) eff->dispatcher);
  26801. thingsToDelete.add ((void*) eff->process);
  26802. thingsToDelete.add ((void*) eff->setParameter);
  26803. thingsToDelete.add ((void*) eff->getParameter);
  26804. thingsToDelete.add ((void*) eff->processReplacing);
  26805. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26806. for (int i = thingsToDelete.size(); --i >= 0;)
  26807. disposeMachOFromCFM (thingsToDelete[i]);
  26808. }
  26809. else
  26810. #endif
  26811. {
  26812. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26813. }
  26814. }
  26815. #if JUCE_PPC
  26816. static void* newMachOFromCFM (void* cfmfp)
  26817. {
  26818. if (cfmfp == 0)
  26819. return 0;
  26820. UInt32* const mfp = new UInt32[6];
  26821. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26822. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26823. mfp[2] = 0x800c0000;
  26824. mfp[3] = 0x804c0004;
  26825. mfp[4] = 0x7c0903a6;
  26826. mfp[5] = 0x4e800420;
  26827. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26828. return mfp;
  26829. }
  26830. static void disposeMachOFromCFM (void* ptr)
  26831. {
  26832. delete[] static_cast <UInt32*> (ptr);
  26833. }
  26834. void coerceAEffectFunctionCalls (AEffect* eff)
  26835. {
  26836. if (fragId != 0)
  26837. {
  26838. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26839. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26840. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26841. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26842. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26843. }
  26844. }
  26845. #endif
  26846. #endif
  26847. private:
  26848. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleHandle);
  26849. };
  26850. /**
  26851. An instance of a plugin, created by a VSTPluginFormat.
  26852. */
  26853. class VSTPluginInstance : public AudioPluginInstance,
  26854. private Timer,
  26855. private AsyncUpdater
  26856. {
  26857. public:
  26858. ~VSTPluginInstance();
  26859. // AudioPluginInstance methods:
  26860. void fillInPluginDescription (PluginDescription& desc) const
  26861. {
  26862. desc.name = name;
  26863. {
  26864. char buffer [512];
  26865. zerostruct (buffer);
  26866. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26867. desc.descriptiveName = String (buffer).trim();
  26868. if (desc.descriptiveName.isEmpty())
  26869. desc.descriptiveName = name;
  26870. }
  26871. desc.fileOrIdentifier = module->file.getFullPathName();
  26872. desc.uid = getUID();
  26873. desc.lastFileModTime = module->file.getLastModificationTime();
  26874. desc.pluginFormatName = "VST";
  26875. desc.category = getCategory();
  26876. {
  26877. char buffer [kVstMaxVendorStrLen + 8];
  26878. zerostruct (buffer);
  26879. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26880. desc.manufacturerName = buffer;
  26881. }
  26882. desc.version = getVersion();
  26883. desc.numInputChannels = getNumInputChannels();
  26884. desc.numOutputChannels = getNumOutputChannels();
  26885. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26886. }
  26887. void* getPlatformSpecificData() { return effect; }
  26888. const String getName() const { return name; }
  26889. int getUID() const;
  26890. bool acceptsMidi() const { return wantsMidiMessages; }
  26891. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26892. // AudioProcessor methods:
  26893. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26894. void releaseResources();
  26895. void processBlock (AudioSampleBuffer& buffer,
  26896. MidiBuffer& midiMessages);
  26897. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26898. AudioProcessorEditor* createEditor();
  26899. const String getInputChannelName (int index) const;
  26900. bool isInputChannelStereoPair (int index) const;
  26901. const String getOutputChannelName (int index) const;
  26902. bool isOutputChannelStereoPair (int index) const;
  26903. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26904. float getParameter (int index);
  26905. void setParameter (int index, float newValue);
  26906. const String getParameterName (int index);
  26907. const String getParameterText (int index);
  26908. bool isParameterAutomatable (int index) const;
  26909. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26910. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26911. void setCurrentProgram (int index);
  26912. const String getProgramName (int index);
  26913. void changeProgramName (int index, const String& newName);
  26914. void getStateInformation (MemoryBlock& destData);
  26915. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26916. void setStateInformation (const void* data, int sizeInBytes);
  26917. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26918. void timerCallback();
  26919. void handleAsyncUpdate();
  26920. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26921. private:
  26922. friend class VSTPluginWindow;
  26923. friend class VSTPluginFormat;
  26924. AEffect* effect;
  26925. String name;
  26926. CriticalSection lock;
  26927. bool wantsMidiMessages, initialised, isPowerOn;
  26928. mutable StringArray programNames;
  26929. AudioSampleBuffer tempBuffer;
  26930. CriticalSection midiInLock;
  26931. MidiBuffer incomingMidi;
  26932. VSTMidiEventList midiEventsToSend;
  26933. VstTimeInfo vstHostTime;
  26934. ReferenceCountedObjectPtr <ModuleHandle> module;
  26935. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26936. bool restoreProgramSettings (const fxProgram* const prog);
  26937. const String getCurrentProgramName();
  26938. void setParamsInProgramBlock (fxProgram* const prog);
  26939. void updateStoredProgramNames();
  26940. void initialise();
  26941. void handleMidiFromPlugin (const VstEvents* const events);
  26942. void createTempParameterStore (MemoryBlock& dest);
  26943. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26944. const String getParameterLabel (int index) const;
  26945. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26946. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26947. void setChunkData (const char* data, int size, bool isPreset);
  26948. bool loadFromFXBFile (const void* data, int numBytes);
  26949. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26950. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26951. const String getVersion() const;
  26952. const String getCategory() const;
  26953. void setPower (const bool on);
  26954. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26955. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginInstance);
  26956. };
  26957. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26958. : effect (0),
  26959. wantsMidiMessages (false),
  26960. initialised (false),
  26961. isPowerOn (false),
  26962. tempBuffer (1, 1),
  26963. module (module_)
  26964. {
  26965. try
  26966. {
  26967. _fpreset();
  26968. ++insideVSTCallback;
  26969. name = module->pluginName;
  26970. log ("Creating VST instance: " + name);
  26971. #if JUCE_MAC
  26972. if (module->resFileId != 0)
  26973. UseResFile (module->resFileId);
  26974. #if JUCE_PPC
  26975. if (module->fragId != 0)
  26976. {
  26977. static void* audioMasterCoerced = 0;
  26978. if (audioMasterCoerced == 0)
  26979. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26980. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26981. }
  26982. else
  26983. #endif
  26984. #endif
  26985. {
  26986. effect = module->moduleMain (&audioMaster);
  26987. }
  26988. --insideVSTCallback;
  26989. if (effect != 0 && effect->magic == kEffectMagic)
  26990. {
  26991. #if JUCE_PPC
  26992. module->coerceAEffectFunctionCalls (effect);
  26993. #endif
  26994. jassert (effect->resvd2 == 0);
  26995. jassert (effect->object != 0);
  26996. _fpreset(); // some dodgy plugs fuck around with this
  26997. }
  26998. else
  26999. {
  27000. effect = 0;
  27001. }
  27002. }
  27003. catch (...)
  27004. {
  27005. --insideVSTCallback;
  27006. }
  27007. }
  27008. VSTPluginInstance::~VSTPluginInstance()
  27009. {
  27010. const ScopedLock sl (lock);
  27011. jassert (insideVSTCallback == 0);
  27012. if (effect != 0 && effect->magic == kEffectMagic)
  27013. {
  27014. try
  27015. {
  27016. #if JUCE_MAC
  27017. if (module->resFileId != 0)
  27018. UseResFile (module->resFileId);
  27019. #endif
  27020. // Must delete any editors before deleting the plugin instance!
  27021. jassert (getActiveEditor() == 0);
  27022. _fpreset(); // some dodgy plugs fuck around with this
  27023. module->closeEffect (effect);
  27024. }
  27025. catch (...)
  27026. {}
  27027. }
  27028. module = 0;
  27029. effect = 0;
  27030. }
  27031. void VSTPluginInstance::initialise()
  27032. {
  27033. if (initialised || effect == 0)
  27034. return;
  27035. log ("Initialising VST: " + module->pluginName);
  27036. initialised = true;
  27037. dispatch (effIdentify, 0, 0, 0, 0);
  27038. if (getSampleRate() > 0)
  27039. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27040. if (getBlockSize() > 0)
  27041. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27042. dispatch (effOpen, 0, 0, 0, 0);
  27043. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27044. getSampleRate(), getBlockSize());
  27045. if (getNumPrograms() > 1)
  27046. setCurrentProgram (0);
  27047. else
  27048. dispatch (effSetProgram, 0, 0, 0, 0);
  27049. int i;
  27050. for (i = effect->numInputs; --i >= 0;)
  27051. dispatch (effConnectInput, i, 1, 0, 0);
  27052. for (i = effect->numOutputs; --i >= 0;)
  27053. dispatch (effConnectOutput, i, 1, 0, 0);
  27054. updateStoredProgramNames();
  27055. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27056. setLatencySamples (effect->initialDelay);
  27057. }
  27058. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27059. int samplesPerBlockExpected)
  27060. {
  27061. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27062. sampleRate_, samplesPerBlockExpected);
  27063. setLatencySamples (effect->initialDelay);
  27064. vstHostTime.tempo = 120.0;
  27065. vstHostTime.timeSigNumerator = 4;
  27066. vstHostTime.timeSigDenominator = 4;
  27067. vstHostTime.sampleRate = sampleRate_;
  27068. vstHostTime.samplePos = 0;
  27069. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27070. initialise();
  27071. if (initialised)
  27072. {
  27073. wantsMidiMessages = wantsMidiMessages
  27074. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27075. if (wantsMidiMessages)
  27076. midiEventsToSend.ensureSize (256);
  27077. else
  27078. midiEventsToSend.freeEvents();
  27079. incomingMidi.clear();
  27080. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27081. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27082. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27083. if (! isPowerOn)
  27084. setPower (true);
  27085. // dodgy hack to force some plugins to initialise the sample rate..
  27086. if ((! hasEditor()) && getNumParameters() > 0)
  27087. {
  27088. const float old = getParameter (0);
  27089. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27090. setParameter (0, old);
  27091. }
  27092. dispatch (effStartProcess, 0, 0, 0, 0);
  27093. }
  27094. }
  27095. void VSTPluginInstance::releaseResources()
  27096. {
  27097. if (initialised)
  27098. {
  27099. dispatch (effStopProcess, 0, 0, 0, 0);
  27100. setPower (false);
  27101. }
  27102. tempBuffer.setSize (1, 1);
  27103. incomingMidi.clear();
  27104. midiEventsToSend.freeEvents();
  27105. }
  27106. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27107. MidiBuffer& midiMessages)
  27108. {
  27109. const int numSamples = buffer.getNumSamples();
  27110. if (initialised)
  27111. {
  27112. AudioPlayHead* playHead = getPlayHead();
  27113. if (playHead != 0)
  27114. {
  27115. AudioPlayHead::CurrentPositionInfo position;
  27116. playHead->getCurrentPosition (position);
  27117. vstHostTime.tempo = position.bpm;
  27118. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27119. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27120. vstHostTime.ppqPos = position.ppqPosition;
  27121. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27122. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27123. if (position.isPlaying)
  27124. vstHostTime.flags |= kVstTransportPlaying;
  27125. else
  27126. vstHostTime.flags &= ~kVstTransportPlaying;
  27127. }
  27128. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27129. if (wantsMidiMessages)
  27130. {
  27131. midiEventsToSend.clear();
  27132. midiEventsToSend.ensureSize (1);
  27133. MidiBuffer::Iterator iter (midiMessages);
  27134. const uint8* midiData;
  27135. int numBytesOfMidiData, samplePosition;
  27136. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27137. {
  27138. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27139. jlimit (0, numSamples - 1, samplePosition));
  27140. }
  27141. try
  27142. {
  27143. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27144. }
  27145. catch (...)
  27146. {}
  27147. }
  27148. _clearfp();
  27149. if ((effect->flags & effFlagsCanReplacing) != 0)
  27150. {
  27151. try
  27152. {
  27153. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27154. }
  27155. catch (...)
  27156. {}
  27157. }
  27158. else
  27159. {
  27160. tempBuffer.setSize (effect->numOutputs, numSamples);
  27161. tempBuffer.clear();
  27162. try
  27163. {
  27164. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27165. }
  27166. catch (...)
  27167. {}
  27168. for (int i = effect->numOutputs; --i >= 0;)
  27169. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27170. }
  27171. }
  27172. else
  27173. {
  27174. // Not initialised, so just bypass..
  27175. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27176. buffer.clear (i, 0, buffer.getNumSamples());
  27177. }
  27178. {
  27179. // copy any incoming midi..
  27180. const ScopedLock sl (midiInLock);
  27181. midiMessages.swapWith (incomingMidi);
  27182. incomingMidi.clear();
  27183. }
  27184. }
  27185. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27186. {
  27187. if (events != 0)
  27188. {
  27189. const ScopedLock sl (midiInLock);
  27190. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27191. }
  27192. }
  27193. static Array <VSTPluginWindow*> activeVSTWindows;
  27194. class VSTPluginWindow : public AudioProcessorEditor,
  27195. #if ! JUCE_MAC
  27196. public ComponentMovementWatcher,
  27197. #endif
  27198. public Timer
  27199. {
  27200. public:
  27201. VSTPluginWindow (VSTPluginInstance& plugin_)
  27202. : AudioProcessorEditor (&plugin_),
  27203. #if ! JUCE_MAC
  27204. ComponentMovementWatcher (this),
  27205. #endif
  27206. plugin (plugin_),
  27207. isOpen (false),
  27208. recursiveResize (false),
  27209. pluginWantsKeys (false),
  27210. pluginRefusesToResize (false),
  27211. alreadyInside (false)
  27212. {
  27213. #if JUCE_WINDOWS
  27214. sizeCheckCount = 0;
  27215. pluginHWND = 0;
  27216. #elif JUCE_LINUX
  27217. pluginWindow = None;
  27218. pluginProc = None;
  27219. #else
  27220. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27221. #endif
  27222. activeVSTWindows.add (this);
  27223. setSize (1, 1);
  27224. setOpaque (true);
  27225. setVisible (true);
  27226. }
  27227. ~VSTPluginWindow()
  27228. {
  27229. #if JUCE_MAC
  27230. innerWrapper = 0;
  27231. #else
  27232. closePluginWindow();
  27233. #endif
  27234. activeVSTWindows.removeValue (this);
  27235. plugin.editorBeingDeleted (this);
  27236. }
  27237. #if ! JUCE_MAC
  27238. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27239. {
  27240. if (recursiveResize)
  27241. return;
  27242. Component* const topComp = getTopLevelComponent();
  27243. if (topComp->getPeer() != 0)
  27244. {
  27245. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27246. recursiveResize = true;
  27247. #if JUCE_WINDOWS
  27248. if (pluginHWND != 0)
  27249. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27250. #elif JUCE_LINUX
  27251. if (pluginWindow != 0)
  27252. {
  27253. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27254. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27255. XMapRaised (display, pluginWindow);
  27256. }
  27257. #endif
  27258. recursiveResize = false;
  27259. }
  27260. }
  27261. void componentVisibilityChanged()
  27262. {
  27263. if (isShowing())
  27264. openPluginWindow();
  27265. else
  27266. closePluginWindow();
  27267. componentMovedOrResized (true, true);
  27268. }
  27269. void componentPeerChanged()
  27270. {
  27271. closePluginWindow();
  27272. openPluginWindow();
  27273. }
  27274. #endif
  27275. bool keyStateChanged (bool)
  27276. {
  27277. return pluginWantsKeys;
  27278. }
  27279. bool keyPressed (const KeyPress&)
  27280. {
  27281. return pluginWantsKeys;
  27282. }
  27283. #if JUCE_MAC
  27284. void paint (Graphics& g)
  27285. {
  27286. g.fillAll (Colours::black);
  27287. }
  27288. #else
  27289. void paint (Graphics& g)
  27290. {
  27291. if (isOpen)
  27292. {
  27293. ComponentPeer* const peer = getPeer();
  27294. if (peer != 0)
  27295. {
  27296. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27297. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27298. #if JUCE_LINUX
  27299. if (pluginWindow != 0)
  27300. {
  27301. const Rectangle<int> clip (g.getClipBounds());
  27302. XEvent ev;
  27303. zerostruct (ev);
  27304. ev.xexpose.type = Expose;
  27305. ev.xexpose.display = display;
  27306. ev.xexpose.window = pluginWindow;
  27307. ev.xexpose.x = clip.getX();
  27308. ev.xexpose.y = clip.getY();
  27309. ev.xexpose.width = clip.getWidth();
  27310. ev.xexpose.height = clip.getHeight();
  27311. sendEventToChild (&ev);
  27312. }
  27313. #endif
  27314. }
  27315. }
  27316. else
  27317. {
  27318. g.fillAll (Colours::black);
  27319. }
  27320. }
  27321. #endif
  27322. void timerCallback()
  27323. {
  27324. #if JUCE_WINDOWS
  27325. if (--sizeCheckCount <= 0)
  27326. {
  27327. sizeCheckCount = 10;
  27328. checkPluginWindowSize();
  27329. }
  27330. #endif
  27331. try
  27332. {
  27333. static bool reentrant = false;
  27334. if (! reentrant)
  27335. {
  27336. reentrant = true;
  27337. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27338. reentrant = false;
  27339. }
  27340. }
  27341. catch (...)
  27342. {}
  27343. }
  27344. void mouseDown (const MouseEvent& e)
  27345. {
  27346. #if JUCE_LINUX
  27347. if (pluginWindow == 0)
  27348. return;
  27349. toFront (true);
  27350. XEvent ev;
  27351. zerostruct (ev);
  27352. ev.xbutton.display = display;
  27353. ev.xbutton.type = ButtonPress;
  27354. ev.xbutton.window = pluginWindow;
  27355. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27356. ev.xbutton.time = CurrentTime;
  27357. ev.xbutton.x = e.x;
  27358. ev.xbutton.y = e.y;
  27359. ev.xbutton.x_root = e.getScreenX();
  27360. ev.xbutton.y_root = e.getScreenY();
  27361. translateJuceToXButtonModifiers (e, ev);
  27362. sendEventToChild (&ev);
  27363. #elif JUCE_WINDOWS
  27364. (void) e;
  27365. toFront (true);
  27366. #endif
  27367. }
  27368. void broughtToFront()
  27369. {
  27370. activeVSTWindows.removeValue (this);
  27371. activeVSTWindows.add (this);
  27372. #if JUCE_MAC
  27373. dispatch (effEditTop, 0, 0, 0, 0);
  27374. #endif
  27375. }
  27376. private:
  27377. VSTPluginInstance& plugin;
  27378. bool isOpen, recursiveResize;
  27379. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27380. #if JUCE_WINDOWS
  27381. HWND pluginHWND;
  27382. void* originalWndProc;
  27383. int sizeCheckCount;
  27384. #elif JUCE_LINUX
  27385. Window pluginWindow;
  27386. EventProcPtr pluginProc;
  27387. #endif
  27388. #if JUCE_MAC
  27389. void openPluginWindow (WindowRef parentWindow)
  27390. {
  27391. if (isOpen || parentWindow == 0)
  27392. return;
  27393. isOpen = true;
  27394. ERect* rect = 0;
  27395. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27396. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27397. // do this before and after like in the steinberg example
  27398. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27399. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27400. // Install keyboard hooks
  27401. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27402. // double-check it's not too tiny
  27403. int w = 250, h = 150;
  27404. if (rect != 0)
  27405. {
  27406. w = rect->right - rect->left;
  27407. h = rect->bottom - rect->top;
  27408. if (w == 0 || h == 0)
  27409. {
  27410. w = 250;
  27411. h = 150;
  27412. }
  27413. }
  27414. w = jmax (w, 32);
  27415. h = jmax (h, 32);
  27416. setSize (w, h);
  27417. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27418. repaint();
  27419. }
  27420. #else
  27421. void openPluginWindow()
  27422. {
  27423. if (isOpen || getWindowHandle() == 0)
  27424. return;
  27425. log ("Opening VST UI: " + plugin.name);
  27426. isOpen = true;
  27427. ERect* rect = 0;
  27428. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27429. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27430. // do this before and after like in the steinberg example
  27431. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27432. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27433. // Install keyboard hooks
  27434. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27435. #if JUCE_WINDOWS
  27436. originalWndProc = 0;
  27437. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27438. if (pluginHWND == 0)
  27439. {
  27440. isOpen = false;
  27441. setSize (300, 150);
  27442. return;
  27443. }
  27444. #pragma warning (push)
  27445. #pragma warning (disable: 4244)
  27446. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27447. if (! pluginWantsKeys)
  27448. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27449. #pragma warning (pop)
  27450. int w, h;
  27451. RECT r;
  27452. GetWindowRect (pluginHWND, &r);
  27453. w = r.right - r.left;
  27454. h = r.bottom - r.top;
  27455. if (rect != 0)
  27456. {
  27457. const int rw = rect->right - rect->left;
  27458. const int rh = rect->bottom - rect->top;
  27459. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27460. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27461. {
  27462. // very dodgy logic to decide which size is right.
  27463. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27464. {
  27465. SetWindowPos (pluginHWND, 0,
  27466. 0, 0, rw, rh,
  27467. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27468. GetWindowRect (pluginHWND, &r);
  27469. w = r.right - r.left;
  27470. h = r.bottom - r.top;
  27471. pluginRefusesToResize = (w != rw) || (h != rh);
  27472. w = rw;
  27473. h = rh;
  27474. }
  27475. }
  27476. }
  27477. #elif JUCE_LINUX
  27478. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27479. if (pluginWindow != 0)
  27480. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27481. XInternAtom (display, "_XEventProc", False));
  27482. int w = 250, h = 150;
  27483. if (rect != 0)
  27484. {
  27485. w = rect->right - rect->left;
  27486. h = rect->bottom - rect->top;
  27487. if (w == 0 || h == 0)
  27488. {
  27489. w = 250;
  27490. h = 150;
  27491. }
  27492. }
  27493. if (pluginWindow != 0)
  27494. XMapRaised (display, pluginWindow);
  27495. #endif
  27496. // double-check it's not too tiny
  27497. w = jmax (w, 32);
  27498. h = jmax (h, 32);
  27499. setSize (w, h);
  27500. #if JUCE_WINDOWS
  27501. checkPluginWindowSize();
  27502. #endif
  27503. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27504. repaint();
  27505. }
  27506. #endif
  27507. #if ! JUCE_MAC
  27508. void closePluginWindow()
  27509. {
  27510. if (isOpen)
  27511. {
  27512. log ("Closing VST UI: " + plugin.getName());
  27513. isOpen = false;
  27514. dispatch (effEditClose, 0, 0, 0, 0);
  27515. #if JUCE_WINDOWS
  27516. #pragma warning (push)
  27517. #pragma warning (disable: 4244)
  27518. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27519. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27520. #pragma warning (pop)
  27521. stopTimer();
  27522. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27523. DestroyWindow (pluginHWND);
  27524. pluginHWND = 0;
  27525. #elif JUCE_LINUX
  27526. stopTimer();
  27527. pluginWindow = 0;
  27528. pluginProc = 0;
  27529. #endif
  27530. }
  27531. }
  27532. #endif
  27533. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27534. {
  27535. return plugin.dispatch (opcode, index, value, ptr, opt);
  27536. }
  27537. #if JUCE_WINDOWS
  27538. void checkPluginWindowSize()
  27539. {
  27540. RECT r;
  27541. GetWindowRect (pluginHWND, &r);
  27542. const int w = r.right - r.left;
  27543. const int h = r.bottom - r.top;
  27544. if (isShowing() && w > 0 && h > 0
  27545. && (w != getWidth() || h != getHeight())
  27546. && ! pluginRefusesToResize)
  27547. {
  27548. setSize (w, h);
  27549. sizeCheckCount = 0;
  27550. }
  27551. }
  27552. // hooks to get keyboard events from VST windows..
  27553. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27554. {
  27555. for (int i = activeVSTWindows.size(); --i >= 0;)
  27556. {
  27557. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27558. if (w->pluginHWND == hW)
  27559. {
  27560. if (message == WM_CHAR
  27561. || message == WM_KEYDOWN
  27562. || message == WM_SYSKEYDOWN
  27563. || message == WM_KEYUP
  27564. || message == WM_SYSKEYUP
  27565. || message == WM_APPCOMMAND)
  27566. {
  27567. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27568. message, wParam, lParam);
  27569. }
  27570. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27571. (HWND) w->pluginHWND,
  27572. message,
  27573. wParam,
  27574. lParam);
  27575. }
  27576. }
  27577. return DefWindowProc (hW, message, wParam, lParam);
  27578. }
  27579. #endif
  27580. #if JUCE_LINUX
  27581. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27582. void sendEventToChild (XEvent* event)
  27583. {
  27584. if (pluginProc != 0)
  27585. {
  27586. // if the plugin publishes an event procedure, pass the event directly..
  27587. pluginProc (event);
  27588. }
  27589. else if (pluginWindow != 0)
  27590. {
  27591. // if the plugin has a window, then send the event to the window so that
  27592. // its message thread will pick it up..
  27593. XSendEvent (display, pluginWindow, False, 0L, event);
  27594. XFlush (display);
  27595. }
  27596. }
  27597. void mouseEnter (const MouseEvent& e)
  27598. {
  27599. if (pluginWindow != 0)
  27600. {
  27601. XEvent ev;
  27602. zerostruct (ev);
  27603. ev.xcrossing.display = display;
  27604. ev.xcrossing.type = EnterNotify;
  27605. ev.xcrossing.window = pluginWindow;
  27606. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27607. ev.xcrossing.time = CurrentTime;
  27608. ev.xcrossing.x = e.x;
  27609. ev.xcrossing.y = e.y;
  27610. ev.xcrossing.x_root = e.getScreenX();
  27611. ev.xcrossing.y_root = e.getScreenY();
  27612. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27613. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27614. translateJuceToXCrossingModifiers (e, ev);
  27615. sendEventToChild (&ev);
  27616. }
  27617. }
  27618. void mouseExit (const MouseEvent& e)
  27619. {
  27620. if (pluginWindow != 0)
  27621. {
  27622. XEvent ev;
  27623. zerostruct (ev);
  27624. ev.xcrossing.display = display;
  27625. ev.xcrossing.type = LeaveNotify;
  27626. ev.xcrossing.window = pluginWindow;
  27627. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27628. ev.xcrossing.time = CurrentTime;
  27629. ev.xcrossing.x = e.x;
  27630. ev.xcrossing.y = e.y;
  27631. ev.xcrossing.x_root = e.getScreenX();
  27632. ev.xcrossing.y_root = e.getScreenY();
  27633. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27634. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27635. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27636. translateJuceToXCrossingModifiers (e, ev);
  27637. sendEventToChild (&ev);
  27638. }
  27639. }
  27640. void mouseMove (const MouseEvent& e)
  27641. {
  27642. if (pluginWindow != 0)
  27643. {
  27644. XEvent ev;
  27645. zerostruct (ev);
  27646. ev.xmotion.display = display;
  27647. ev.xmotion.type = MotionNotify;
  27648. ev.xmotion.window = pluginWindow;
  27649. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27650. ev.xmotion.time = CurrentTime;
  27651. ev.xmotion.is_hint = NotifyNormal;
  27652. ev.xmotion.x = e.x;
  27653. ev.xmotion.y = e.y;
  27654. ev.xmotion.x_root = e.getScreenX();
  27655. ev.xmotion.y_root = e.getScreenY();
  27656. sendEventToChild (&ev);
  27657. }
  27658. }
  27659. void mouseDrag (const MouseEvent& e)
  27660. {
  27661. if (pluginWindow != 0)
  27662. {
  27663. XEvent ev;
  27664. zerostruct (ev);
  27665. ev.xmotion.display = display;
  27666. ev.xmotion.type = MotionNotify;
  27667. ev.xmotion.window = pluginWindow;
  27668. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27669. ev.xmotion.time = CurrentTime;
  27670. ev.xmotion.x = e.x ;
  27671. ev.xmotion.y = e.y;
  27672. ev.xmotion.x_root = e.getScreenX();
  27673. ev.xmotion.y_root = e.getScreenY();
  27674. ev.xmotion.is_hint = NotifyNormal;
  27675. translateJuceToXMotionModifiers (e, ev);
  27676. sendEventToChild (&ev);
  27677. }
  27678. }
  27679. void mouseUp (const MouseEvent& e)
  27680. {
  27681. if (pluginWindow != 0)
  27682. {
  27683. XEvent ev;
  27684. zerostruct (ev);
  27685. ev.xbutton.display = display;
  27686. ev.xbutton.type = ButtonRelease;
  27687. ev.xbutton.window = pluginWindow;
  27688. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27689. ev.xbutton.time = CurrentTime;
  27690. ev.xbutton.x = e.x;
  27691. ev.xbutton.y = e.y;
  27692. ev.xbutton.x_root = e.getScreenX();
  27693. ev.xbutton.y_root = e.getScreenY();
  27694. translateJuceToXButtonModifiers (e, ev);
  27695. sendEventToChild (&ev);
  27696. }
  27697. }
  27698. void mouseWheelMove (const MouseEvent& e,
  27699. float incrementX,
  27700. float incrementY)
  27701. {
  27702. if (pluginWindow != 0)
  27703. {
  27704. XEvent ev;
  27705. zerostruct (ev);
  27706. ev.xbutton.display = display;
  27707. ev.xbutton.type = ButtonPress;
  27708. ev.xbutton.window = pluginWindow;
  27709. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27710. ev.xbutton.time = CurrentTime;
  27711. ev.xbutton.x = e.x;
  27712. ev.xbutton.y = e.y;
  27713. ev.xbutton.x_root = e.getScreenX();
  27714. ev.xbutton.y_root = e.getScreenY();
  27715. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27716. sendEventToChild (&ev);
  27717. // TODO - put a usleep here ?
  27718. ev.xbutton.type = ButtonRelease;
  27719. sendEventToChild (&ev);
  27720. }
  27721. }
  27722. #endif
  27723. #if JUCE_MAC
  27724. #if ! JUCE_SUPPORT_CARBON
  27725. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27726. #endif
  27727. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27728. {
  27729. public:
  27730. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27731. : owner (owner_),
  27732. alreadyInside (false)
  27733. {
  27734. }
  27735. ~InnerWrapperComponent()
  27736. {
  27737. deleteWindow();
  27738. }
  27739. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27740. {
  27741. owner->openPluginWindow (windowRef);
  27742. return 0;
  27743. }
  27744. void removeView (HIViewRef)
  27745. {
  27746. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27747. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27748. }
  27749. bool getEmbeddedViewSize (int& w, int& h)
  27750. {
  27751. ERect* rect = 0;
  27752. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27753. w = rect->right - rect->left;
  27754. h = rect->bottom - rect->top;
  27755. return true;
  27756. }
  27757. void mouseDown (int x, int y)
  27758. {
  27759. if (! alreadyInside)
  27760. {
  27761. alreadyInside = true;
  27762. getTopLevelComponent()->toFront (true);
  27763. owner->dispatch (effEditMouse, x, y, 0, 0);
  27764. alreadyInside = false;
  27765. }
  27766. else
  27767. {
  27768. PostEvent (::mouseDown, 0);
  27769. }
  27770. }
  27771. void paint()
  27772. {
  27773. ComponentPeer* const peer = getPeer();
  27774. if (peer != 0)
  27775. {
  27776. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27777. ERect r;
  27778. r.left = pos.getX();
  27779. r.right = r.left + getWidth();
  27780. r.top = pos.getY();
  27781. r.bottom = r.top + getHeight();
  27782. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27783. }
  27784. }
  27785. private:
  27786. VSTPluginWindow* const owner;
  27787. bool alreadyInside;
  27788. };
  27789. friend class InnerWrapperComponent;
  27790. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27791. void resized()
  27792. {
  27793. innerWrapper->setSize (getWidth(), getHeight());
  27794. }
  27795. #endif
  27796. private:
  27797. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow);
  27798. };
  27799. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27800. {
  27801. if (hasEditor())
  27802. return new VSTPluginWindow (*this);
  27803. return 0;
  27804. }
  27805. void VSTPluginInstance::handleAsyncUpdate()
  27806. {
  27807. // indicates that something about the plugin has changed..
  27808. updateHostDisplay();
  27809. }
  27810. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27811. {
  27812. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27813. {
  27814. changeProgramName (getCurrentProgram(), prog->prgName);
  27815. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27816. setParameter (i, vst_swapFloat (prog->params[i]));
  27817. return true;
  27818. }
  27819. return false;
  27820. }
  27821. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27822. const int dataSize)
  27823. {
  27824. if (dataSize < 28)
  27825. return false;
  27826. const fxSet* const set = (const fxSet*) data;
  27827. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27828. || vst_swap (set->version) > fxbVersionNum)
  27829. return false;
  27830. if (vst_swap (set->fxMagic) == 'FxBk')
  27831. {
  27832. // bank of programs
  27833. if (vst_swap (set->numPrograms) >= 0)
  27834. {
  27835. const int oldProg = getCurrentProgram();
  27836. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27837. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27838. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27839. {
  27840. if (i != oldProg)
  27841. {
  27842. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27843. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27844. return false;
  27845. if (vst_swap (set->numPrograms) > 0)
  27846. setCurrentProgram (i);
  27847. if (! restoreProgramSettings (prog))
  27848. return false;
  27849. }
  27850. }
  27851. if (vst_swap (set->numPrograms) > 0)
  27852. setCurrentProgram (oldProg);
  27853. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27854. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27855. return false;
  27856. if (! restoreProgramSettings (prog))
  27857. return false;
  27858. }
  27859. }
  27860. else if (vst_swap (set->fxMagic) == 'FxCk')
  27861. {
  27862. // single program
  27863. const fxProgram* const prog = (const fxProgram*) data;
  27864. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27865. return false;
  27866. changeProgramName (getCurrentProgram(), prog->prgName);
  27867. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27868. setParameter (i, vst_swapFloat (prog->params[i]));
  27869. }
  27870. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27871. {
  27872. // non-preset chunk
  27873. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27874. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27875. return false;
  27876. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27877. }
  27878. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27879. {
  27880. // preset chunk
  27881. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27882. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27883. return false;
  27884. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27885. changeProgramName (getCurrentProgram(), cset->name);
  27886. }
  27887. else
  27888. {
  27889. return false;
  27890. }
  27891. return true;
  27892. }
  27893. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27894. {
  27895. const int numParams = getNumParameters();
  27896. prog->chunkMagic = vst_swap ('CcnK');
  27897. prog->byteSize = 0;
  27898. prog->fxMagic = vst_swap ('FxCk');
  27899. prog->version = vst_swap (fxbVersionNum);
  27900. prog->fxID = vst_swap (getUID());
  27901. prog->fxVersion = vst_swap (getVersionNumber());
  27902. prog->numParams = vst_swap (numParams);
  27903. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27904. for (int i = 0; i < numParams; ++i)
  27905. prog->params[i] = vst_swapFloat (getParameter (i));
  27906. }
  27907. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27908. {
  27909. const int numPrograms = getNumPrograms();
  27910. const int numParams = getNumParameters();
  27911. if (usesChunks())
  27912. {
  27913. if (isFXB)
  27914. {
  27915. MemoryBlock chunk;
  27916. getChunkData (chunk, false, maxSizeMB);
  27917. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27918. dest.setSize (totalLen, true);
  27919. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27920. set->chunkMagic = vst_swap ('CcnK');
  27921. set->byteSize = 0;
  27922. set->fxMagic = vst_swap ('FBCh');
  27923. set->version = vst_swap (fxbVersionNum);
  27924. set->fxID = vst_swap (getUID());
  27925. set->fxVersion = vst_swap (getVersionNumber());
  27926. set->numPrograms = vst_swap (numPrograms);
  27927. set->chunkSize = vst_swap ((long) chunk.getSize());
  27928. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27929. }
  27930. else
  27931. {
  27932. MemoryBlock chunk;
  27933. getChunkData (chunk, true, maxSizeMB);
  27934. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27935. dest.setSize (totalLen, true);
  27936. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27937. set->chunkMagic = vst_swap ('CcnK');
  27938. set->byteSize = 0;
  27939. set->fxMagic = vst_swap ('FPCh');
  27940. set->version = vst_swap (fxbVersionNum);
  27941. set->fxID = vst_swap (getUID());
  27942. set->fxVersion = vst_swap (getVersionNumber());
  27943. set->numPrograms = vst_swap (numPrograms);
  27944. set->chunkSize = vst_swap ((long) chunk.getSize());
  27945. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27946. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27947. }
  27948. }
  27949. else
  27950. {
  27951. if (isFXB)
  27952. {
  27953. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27954. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27955. dest.setSize (len, true);
  27956. fxSet* const set = (fxSet*) dest.getData();
  27957. set->chunkMagic = vst_swap ('CcnK');
  27958. set->byteSize = 0;
  27959. set->fxMagic = vst_swap ('FxBk');
  27960. set->version = vst_swap (fxbVersionNum);
  27961. set->fxID = vst_swap (getUID());
  27962. set->fxVersion = vst_swap (getVersionNumber());
  27963. set->numPrograms = vst_swap (numPrograms);
  27964. const int oldProgram = getCurrentProgram();
  27965. MemoryBlock oldSettings;
  27966. createTempParameterStore (oldSettings);
  27967. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27968. for (int i = 0; i < numPrograms; ++i)
  27969. {
  27970. if (i != oldProgram)
  27971. {
  27972. setCurrentProgram (i);
  27973. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27974. }
  27975. }
  27976. setCurrentProgram (oldProgram);
  27977. restoreFromTempParameterStore (oldSettings);
  27978. }
  27979. else
  27980. {
  27981. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27982. dest.setSize (totalLen, true);
  27983. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27984. }
  27985. }
  27986. return true;
  27987. }
  27988. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27989. {
  27990. if (usesChunks())
  27991. {
  27992. void* data = 0;
  27993. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27994. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27995. {
  27996. mb.setSize (bytes);
  27997. mb.copyFrom (data, 0, bytes);
  27998. }
  27999. }
  28000. }
  28001. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28002. {
  28003. if (size > 0 && usesChunks())
  28004. {
  28005. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28006. if (! isPreset)
  28007. updateStoredProgramNames();
  28008. }
  28009. }
  28010. void VSTPluginInstance::timerCallback()
  28011. {
  28012. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28013. stopTimer();
  28014. }
  28015. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28016. {
  28017. const ScopedLock sl (lock);
  28018. ++insideVSTCallback;
  28019. int result = 0;
  28020. try
  28021. {
  28022. if (effect != 0)
  28023. {
  28024. #if JUCE_MAC
  28025. if (module->resFileId != 0)
  28026. UseResFile (module->resFileId);
  28027. #endif
  28028. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28029. #if JUCE_MAC
  28030. module->resFileId = CurResFile();
  28031. #endif
  28032. --insideVSTCallback;
  28033. return result;
  28034. }
  28035. }
  28036. catch (...)
  28037. {
  28038. }
  28039. --insideVSTCallback;
  28040. return result;
  28041. }
  28042. namespace
  28043. {
  28044. static const int defaultVSTSampleRateValue = 16384;
  28045. static const int defaultVSTBlockSizeValue = 512;
  28046. // handles non plugin-specific callbacks..
  28047. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28048. {
  28049. (void) index;
  28050. (void) value;
  28051. (void) opt;
  28052. switch (opcode)
  28053. {
  28054. case audioMasterCanDo:
  28055. {
  28056. static const char* canDos[] = { "supplyIdle",
  28057. "sendVstEvents",
  28058. "sendVstMidiEvent",
  28059. "sendVstTimeInfo",
  28060. "receiveVstEvents",
  28061. "receiveVstMidiEvent",
  28062. "supportShell",
  28063. "shellCategory" };
  28064. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28065. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28066. return 1;
  28067. return 0;
  28068. }
  28069. case audioMasterVersion: return 0x2400;
  28070. case audioMasterCurrentId: return shellUIDToCreate;
  28071. case audioMasterGetNumAutomatableParameters: return 0;
  28072. case audioMasterGetAutomationState: return 1;
  28073. case audioMasterGetVendorVersion: return 0x0101;
  28074. case audioMasterGetVendorString:
  28075. case audioMasterGetProductString:
  28076. {
  28077. String hostName ("Juce VST Host");
  28078. if (JUCEApplication::getInstance() != 0)
  28079. hostName = JUCEApplication::getInstance()->getApplicationName();
  28080. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28081. break;
  28082. }
  28083. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28084. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28085. case audioMasterSetOutputSampleRate: return 0;
  28086. default:
  28087. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28088. break;
  28089. }
  28090. return 0;
  28091. }
  28092. }
  28093. // handles callbacks for a specific plugin
  28094. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28095. {
  28096. switch (opcode)
  28097. {
  28098. case audioMasterAutomate:
  28099. sendParamChangeMessageToListeners (index, opt);
  28100. break;
  28101. case audioMasterProcessEvents:
  28102. handleMidiFromPlugin ((const VstEvents*) ptr);
  28103. break;
  28104. case audioMasterGetTime:
  28105. #if JUCE_MSVC
  28106. #pragma warning (push)
  28107. #pragma warning (disable: 4311)
  28108. #endif
  28109. return (VstIntPtr) &vstHostTime;
  28110. #if JUCE_MSVC
  28111. #pragma warning (pop)
  28112. #endif
  28113. break;
  28114. case audioMasterIdle:
  28115. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28116. {
  28117. ++insideVSTCallback;
  28118. #if JUCE_MAC
  28119. if (getActiveEditor() != 0)
  28120. dispatch (effEditIdle, 0, 0, 0, 0);
  28121. #endif
  28122. juce_callAnyTimersSynchronously();
  28123. handleUpdateNowIfNeeded();
  28124. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28125. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28126. --insideVSTCallback;
  28127. }
  28128. break;
  28129. case audioMasterUpdateDisplay:
  28130. triggerAsyncUpdate();
  28131. break;
  28132. case audioMasterTempoAt:
  28133. // returns (10000 * bpm)
  28134. break;
  28135. case audioMasterNeedIdle:
  28136. startTimer (50);
  28137. break;
  28138. case audioMasterSizeWindow:
  28139. if (getActiveEditor() != 0)
  28140. getActiveEditor()->setSize (index, value);
  28141. return 1;
  28142. case audioMasterGetSampleRate:
  28143. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28144. case audioMasterGetBlockSize:
  28145. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28146. case audioMasterWantMidi:
  28147. wantsMidiMessages = true;
  28148. break;
  28149. case audioMasterGetDirectory:
  28150. #if JUCE_MAC
  28151. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28152. #else
  28153. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28154. #endif
  28155. case audioMasterGetAutomationState:
  28156. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28157. break;
  28158. // none of these are handled (yet)..
  28159. case audioMasterBeginEdit:
  28160. case audioMasterEndEdit:
  28161. case audioMasterSetTime:
  28162. case audioMasterPinConnected:
  28163. case audioMasterGetParameterQuantization:
  28164. case audioMasterIOChanged:
  28165. case audioMasterGetInputLatency:
  28166. case audioMasterGetOutputLatency:
  28167. case audioMasterGetPreviousPlug:
  28168. case audioMasterGetNextPlug:
  28169. case audioMasterWillReplaceOrAccumulate:
  28170. case audioMasterGetCurrentProcessLevel:
  28171. case audioMasterOfflineStart:
  28172. case audioMasterOfflineRead:
  28173. case audioMasterOfflineWrite:
  28174. case audioMasterOfflineGetCurrentPass:
  28175. case audioMasterOfflineGetCurrentMetaPass:
  28176. case audioMasterVendorSpecific:
  28177. case audioMasterSetIcon:
  28178. case audioMasterGetLanguage:
  28179. case audioMasterOpenWindow:
  28180. case audioMasterCloseWindow:
  28181. break;
  28182. default:
  28183. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28184. }
  28185. return 0;
  28186. }
  28187. // entry point for all callbacks from the plugin
  28188. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28189. {
  28190. try
  28191. {
  28192. if (effect != 0 && effect->resvd2 != 0)
  28193. {
  28194. return ((VSTPluginInstance*)(effect->resvd2))
  28195. ->handleCallback (opcode, index, value, ptr, opt);
  28196. }
  28197. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28198. }
  28199. catch (...)
  28200. {
  28201. return 0;
  28202. }
  28203. }
  28204. const String VSTPluginInstance::getVersion() const
  28205. {
  28206. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28207. String s;
  28208. if (v == 0 || v == -1)
  28209. v = getVersionNumber();
  28210. if (v != 0)
  28211. {
  28212. int versionBits[4];
  28213. int n = 0;
  28214. while (v != 0)
  28215. {
  28216. versionBits [n++] = (v & 0xff);
  28217. v >>= 8;
  28218. }
  28219. s << 'V';
  28220. while (n > 0)
  28221. {
  28222. s << versionBits [--n];
  28223. if (n > 0)
  28224. s << '.';
  28225. }
  28226. }
  28227. return s;
  28228. }
  28229. int VSTPluginInstance::getUID() const
  28230. {
  28231. int uid = effect != 0 ? effect->uniqueID : 0;
  28232. if (uid == 0)
  28233. uid = module->file.hashCode();
  28234. return uid;
  28235. }
  28236. const String VSTPluginInstance::getCategory() const
  28237. {
  28238. const char* result = 0;
  28239. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28240. {
  28241. case kPlugCategEffect: result = "Effect"; break;
  28242. case kPlugCategSynth: result = "Synth"; break;
  28243. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28244. case kPlugCategMastering: result = "Mastering"; break;
  28245. case kPlugCategSpacializer: result = "Spacial"; break;
  28246. case kPlugCategRoomFx: result = "Reverb"; break;
  28247. case kPlugSurroundFx: result = "Surround"; break;
  28248. case kPlugCategRestoration: result = "Restoration"; break;
  28249. case kPlugCategGenerator: result = "Tone generation"; break;
  28250. default: break;
  28251. }
  28252. return result;
  28253. }
  28254. float VSTPluginInstance::getParameter (int index)
  28255. {
  28256. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28257. {
  28258. try
  28259. {
  28260. const ScopedLock sl (lock);
  28261. return effect->getParameter (effect, index);
  28262. }
  28263. catch (...)
  28264. {
  28265. }
  28266. }
  28267. return 0.0f;
  28268. }
  28269. void VSTPluginInstance::setParameter (int index, float newValue)
  28270. {
  28271. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28272. {
  28273. try
  28274. {
  28275. const ScopedLock sl (lock);
  28276. if (effect->getParameter (effect, index) != newValue)
  28277. effect->setParameter (effect, index, newValue);
  28278. }
  28279. catch (...)
  28280. {
  28281. }
  28282. }
  28283. }
  28284. const String VSTPluginInstance::getParameterName (int index)
  28285. {
  28286. if (effect != 0)
  28287. {
  28288. jassert (index >= 0 && index < effect->numParams);
  28289. char nm [256];
  28290. zerostruct (nm);
  28291. dispatch (effGetParamName, index, 0, nm, 0);
  28292. return String (nm).trim();
  28293. }
  28294. return String::empty;
  28295. }
  28296. const String VSTPluginInstance::getParameterLabel (int index) const
  28297. {
  28298. if (effect != 0)
  28299. {
  28300. jassert (index >= 0 && index < effect->numParams);
  28301. char nm [256];
  28302. zerostruct (nm);
  28303. dispatch (effGetParamLabel, index, 0, nm, 0);
  28304. return String (nm).trim();
  28305. }
  28306. return String::empty;
  28307. }
  28308. const String VSTPluginInstance::getParameterText (int index)
  28309. {
  28310. if (effect != 0)
  28311. {
  28312. jassert (index >= 0 && index < effect->numParams);
  28313. char nm [256];
  28314. zerostruct (nm);
  28315. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28316. return String (nm).trim();
  28317. }
  28318. return String::empty;
  28319. }
  28320. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28321. {
  28322. if (effect != 0)
  28323. {
  28324. jassert (index >= 0 && index < effect->numParams);
  28325. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28326. }
  28327. return false;
  28328. }
  28329. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28330. {
  28331. dest.setSize (64 + 4 * getNumParameters());
  28332. dest.fillWith (0);
  28333. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28334. float* const p = (float*) (((char*) dest.getData()) + 64);
  28335. for (int i = 0; i < getNumParameters(); ++i)
  28336. p[i] = getParameter(i);
  28337. }
  28338. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28339. {
  28340. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28341. float* p = (float*) (((char*) m.getData()) + 64);
  28342. for (int i = 0; i < getNumParameters(); ++i)
  28343. setParameter (i, p[i]);
  28344. }
  28345. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28346. {
  28347. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28348. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28349. }
  28350. const String VSTPluginInstance::getProgramName (int index)
  28351. {
  28352. if (index == getCurrentProgram())
  28353. {
  28354. return getCurrentProgramName();
  28355. }
  28356. else if (effect != 0)
  28357. {
  28358. char nm [256];
  28359. zerostruct (nm);
  28360. if (dispatch (effGetProgramNameIndexed,
  28361. jlimit (0, getNumPrograms(), index),
  28362. -1, nm, 0) != 0)
  28363. {
  28364. return String (nm).trim();
  28365. }
  28366. }
  28367. return programNames [index];
  28368. }
  28369. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28370. {
  28371. if (index == getCurrentProgram())
  28372. {
  28373. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28374. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28375. }
  28376. else
  28377. {
  28378. jassertfalse; // xxx not implemented!
  28379. }
  28380. }
  28381. void VSTPluginInstance::updateStoredProgramNames()
  28382. {
  28383. if (effect != 0 && getNumPrograms() > 0)
  28384. {
  28385. char nm [256];
  28386. zerostruct (nm);
  28387. // only do this if the plugin can't use indexed names..
  28388. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28389. {
  28390. const int oldProgram = getCurrentProgram();
  28391. MemoryBlock oldSettings;
  28392. createTempParameterStore (oldSettings);
  28393. for (int i = 0; i < getNumPrograms(); ++i)
  28394. {
  28395. setCurrentProgram (i);
  28396. getCurrentProgramName(); // (this updates the list)
  28397. }
  28398. setCurrentProgram (oldProgram);
  28399. restoreFromTempParameterStore (oldSettings);
  28400. }
  28401. }
  28402. }
  28403. const String VSTPluginInstance::getCurrentProgramName()
  28404. {
  28405. if (effect != 0)
  28406. {
  28407. char nm [256];
  28408. zerostruct (nm);
  28409. dispatch (effGetProgramName, 0, 0, nm, 0);
  28410. const int index = getCurrentProgram();
  28411. if (programNames[index].isEmpty())
  28412. {
  28413. while (programNames.size() < index)
  28414. programNames.add (String::empty);
  28415. programNames.set (index, String (nm).trim());
  28416. }
  28417. return String (nm).trim();
  28418. }
  28419. return String::empty;
  28420. }
  28421. const String VSTPluginInstance::getInputChannelName (int index) const
  28422. {
  28423. if (index >= 0 && index < getNumInputChannels())
  28424. {
  28425. VstPinProperties pinProps;
  28426. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28427. return String (pinProps.label, sizeof (pinProps.label));
  28428. }
  28429. return String::empty;
  28430. }
  28431. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28432. {
  28433. if (index < 0 || index >= getNumInputChannels())
  28434. return false;
  28435. VstPinProperties pinProps;
  28436. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28437. return (pinProps.flags & kVstPinIsStereo) != 0;
  28438. return true;
  28439. }
  28440. const String VSTPluginInstance::getOutputChannelName (int index) const
  28441. {
  28442. if (index >= 0 && index < getNumOutputChannels())
  28443. {
  28444. VstPinProperties pinProps;
  28445. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28446. return String (pinProps.label, sizeof (pinProps.label));
  28447. }
  28448. return String::empty;
  28449. }
  28450. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28451. {
  28452. if (index < 0 || index >= getNumOutputChannels())
  28453. return false;
  28454. VstPinProperties pinProps;
  28455. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28456. return (pinProps.flags & kVstPinIsStereo) != 0;
  28457. return true;
  28458. }
  28459. void VSTPluginInstance::setPower (const bool on)
  28460. {
  28461. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28462. isPowerOn = on;
  28463. }
  28464. const int defaultMaxSizeMB = 64;
  28465. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28466. {
  28467. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28468. }
  28469. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28470. {
  28471. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28472. }
  28473. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28474. {
  28475. loadFromFXBFile (data, sizeInBytes);
  28476. }
  28477. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28478. {
  28479. loadFromFXBFile (data, sizeInBytes);
  28480. }
  28481. VSTPluginFormat::VSTPluginFormat()
  28482. {
  28483. }
  28484. VSTPluginFormat::~VSTPluginFormat()
  28485. {
  28486. }
  28487. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28488. const String& fileOrIdentifier)
  28489. {
  28490. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28491. return;
  28492. PluginDescription desc;
  28493. desc.fileOrIdentifier = fileOrIdentifier;
  28494. desc.uid = 0;
  28495. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28496. if (instance == 0)
  28497. return;
  28498. try
  28499. {
  28500. #if JUCE_MAC
  28501. if (instance->module->resFileId != 0)
  28502. UseResFile (instance->module->resFileId);
  28503. #endif
  28504. instance->fillInPluginDescription (desc);
  28505. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28506. if (category != kPlugCategShell)
  28507. {
  28508. // Normal plugin...
  28509. results.add (new PluginDescription (desc));
  28510. ++insideVSTCallback;
  28511. instance->dispatch (effOpen, 0, 0, 0, 0);
  28512. --insideVSTCallback;
  28513. }
  28514. else
  28515. {
  28516. // It's a shell plugin, so iterate all the subtypes...
  28517. char shellEffectName [64];
  28518. for (;;)
  28519. {
  28520. zerostruct (shellEffectName);
  28521. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28522. if (uid == 0)
  28523. {
  28524. break;
  28525. }
  28526. else
  28527. {
  28528. desc.uid = uid;
  28529. desc.name = shellEffectName;
  28530. desc.descriptiveName = shellEffectName;
  28531. bool alreadyThere = false;
  28532. for (int i = results.size(); --i >= 0;)
  28533. {
  28534. PluginDescription* const d = results.getUnchecked(i);
  28535. if (d->isDuplicateOf (desc))
  28536. {
  28537. alreadyThere = true;
  28538. break;
  28539. }
  28540. }
  28541. if (! alreadyThere)
  28542. results.add (new PluginDescription (desc));
  28543. }
  28544. }
  28545. }
  28546. }
  28547. catch (...)
  28548. {
  28549. // crashed while loading...
  28550. }
  28551. }
  28552. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28553. {
  28554. ScopedPointer <VSTPluginInstance> result;
  28555. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28556. {
  28557. File file (desc.fileOrIdentifier);
  28558. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28559. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28560. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28561. if (module != 0)
  28562. {
  28563. shellUIDToCreate = desc.uid;
  28564. result = new VSTPluginInstance (module);
  28565. if (result->effect != 0)
  28566. {
  28567. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28568. result->initialise();
  28569. }
  28570. else
  28571. {
  28572. result = 0;
  28573. }
  28574. }
  28575. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28576. }
  28577. return result.release();
  28578. }
  28579. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28580. {
  28581. const File f (fileOrIdentifier);
  28582. #if JUCE_MAC
  28583. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28584. return true;
  28585. #if JUCE_PPC
  28586. FSRef fileRef;
  28587. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28588. {
  28589. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28590. if (resFileId != -1)
  28591. {
  28592. const int numEffects = Count1Resources ('aEff');
  28593. CloseResFile (resFileId);
  28594. if (numEffects > 0)
  28595. return true;
  28596. }
  28597. }
  28598. #endif
  28599. return false;
  28600. #elif JUCE_WINDOWS
  28601. return f.existsAsFile() && f.hasFileExtension (".dll");
  28602. #elif JUCE_LINUX
  28603. return f.existsAsFile() && f.hasFileExtension (".so");
  28604. #endif
  28605. }
  28606. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28607. {
  28608. return fileOrIdentifier;
  28609. }
  28610. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28611. {
  28612. return File (desc.fileOrIdentifier).exists();
  28613. }
  28614. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28615. {
  28616. StringArray results;
  28617. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28618. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28619. return results;
  28620. }
  28621. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28622. {
  28623. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28624. // .component or .vst directories.
  28625. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28626. while (iter.next())
  28627. {
  28628. const File f (iter.getFile());
  28629. bool isPlugin = false;
  28630. if (fileMightContainThisPluginType (f.getFullPathName()))
  28631. {
  28632. isPlugin = true;
  28633. results.add (f.getFullPathName());
  28634. }
  28635. if (recursive && (! isPlugin) && f.isDirectory())
  28636. recursiveFileSearch (results, f, true);
  28637. }
  28638. }
  28639. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28640. {
  28641. #if JUCE_MAC
  28642. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28643. #elif JUCE_WINDOWS
  28644. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28645. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28646. #elif JUCE_LINUX
  28647. return FileSearchPath ("/usr/lib/vst");
  28648. #endif
  28649. }
  28650. END_JUCE_NAMESPACE
  28651. #endif
  28652. #undef log
  28653. #endif
  28654. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28655. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28656. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28657. BEGIN_JUCE_NAMESPACE
  28658. AudioProcessor::AudioProcessor()
  28659. : playHead (0),
  28660. sampleRate (0),
  28661. blockSize (0),
  28662. numInputChannels (0),
  28663. numOutputChannels (0),
  28664. latencySamples (0),
  28665. suspended (false),
  28666. nonRealtime (false)
  28667. {
  28668. }
  28669. AudioProcessor::~AudioProcessor()
  28670. {
  28671. // ooh, nasty - the editor should have been deleted before the filter
  28672. // that it refers to is deleted..
  28673. jassert (activeEditor == 0);
  28674. #if JUCE_DEBUG
  28675. // This will fail if you've called beginParameterChangeGesture() for one
  28676. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28677. jassert (changingParams.countNumberOfSetBits() == 0);
  28678. #endif
  28679. }
  28680. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28681. {
  28682. playHead = newPlayHead;
  28683. }
  28684. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28685. {
  28686. const ScopedLock sl (listenerLock);
  28687. listeners.addIfNotAlreadyThere (newListener);
  28688. }
  28689. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28690. {
  28691. const ScopedLock sl (listenerLock);
  28692. listeners.removeValue (listenerToRemove);
  28693. }
  28694. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28695. const int numOuts,
  28696. const double sampleRate_,
  28697. const int blockSize_) throw()
  28698. {
  28699. numInputChannels = numIns;
  28700. numOutputChannels = numOuts;
  28701. sampleRate = sampleRate_;
  28702. blockSize = blockSize_;
  28703. }
  28704. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28705. {
  28706. nonRealtime = nonRealtime_;
  28707. }
  28708. void AudioProcessor::setLatencySamples (const int newLatency)
  28709. {
  28710. if (latencySamples != newLatency)
  28711. {
  28712. latencySamples = newLatency;
  28713. updateHostDisplay();
  28714. }
  28715. }
  28716. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28717. const float newValue)
  28718. {
  28719. setParameter (parameterIndex, newValue);
  28720. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28721. }
  28722. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28723. {
  28724. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28725. for (int i = listeners.size(); --i >= 0;)
  28726. {
  28727. AudioProcessorListener* l;
  28728. {
  28729. const ScopedLock sl (listenerLock);
  28730. l = listeners [i];
  28731. }
  28732. if (l != 0)
  28733. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28734. }
  28735. }
  28736. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28737. {
  28738. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28739. #if JUCE_DEBUG
  28740. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28741. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28742. jassert (! changingParams [parameterIndex]);
  28743. changingParams.setBit (parameterIndex);
  28744. #endif
  28745. for (int i = listeners.size(); --i >= 0;)
  28746. {
  28747. AudioProcessorListener* l;
  28748. {
  28749. const ScopedLock sl (listenerLock);
  28750. l = listeners [i];
  28751. }
  28752. if (l != 0)
  28753. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28754. }
  28755. }
  28756. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28757. {
  28758. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28759. #if JUCE_DEBUG
  28760. // This means you've called endParameterChangeGesture without having previously called
  28761. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28762. // calls matched correctly.
  28763. jassert (changingParams [parameterIndex]);
  28764. changingParams.clearBit (parameterIndex);
  28765. #endif
  28766. for (int i = listeners.size(); --i >= 0;)
  28767. {
  28768. AudioProcessorListener* l;
  28769. {
  28770. const ScopedLock sl (listenerLock);
  28771. l = listeners [i];
  28772. }
  28773. if (l != 0)
  28774. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28775. }
  28776. }
  28777. void AudioProcessor::updateHostDisplay()
  28778. {
  28779. for (int i = listeners.size(); --i >= 0;)
  28780. {
  28781. AudioProcessorListener* l;
  28782. {
  28783. const ScopedLock sl (listenerLock);
  28784. l = listeners [i];
  28785. }
  28786. if (l != 0)
  28787. l->audioProcessorChanged (this);
  28788. }
  28789. }
  28790. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28791. {
  28792. return true;
  28793. }
  28794. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28795. {
  28796. return false;
  28797. }
  28798. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28799. {
  28800. const ScopedLock sl (callbackLock);
  28801. suspended = shouldBeSuspended;
  28802. }
  28803. void AudioProcessor::reset()
  28804. {
  28805. }
  28806. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28807. {
  28808. const ScopedLock sl (callbackLock);
  28809. if (activeEditor == editor)
  28810. activeEditor = 0;
  28811. }
  28812. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28813. {
  28814. if (activeEditor != 0)
  28815. return activeEditor;
  28816. AudioProcessorEditor* const ed = createEditor();
  28817. // You must make your hasEditor() method return a consistent result!
  28818. jassert (hasEditor() == (ed != 0));
  28819. if (ed != 0)
  28820. {
  28821. // you must give your editor comp a size before returning it..
  28822. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28823. const ScopedLock sl (callbackLock);
  28824. activeEditor = ed;
  28825. }
  28826. return ed;
  28827. }
  28828. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28829. {
  28830. getStateInformation (destData);
  28831. }
  28832. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28833. {
  28834. setStateInformation (data, sizeInBytes);
  28835. }
  28836. // magic number to identify memory blocks that we've stored as XML
  28837. const uint32 magicXmlNumber = 0x21324356;
  28838. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28839. JUCE_NAMESPACE::MemoryBlock& destData)
  28840. {
  28841. const String xmlString (xml.createDocument (String::empty, true, false));
  28842. const int stringLength = xmlString.getNumBytesAsUTF8();
  28843. destData.setSize (stringLength + 10);
  28844. char* const d = static_cast<char*> (destData.getData());
  28845. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28846. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28847. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28848. }
  28849. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28850. const int sizeInBytes)
  28851. {
  28852. if (sizeInBytes > 8
  28853. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28854. {
  28855. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28856. if (stringLength > 0)
  28857. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28858. jmin ((sizeInBytes - 8), stringLength)));
  28859. }
  28860. return 0;
  28861. }
  28862. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28863. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28864. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28865. {
  28866. return timeInSeconds == other.timeInSeconds
  28867. && ppqPosition == other.ppqPosition
  28868. && editOriginTime == other.editOriginTime
  28869. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28870. && frameRate == other.frameRate
  28871. && isPlaying == other.isPlaying
  28872. && isRecording == other.isRecording
  28873. && bpm == other.bpm
  28874. && timeSigNumerator == other.timeSigNumerator
  28875. && timeSigDenominator == other.timeSigDenominator;
  28876. }
  28877. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28878. {
  28879. return ! operator== (other);
  28880. }
  28881. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28882. {
  28883. zerostruct (*this);
  28884. timeSigNumerator = 4;
  28885. timeSigDenominator = 4;
  28886. bpm = 120;
  28887. }
  28888. END_JUCE_NAMESPACE
  28889. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28890. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28891. BEGIN_JUCE_NAMESPACE
  28892. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28893. : owner (owner_)
  28894. {
  28895. // the filter must be valid..
  28896. jassert (owner != 0);
  28897. }
  28898. AudioProcessorEditor::~AudioProcessorEditor()
  28899. {
  28900. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28901. // filter for some reason..
  28902. jassert (owner->getActiveEditor() != this);
  28903. }
  28904. END_JUCE_NAMESPACE
  28905. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28906. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28907. BEGIN_JUCE_NAMESPACE
  28908. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28909. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28910. : id (id_),
  28911. processor (processor_),
  28912. isPrepared (false)
  28913. {
  28914. jassert (processor_ != 0);
  28915. }
  28916. AudioProcessorGraph::Node::~Node()
  28917. {
  28918. }
  28919. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28920. AudioProcessorGraph* const graph)
  28921. {
  28922. if (! isPrepared)
  28923. {
  28924. isPrepared = true;
  28925. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28926. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28927. if (ioProc != 0)
  28928. ioProc->setParentGraph (graph);
  28929. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28930. processor->getNumOutputChannels(),
  28931. sampleRate, blockSize);
  28932. processor->prepareToPlay (sampleRate, blockSize);
  28933. }
  28934. }
  28935. void AudioProcessorGraph::Node::unprepare()
  28936. {
  28937. if (isPrepared)
  28938. {
  28939. isPrepared = false;
  28940. processor->releaseResources();
  28941. }
  28942. }
  28943. AudioProcessorGraph::AudioProcessorGraph()
  28944. : lastNodeId (0),
  28945. renderingBuffers (1, 1),
  28946. currentAudioOutputBuffer (1, 1)
  28947. {
  28948. }
  28949. AudioProcessorGraph::~AudioProcessorGraph()
  28950. {
  28951. clearRenderingSequence();
  28952. clear();
  28953. }
  28954. const String AudioProcessorGraph::getName() const
  28955. {
  28956. return "Audio Graph";
  28957. }
  28958. void AudioProcessorGraph::clear()
  28959. {
  28960. nodes.clear();
  28961. connections.clear();
  28962. triggerAsyncUpdate();
  28963. }
  28964. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28965. {
  28966. for (int i = nodes.size(); --i >= 0;)
  28967. if (nodes.getUnchecked(i)->id == nodeId)
  28968. return nodes.getUnchecked(i);
  28969. return 0;
  28970. }
  28971. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28972. uint32 nodeId)
  28973. {
  28974. if (newProcessor == 0)
  28975. {
  28976. jassertfalse;
  28977. return 0;
  28978. }
  28979. if (nodeId == 0)
  28980. {
  28981. nodeId = ++lastNodeId;
  28982. }
  28983. else
  28984. {
  28985. // you can't add a node with an id that already exists in the graph..
  28986. jassert (getNodeForId (nodeId) == 0);
  28987. removeNode (nodeId);
  28988. }
  28989. lastNodeId = nodeId;
  28990. Node* const n = new Node (nodeId, newProcessor);
  28991. nodes.add (n);
  28992. triggerAsyncUpdate();
  28993. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28994. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  28995. if (ioProc != 0)
  28996. ioProc->setParentGraph (this);
  28997. return n;
  28998. }
  28999. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29000. {
  29001. disconnectNode (nodeId);
  29002. for (int i = nodes.size(); --i >= 0;)
  29003. {
  29004. if (nodes.getUnchecked(i)->id == nodeId)
  29005. {
  29006. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29007. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29008. if (ioProc != 0)
  29009. ioProc->setParentGraph (0);
  29010. nodes.remove (i);
  29011. triggerAsyncUpdate();
  29012. return true;
  29013. }
  29014. }
  29015. return false;
  29016. }
  29017. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29018. const int sourceChannelIndex,
  29019. const uint32 destNodeId,
  29020. const int destChannelIndex) const
  29021. {
  29022. for (int i = connections.size(); --i >= 0;)
  29023. {
  29024. const Connection* const c = connections.getUnchecked(i);
  29025. if (c->sourceNodeId == sourceNodeId
  29026. && c->destNodeId == destNodeId
  29027. && c->sourceChannelIndex == sourceChannelIndex
  29028. && c->destChannelIndex == destChannelIndex)
  29029. {
  29030. return c;
  29031. }
  29032. }
  29033. return 0;
  29034. }
  29035. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29036. const uint32 possibleDestNodeId) const
  29037. {
  29038. for (int i = connections.size(); --i >= 0;)
  29039. {
  29040. const Connection* const c = connections.getUnchecked(i);
  29041. if (c->sourceNodeId == possibleSourceNodeId
  29042. && c->destNodeId == possibleDestNodeId)
  29043. {
  29044. return true;
  29045. }
  29046. }
  29047. return false;
  29048. }
  29049. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29050. const int sourceChannelIndex,
  29051. const uint32 destNodeId,
  29052. const int destChannelIndex) const
  29053. {
  29054. if (sourceChannelIndex < 0
  29055. || destChannelIndex < 0
  29056. || sourceNodeId == destNodeId
  29057. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29058. return false;
  29059. const Node* const source = getNodeForId (sourceNodeId);
  29060. if (source == 0
  29061. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29062. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29063. return false;
  29064. const Node* const dest = getNodeForId (destNodeId);
  29065. if (dest == 0
  29066. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29067. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29068. return false;
  29069. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29070. destNodeId, destChannelIndex) == 0;
  29071. }
  29072. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29073. const int sourceChannelIndex,
  29074. const uint32 destNodeId,
  29075. const int destChannelIndex)
  29076. {
  29077. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29078. return false;
  29079. Connection* const c = new Connection();
  29080. c->sourceNodeId = sourceNodeId;
  29081. c->sourceChannelIndex = sourceChannelIndex;
  29082. c->destNodeId = destNodeId;
  29083. c->destChannelIndex = destChannelIndex;
  29084. connections.add (c);
  29085. triggerAsyncUpdate();
  29086. return true;
  29087. }
  29088. void AudioProcessorGraph::removeConnection (const int index)
  29089. {
  29090. connections.remove (index);
  29091. triggerAsyncUpdate();
  29092. }
  29093. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29094. const uint32 destNodeId, const int destChannelIndex)
  29095. {
  29096. bool doneAnything = false;
  29097. for (int i = connections.size(); --i >= 0;)
  29098. {
  29099. const Connection* const c = connections.getUnchecked(i);
  29100. if (c->sourceNodeId == sourceNodeId
  29101. && c->destNodeId == destNodeId
  29102. && c->sourceChannelIndex == sourceChannelIndex
  29103. && c->destChannelIndex == destChannelIndex)
  29104. {
  29105. removeConnection (i);
  29106. doneAnything = true;
  29107. triggerAsyncUpdate();
  29108. }
  29109. }
  29110. return doneAnything;
  29111. }
  29112. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29113. {
  29114. bool doneAnything = false;
  29115. for (int i = connections.size(); --i >= 0;)
  29116. {
  29117. const Connection* const c = connections.getUnchecked(i);
  29118. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29119. {
  29120. removeConnection (i);
  29121. doneAnything = true;
  29122. triggerAsyncUpdate();
  29123. }
  29124. }
  29125. return doneAnything;
  29126. }
  29127. bool AudioProcessorGraph::removeIllegalConnections()
  29128. {
  29129. bool doneAnything = false;
  29130. for (int i = connections.size(); --i >= 0;)
  29131. {
  29132. const Connection* const c = connections.getUnchecked(i);
  29133. const Node* const source = getNodeForId (c->sourceNodeId);
  29134. const Node* const dest = getNodeForId (c->destNodeId);
  29135. if (source == 0 || dest == 0
  29136. || (c->sourceChannelIndex != midiChannelIndex
  29137. && ! isPositiveAndBelow (c->sourceChannelIndex, source->processor->getNumOutputChannels()))
  29138. || (c->sourceChannelIndex == midiChannelIndex
  29139. && ! source->processor->producesMidi())
  29140. || (c->destChannelIndex != midiChannelIndex
  29141. && ! isPositiveAndBelow (c->destChannelIndex, dest->processor->getNumInputChannels()))
  29142. || (c->destChannelIndex == midiChannelIndex
  29143. && ! dest->processor->acceptsMidi()))
  29144. {
  29145. removeConnection (i);
  29146. doneAnything = true;
  29147. triggerAsyncUpdate();
  29148. }
  29149. }
  29150. return doneAnything;
  29151. }
  29152. namespace GraphRenderingOps
  29153. {
  29154. class AudioGraphRenderingOp
  29155. {
  29156. public:
  29157. AudioGraphRenderingOp() {}
  29158. virtual ~AudioGraphRenderingOp() {}
  29159. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29160. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29161. const int numSamples) = 0;
  29162. JUCE_LEAK_DETECTOR (AudioGraphRenderingOp);
  29163. };
  29164. class ClearChannelOp : public AudioGraphRenderingOp
  29165. {
  29166. public:
  29167. ClearChannelOp (const int channelNum_)
  29168. : channelNum (channelNum_)
  29169. {}
  29170. ~ClearChannelOp() {}
  29171. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29172. {
  29173. sharedBufferChans.clear (channelNum, 0, numSamples);
  29174. }
  29175. private:
  29176. const int channelNum;
  29177. JUCE_DECLARE_NON_COPYABLE (ClearChannelOp);
  29178. };
  29179. class CopyChannelOp : public AudioGraphRenderingOp
  29180. {
  29181. public:
  29182. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29183. : srcChannelNum (srcChannelNum_),
  29184. dstChannelNum (dstChannelNum_)
  29185. {}
  29186. ~CopyChannelOp() {}
  29187. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29188. {
  29189. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29190. }
  29191. private:
  29192. const int srcChannelNum, dstChannelNum;
  29193. JUCE_DECLARE_NON_COPYABLE (CopyChannelOp);
  29194. };
  29195. class AddChannelOp : public AudioGraphRenderingOp
  29196. {
  29197. public:
  29198. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29199. : srcChannelNum (srcChannelNum_),
  29200. dstChannelNum (dstChannelNum_)
  29201. {}
  29202. ~AddChannelOp() {}
  29203. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29204. {
  29205. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29206. }
  29207. private:
  29208. const int srcChannelNum, dstChannelNum;
  29209. JUCE_DECLARE_NON_COPYABLE (AddChannelOp);
  29210. };
  29211. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29212. {
  29213. public:
  29214. ClearMidiBufferOp (const int bufferNum_)
  29215. : bufferNum (bufferNum_)
  29216. {}
  29217. ~ClearMidiBufferOp() {}
  29218. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29219. {
  29220. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29221. }
  29222. private:
  29223. const int bufferNum;
  29224. JUCE_DECLARE_NON_COPYABLE (ClearMidiBufferOp);
  29225. };
  29226. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29227. {
  29228. public:
  29229. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29230. : srcBufferNum (srcBufferNum_),
  29231. dstBufferNum (dstBufferNum_)
  29232. {}
  29233. ~CopyMidiBufferOp() {}
  29234. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29235. {
  29236. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29237. }
  29238. private:
  29239. const int srcBufferNum, dstBufferNum;
  29240. JUCE_DECLARE_NON_COPYABLE (CopyMidiBufferOp);
  29241. };
  29242. class AddMidiBufferOp : public AudioGraphRenderingOp
  29243. {
  29244. public:
  29245. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29246. : srcBufferNum (srcBufferNum_),
  29247. dstBufferNum (dstBufferNum_)
  29248. {}
  29249. ~AddMidiBufferOp() {}
  29250. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29251. {
  29252. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29253. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29254. }
  29255. private:
  29256. const int srcBufferNum, dstBufferNum;
  29257. JUCE_DECLARE_NON_COPYABLE (AddMidiBufferOp);
  29258. };
  29259. class ProcessBufferOp : public AudioGraphRenderingOp
  29260. {
  29261. public:
  29262. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29263. const Array <int>& audioChannelsToUse_,
  29264. const int totalChans_,
  29265. const int midiBufferToUse_)
  29266. : node (node_),
  29267. processor (node_->getProcessor()),
  29268. audioChannelsToUse (audioChannelsToUse_),
  29269. totalChans (jmax (1, totalChans_)),
  29270. midiBufferToUse (midiBufferToUse_)
  29271. {
  29272. channels.calloc (totalChans);
  29273. while (audioChannelsToUse.size() < totalChans)
  29274. audioChannelsToUse.add (0);
  29275. }
  29276. ~ProcessBufferOp()
  29277. {
  29278. }
  29279. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29280. {
  29281. for (int i = totalChans; --i >= 0;)
  29282. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29283. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29284. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29285. }
  29286. const AudioProcessorGraph::Node::Ptr node;
  29287. AudioProcessor* const processor;
  29288. private:
  29289. Array <int> audioChannelsToUse;
  29290. HeapBlock <float*> channels;
  29291. int totalChans;
  29292. int midiBufferToUse;
  29293. JUCE_DECLARE_NON_COPYABLE (ProcessBufferOp);
  29294. };
  29295. /** Used to calculate the correct sequence of rendering ops needed, based on
  29296. the best re-use of shared buffers at each stage.
  29297. */
  29298. class RenderingOpSequenceCalculator
  29299. {
  29300. public:
  29301. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29302. const Array<void*>& orderedNodes_,
  29303. Array<void*>& renderingOps)
  29304. : graph (graph_),
  29305. orderedNodes (orderedNodes_)
  29306. {
  29307. nodeIds.add ((uint32) zeroNodeID); // first buffer is read-only zeros
  29308. channels.add (0);
  29309. midiNodeIds.add ((uint32) zeroNodeID);
  29310. for (int i = 0; i < orderedNodes.size(); ++i)
  29311. {
  29312. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29313. renderingOps, i);
  29314. markAnyUnusedBuffersAsFree (i);
  29315. }
  29316. }
  29317. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29318. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29319. private:
  29320. AudioProcessorGraph& graph;
  29321. const Array<void*>& orderedNodes;
  29322. Array <int> channels;
  29323. Array <uint32> nodeIds, midiNodeIds;
  29324. enum { freeNodeID = 0xffffffff, zeroNodeID = 0xfffffffe };
  29325. static bool isNodeBusy (uint32 nodeID) throw() { return nodeID != freeNodeID && nodeID != zeroNodeID; }
  29326. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29327. Array<void*>& renderingOps,
  29328. const int ourRenderingIndex)
  29329. {
  29330. const int numIns = node->getProcessor()->getNumInputChannels();
  29331. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29332. const int totalChans = jmax (numIns, numOuts);
  29333. Array <int> audioChannelsToUse;
  29334. int midiBufferToUse = -1;
  29335. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29336. {
  29337. // get a list of all the inputs to this node
  29338. Array <int> sourceNodes, sourceOutputChans;
  29339. for (int i = graph.getNumConnections(); --i >= 0;)
  29340. {
  29341. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29342. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29343. {
  29344. sourceNodes.add (c->sourceNodeId);
  29345. sourceOutputChans.add (c->sourceChannelIndex);
  29346. }
  29347. }
  29348. int bufIndex = -1;
  29349. if (sourceNodes.size() == 0)
  29350. {
  29351. // unconnected input channel
  29352. if (inputChan >= numOuts)
  29353. {
  29354. bufIndex = getReadOnlyEmptyBuffer();
  29355. jassert (bufIndex >= 0);
  29356. }
  29357. else
  29358. {
  29359. bufIndex = getFreeBuffer (false);
  29360. renderingOps.add (new ClearChannelOp (bufIndex));
  29361. }
  29362. }
  29363. else if (sourceNodes.size() == 1)
  29364. {
  29365. // channel with a straightforward single input..
  29366. const int srcNode = sourceNodes.getUnchecked(0);
  29367. const int srcChan = sourceOutputChans.getUnchecked(0);
  29368. bufIndex = getBufferContaining (srcNode, srcChan);
  29369. if (bufIndex < 0)
  29370. {
  29371. // if not found, this is probably a feedback loop
  29372. bufIndex = getReadOnlyEmptyBuffer();
  29373. jassert (bufIndex >= 0);
  29374. }
  29375. if (inputChan < numOuts
  29376. && isBufferNeededLater (ourRenderingIndex,
  29377. inputChan,
  29378. srcNode, srcChan))
  29379. {
  29380. // can't mess up this channel because it's needed later by another node, so we
  29381. // need to use a copy of it..
  29382. const int newFreeBuffer = getFreeBuffer (false);
  29383. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29384. bufIndex = newFreeBuffer;
  29385. }
  29386. }
  29387. else
  29388. {
  29389. // channel with a mix of several inputs..
  29390. // try to find a re-usable channel from our inputs..
  29391. int reusableInputIndex = -1;
  29392. for (int i = 0; i < sourceNodes.size(); ++i)
  29393. {
  29394. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29395. sourceOutputChans.getUnchecked(i));
  29396. if (sourceBufIndex >= 0
  29397. && ! isBufferNeededLater (ourRenderingIndex,
  29398. inputChan,
  29399. sourceNodes.getUnchecked(i),
  29400. sourceOutputChans.getUnchecked(i)))
  29401. {
  29402. // we've found one of our input chans that can be re-used..
  29403. reusableInputIndex = i;
  29404. bufIndex = sourceBufIndex;
  29405. break;
  29406. }
  29407. }
  29408. if (reusableInputIndex < 0)
  29409. {
  29410. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29411. bufIndex = getFreeBuffer (false);
  29412. jassert (bufIndex != 0);
  29413. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29414. sourceOutputChans.getUnchecked (0));
  29415. if (srcIndex < 0)
  29416. {
  29417. // if not found, this is probably a feedback loop
  29418. renderingOps.add (new ClearChannelOp (bufIndex));
  29419. }
  29420. else
  29421. {
  29422. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29423. }
  29424. reusableInputIndex = 0;
  29425. }
  29426. for (int j = 0; j < sourceNodes.size(); ++j)
  29427. {
  29428. if (j != reusableInputIndex)
  29429. {
  29430. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29431. sourceOutputChans.getUnchecked(j));
  29432. if (srcIndex >= 0)
  29433. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29434. }
  29435. }
  29436. }
  29437. jassert (bufIndex >= 0);
  29438. audioChannelsToUse.add (bufIndex);
  29439. if (inputChan < numOuts)
  29440. markBufferAsContaining (bufIndex, node->id, inputChan);
  29441. }
  29442. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29443. {
  29444. const int bufIndex = getFreeBuffer (false);
  29445. jassert (bufIndex != 0);
  29446. audioChannelsToUse.add (bufIndex);
  29447. markBufferAsContaining (bufIndex, node->id, outputChan);
  29448. }
  29449. // Now the same thing for midi..
  29450. Array <int> midiSourceNodes;
  29451. for (int i = graph.getNumConnections(); --i >= 0;)
  29452. {
  29453. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29454. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29455. midiSourceNodes.add (c->sourceNodeId);
  29456. }
  29457. if (midiSourceNodes.size() == 0)
  29458. {
  29459. // No midi inputs..
  29460. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29461. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29462. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29463. }
  29464. else if (midiSourceNodes.size() == 1)
  29465. {
  29466. // One midi input..
  29467. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29468. AudioProcessorGraph::midiChannelIndex);
  29469. if (midiBufferToUse >= 0)
  29470. {
  29471. if (isBufferNeededLater (ourRenderingIndex,
  29472. AudioProcessorGraph::midiChannelIndex,
  29473. midiSourceNodes.getUnchecked(0),
  29474. AudioProcessorGraph::midiChannelIndex))
  29475. {
  29476. // can't mess up this channel because it's needed later by another node, so we
  29477. // need to use a copy of it..
  29478. const int newFreeBuffer = getFreeBuffer (true);
  29479. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29480. midiBufferToUse = newFreeBuffer;
  29481. }
  29482. }
  29483. else
  29484. {
  29485. // probably a feedback loop, so just use an empty one..
  29486. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29487. }
  29488. }
  29489. else
  29490. {
  29491. // More than one midi input being mixed..
  29492. int reusableInputIndex = -1;
  29493. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29494. {
  29495. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29496. AudioProcessorGraph::midiChannelIndex);
  29497. if (sourceBufIndex >= 0
  29498. && ! isBufferNeededLater (ourRenderingIndex,
  29499. AudioProcessorGraph::midiChannelIndex,
  29500. midiSourceNodes.getUnchecked(i),
  29501. AudioProcessorGraph::midiChannelIndex))
  29502. {
  29503. // we've found one of our input buffers that can be re-used..
  29504. reusableInputIndex = i;
  29505. midiBufferToUse = sourceBufIndex;
  29506. break;
  29507. }
  29508. }
  29509. if (reusableInputIndex < 0)
  29510. {
  29511. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29512. midiBufferToUse = getFreeBuffer (true);
  29513. jassert (midiBufferToUse >= 0);
  29514. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29515. AudioProcessorGraph::midiChannelIndex);
  29516. if (srcIndex >= 0)
  29517. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29518. else
  29519. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29520. reusableInputIndex = 0;
  29521. }
  29522. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29523. {
  29524. if (j != reusableInputIndex)
  29525. {
  29526. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29527. AudioProcessorGraph::midiChannelIndex);
  29528. if (srcIndex >= 0)
  29529. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29530. }
  29531. }
  29532. }
  29533. if (node->getProcessor()->producesMidi())
  29534. markBufferAsContaining (midiBufferToUse, node->id,
  29535. AudioProcessorGraph::midiChannelIndex);
  29536. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29537. totalChans, midiBufferToUse));
  29538. }
  29539. int getFreeBuffer (const bool forMidi)
  29540. {
  29541. if (forMidi)
  29542. {
  29543. for (int i = 1; i < midiNodeIds.size(); ++i)
  29544. if (midiNodeIds.getUnchecked(i) == freeNodeID)
  29545. return i;
  29546. midiNodeIds.add ((uint32) freeNodeID);
  29547. return midiNodeIds.size() - 1;
  29548. }
  29549. else
  29550. {
  29551. for (int i = 1; i < nodeIds.size(); ++i)
  29552. if (nodeIds.getUnchecked(i) == freeNodeID)
  29553. return i;
  29554. nodeIds.add ((uint32) freeNodeID);
  29555. channels.add (0);
  29556. return nodeIds.size() - 1;
  29557. }
  29558. }
  29559. int getReadOnlyEmptyBuffer() const
  29560. {
  29561. return 0;
  29562. }
  29563. int getBufferContaining (const uint32 nodeId, const int outputChannel) const
  29564. {
  29565. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29566. {
  29567. for (int i = midiNodeIds.size(); --i >= 0;)
  29568. if (midiNodeIds.getUnchecked(i) == nodeId)
  29569. return i;
  29570. }
  29571. else
  29572. {
  29573. for (int i = nodeIds.size(); --i >= 0;)
  29574. if (nodeIds.getUnchecked(i) == nodeId
  29575. && channels.getUnchecked(i) == outputChannel)
  29576. return i;
  29577. }
  29578. return -1;
  29579. }
  29580. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29581. {
  29582. int i;
  29583. for (i = 0; i < nodeIds.size(); ++i)
  29584. {
  29585. if (isNodeBusy (nodeIds.getUnchecked(i))
  29586. && ! isBufferNeededLater (stepIndex, -1,
  29587. nodeIds.getUnchecked(i),
  29588. channels.getUnchecked(i)))
  29589. {
  29590. nodeIds.set (i, (uint32) freeNodeID);
  29591. }
  29592. }
  29593. for (i = 0; i < midiNodeIds.size(); ++i)
  29594. {
  29595. if (isNodeBusy (midiNodeIds.getUnchecked(i))
  29596. && ! isBufferNeededLater (stepIndex, -1,
  29597. midiNodeIds.getUnchecked(i),
  29598. AudioProcessorGraph::midiChannelIndex))
  29599. {
  29600. midiNodeIds.set (i, (uint32) freeNodeID);
  29601. }
  29602. }
  29603. }
  29604. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29605. int inputChannelOfIndexToIgnore,
  29606. const uint32 nodeId,
  29607. const int outputChanIndex) const
  29608. {
  29609. while (stepIndexToSearchFrom < orderedNodes.size())
  29610. {
  29611. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29612. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29613. {
  29614. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29615. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29616. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29617. return true;
  29618. }
  29619. else
  29620. {
  29621. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29622. if (i != inputChannelOfIndexToIgnore
  29623. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29624. node->id, i) != 0)
  29625. return true;
  29626. }
  29627. inputChannelOfIndexToIgnore = -1;
  29628. ++stepIndexToSearchFrom;
  29629. }
  29630. return false;
  29631. }
  29632. void markBufferAsContaining (int bufferNum, uint32 nodeId, int outputIndex)
  29633. {
  29634. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29635. {
  29636. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29637. midiNodeIds.set (bufferNum, nodeId);
  29638. }
  29639. else
  29640. {
  29641. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29642. nodeIds.set (bufferNum, nodeId);
  29643. channels.set (bufferNum, outputIndex);
  29644. }
  29645. }
  29646. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RenderingOpSequenceCalculator);
  29647. };
  29648. }
  29649. void AudioProcessorGraph::clearRenderingSequence()
  29650. {
  29651. const ScopedLock sl (renderLock);
  29652. for (int i = renderingOps.size(); --i >= 0;)
  29653. {
  29654. GraphRenderingOps::AudioGraphRenderingOp* const r
  29655. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29656. renderingOps.remove (i);
  29657. delete r;
  29658. }
  29659. }
  29660. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29661. const uint32 possibleDestinationId,
  29662. const int recursionCheck) const
  29663. {
  29664. if (recursionCheck > 0)
  29665. {
  29666. for (int i = connections.size(); --i >= 0;)
  29667. {
  29668. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29669. if (c->destNodeId == possibleDestinationId
  29670. && (c->sourceNodeId == possibleInputId
  29671. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29672. return true;
  29673. }
  29674. }
  29675. return false;
  29676. }
  29677. void AudioProcessorGraph::buildRenderingSequence()
  29678. {
  29679. Array<void*> newRenderingOps;
  29680. int numRenderingBuffersNeeded = 2;
  29681. int numMidiBuffersNeeded = 1;
  29682. {
  29683. MessageManagerLock mml;
  29684. Array<void*> orderedNodes;
  29685. int i;
  29686. for (i = 0; i < nodes.size(); ++i)
  29687. {
  29688. Node* const node = nodes.getUnchecked(i);
  29689. node->prepare (getSampleRate(), getBlockSize(), this);
  29690. int j = 0;
  29691. for (; j < orderedNodes.size(); ++j)
  29692. if (isAnInputTo (node->id,
  29693. ((Node*) orderedNodes.getUnchecked (j))->id,
  29694. nodes.size() + 1))
  29695. break;
  29696. orderedNodes.insert (j, node);
  29697. }
  29698. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29699. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29700. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29701. }
  29702. Array<void*> oldRenderingOps (renderingOps);
  29703. {
  29704. // swap over to the new rendering sequence..
  29705. const ScopedLock sl (renderLock);
  29706. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29707. renderingBuffers.clear();
  29708. for (int i = midiBuffers.size(); --i >= 0;)
  29709. midiBuffers.getUnchecked(i)->clear();
  29710. while (midiBuffers.size() < numMidiBuffersNeeded)
  29711. midiBuffers.add (new MidiBuffer());
  29712. renderingOps = newRenderingOps;
  29713. }
  29714. for (int i = oldRenderingOps.size(); --i >= 0;)
  29715. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29716. }
  29717. void AudioProcessorGraph::handleAsyncUpdate()
  29718. {
  29719. buildRenderingSequence();
  29720. }
  29721. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29722. {
  29723. currentAudioInputBuffer = 0;
  29724. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29725. currentMidiInputBuffer = 0;
  29726. currentMidiOutputBuffer.clear();
  29727. clearRenderingSequence();
  29728. buildRenderingSequence();
  29729. }
  29730. void AudioProcessorGraph::releaseResources()
  29731. {
  29732. for (int i = 0; i < nodes.size(); ++i)
  29733. nodes.getUnchecked(i)->unprepare();
  29734. renderingBuffers.setSize (1, 1);
  29735. midiBuffers.clear();
  29736. currentAudioInputBuffer = 0;
  29737. currentAudioOutputBuffer.setSize (1, 1);
  29738. currentMidiInputBuffer = 0;
  29739. currentMidiOutputBuffer.clear();
  29740. }
  29741. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29742. {
  29743. const int numSamples = buffer.getNumSamples();
  29744. const ScopedLock sl (renderLock);
  29745. currentAudioInputBuffer = &buffer;
  29746. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29747. currentAudioOutputBuffer.clear();
  29748. currentMidiInputBuffer = &midiMessages;
  29749. currentMidiOutputBuffer.clear();
  29750. int i;
  29751. for (i = 0; i < renderingOps.size(); ++i)
  29752. {
  29753. GraphRenderingOps::AudioGraphRenderingOp* const op
  29754. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29755. op->perform (renderingBuffers, midiBuffers, numSamples);
  29756. }
  29757. for (i = 0; i < buffer.getNumChannels(); ++i)
  29758. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29759. midiMessages.clear();
  29760. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29761. }
  29762. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29763. {
  29764. return "Input " + String (channelIndex + 1);
  29765. }
  29766. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29767. {
  29768. return "Output " + String (channelIndex + 1);
  29769. }
  29770. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29771. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29772. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29773. bool AudioProcessorGraph::producesMidi() const { return true; }
  29774. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29775. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29776. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29777. : type (type_),
  29778. graph (0)
  29779. {
  29780. }
  29781. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29782. {
  29783. }
  29784. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29785. {
  29786. switch (type)
  29787. {
  29788. case audioOutputNode: return "Audio Output";
  29789. case audioInputNode: return "Audio Input";
  29790. case midiOutputNode: return "Midi Output";
  29791. case midiInputNode: return "Midi Input";
  29792. default: break;
  29793. }
  29794. return String::empty;
  29795. }
  29796. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29797. {
  29798. d.name = getName();
  29799. d.uid = d.name.hashCode();
  29800. d.category = "I/O devices";
  29801. d.pluginFormatName = "Internal";
  29802. d.manufacturerName = "Raw Material Software";
  29803. d.version = "1.0";
  29804. d.isInstrument = false;
  29805. d.numInputChannels = getNumInputChannels();
  29806. if (type == audioOutputNode && graph != 0)
  29807. d.numInputChannels = graph->getNumInputChannels();
  29808. d.numOutputChannels = getNumOutputChannels();
  29809. if (type == audioInputNode && graph != 0)
  29810. d.numOutputChannels = graph->getNumOutputChannels();
  29811. }
  29812. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29813. {
  29814. jassert (graph != 0);
  29815. }
  29816. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29817. {
  29818. }
  29819. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29820. MidiBuffer& midiMessages)
  29821. {
  29822. jassert (graph != 0);
  29823. switch (type)
  29824. {
  29825. case audioOutputNode:
  29826. {
  29827. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29828. buffer.getNumChannels()); --i >= 0;)
  29829. {
  29830. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29831. }
  29832. break;
  29833. }
  29834. case audioInputNode:
  29835. {
  29836. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29837. buffer.getNumChannels()); --i >= 0;)
  29838. {
  29839. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29840. }
  29841. break;
  29842. }
  29843. case midiOutputNode:
  29844. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29845. break;
  29846. case midiInputNode:
  29847. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29848. break;
  29849. default:
  29850. break;
  29851. }
  29852. }
  29853. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29854. {
  29855. return type == midiOutputNode;
  29856. }
  29857. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29858. {
  29859. return type == midiInputNode;
  29860. }
  29861. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29862. {
  29863. switch (type)
  29864. {
  29865. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29866. case midiOutputNode: return "Midi Output";
  29867. default: break;
  29868. }
  29869. return String::empty;
  29870. }
  29871. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29872. {
  29873. switch (type)
  29874. {
  29875. case audioInputNode: return "Input " + String (channelIndex + 1);
  29876. case midiInputNode: return "Midi Input";
  29877. default: break;
  29878. }
  29879. return String::empty;
  29880. }
  29881. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29882. {
  29883. return type == audioInputNode || type == audioOutputNode;
  29884. }
  29885. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29886. {
  29887. return isInputChannelStereoPair (index);
  29888. }
  29889. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29890. {
  29891. return type == audioInputNode || type == midiInputNode;
  29892. }
  29893. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29894. {
  29895. return type == audioOutputNode || type == midiOutputNode;
  29896. }
  29897. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29898. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29899. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29900. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29901. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29902. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29903. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29904. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29905. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29906. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29907. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29908. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29909. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29910. {
  29911. }
  29912. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29913. {
  29914. }
  29915. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29916. {
  29917. graph = newGraph;
  29918. if (graph != 0)
  29919. {
  29920. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29921. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29922. getSampleRate(),
  29923. getBlockSize());
  29924. updateHostDisplay();
  29925. }
  29926. }
  29927. END_JUCE_NAMESPACE
  29928. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29929. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29930. BEGIN_JUCE_NAMESPACE
  29931. AudioProcessorPlayer::AudioProcessorPlayer()
  29932. : processor (0),
  29933. sampleRate (0),
  29934. blockSize (0),
  29935. isPrepared (false),
  29936. numInputChans (0),
  29937. numOutputChans (0),
  29938. tempBuffer (1, 1)
  29939. {
  29940. }
  29941. AudioProcessorPlayer::~AudioProcessorPlayer()
  29942. {
  29943. setProcessor (0);
  29944. }
  29945. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29946. {
  29947. if (processor != processorToPlay)
  29948. {
  29949. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29950. {
  29951. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29952. sampleRate, blockSize);
  29953. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29954. }
  29955. AudioProcessor* oldOne;
  29956. {
  29957. const ScopedLock sl (lock);
  29958. oldOne = isPrepared ? processor : 0;
  29959. processor = processorToPlay;
  29960. isPrepared = true;
  29961. }
  29962. if (oldOne != 0)
  29963. oldOne->releaseResources();
  29964. }
  29965. }
  29966. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29967. const int numInputChannels,
  29968. float** const outputChannelData,
  29969. const int numOutputChannels,
  29970. const int numSamples)
  29971. {
  29972. // these should have been prepared by audioDeviceAboutToStart()...
  29973. jassert (sampleRate > 0 && blockSize > 0);
  29974. incomingMidi.clear();
  29975. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29976. int i, totalNumChans = 0;
  29977. if (numInputChannels > numOutputChannels)
  29978. {
  29979. // if there aren't enough output channels for the number of
  29980. // inputs, we need to create some temporary extra ones (can't
  29981. // use the input data in case it gets written to)
  29982. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29983. false, false, true);
  29984. for (i = 0; i < numOutputChannels; ++i)
  29985. {
  29986. channels[totalNumChans] = outputChannelData[i];
  29987. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29988. ++totalNumChans;
  29989. }
  29990. for (i = numOutputChannels; i < numInputChannels; ++i)
  29991. {
  29992. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29993. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29994. ++totalNumChans;
  29995. }
  29996. }
  29997. else
  29998. {
  29999. for (i = 0; i < numInputChannels; ++i)
  30000. {
  30001. channels[totalNumChans] = outputChannelData[i];
  30002. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30003. ++totalNumChans;
  30004. }
  30005. for (i = numInputChannels; i < numOutputChannels; ++i)
  30006. {
  30007. channels[totalNumChans] = outputChannelData[i];
  30008. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30009. ++totalNumChans;
  30010. }
  30011. }
  30012. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30013. const ScopedLock sl (lock);
  30014. if (processor != 0)
  30015. {
  30016. const ScopedLock sl2 (processor->getCallbackLock());
  30017. if (processor->isSuspended())
  30018. {
  30019. for (i = 0; i < numOutputChannels; ++i)
  30020. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30021. }
  30022. else
  30023. {
  30024. processor->processBlock (buffer, incomingMidi);
  30025. }
  30026. }
  30027. }
  30028. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30029. {
  30030. const ScopedLock sl (lock);
  30031. sampleRate = device->getCurrentSampleRate();
  30032. blockSize = device->getCurrentBufferSizeSamples();
  30033. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30034. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30035. messageCollector.reset (sampleRate);
  30036. zeromem (channels, sizeof (channels));
  30037. if (processor != 0)
  30038. {
  30039. if (isPrepared)
  30040. processor->releaseResources();
  30041. AudioProcessor* const oldProcessor = processor;
  30042. setProcessor (0);
  30043. setProcessor (oldProcessor);
  30044. }
  30045. }
  30046. void AudioProcessorPlayer::audioDeviceStopped()
  30047. {
  30048. const ScopedLock sl (lock);
  30049. if (processor != 0 && isPrepared)
  30050. processor->releaseResources();
  30051. sampleRate = 0.0;
  30052. blockSize = 0;
  30053. isPrepared = false;
  30054. tempBuffer.setSize (1, 1);
  30055. }
  30056. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30057. {
  30058. messageCollector.addMessageToQueue (message);
  30059. }
  30060. END_JUCE_NAMESPACE
  30061. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30062. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30063. BEGIN_JUCE_NAMESPACE
  30064. class ProcessorParameterPropertyComp : public PropertyComponent,
  30065. public AudioProcessorListener,
  30066. public Timer
  30067. {
  30068. public:
  30069. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  30070. : PropertyComponent (name),
  30071. owner (owner_),
  30072. index (index_),
  30073. paramHasChanged (false),
  30074. slider (owner_, index_)
  30075. {
  30076. startTimer (100);
  30077. addAndMakeVisible (&slider);
  30078. owner_.addListener (this);
  30079. }
  30080. ~ProcessorParameterPropertyComp()
  30081. {
  30082. owner.removeListener (this);
  30083. }
  30084. void refresh()
  30085. {
  30086. paramHasChanged = false;
  30087. slider.setValue (owner.getParameter (index), false);
  30088. }
  30089. void audioProcessorChanged (AudioProcessor*) {}
  30090. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30091. {
  30092. if (parameterIndex == index)
  30093. paramHasChanged = true;
  30094. }
  30095. void timerCallback()
  30096. {
  30097. if (paramHasChanged)
  30098. {
  30099. refresh();
  30100. startTimer (1000 / 50);
  30101. }
  30102. else
  30103. {
  30104. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  30105. }
  30106. }
  30107. private:
  30108. class ParamSlider : public Slider
  30109. {
  30110. public:
  30111. ParamSlider (AudioProcessor& owner_, const int index_)
  30112. : owner (owner_),
  30113. index (index_)
  30114. {
  30115. setRange (0.0, 1.0, 0.0);
  30116. setSliderStyle (Slider::LinearBar);
  30117. setTextBoxIsEditable (false);
  30118. setScrollWheelEnabled (false);
  30119. }
  30120. void valueChanged()
  30121. {
  30122. const float newVal = (float) getValue();
  30123. if (owner.getParameter (index) != newVal)
  30124. owner.setParameter (index, newVal);
  30125. }
  30126. const String getTextFromValue (double /*value*/)
  30127. {
  30128. return owner.getParameterText (index);
  30129. }
  30130. private:
  30131. AudioProcessor& owner;
  30132. const int index;
  30133. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParamSlider);
  30134. };
  30135. AudioProcessor& owner;
  30136. const int index;
  30137. bool volatile paramHasChanged;
  30138. ParamSlider slider;
  30139. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProcessorParameterPropertyComp);
  30140. };
  30141. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30142. : AudioProcessorEditor (owner_)
  30143. {
  30144. jassert (owner_ != 0);
  30145. setOpaque (true);
  30146. addAndMakeVisible (&panel);
  30147. Array <PropertyComponent*> params;
  30148. const int numParams = owner_->getNumParameters();
  30149. int totalHeight = 0;
  30150. for (int i = 0; i < numParams; ++i)
  30151. {
  30152. String name (owner_->getParameterName (i));
  30153. if (name.trim().isEmpty())
  30154. name = "Unnamed";
  30155. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30156. params.add (pc);
  30157. totalHeight += pc->getPreferredHeight();
  30158. }
  30159. panel.addProperties (params);
  30160. setSize (400, jlimit (25, 400, totalHeight));
  30161. }
  30162. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30163. {
  30164. }
  30165. void GenericAudioProcessorEditor::paint (Graphics& g)
  30166. {
  30167. g.fillAll (Colours::white);
  30168. }
  30169. void GenericAudioProcessorEditor::resized()
  30170. {
  30171. panel.setBounds (getLocalBounds());
  30172. }
  30173. END_JUCE_NAMESPACE
  30174. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30175. /*** Start of inlined file: juce_Sampler.cpp ***/
  30176. BEGIN_JUCE_NAMESPACE
  30177. SamplerSound::SamplerSound (const String& name_,
  30178. AudioFormatReader& source,
  30179. const BigInteger& midiNotes_,
  30180. const int midiNoteForNormalPitch,
  30181. const double attackTimeSecs,
  30182. const double releaseTimeSecs,
  30183. const double maxSampleLengthSeconds)
  30184. : name (name_),
  30185. midiNotes (midiNotes_),
  30186. midiRootNote (midiNoteForNormalPitch)
  30187. {
  30188. sourceSampleRate = source.sampleRate;
  30189. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30190. {
  30191. length = 0;
  30192. attackSamples = 0;
  30193. releaseSamples = 0;
  30194. }
  30195. else
  30196. {
  30197. length = jmin ((int) source.lengthInSamples,
  30198. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30199. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30200. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30201. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30202. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30203. }
  30204. }
  30205. SamplerSound::~SamplerSound()
  30206. {
  30207. }
  30208. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30209. {
  30210. return midiNotes [midiNoteNumber];
  30211. }
  30212. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30213. {
  30214. return true;
  30215. }
  30216. SamplerVoice::SamplerVoice()
  30217. : pitchRatio (0.0),
  30218. sourceSamplePosition (0.0),
  30219. lgain (0.0f),
  30220. rgain (0.0f),
  30221. isInAttack (false),
  30222. isInRelease (false)
  30223. {
  30224. }
  30225. SamplerVoice::~SamplerVoice()
  30226. {
  30227. }
  30228. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30229. {
  30230. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30231. }
  30232. void SamplerVoice::startNote (const int midiNoteNumber,
  30233. const float velocity,
  30234. SynthesiserSound* s,
  30235. const int /*currentPitchWheelPosition*/)
  30236. {
  30237. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30238. jassert (sound != 0); // this object can only play SamplerSounds!
  30239. if (sound != 0)
  30240. {
  30241. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30242. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30243. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30244. sourceSamplePosition = 0.0;
  30245. lgain = velocity;
  30246. rgain = velocity;
  30247. isInAttack = (sound->attackSamples > 0);
  30248. isInRelease = false;
  30249. if (isInAttack)
  30250. {
  30251. attackReleaseLevel = 0.0f;
  30252. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30253. }
  30254. else
  30255. {
  30256. attackReleaseLevel = 1.0f;
  30257. attackDelta = 0.0f;
  30258. }
  30259. if (sound->releaseSamples > 0)
  30260. {
  30261. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30262. }
  30263. else
  30264. {
  30265. releaseDelta = 0.0f;
  30266. }
  30267. }
  30268. }
  30269. void SamplerVoice::stopNote (const bool allowTailOff)
  30270. {
  30271. if (allowTailOff)
  30272. {
  30273. isInAttack = false;
  30274. isInRelease = true;
  30275. }
  30276. else
  30277. {
  30278. clearCurrentNote();
  30279. }
  30280. }
  30281. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30282. {
  30283. }
  30284. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30285. const int /*newValue*/)
  30286. {
  30287. }
  30288. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30289. {
  30290. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30291. if (playingSound != 0)
  30292. {
  30293. const float* const inL = playingSound->data->getSampleData (0, 0);
  30294. const float* const inR = playingSound->data->getNumChannels() > 1
  30295. ? playingSound->data->getSampleData (1, 0) : 0;
  30296. float* outL = outputBuffer.getSampleData (0, startSample);
  30297. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30298. while (--numSamples >= 0)
  30299. {
  30300. const int pos = (int) sourceSamplePosition;
  30301. const float alpha = (float) (sourceSamplePosition - pos);
  30302. const float invAlpha = 1.0f - alpha;
  30303. // just using a very simple linear interpolation here..
  30304. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30305. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30306. : l;
  30307. l *= lgain;
  30308. r *= rgain;
  30309. if (isInAttack)
  30310. {
  30311. l *= attackReleaseLevel;
  30312. r *= attackReleaseLevel;
  30313. attackReleaseLevel += attackDelta;
  30314. if (attackReleaseLevel >= 1.0f)
  30315. {
  30316. attackReleaseLevel = 1.0f;
  30317. isInAttack = false;
  30318. }
  30319. }
  30320. else if (isInRelease)
  30321. {
  30322. l *= attackReleaseLevel;
  30323. r *= attackReleaseLevel;
  30324. attackReleaseLevel += releaseDelta;
  30325. if (attackReleaseLevel <= 0.0f)
  30326. {
  30327. stopNote (false);
  30328. break;
  30329. }
  30330. }
  30331. if (outR != 0)
  30332. {
  30333. *outL++ += l;
  30334. *outR++ += r;
  30335. }
  30336. else
  30337. {
  30338. *outL++ += (l + r) * 0.5f;
  30339. }
  30340. sourceSamplePosition += pitchRatio;
  30341. if (sourceSamplePosition > playingSound->length)
  30342. {
  30343. stopNote (false);
  30344. break;
  30345. }
  30346. }
  30347. }
  30348. }
  30349. END_JUCE_NAMESPACE
  30350. /*** End of inlined file: juce_Sampler.cpp ***/
  30351. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30352. BEGIN_JUCE_NAMESPACE
  30353. SynthesiserSound::SynthesiserSound()
  30354. {
  30355. }
  30356. SynthesiserSound::~SynthesiserSound()
  30357. {
  30358. }
  30359. SynthesiserVoice::SynthesiserVoice()
  30360. : currentSampleRate (44100.0),
  30361. currentlyPlayingNote (-1),
  30362. noteOnTime (0),
  30363. currentlyPlayingSound (0)
  30364. {
  30365. }
  30366. SynthesiserVoice::~SynthesiserVoice()
  30367. {
  30368. }
  30369. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30370. {
  30371. return currentlyPlayingSound != 0
  30372. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30373. }
  30374. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30375. {
  30376. currentSampleRate = newRate;
  30377. }
  30378. void SynthesiserVoice::clearCurrentNote()
  30379. {
  30380. currentlyPlayingNote = -1;
  30381. currentlyPlayingSound = 0;
  30382. }
  30383. Synthesiser::Synthesiser()
  30384. : sampleRate (0),
  30385. lastNoteOnCounter (0),
  30386. shouldStealNotes (true)
  30387. {
  30388. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30389. lastPitchWheelValues[i] = 0x2000;
  30390. }
  30391. Synthesiser::~Synthesiser()
  30392. {
  30393. }
  30394. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30395. {
  30396. const ScopedLock sl (lock);
  30397. return voices [index];
  30398. }
  30399. void Synthesiser::clearVoices()
  30400. {
  30401. const ScopedLock sl (lock);
  30402. voices.clear();
  30403. }
  30404. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30405. {
  30406. const ScopedLock sl (lock);
  30407. voices.add (newVoice);
  30408. }
  30409. void Synthesiser::removeVoice (const int index)
  30410. {
  30411. const ScopedLock sl (lock);
  30412. voices.remove (index);
  30413. }
  30414. void Synthesiser::clearSounds()
  30415. {
  30416. const ScopedLock sl (lock);
  30417. sounds.clear();
  30418. }
  30419. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30420. {
  30421. const ScopedLock sl (lock);
  30422. sounds.add (newSound);
  30423. }
  30424. void Synthesiser::removeSound (const int index)
  30425. {
  30426. const ScopedLock sl (lock);
  30427. sounds.remove (index);
  30428. }
  30429. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30430. {
  30431. shouldStealNotes = shouldStealNotes_;
  30432. }
  30433. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30434. {
  30435. if (sampleRate != newRate)
  30436. {
  30437. const ScopedLock sl (lock);
  30438. allNotesOff (0, false);
  30439. sampleRate = newRate;
  30440. for (int i = voices.size(); --i >= 0;)
  30441. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30442. }
  30443. }
  30444. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30445. const MidiBuffer& midiData,
  30446. int startSample,
  30447. int numSamples)
  30448. {
  30449. // must set the sample rate before using this!
  30450. jassert (sampleRate != 0);
  30451. const ScopedLock sl (lock);
  30452. MidiBuffer::Iterator midiIterator (midiData);
  30453. midiIterator.setNextSamplePosition (startSample);
  30454. MidiMessage m (0xf4, 0.0);
  30455. while (numSamples > 0)
  30456. {
  30457. int midiEventPos;
  30458. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30459. && midiEventPos < startSample + numSamples;
  30460. const int numThisTime = useEvent ? midiEventPos - startSample
  30461. : numSamples;
  30462. if (numThisTime > 0)
  30463. {
  30464. for (int i = voices.size(); --i >= 0;)
  30465. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30466. }
  30467. if (useEvent)
  30468. {
  30469. if (m.isNoteOn())
  30470. {
  30471. const int channel = m.getChannel();
  30472. noteOn (channel,
  30473. m.getNoteNumber(),
  30474. m.getFloatVelocity());
  30475. }
  30476. else if (m.isNoteOff())
  30477. {
  30478. noteOff (m.getChannel(),
  30479. m.getNoteNumber(),
  30480. true);
  30481. }
  30482. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30483. {
  30484. allNotesOff (m.getChannel(), true);
  30485. }
  30486. else if (m.isPitchWheel())
  30487. {
  30488. const int channel = m.getChannel();
  30489. const int wheelPos = m.getPitchWheelValue();
  30490. lastPitchWheelValues [channel - 1] = wheelPos;
  30491. handlePitchWheel (channel, wheelPos);
  30492. }
  30493. else if (m.isController())
  30494. {
  30495. handleController (m.getChannel(),
  30496. m.getControllerNumber(),
  30497. m.getControllerValue());
  30498. }
  30499. }
  30500. startSample += numThisTime;
  30501. numSamples -= numThisTime;
  30502. }
  30503. }
  30504. void Synthesiser::noteOn (const int midiChannel,
  30505. const int midiNoteNumber,
  30506. const float velocity)
  30507. {
  30508. const ScopedLock sl (lock);
  30509. for (int i = sounds.size(); --i >= 0;)
  30510. {
  30511. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30512. if (sound->appliesToNote (midiNoteNumber)
  30513. && sound->appliesToChannel (midiChannel))
  30514. {
  30515. startVoice (findFreeVoice (sound, shouldStealNotes),
  30516. sound, midiChannel, midiNoteNumber, velocity);
  30517. }
  30518. }
  30519. }
  30520. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30521. SynthesiserSound* const sound,
  30522. const int midiChannel,
  30523. const int midiNoteNumber,
  30524. const float velocity)
  30525. {
  30526. if (voice != 0 && sound != 0)
  30527. {
  30528. if (voice->currentlyPlayingSound != 0)
  30529. voice->stopNote (false);
  30530. voice->startNote (midiNoteNumber,
  30531. velocity,
  30532. sound,
  30533. lastPitchWheelValues [midiChannel - 1]);
  30534. voice->currentlyPlayingNote = midiNoteNumber;
  30535. voice->noteOnTime = ++lastNoteOnCounter;
  30536. voice->currentlyPlayingSound = sound;
  30537. }
  30538. }
  30539. void Synthesiser::noteOff (const int midiChannel,
  30540. const int midiNoteNumber,
  30541. const bool allowTailOff)
  30542. {
  30543. const ScopedLock sl (lock);
  30544. for (int i = voices.size(); --i >= 0;)
  30545. {
  30546. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30547. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30548. {
  30549. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30550. if (sound != 0
  30551. && sound->appliesToNote (midiNoteNumber)
  30552. && sound->appliesToChannel (midiChannel))
  30553. {
  30554. voice->stopNote (allowTailOff);
  30555. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30556. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30557. }
  30558. }
  30559. }
  30560. }
  30561. void Synthesiser::allNotesOff (const int midiChannel,
  30562. const bool allowTailOff)
  30563. {
  30564. const ScopedLock sl (lock);
  30565. for (int i = voices.size(); --i >= 0;)
  30566. {
  30567. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30568. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30569. voice->stopNote (allowTailOff);
  30570. }
  30571. }
  30572. void Synthesiser::handlePitchWheel (const int midiChannel,
  30573. const int wheelValue)
  30574. {
  30575. const ScopedLock sl (lock);
  30576. for (int i = voices.size(); --i >= 0;)
  30577. {
  30578. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30579. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30580. {
  30581. voice->pitchWheelMoved (wheelValue);
  30582. }
  30583. }
  30584. }
  30585. void Synthesiser::handleController (const int midiChannel,
  30586. const int controllerNumber,
  30587. const int controllerValue)
  30588. {
  30589. const ScopedLock sl (lock);
  30590. for (int i = voices.size(); --i >= 0;)
  30591. {
  30592. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30593. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30594. voice->controllerMoved (controllerNumber, controllerValue);
  30595. }
  30596. }
  30597. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30598. const bool stealIfNoneAvailable) const
  30599. {
  30600. const ScopedLock sl (lock);
  30601. for (int i = voices.size(); --i >= 0;)
  30602. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30603. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30604. return voices.getUnchecked (i);
  30605. if (stealIfNoneAvailable)
  30606. {
  30607. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30608. SynthesiserVoice* oldest = 0;
  30609. for (int i = voices.size(); --i >= 0;)
  30610. {
  30611. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30612. if (voice->canPlaySound (soundToPlay)
  30613. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30614. oldest = voice;
  30615. }
  30616. jassert (oldest != 0);
  30617. return oldest;
  30618. }
  30619. return 0;
  30620. }
  30621. END_JUCE_NAMESPACE
  30622. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30623. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30624. BEGIN_JUCE_NAMESPACE
  30625. // special message of our own with a string in it
  30626. class ActionMessage : public Message
  30627. {
  30628. public:
  30629. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30630. : message (messageText)
  30631. {
  30632. pointerParameter = listener_;
  30633. }
  30634. const String message;
  30635. private:
  30636. JUCE_DECLARE_NON_COPYABLE (ActionMessage);
  30637. };
  30638. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30639. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30640. {
  30641. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30642. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30643. if (owner->actionListeners.contains (target))
  30644. target->actionListenerCallback (am.message);
  30645. }
  30646. ActionBroadcaster::ActionBroadcaster()
  30647. {
  30648. // are you trying to create this object before or after juce has been intialised??
  30649. jassert (MessageManager::instance != 0);
  30650. callback.owner = this;
  30651. }
  30652. ActionBroadcaster::~ActionBroadcaster()
  30653. {
  30654. // all event-based objects must be deleted BEFORE juce is shut down!
  30655. jassert (MessageManager::instance != 0);
  30656. }
  30657. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30658. {
  30659. const ScopedLock sl (actionListenerLock);
  30660. if (listener != 0)
  30661. actionListeners.add (listener);
  30662. }
  30663. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30664. {
  30665. const ScopedLock sl (actionListenerLock);
  30666. actionListeners.removeValue (listener);
  30667. }
  30668. void ActionBroadcaster::removeAllActionListeners()
  30669. {
  30670. const ScopedLock sl (actionListenerLock);
  30671. actionListeners.clear();
  30672. }
  30673. void ActionBroadcaster::sendActionMessage (const String& message) const
  30674. {
  30675. const ScopedLock sl (actionListenerLock);
  30676. for (int i = actionListeners.size(); --i >= 0;)
  30677. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30678. }
  30679. END_JUCE_NAMESPACE
  30680. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30681. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30682. BEGIN_JUCE_NAMESPACE
  30683. class AsyncUpdaterMessage : public CallbackMessage
  30684. {
  30685. public:
  30686. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30687. : owner (owner_)
  30688. {
  30689. }
  30690. void messageCallback()
  30691. {
  30692. if (shouldDeliver.compareAndSetBool (0, 1))
  30693. owner.handleAsyncUpdate();
  30694. }
  30695. Atomic<int> shouldDeliver;
  30696. private:
  30697. AsyncUpdater& owner;
  30698. };
  30699. AsyncUpdater::AsyncUpdater()
  30700. {
  30701. message = new AsyncUpdaterMessage (*this);
  30702. }
  30703. inline Atomic<int>& AsyncUpdater::getDeliveryFlag() const throw()
  30704. {
  30705. return static_cast <AsyncUpdaterMessage*> (message.getObject())->shouldDeliver;
  30706. }
  30707. AsyncUpdater::~AsyncUpdater()
  30708. {
  30709. // You're deleting this object with a background thread while there's an update
  30710. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30711. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30712. // deleting this object, or find some other way to avoid such a race condition.
  30713. jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30714. getDeliveryFlag().set (0);
  30715. }
  30716. void AsyncUpdater::triggerAsyncUpdate()
  30717. {
  30718. if (getDeliveryFlag().compareAndSetBool (1, 0))
  30719. message->post();
  30720. }
  30721. void AsyncUpdater::cancelPendingUpdate() throw()
  30722. {
  30723. getDeliveryFlag().set (0);
  30724. }
  30725. void AsyncUpdater::handleUpdateNowIfNeeded()
  30726. {
  30727. // This can only be called by the event thread.
  30728. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30729. if (getDeliveryFlag().exchange (0) != 0)
  30730. handleAsyncUpdate();
  30731. }
  30732. bool AsyncUpdater::isUpdatePending() const throw()
  30733. {
  30734. return getDeliveryFlag().value != 0;
  30735. }
  30736. END_JUCE_NAMESPACE
  30737. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30738. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30739. BEGIN_JUCE_NAMESPACE
  30740. ChangeBroadcaster::ChangeBroadcaster() throw()
  30741. {
  30742. // are you trying to create this object before or after juce has been intialised??
  30743. jassert (MessageManager::instance != 0);
  30744. callback.owner = this;
  30745. }
  30746. ChangeBroadcaster::~ChangeBroadcaster()
  30747. {
  30748. // all event-based objects must be deleted BEFORE juce is shut down!
  30749. jassert (MessageManager::instance != 0);
  30750. }
  30751. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30752. {
  30753. // Listeners can only be safely added when the event thread is locked
  30754. // You can use a MessageManagerLock if you need to call this from another thread.
  30755. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30756. changeListeners.add (listener);
  30757. }
  30758. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30759. {
  30760. // Listeners can only be safely added when the event thread is locked
  30761. // You can use a MessageManagerLock if you need to call this from another thread.
  30762. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30763. changeListeners.remove (listener);
  30764. }
  30765. void ChangeBroadcaster::removeAllChangeListeners()
  30766. {
  30767. // Listeners can only be safely added when the event thread is locked
  30768. // You can use a MessageManagerLock if you need to call this from another thread.
  30769. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30770. changeListeners.clear();
  30771. }
  30772. void ChangeBroadcaster::sendChangeMessage()
  30773. {
  30774. if (changeListeners.size() > 0)
  30775. callback.triggerAsyncUpdate();
  30776. }
  30777. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30778. {
  30779. // This can only be called by the event thread.
  30780. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30781. callback.cancelPendingUpdate();
  30782. callListeners();
  30783. }
  30784. void ChangeBroadcaster::dispatchPendingMessages()
  30785. {
  30786. callback.handleUpdateNowIfNeeded();
  30787. }
  30788. void ChangeBroadcaster::callListeners()
  30789. {
  30790. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30791. }
  30792. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30793. : owner (0)
  30794. {
  30795. }
  30796. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  30797. {
  30798. jassert (owner != 0);
  30799. owner->callListeners();
  30800. }
  30801. END_JUCE_NAMESPACE
  30802. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30803. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30804. BEGIN_JUCE_NAMESPACE
  30805. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30806. const uint32 magicMessageHeaderNumber)
  30807. : Thread ("Juce IPC connection"),
  30808. callbackConnectionState (false),
  30809. useMessageThread (callbacksOnMessageThread),
  30810. magicMessageHeader (magicMessageHeaderNumber),
  30811. pipeReceiveMessageTimeout (-1)
  30812. {
  30813. }
  30814. InterprocessConnection::~InterprocessConnection()
  30815. {
  30816. callbackConnectionState = false;
  30817. disconnect();
  30818. }
  30819. bool InterprocessConnection::connectToSocket (const String& hostName,
  30820. const int portNumber,
  30821. const int timeOutMillisecs)
  30822. {
  30823. disconnect();
  30824. const ScopedLock sl (pipeAndSocketLock);
  30825. socket = new StreamingSocket();
  30826. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30827. {
  30828. connectionMadeInt();
  30829. startThread();
  30830. return true;
  30831. }
  30832. else
  30833. {
  30834. socket = 0;
  30835. return false;
  30836. }
  30837. }
  30838. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30839. const int pipeReceiveMessageTimeoutMs)
  30840. {
  30841. disconnect();
  30842. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30843. if (newPipe->openExisting (pipeName))
  30844. {
  30845. const ScopedLock sl (pipeAndSocketLock);
  30846. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30847. initialiseWithPipe (newPipe.release());
  30848. return true;
  30849. }
  30850. return false;
  30851. }
  30852. bool InterprocessConnection::createPipe (const String& pipeName,
  30853. const int pipeReceiveMessageTimeoutMs)
  30854. {
  30855. disconnect();
  30856. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30857. if (newPipe->createNewPipe (pipeName))
  30858. {
  30859. const ScopedLock sl (pipeAndSocketLock);
  30860. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30861. initialiseWithPipe (newPipe.release());
  30862. return true;
  30863. }
  30864. return false;
  30865. }
  30866. void InterprocessConnection::disconnect()
  30867. {
  30868. if (socket != 0)
  30869. socket->close();
  30870. if (pipe != 0)
  30871. {
  30872. pipe->cancelPendingReads();
  30873. pipe->close();
  30874. }
  30875. stopThread (4000);
  30876. {
  30877. const ScopedLock sl (pipeAndSocketLock);
  30878. socket = 0;
  30879. pipe = 0;
  30880. }
  30881. connectionLostInt();
  30882. }
  30883. bool InterprocessConnection::isConnected() const
  30884. {
  30885. const ScopedLock sl (pipeAndSocketLock);
  30886. return ((socket != 0 && socket->isConnected())
  30887. || (pipe != 0 && pipe->isOpen()))
  30888. && isThreadRunning();
  30889. }
  30890. const String InterprocessConnection::getConnectedHostName() const
  30891. {
  30892. if (pipe != 0)
  30893. {
  30894. return "localhost";
  30895. }
  30896. else if (socket != 0)
  30897. {
  30898. if (! socket->isLocal())
  30899. return socket->getHostName();
  30900. return "localhost";
  30901. }
  30902. return String::empty;
  30903. }
  30904. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30905. {
  30906. uint32 messageHeader[2];
  30907. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30908. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30909. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30910. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30911. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30912. size_t bytesWritten = 0;
  30913. const ScopedLock sl (pipeAndSocketLock);
  30914. if (socket != 0)
  30915. {
  30916. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30917. }
  30918. else if (pipe != 0)
  30919. {
  30920. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30921. }
  30922. if (bytesWritten < 0)
  30923. {
  30924. // error..
  30925. return false;
  30926. }
  30927. return (bytesWritten == messageData.getSize());
  30928. }
  30929. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30930. {
  30931. jassert (socket == 0);
  30932. socket = socket_;
  30933. connectionMadeInt();
  30934. startThread();
  30935. }
  30936. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30937. {
  30938. jassert (pipe == 0);
  30939. pipe = pipe_;
  30940. connectionMadeInt();
  30941. startThread();
  30942. }
  30943. const int messageMagicNumber = 0xb734128b;
  30944. void InterprocessConnection::handleMessage (const Message& message)
  30945. {
  30946. if (message.intParameter1 == messageMagicNumber)
  30947. {
  30948. switch (message.intParameter2)
  30949. {
  30950. case 0:
  30951. {
  30952. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30953. messageReceived (*data);
  30954. break;
  30955. }
  30956. case 1:
  30957. connectionMade();
  30958. break;
  30959. case 2:
  30960. connectionLost();
  30961. break;
  30962. }
  30963. }
  30964. }
  30965. void InterprocessConnection::connectionMadeInt()
  30966. {
  30967. if (! callbackConnectionState)
  30968. {
  30969. callbackConnectionState = true;
  30970. if (useMessageThread)
  30971. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30972. else
  30973. connectionMade();
  30974. }
  30975. }
  30976. void InterprocessConnection::connectionLostInt()
  30977. {
  30978. if (callbackConnectionState)
  30979. {
  30980. callbackConnectionState = false;
  30981. if (useMessageThread)
  30982. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30983. else
  30984. connectionLost();
  30985. }
  30986. }
  30987. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30988. {
  30989. jassert (callbackConnectionState);
  30990. if (useMessageThread)
  30991. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30992. else
  30993. messageReceived (data);
  30994. }
  30995. bool InterprocessConnection::readNextMessageInt()
  30996. {
  30997. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30998. uint32 messageHeader[2];
  30999. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31000. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31001. if (bytes == sizeof (messageHeader)
  31002. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31003. {
  31004. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31005. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31006. {
  31007. MemoryBlock messageData (bytesInMessage, true);
  31008. int bytesRead = 0;
  31009. while (bytesInMessage > 0)
  31010. {
  31011. if (threadShouldExit())
  31012. return false;
  31013. const int numThisTime = jmin (bytesInMessage, 65536);
  31014. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31015. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31016. if (bytesIn <= 0)
  31017. break;
  31018. bytesRead += bytesIn;
  31019. bytesInMessage -= bytesIn;
  31020. }
  31021. if (bytesRead >= 0)
  31022. deliverDataInt (messageData);
  31023. }
  31024. }
  31025. else if (bytes < 0)
  31026. {
  31027. {
  31028. const ScopedLock sl (pipeAndSocketLock);
  31029. socket = 0;
  31030. }
  31031. connectionLostInt();
  31032. return false;
  31033. }
  31034. return true;
  31035. }
  31036. void InterprocessConnection::run()
  31037. {
  31038. while (! threadShouldExit())
  31039. {
  31040. if (socket != 0)
  31041. {
  31042. const int ready = socket->waitUntilReady (true, 0);
  31043. if (ready < 0)
  31044. {
  31045. {
  31046. const ScopedLock sl (pipeAndSocketLock);
  31047. socket = 0;
  31048. }
  31049. connectionLostInt();
  31050. break;
  31051. }
  31052. else if (ready > 0)
  31053. {
  31054. if (! readNextMessageInt())
  31055. break;
  31056. }
  31057. else
  31058. {
  31059. Thread::sleep (2);
  31060. }
  31061. }
  31062. else if (pipe != 0)
  31063. {
  31064. if (! pipe->isOpen())
  31065. {
  31066. {
  31067. const ScopedLock sl (pipeAndSocketLock);
  31068. pipe = 0;
  31069. }
  31070. connectionLostInt();
  31071. break;
  31072. }
  31073. else
  31074. {
  31075. if (! readNextMessageInt())
  31076. break;
  31077. }
  31078. }
  31079. else
  31080. {
  31081. break;
  31082. }
  31083. }
  31084. }
  31085. END_JUCE_NAMESPACE
  31086. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31087. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31088. BEGIN_JUCE_NAMESPACE
  31089. InterprocessConnectionServer::InterprocessConnectionServer()
  31090. : Thread ("Juce IPC server")
  31091. {
  31092. }
  31093. InterprocessConnectionServer::~InterprocessConnectionServer()
  31094. {
  31095. stop();
  31096. }
  31097. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31098. {
  31099. stop();
  31100. socket = new StreamingSocket();
  31101. if (socket->createListener (portNumber))
  31102. {
  31103. startThread();
  31104. return true;
  31105. }
  31106. socket = 0;
  31107. return false;
  31108. }
  31109. void InterprocessConnectionServer::stop()
  31110. {
  31111. signalThreadShouldExit();
  31112. if (socket != 0)
  31113. socket->close();
  31114. stopThread (4000);
  31115. socket = 0;
  31116. }
  31117. void InterprocessConnectionServer::run()
  31118. {
  31119. while ((! threadShouldExit()) && socket != 0)
  31120. {
  31121. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31122. if (clientSocket != 0)
  31123. {
  31124. InterprocessConnection* newConnection = createConnectionObject();
  31125. if (newConnection != 0)
  31126. newConnection->initialiseWithSocket (clientSocket.release());
  31127. }
  31128. }
  31129. }
  31130. END_JUCE_NAMESPACE
  31131. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31132. /*** Start of inlined file: juce_Message.cpp ***/
  31133. BEGIN_JUCE_NAMESPACE
  31134. Message::Message() throw()
  31135. : intParameter1 (0),
  31136. intParameter2 (0),
  31137. intParameter3 (0),
  31138. pointerParameter (0),
  31139. messageRecipient (0)
  31140. {
  31141. }
  31142. Message::Message (const int intParameter1_,
  31143. const int intParameter2_,
  31144. const int intParameter3_,
  31145. void* const pointerParameter_) throw()
  31146. : intParameter1 (intParameter1_),
  31147. intParameter2 (intParameter2_),
  31148. intParameter3 (intParameter3_),
  31149. pointerParameter (pointerParameter_),
  31150. messageRecipient (0)
  31151. {
  31152. }
  31153. Message::~Message()
  31154. {
  31155. }
  31156. END_JUCE_NAMESPACE
  31157. /*** End of inlined file: juce_Message.cpp ***/
  31158. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31159. BEGIN_JUCE_NAMESPACE
  31160. MessageListener::MessageListener() throw()
  31161. {
  31162. // are you trying to create a messagelistener before or after juce has been intialised??
  31163. jassert (MessageManager::instance != 0);
  31164. if (MessageManager::instance != 0)
  31165. MessageManager::instance->messageListeners.add (this);
  31166. }
  31167. MessageListener::~MessageListener()
  31168. {
  31169. if (MessageManager::instance != 0)
  31170. MessageManager::instance->messageListeners.removeValue (this);
  31171. }
  31172. void MessageListener::postMessage (Message* const message) const throw()
  31173. {
  31174. message->messageRecipient = const_cast <MessageListener*> (this);
  31175. if (MessageManager::instance == 0)
  31176. MessageManager::getInstance();
  31177. MessageManager::instance->postMessageToQueue (message);
  31178. }
  31179. bool MessageListener::isValidMessageListener() const throw()
  31180. {
  31181. return (MessageManager::instance != 0)
  31182. && MessageManager::instance->messageListeners.contains (this);
  31183. }
  31184. END_JUCE_NAMESPACE
  31185. /*** End of inlined file: juce_MessageListener.cpp ***/
  31186. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31187. BEGIN_JUCE_NAMESPACE
  31188. // platform-specific functions..
  31189. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31190. bool juce_postMessageToSystemQueue (Message* message);
  31191. MessageManager* MessageManager::instance = 0;
  31192. static const int quitMessageId = 0xfffff321;
  31193. MessageManager::MessageManager() throw()
  31194. : quitMessagePosted (false),
  31195. quitMessageReceived (false),
  31196. threadWithLock (0)
  31197. {
  31198. messageThreadId = Thread::getCurrentThreadId();
  31199. if (JUCEApplication::isStandaloneApp())
  31200. Thread::setCurrentThreadName ("Juce Message Thread");
  31201. }
  31202. MessageManager::~MessageManager() throw()
  31203. {
  31204. broadcaster = 0;
  31205. doPlatformSpecificShutdown();
  31206. // If you hit this assertion, then you've probably leaked some kind of MessageListener object..
  31207. jassert (messageListeners.size() == 0);
  31208. jassert (instance == this);
  31209. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31210. }
  31211. MessageManager* MessageManager::getInstance() throw()
  31212. {
  31213. if (instance == 0)
  31214. {
  31215. instance = new MessageManager();
  31216. doPlatformSpecificInitialisation();
  31217. }
  31218. return instance;
  31219. }
  31220. void MessageManager::postMessageToQueue (Message* const message)
  31221. {
  31222. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31223. Message::Ptr deleter (message); // (this will delete messages that were just created with a 0 ref count)
  31224. }
  31225. CallbackMessage::CallbackMessage() throw() {}
  31226. CallbackMessage::~CallbackMessage() {}
  31227. void CallbackMessage::post()
  31228. {
  31229. if (MessageManager::instance != 0)
  31230. MessageManager::instance->postMessageToQueue (this);
  31231. }
  31232. // not for public use..
  31233. void MessageManager::deliverMessage (Message* const message)
  31234. {
  31235. JUCE_TRY
  31236. {
  31237. MessageListener* const recipient = message->messageRecipient;
  31238. if (recipient == 0)
  31239. {
  31240. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31241. if (callbackMessage != 0)
  31242. {
  31243. callbackMessage->messageCallback();
  31244. }
  31245. else if (message->intParameter1 == quitMessageId)
  31246. {
  31247. quitMessageReceived = true;
  31248. }
  31249. }
  31250. else if (messageListeners.contains (recipient))
  31251. {
  31252. recipient->handleMessage (*message);
  31253. }
  31254. }
  31255. JUCE_CATCH_EXCEPTION
  31256. }
  31257. #if ! (JUCE_MAC || JUCE_IOS)
  31258. void MessageManager::runDispatchLoop()
  31259. {
  31260. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31261. runDispatchLoopUntil (-1);
  31262. }
  31263. void MessageManager::stopDispatchLoop()
  31264. {
  31265. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31266. quitMessagePosted = true;
  31267. }
  31268. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31269. {
  31270. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31271. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31272. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31273. && ! quitMessageReceived)
  31274. {
  31275. JUCE_TRY
  31276. {
  31277. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31278. {
  31279. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31280. if (msToWait > 0)
  31281. Thread::sleep (jmin (5, msToWait));
  31282. }
  31283. }
  31284. JUCE_CATCH_EXCEPTION
  31285. }
  31286. return ! quitMessageReceived;
  31287. }
  31288. #endif
  31289. void MessageManager::deliverBroadcastMessage (const String& value)
  31290. {
  31291. if (broadcaster != 0)
  31292. broadcaster->sendActionMessage (value);
  31293. }
  31294. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31295. {
  31296. if (broadcaster == 0)
  31297. broadcaster = new ActionBroadcaster();
  31298. broadcaster->addActionListener (listener);
  31299. }
  31300. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31301. {
  31302. if (broadcaster != 0)
  31303. broadcaster->removeActionListener (listener);
  31304. }
  31305. bool MessageManager::isThisTheMessageThread() const throw()
  31306. {
  31307. return Thread::getCurrentThreadId() == messageThreadId;
  31308. }
  31309. void MessageManager::setCurrentThreadAsMessageThread()
  31310. {
  31311. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31312. if (messageThreadId != thisThread)
  31313. {
  31314. messageThreadId = thisThread;
  31315. // This is needed on windows to make sure the message window is created by this thread
  31316. doPlatformSpecificShutdown();
  31317. doPlatformSpecificInitialisation();
  31318. }
  31319. }
  31320. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31321. {
  31322. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31323. return thisThread == messageThreadId || thisThread == threadWithLock;
  31324. }
  31325. /* The only safe way to lock the message thread while another thread does
  31326. some work is by posting a special message, whose purpose is to tie up the event
  31327. loop until the other thread has finished its business.
  31328. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31329. get locked before making an event callback, because if the same OS lock gets indirectly
  31330. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31331. in Cocoa).
  31332. */
  31333. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31334. {
  31335. public:
  31336. BlockingMessage() {}
  31337. void messageCallback()
  31338. {
  31339. lockedEvent.signal();
  31340. releaseEvent.wait();
  31341. }
  31342. WaitableEvent lockedEvent, releaseEvent;
  31343. private:
  31344. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockingMessage);
  31345. };
  31346. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31347. : locked (false)
  31348. {
  31349. init (threadToCheck, 0);
  31350. }
  31351. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31352. : locked (false)
  31353. {
  31354. init (0, jobToCheckForExitSignal);
  31355. }
  31356. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31357. {
  31358. if (MessageManager::instance != 0)
  31359. {
  31360. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31361. {
  31362. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31363. }
  31364. else
  31365. {
  31366. if (threadToCheck == 0 && job == 0)
  31367. {
  31368. MessageManager::instance->lockingLock.enter();
  31369. }
  31370. else
  31371. {
  31372. while (! MessageManager::instance->lockingLock.tryEnter())
  31373. {
  31374. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31375. || (job != 0 && job->shouldExit()))
  31376. return;
  31377. Thread::sleep (1);
  31378. }
  31379. }
  31380. blockingMessage = new BlockingMessage();
  31381. blockingMessage->post();
  31382. while (! blockingMessage->lockedEvent.wait (20))
  31383. {
  31384. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31385. || (job != 0 && job->shouldExit()))
  31386. {
  31387. blockingMessage->releaseEvent.signal();
  31388. blockingMessage = 0;
  31389. MessageManager::instance->lockingLock.exit();
  31390. return;
  31391. }
  31392. }
  31393. jassert (MessageManager::instance->threadWithLock == 0);
  31394. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31395. locked = true;
  31396. }
  31397. }
  31398. }
  31399. MessageManagerLock::~MessageManagerLock() throw()
  31400. {
  31401. if (blockingMessage != 0)
  31402. {
  31403. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31404. blockingMessage->releaseEvent.signal();
  31405. blockingMessage = 0;
  31406. if (MessageManager::instance != 0)
  31407. {
  31408. MessageManager::instance->threadWithLock = 0;
  31409. MessageManager::instance->lockingLock.exit();
  31410. }
  31411. }
  31412. }
  31413. END_JUCE_NAMESPACE
  31414. /*** End of inlined file: juce_MessageManager.cpp ***/
  31415. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31416. BEGIN_JUCE_NAMESPACE
  31417. class MultiTimer::MultiTimerCallback : public Timer
  31418. {
  31419. public:
  31420. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31421. : timerId (timerId_),
  31422. owner (owner_)
  31423. {
  31424. }
  31425. ~MultiTimerCallback()
  31426. {
  31427. }
  31428. void timerCallback()
  31429. {
  31430. owner.timerCallback (timerId);
  31431. }
  31432. const int timerId;
  31433. private:
  31434. MultiTimer& owner;
  31435. };
  31436. MultiTimer::MultiTimer() throw()
  31437. {
  31438. }
  31439. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31440. {
  31441. }
  31442. MultiTimer::~MultiTimer()
  31443. {
  31444. const ScopedLock sl (timerListLock);
  31445. timers.clear();
  31446. }
  31447. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31448. {
  31449. const ScopedLock sl (timerListLock);
  31450. for (int i = timers.size(); --i >= 0;)
  31451. {
  31452. MultiTimerCallback* const t = timers.getUnchecked(i);
  31453. if (t->timerId == timerId)
  31454. {
  31455. t->startTimer (intervalInMilliseconds);
  31456. return;
  31457. }
  31458. }
  31459. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31460. timers.add (newTimer);
  31461. newTimer->startTimer (intervalInMilliseconds);
  31462. }
  31463. void MultiTimer::stopTimer (const int timerId) throw()
  31464. {
  31465. const ScopedLock sl (timerListLock);
  31466. for (int i = timers.size(); --i >= 0;)
  31467. {
  31468. MultiTimerCallback* const t = timers.getUnchecked(i);
  31469. if (t->timerId == timerId)
  31470. t->stopTimer();
  31471. }
  31472. }
  31473. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31474. {
  31475. const ScopedLock sl (timerListLock);
  31476. for (int i = timers.size(); --i >= 0;)
  31477. {
  31478. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31479. if (t->timerId == timerId)
  31480. return t->isTimerRunning();
  31481. }
  31482. return false;
  31483. }
  31484. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31485. {
  31486. const ScopedLock sl (timerListLock);
  31487. for (int i = timers.size(); --i >= 0;)
  31488. {
  31489. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31490. if (t->timerId == timerId)
  31491. return t->getTimerInterval();
  31492. }
  31493. return 0;
  31494. }
  31495. END_JUCE_NAMESPACE
  31496. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31497. /*** Start of inlined file: juce_Timer.cpp ***/
  31498. BEGIN_JUCE_NAMESPACE
  31499. class InternalTimerThread : private Thread,
  31500. private MessageListener,
  31501. private DeletedAtShutdown,
  31502. private AsyncUpdater
  31503. {
  31504. public:
  31505. InternalTimerThread()
  31506. : Thread ("Juce Timer"),
  31507. firstTimer (0),
  31508. callbackNeeded (0)
  31509. {
  31510. triggerAsyncUpdate();
  31511. }
  31512. ~InternalTimerThread() throw()
  31513. {
  31514. stopThread (4000);
  31515. jassert (instance == this || instance == 0);
  31516. if (instance == this)
  31517. instance = 0;
  31518. }
  31519. void run()
  31520. {
  31521. uint32 lastTime = Time::getMillisecondCounter();
  31522. Message::Ptr message (new Message());
  31523. while (! threadShouldExit())
  31524. {
  31525. const uint32 now = Time::getMillisecondCounter();
  31526. if (now <= lastTime)
  31527. {
  31528. wait (2);
  31529. continue;
  31530. }
  31531. const int elapsed = now - lastTime;
  31532. lastTime = now;
  31533. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  31534. if (timeUntilFirstTimer <= 0)
  31535. {
  31536. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31537. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31538. but if it fails it means the message-thread changed the value from under us so at least
  31539. some processing is happenening and we can just loop around and try again
  31540. */
  31541. if (callbackNeeded.compareAndSetBool (1, 0))
  31542. {
  31543. postMessage (message);
  31544. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31545. when the app has a modal loop), so this is how long to wait before assuming the
  31546. message has been lost and trying again.
  31547. */
  31548. const uint32 messageDeliveryTimeout = now + 2000;
  31549. while (callbackNeeded.get() != 0)
  31550. {
  31551. wait (4);
  31552. if (threadShouldExit())
  31553. return;
  31554. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31555. break;
  31556. }
  31557. }
  31558. }
  31559. else
  31560. {
  31561. // don't wait for too long because running this loop also helps keep the
  31562. // Time::getApproximateMillisecondTimer value stay up-to-date
  31563. wait (jlimit (1, 50, timeUntilFirstTimer));
  31564. }
  31565. }
  31566. }
  31567. void callTimers()
  31568. {
  31569. const ScopedLock sl (lock);
  31570. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31571. {
  31572. Timer* const t = firstTimer;
  31573. t->countdownMs = t->periodMs;
  31574. removeTimer (t);
  31575. addTimer (t);
  31576. const ScopedUnlock ul (lock);
  31577. JUCE_TRY
  31578. {
  31579. t->timerCallback();
  31580. }
  31581. JUCE_CATCH_EXCEPTION
  31582. }
  31583. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31584. before the boolean is set. This set should never fail since if it was false in the first place,
  31585. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31586. get a message then the value is true and the other thread can only set it to true again and
  31587. we will get another callback to set it to false.
  31588. */
  31589. callbackNeeded.set (0);
  31590. }
  31591. void handleMessage (const Message&)
  31592. {
  31593. callTimers();
  31594. }
  31595. void callTimersSynchronously()
  31596. {
  31597. if (! isThreadRunning())
  31598. {
  31599. // (This is relied on by some plugins in cases where the MM has
  31600. // had to restart and the async callback never started)
  31601. cancelPendingUpdate();
  31602. triggerAsyncUpdate();
  31603. }
  31604. callTimers();
  31605. }
  31606. static void callAnyTimersSynchronously()
  31607. {
  31608. if (InternalTimerThread::instance != 0)
  31609. InternalTimerThread::instance->callTimersSynchronously();
  31610. }
  31611. static inline void add (Timer* const tim) throw()
  31612. {
  31613. if (instance == 0)
  31614. instance = new InternalTimerThread();
  31615. const ScopedLock sl (instance->lock);
  31616. instance->addTimer (tim);
  31617. }
  31618. static inline void remove (Timer* const tim) throw()
  31619. {
  31620. if (instance != 0)
  31621. {
  31622. const ScopedLock sl (instance->lock);
  31623. instance->removeTimer (tim);
  31624. }
  31625. }
  31626. static inline void resetCounter (Timer* const tim,
  31627. const int newCounter) throw()
  31628. {
  31629. if (instance != 0)
  31630. {
  31631. tim->countdownMs = newCounter;
  31632. tim->periodMs = newCounter;
  31633. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31634. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31635. {
  31636. const ScopedLock sl (instance->lock);
  31637. instance->removeTimer (tim);
  31638. instance->addTimer (tim);
  31639. }
  31640. }
  31641. }
  31642. private:
  31643. friend class Timer;
  31644. static InternalTimerThread* instance;
  31645. static CriticalSection lock;
  31646. Timer* volatile firstTimer;
  31647. Atomic <int> callbackNeeded;
  31648. void addTimer (Timer* const t) throw()
  31649. {
  31650. #if JUCE_DEBUG
  31651. Timer* tt = firstTimer;
  31652. while (tt != 0)
  31653. {
  31654. // trying to add a timer that's already here - shouldn't get to this point,
  31655. // so if you get this assertion, let me know!
  31656. jassert (tt != t);
  31657. tt = tt->next;
  31658. }
  31659. jassert (t->previous == 0 && t->next == 0);
  31660. #endif
  31661. Timer* i = firstTimer;
  31662. if (i == 0 || i->countdownMs > t->countdownMs)
  31663. {
  31664. t->next = firstTimer;
  31665. firstTimer = t;
  31666. }
  31667. else
  31668. {
  31669. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31670. i = i->next;
  31671. jassert (i != 0);
  31672. t->next = i->next;
  31673. t->previous = i;
  31674. i->next = t;
  31675. }
  31676. if (t->next != 0)
  31677. t->next->previous = t;
  31678. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31679. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31680. notify();
  31681. }
  31682. void removeTimer (Timer* const t) throw()
  31683. {
  31684. #if JUCE_DEBUG
  31685. Timer* tt = firstTimer;
  31686. bool found = false;
  31687. while (tt != 0)
  31688. {
  31689. if (tt == t)
  31690. {
  31691. found = true;
  31692. break;
  31693. }
  31694. tt = tt->next;
  31695. }
  31696. // trying to remove a timer that's not here - shouldn't get to this point,
  31697. // so if you get this assertion, let me know!
  31698. jassert (found);
  31699. #endif
  31700. if (t->previous != 0)
  31701. {
  31702. jassert (firstTimer != t);
  31703. t->previous->next = t->next;
  31704. }
  31705. else
  31706. {
  31707. jassert (firstTimer == t);
  31708. firstTimer = t->next;
  31709. }
  31710. if (t->next != 0)
  31711. t->next->previous = t->previous;
  31712. t->next = 0;
  31713. t->previous = 0;
  31714. }
  31715. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  31716. {
  31717. const ScopedLock sl (lock);
  31718. for (Timer* t = firstTimer; t != 0; t = t->next)
  31719. t->countdownMs -= numMillisecsElapsed;
  31720. return firstTimer != 0 ? firstTimer->countdownMs : 1000;
  31721. }
  31722. void handleAsyncUpdate()
  31723. {
  31724. startThread (7);
  31725. }
  31726. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternalTimerThread);
  31727. };
  31728. InternalTimerThread* InternalTimerThread::instance = 0;
  31729. CriticalSection InternalTimerThread::lock;
  31730. void juce_callAnyTimersSynchronously()
  31731. {
  31732. InternalTimerThread::callAnyTimersSynchronously();
  31733. }
  31734. #if JUCE_DEBUG
  31735. static SortedSet <Timer*> activeTimers;
  31736. #endif
  31737. Timer::Timer() throw()
  31738. : countdownMs (0),
  31739. periodMs (0),
  31740. previous (0),
  31741. next (0)
  31742. {
  31743. #if JUCE_DEBUG
  31744. activeTimers.add (this);
  31745. #endif
  31746. }
  31747. Timer::Timer (const Timer&) throw()
  31748. : countdownMs (0),
  31749. periodMs (0),
  31750. previous (0),
  31751. next (0)
  31752. {
  31753. #if JUCE_DEBUG
  31754. activeTimers.add (this);
  31755. #endif
  31756. }
  31757. Timer::~Timer()
  31758. {
  31759. stopTimer();
  31760. #if JUCE_DEBUG
  31761. activeTimers.removeValue (this);
  31762. #endif
  31763. }
  31764. void Timer::startTimer (const int interval) throw()
  31765. {
  31766. const ScopedLock sl (InternalTimerThread::lock);
  31767. #if JUCE_DEBUG
  31768. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31769. jassert (activeTimers.contains (this));
  31770. #endif
  31771. if (periodMs == 0)
  31772. {
  31773. countdownMs = interval;
  31774. periodMs = jmax (1, interval);
  31775. InternalTimerThread::add (this);
  31776. }
  31777. else
  31778. {
  31779. InternalTimerThread::resetCounter (this, interval);
  31780. }
  31781. }
  31782. void Timer::stopTimer() throw()
  31783. {
  31784. const ScopedLock sl (InternalTimerThread::lock);
  31785. #if JUCE_DEBUG
  31786. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31787. jassert (activeTimers.contains (this));
  31788. #endif
  31789. if (periodMs > 0)
  31790. {
  31791. InternalTimerThread::remove (this);
  31792. periodMs = 0;
  31793. }
  31794. }
  31795. END_JUCE_NAMESPACE
  31796. /*** End of inlined file: juce_Timer.cpp ***/
  31797. #endif
  31798. #if JUCE_BUILD_GUI
  31799. /*** Start of inlined file: juce_Component.cpp ***/
  31800. BEGIN_JUCE_NAMESPACE
  31801. #define CHECK_MESSAGE_MANAGER_IS_LOCKED jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31802. Component* Component::currentlyFocusedComponent = 0;
  31803. class Component::MouseListenerList
  31804. {
  31805. public:
  31806. MouseListenerList()
  31807. : numDeepMouseListeners (0)
  31808. {
  31809. }
  31810. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  31811. {
  31812. if (! listeners.contains (newListener))
  31813. {
  31814. if (wantsEventsForAllNestedChildComponents)
  31815. {
  31816. listeners.insert (0, newListener);
  31817. ++numDeepMouseListeners;
  31818. }
  31819. else
  31820. {
  31821. listeners.add (newListener);
  31822. }
  31823. }
  31824. }
  31825. void removeListener (MouseListener* const listenerToRemove)
  31826. {
  31827. const int index = listeners.indexOf (listenerToRemove);
  31828. if (index >= 0)
  31829. {
  31830. if (index < numDeepMouseListeners)
  31831. --numDeepMouseListeners;
  31832. listeners.remove (index);
  31833. }
  31834. }
  31835. static void sendMouseEvent (Component& comp, BailOutChecker& checker,
  31836. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  31837. {
  31838. if (checker.shouldBailOut())
  31839. return;
  31840. {
  31841. MouseListenerList* const list = comp.mouseListeners;
  31842. if (list != 0)
  31843. {
  31844. for (int i = list->listeners.size(); --i >= 0;)
  31845. {
  31846. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31847. if (checker.shouldBailOut())
  31848. return;
  31849. i = jmin (i, list->listeners.size());
  31850. }
  31851. }
  31852. }
  31853. Component* p = comp.parentComponent;
  31854. while (p != 0)
  31855. {
  31856. MouseListenerList* const list = p->mouseListeners;
  31857. if (list != 0 && list->numDeepMouseListeners > 0)
  31858. {
  31859. BailOutChecker2 checker2 (checker, p);
  31860. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31861. {
  31862. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31863. if (checker2.shouldBailOut())
  31864. return;
  31865. i = jmin (i, list->numDeepMouseListeners);
  31866. }
  31867. }
  31868. p = p->parentComponent;
  31869. }
  31870. }
  31871. static void sendWheelEvent (Component& comp, BailOutChecker& checker, const MouseEvent& e,
  31872. const float wheelIncrementX, const float wheelIncrementY)
  31873. {
  31874. {
  31875. MouseListenerList* const list = comp.mouseListeners;
  31876. if (list != 0)
  31877. {
  31878. for (int i = list->listeners.size(); --i >= 0;)
  31879. {
  31880. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31881. if (checker.shouldBailOut())
  31882. return;
  31883. i = jmin (i, list->listeners.size());
  31884. }
  31885. }
  31886. }
  31887. Component* p = comp.parentComponent;
  31888. while (p != 0)
  31889. {
  31890. MouseListenerList* const list = p->mouseListeners;
  31891. if (list != 0 && list->numDeepMouseListeners > 0)
  31892. {
  31893. BailOutChecker2 checker2 (checker, p);
  31894. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31895. {
  31896. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31897. if (checker2.shouldBailOut())
  31898. return;
  31899. i = jmin (i, list->numDeepMouseListeners);
  31900. }
  31901. }
  31902. p = p->parentComponent;
  31903. }
  31904. }
  31905. private:
  31906. Array <MouseListener*> listeners;
  31907. int numDeepMouseListeners;
  31908. class BailOutChecker2
  31909. {
  31910. public:
  31911. BailOutChecker2 (BailOutChecker& checker_, Component* const component)
  31912. : checker (checker_), safePointer (component)
  31913. {
  31914. }
  31915. bool shouldBailOut() const throw()
  31916. {
  31917. return checker.shouldBailOut() || safePointer == 0;
  31918. }
  31919. private:
  31920. BailOutChecker& checker;
  31921. const WeakReference<Component> safePointer;
  31922. JUCE_DECLARE_NON_COPYABLE (BailOutChecker2);
  31923. };
  31924. JUCE_DECLARE_NON_COPYABLE (MouseListenerList);
  31925. };
  31926. class Component::ComponentHelpers
  31927. {
  31928. public:
  31929. static void* runModalLoopCallback (void* userData)
  31930. {
  31931. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  31932. }
  31933. static const Identifier getColourPropertyId (const int colourId)
  31934. {
  31935. String s;
  31936. s.preallocateStorage (18);
  31937. s << "jcclr_" << String::toHexString (colourId);
  31938. return s;
  31939. }
  31940. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  31941. {
  31942. return isPositiveAndBelow (localPoint.getX(), comp.getWidth())
  31943. && isPositiveAndBelow (localPoint.getY(), comp.getHeight())
  31944. && comp.hitTest (localPoint.getX(), localPoint.getY());
  31945. }
  31946. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  31947. {
  31948. if (comp.affineTransform == 0)
  31949. return pointInParentSpace - comp.getPosition();
  31950. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform->inverted()).toInt() - comp.getPosition();
  31951. }
  31952. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  31953. {
  31954. if (comp.affineTransform == 0)
  31955. return areaInParentSpace - comp.getPosition();
  31956. return areaInParentSpace.toFloat().transformed (comp.affineTransform->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  31957. }
  31958. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  31959. {
  31960. if (comp.affineTransform == 0)
  31961. return pointInLocalSpace + comp.getPosition();
  31962. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform).toInt();
  31963. }
  31964. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  31965. {
  31966. if (comp.affineTransform == 0)
  31967. return areaInLocalSpace + comp.getPosition();
  31968. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform).getSmallestIntegerContainer();
  31969. }
  31970. template <typename Type>
  31971. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  31972. {
  31973. const Component* const directParent = target.getParentComponent();
  31974. jassert (directParent != 0);
  31975. if (directParent == parent)
  31976. return convertFromParentSpace (target, coordInParent);
  31977. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  31978. }
  31979. template <typename Type>
  31980. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  31981. {
  31982. while (source != 0)
  31983. {
  31984. if (source == target)
  31985. return p;
  31986. if (source->isParentOf (target))
  31987. return convertFromDistantParentSpace (source, *target, p);
  31988. if (source->isOnDesktop())
  31989. {
  31990. p = source->getPeer()->localToGlobal (p);
  31991. source = 0;
  31992. }
  31993. else
  31994. {
  31995. p = convertToParentSpace (*source, p);
  31996. source = source->getParentComponent();
  31997. }
  31998. }
  31999. jassert (source == 0);
  32000. if (target == 0)
  32001. return p;
  32002. const Component* const topLevelComp = target->getTopLevelComponent();
  32003. if (topLevelComp->isOnDesktop())
  32004. p = topLevelComp->getPeer()->globalToLocal (p);
  32005. else
  32006. p = convertFromParentSpace (*topLevelComp, p);
  32007. if (topLevelComp == target)
  32008. return p;
  32009. return convertFromDistantParentSpace (topLevelComp, *target, p);
  32010. }
  32011. static const Rectangle<int> getUnclippedArea (const Component& comp)
  32012. {
  32013. Rectangle<int> r (comp.getLocalBounds());
  32014. Component* const p = comp.getParentComponent();
  32015. if (p != 0)
  32016. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  32017. return r;
  32018. }
  32019. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  32020. {
  32021. for (int i = comp.childComponentList.size(); --i >= 0;)
  32022. {
  32023. const Component& child = *comp.childComponentList.getUnchecked(i);
  32024. if (child.isVisible() && ! child.isTransformed())
  32025. {
  32026. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds));
  32027. if (! newClip.isEmpty())
  32028. {
  32029. if (child.isOpaque())
  32030. {
  32031. g.excludeClipRegion (newClip + delta);
  32032. }
  32033. else
  32034. {
  32035. const Point<int> childPos (child.getPosition());
  32036. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  32037. }
  32038. }
  32039. }
  32040. }
  32041. }
  32042. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  32043. const Point<int>& delta,
  32044. const Rectangle<int>& clipRect,
  32045. const Component* const compToAvoid)
  32046. {
  32047. for (int i = comp.childComponentList.size(); --i >= 0;)
  32048. {
  32049. const Component* const c = comp.childComponentList.getUnchecked(i);
  32050. if (c != compToAvoid && c->isVisible())
  32051. {
  32052. if (c->isOpaque())
  32053. {
  32054. Rectangle<int> childBounds (c->bounds.getIntersection (clipRect));
  32055. childBounds.translate (delta.getX(), delta.getY());
  32056. result.subtract (childBounds);
  32057. }
  32058. else
  32059. {
  32060. Rectangle<int> newClip (clipRect.getIntersection (c->bounds));
  32061. newClip.translate (-c->getX(), -c->getY());
  32062. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  32063. newClip, compToAvoid);
  32064. }
  32065. }
  32066. }
  32067. }
  32068. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  32069. {
  32070. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  32071. : Desktop::getInstance().getMainMonitorArea();
  32072. }
  32073. };
  32074. Component::Component()
  32075. : parentComponent (0),
  32076. lookAndFeel (0),
  32077. effect (0),
  32078. componentFlags (0),
  32079. componentTransparency (0)
  32080. {
  32081. }
  32082. Component::Component (const String& name)
  32083. : componentName (name),
  32084. parentComponent (0),
  32085. lookAndFeel (0),
  32086. effect (0),
  32087. componentFlags (0),
  32088. componentTransparency (0)
  32089. {
  32090. }
  32091. Component::~Component()
  32092. {
  32093. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  32094. static_jassert (sizeof (flags) <= sizeof (componentFlags));
  32095. #endif
  32096. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32097. weakReferenceMaster.clear();
  32098. while (childComponentList.size() > 0)
  32099. removeChildComponent (childComponentList.size() - 1, false, true);
  32100. if (parentComponent != 0)
  32101. parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false);
  32102. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32103. giveAwayFocus (currentlyFocusedComponent != this);
  32104. if (flags.hasHeavyweightPeerFlag)
  32105. removeFromDesktop();
  32106. // Something has added some children to this component during its destructor! Not a smart idea!
  32107. jassert (childComponentList.size() == 0);
  32108. }
  32109. const WeakReference<Component>::SharedRef& Component::getWeakReference()
  32110. {
  32111. return weakReferenceMaster (this);
  32112. }
  32113. void Component::setName (const String& name)
  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. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32118. if (componentName != name)
  32119. {
  32120. componentName = name;
  32121. if (flags.hasHeavyweightPeerFlag)
  32122. {
  32123. ComponentPeer* const peer = getPeer();
  32124. jassert (peer != 0);
  32125. if (peer != 0)
  32126. peer->setTitle (name);
  32127. }
  32128. BailOutChecker checker (this);
  32129. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32130. }
  32131. }
  32132. void Component::setComponentID (const String& newID)
  32133. {
  32134. componentID = newID;
  32135. }
  32136. void Component::setVisible (bool shouldBeVisible)
  32137. {
  32138. if (flags.visibleFlag != shouldBeVisible)
  32139. {
  32140. // if component methods are being called from threads other than the message
  32141. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32142. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32143. WeakReference<Component> safePointer (this);
  32144. flags.visibleFlag = shouldBeVisible;
  32145. internalRepaint (0, 0, getWidth(), getHeight());
  32146. sendFakeMouseMove();
  32147. if (! shouldBeVisible)
  32148. {
  32149. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32150. {
  32151. if (parentComponent != 0)
  32152. parentComponent->grabKeyboardFocus();
  32153. else
  32154. giveAwayFocus (true);
  32155. }
  32156. }
  32157. if (safePointer != 0)
  32158. {
  32159. sendVisibilityChangeMessage();
  32160. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32161. {
  32162. ComponentPeer* const peer = getPeer();
  32163. jassert (peer != 0);
  32164. if (peer != 0)
  32165. {
  32166. peer->setVisible (shouldBeVisible);
  32167. internalHierarchyChanged();
  32168. }
  32169. }
  32170. }
  32171. }
  32172. }
  32173. void Component::visibilityChanged()
  32174. {
  32175. }
  32176. void Component::sendVisibilityChangeMessage()
  32177. {
  32178. BailOutChecker checker (this);
  32179. visibilityChanged();
  32180. if (! checker.shouldBailOut())
  32181. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32182. }
  32183. bool Component::isShowing() const
  32184. {
  32185. if (flags.visibleFlag)
  32186. {
  32187. if (parentComponent != 0)
  32188. {
  32189. return parentComponent->isShowing();
  32190. }
  32191. else
  32192. {
  32193. const ComponentPeer* const peer = getPeer();
  32194. return peer != 0 && ! peer->isMinimised();
  32195. }
  32196. }
  32197. return false;
  32198. }
  32199. void* Component::getWindowHandle() const
  32200. {
  32201. const ComponentPeer* const peer = getPeer();
  32202. if (peer != 0)
  32203. return peer->getNativeHandle();
  32204. return 0;
  32205. }
  32206. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32207. {
  32208. // if component methods are being called from threads other than the message
  32209. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32210. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32211. if (isOpaque())
  32212. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32213. else
  32214. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32215. int currentStyleFlags = 0;
  32216. // don't use getPeer(), so that we only get the peer that's specifically
  32217. // for this comp, and not for one of its parents.
  32218. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32219. if (peer != 0)
  32220. currentStyleFlags = peer->getStyleFlags();
  32221. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32222. {
  32223. WeakReference<Component> safePointer (this);
  32224. #if JUCE_LINUX
  32225. // it's wise to give the component a non-zero size before
  32226. // putting it on the desktop, as X windows get confused by this, and
  32227. // a (1, 1) minimum size is enforced here.
  32228. setSize (jmax (1, getWidth()),
  32229. jmax (1, getHeight()));
  32230. #endif
  32231. const Point<int> topLeft (getScreenPosition());
  32232. bool wasFullscreen = false;
  32233. bool wasMinimised = false;
  32234. ComponentBoundsConstrainer* currentConstainer = 0;
  32235. Rectangle<int> oldNonFullScreenBounds;
  32236. if (peer != 0)
  32237. {
  32238. wasFullscreen = peer->isFullScreen();
  32239. wasMinimised = peer->isMinimised();
  32240. currentConstainer = peer->getConstrainer();
  32241. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32242. removeFromDesktop();
  32243. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32244. }
  32245. if (parentComponent != 0)
  32246. parentComponent->removeChildComponent (this);
  32247. if (safePointer != 0)
  32248. {
  32249. flags.hasHeavyweightPeerFlag = true;
  32250. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32251. Desktop::getInstance().addDesktopComponent (this);
  32252. bounds.setPosition (topLeft);
  32253. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32254. peer->setVisible (isVisible());
  32255. if (wasFullscreen)
  32256. {
  32257. peer->setFullScreen (true);
  32258. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32259. }
  32260. if (wasMinimised)
  32261. peer->setMinimised (true);
  32262. if (isAlwaysOnTop())
  32263. peer->setAlwaysOnTop (true);
  32264. peer->setConstrainer (currentConstainer);
  32265. repaint();
  32266. }
  32267. internalHierarchyChanged();
  32268. }
  32269. }
  32270. void Component::removeFromDesktop()
  32271. {
  32272. // if component methods are being called from threads other than the message
  32273. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32274. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32275. if (flags.hasHeavyweightPeerFlag)
  32276. {
  32277. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32278. flags.hasHeavyweightPeerFlag = false;
  32279. jassert (peer != 0);
  32280. delete peer;
  32281. Desktop::getInstance().removeDesktopComponent (this);
  32282. }
  32283. }
  32284. bool Component::isOnDesktop() const throw()
  32285. {
  32286. return flags.hasHeavyweightPeerFlag;
  32287. }
  32288. void Component::userTriedToCloseWindow()
  32289. {
  32290. /* This means that the user's trying to get rid of your window with the 'close window' system
  32291. menu option (on windows) or possibly the task manager - you should really handle this
  32292. and delete or hide your component in an appropriate way.
  32293. If you want to ignore the event and don't want to trigger this assertion, just override
  32294. this method and do nothing.
  32295. */
  32296. jassertfalse;
  32297. }
  32298. void Component::minimisationStateChanged (bool)
  32299. {
  32300. }
  32301. void Component::setOpaque (const bool shouldBeOpaque)
  32302. {
  32303. if (shouldBeOpaque != flags.opaqueFlag)
  32304. {
  32305. flags.opaqueFlag = shouldBeOpaque;
  32306. if (flags.hasHeavyweightPeerFlag)
  32307. {
  32308. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32309. if (peer != 0)
  32310. {
  32311. // to make it recreate the heavyweight window
  32312. addToDesktop (peer->getStyleFlags());
  32313. }
  32314. }
  32315. repaint();
  32316. }
  32317. }
  32318. bool Component::isOpaque() const throw()
  32319. {
  32320. return flags.opaqueFlag;
  32321. }
  32322. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32323. {
  32324. if (shouldBeBuffered != flags.bufferToImageFlag)
  32325. {
  32326. bufferedImage = Image::null;
  32327. flags.bufferToImageFlag = shouldBeBuffered;
  32328. }
  32329. }
  32330. void Component::moveChildInternal (const int sourceIndex, const int destIndex)
  32331. {
  32332. if (sourceIndex != destIndex)
  32333. {
  32334. Component* const c = childComponentList.getUnchecked (sourceIndex);
  32335. jassert (c != 0);
  32336. c->repaintParent();
  32337. childComponentList.move (sourceIndex, destIndex);
  32338. sendFakeMouseMove();
  32339. internalChildrenChanged();
  32340. }
  32341. }
  32342. void Component::toFront (const bool setAsForeground)
  32343. {
  32344. // if component methods are being called from threads other than the message
  32345. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32346. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32347. if (flags.hasHeavyweightPeerFlag)
  32348. {
  32349. ComponentPeer* const peer = getPeer();
  32350. if (peer != 0)
  32351. {
  32352. peer->toFront (setAsForeground);
  32353. if (setAsForeground && ! hasKeyboardFocus (true))
  32354. grabKeyboardFocus();
  32355. }
  32356. }
  32357. else if (parentComponent != 0)
  32358. {
  32359. const Array<Component*>& childList = parentComponent->childComponentList;
  32360. if (childList.getLast() != this)
  32361. {
  32362. const int index = childList.indexOf (this);
  32363. if (index >= 0)
  32364. {
  32365. int insertIndex = -1;
  32366. if (! flags.alwaysOnTopFlag)
  32367. {
  32368. insertIndex = childList.size() - 1;
  32369. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32370. --insertIndex;
  32371. }
  32372. parentComponent->moveChildInternal (index, insertIndex);
  32373. }
  32374. }
  32375. if (setAsForeground)
  32376. {
  32377. internalBroughtToFront();
  32378. grabKeyboardFocus();
  32379. }
  32380. }
  32381. }
  32382. void Component::toBehind (Component* const other)
  32383. {
  32384. if (other != 0 && other != this)
  32385. {
  32386. // the two components must belong to the same parent..
  32387. jassert (parentComponent == other->parentComponent);
  32388. if (parentComponent != 0)
  32389. {
  32390. const Array<Component*>& childList = parentComponent->childComponentList;
  32391. const int index = childList.indexOf (this);
  32392. if (index >= 0 && childList [index + 1] != other)
  32393. {
  32394. int otherIndex = childList.indexOf (other);
  32395. if (otherIndex >= 0)
  32396. {
  32397. if (index < otherIndex)
  32398. --otherIndex;
  32399. parentComponent->moveChildInternal (index, otherIndex);
  32400. }
  32401. }
  32402. }
  32403. else if (isOnDesktop())
  32404. {
  32405. jassert (other->isOnDesktop());
  32406. if (other->isOnDesktop())
  32407. {
  32408. ComponentPeer* const us = getPeer();
  32409. ComponentPeer* const them = other->getPeer();
  32410. jassert (us != 0 && them != 0);
  32411. if (us != 0 && them != 0)
  32412. us->toBehind (them);
  32413. }
  32414. }
  32415. }
  32416. }
  32417. void Component::toBack()
  32418. {
  32419. if (isOnDesktop())
  32420. {
  32421. jassertfalse; //xxx need to add this to native window
  32422. }
  32423. else if (parentComponent != 0)
  32424. {
  32425. const Array<Component*>& childList = parentComponent->childComponentList;
  32426. if (childList.getFirst() != this)
  32427. {
  32428. const int index = childList.indexOf (this);
  32429. if (index > 0)
  32430. {
  32431. int insertIndex = 0;
  32432. if (flags.alwaysOnTopFlag)
  32433. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32434. ++insertIndex;
  32435. parentComponent->moveChildInternal (index, insertIndex);
  32436. }
  32437. }
  32438. }
  32439. }
  32440. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32441. {
  32442. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32443. {
  32444. flags.alwaysOnTopFlag = shouldStayOnTop;
  32445. if (isOnDesktop())
  32446. {
  32447. ComponentPeer* const peer = getPeer();
  32448. jassert (peer != 0);
  32449. if (peer != 0)
  32450. {
  32451. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32452. {
  32453. // some kinds of peer can't change their always-on-top status, so
  32454. // for these, we'll need to create a new window
  32455. const int oldFlags = peer->getStyleFlags();
  32456. removeFromDesktop();
  32457. addToDesktop (oldFlags);
  32458. }
  32459. }
  32460. }
  32461. if (shouldStayOnTop)
  32462. toFront (false);
  32463. internalHierarchyChanged();
  32464. }
  32465. }
  32466. bool Component::isAlwaysOnTop() const throw()
  32467. {
  32468. return flags.alwaysOnTopFlag;
  32469. }
  32470. int Component::proportionOfWidth (const float proportion) const throw()
  32471. {
  32472. return roundToInt (proportion * bounds.getWidth());
  32473. }
  32474. int Component::proportionOfHeight (const float proportion) const throw()
  32475. {
  32476. return roundToInt (proportion * bounds.getHeight());
  32477. }
  32478. int Component::getParentWidth() const throw()
  32479. {
  32480. return (parentComponent != 0) ? parentComponent->getWidth()
  32481. : getParentMonitorArea().getWidth();
  32482. }
  32483. int Component::getParentHeight() const throw()
  32484. {
  32485. return (parentComponent != 0) ? parentComponent->getHeight()
  32486. : getParentMonitorArea().getHeight();
  32487. }
  32488. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32489. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32490. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32491. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32492. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32493. {
  32494. return ComponentHelpers::convertCoordinate (this, source, point);
  32495. }
  32496. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32497. {
  32498. return ComponentHelpers::convertCoordinate (this, source, area);
  32499. }
  32500. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32501. {
  32502. return ComponentHelpers::convertCoordinate (0, this, point);
  32503. }
  32504. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32505. {
  32506. return ComponentHelpers::convertCoordinate (0, this, area);
  32507. }
  32508. /* Deprecated methods... */
  32509. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32510. {
  32511. return localPointToGlobal (relativePosition);
  32512. }
  32513. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32514. {
  32515. return getLocalPoint (0, screenPosition);
  32516. }
  32517. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32518. {
  32519. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32520. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32521. }
  32522. void Component::setBounds (const int x, const int y, int w, int h)
  32523. {
  32524. // if component methods are being called from threads other than the message
  32525. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32526. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32527. if (w < 0) w = 0;
  32528. if (h < 0) h = 0;
  32529. const bool wasResized = (getWidth() != w || getHeight() != h);
  32530. const bool wasMoved = (getX() != x || getY() != y);
  32531. #if JUCE_DEBUG
  32532. // It's a very bad idea to try to resize a window during its paint() method!
  32533. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32534. #endif
  32535. if (wasMoved || wasResized)
  32536. {
  32537. const bool showing = isShowing();
  32538. if (showing)
  32539. {
  32540. // send a fake mouse move to trigger enter/exit messages if needed..
  32541. sendFakeMouseMove();
  32542. if (! flags.hasHeavyweightPeerFlag)
  32543. repaintParent();
  32544. }
  32545. bounds.setBounds (x, y, w, h);
  32546. if (showing)
  32547. {
  32548. if (wasResized)
  32549. repaint();
  32550. else if (! flags.hasHeavyweightPeerFlag)
  32551. repaintParent();
  32552. }
  32553. if (flags.hasHeavyweightPeerFlag)
  32554. {
  32555. ComponentPeer* const peer = getPeer();
  32556. if (peer != 0)
  32557. {
  32558. if (wasMoved && wasResized)
  32559. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32560. else if (wasMoved)
  32561. peer->setPosition (getX(), getY());
  32562. else if (wasResized)
  32563. peer->setSize (getWidth(), getHeight());
  32564. }
  32565. }
  32566. sendMovedResizedMessages (wasMoved, wasResized);
  32567. }
  32568. }
  32569. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32570. {
  32571. BailOutChecker checker (this);
  32572. if (wasMoved)
  32573. {
  32574. moved();
  32575. if (checker.shouldBailOut())
  32576. return;
  32577. }
  32578. if (wasResized)
  32579. {
  32580. resized();
  32581. if (checker.shouldBailOut())
  32582. return;
  32583. for (int i = childComponentList.size(); --i >= 0;)
  32584. {
  32585. childComponentList.getUnchecked(i)->parentSizeChanged();
  32586. if (checker.shouldBailOut())
  32587. return;
  32588. i = jmin (i, childComponentList.size());
  32589. }
  32590. }
  32591. if (parentComponent != 0)
  32592. parentComponent->childBoundsChanged (this);
  32593. if (! checker.shouldBailOut())
  32594. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32595. *this, wasMoved, wasResized);
  32596. }
  32597. void Component::setSize (const int w, const int h)
  32598. {
  32599. setBounds (getX(), getY(), w, h);
  32600. }
  32601. void Component::setTopLeftPosition (const int x, const int y)
  32602. {
  32603. setBounds (x, y, getWidth(), getHeight());
  32604. }
  32605. void Component::setTopRightPosition (const int x, const int y)
  32606. {
  32607. setTopLeftPosition (x - getWidth(), y);
  32608. }
  32609. void Component::setBounds (const Rectangle<int>& r)
  32610. {
  32611. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  32612. }
  32613. void Component::setBounds (const RelativeRectangle& newBounds)
  32614. {
  32615. newBounds.applyToComponent (*this);
  32616. }
  32617. void Component::setBoundsRelative (const float x, const float y,
  32618. const float w, const float h)
  32619. {
  32620. const int pw = getParentWidth();
  32621. const int ph = getParentHeight();
  32622. setBounds (roundToInt (x * pw),
  32623. roundToInt (y * ph),
  32624. roundToInt (w * pw),
  32625. roundToInt (h * ph));
  32626. }
  32627. void Component::setCentrePosition (const int x, const int y)
  32628. {
  32629. setTopLeftPosition (x - getWidth() / 2,
  32630. y - getHeight() / 2);
  32631. }
  32632. void Component::setCentreRelative (const float x, const float y)
  32633. {
  32634. setCentrePosition (roundToInt (getParentWidth() * x),
  32635. roundToInt (getParentHeight() * y));
  32636. }
  32637. void Component::centreWithSize (const int width, const int height)
  32638. {
  32639. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32640. setBounds (parentArea.getCentreX() - width / 2,
  32641. parentArea.getCentreY() - height / 2,
  32642. width, height);
  32643. }
  32644. void Component::setBoundsInset (const BorderSize& borders)
  32645. {
  32646. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32647. }
  32648. void Component::setBoundsToFit (int x, int y, int width, int height,
  32649. const Justification& justification,
  32650. const bool onlyReduceInSize)
  32651. {
  32652. // it's no good calling this method unless both the component and
  32653. // target rectangle have a finite size.
  32654. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32655. if (getWidth() > 0 && getHeight() > 0
  32656. && width > 0 && height > 0)
  32657. {
  32658. int newW, newH;
  32659. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32660. {
  32661. newW = getWidth();
  32662. newH = getHeight();
  32663. }
  32664. else
  32665. {
  32666. const double imageRatio = getHeight() / (double) getWidth();
  32667. const double targetRatio = height / (double) width;
  32668. if (imageRatio <= targetRatio)
  32669. {
  32670. newW = width;
  32671. newH = jmin (height, roundToInt (newW * imageRatio));
  32672. }
  32673. else
  32674. {
  32675. newH = height;
  32676. newW = jmin (width, roundToInt (newH / imageRatio));
  32677. }
  32678. }
  32679. if (newW > 0 && newH > 0)
  32680. setBounds (justification.appliedToRectangle (Rectangle<int> (0, 0, newW, newH),
  32681. Rectangle<int> (x, y, width, height)));
  32682. }
  32683. }
  32684. bool Component::isTransformed() const throw()
  32685. {
  32686. return affineTransform != 0;
  32687. }
  32688. void Component::setTransform (const AffineTransform& newTransform)
  32689. {
  32690. // If you pass in a transform with no inverse, the component will have no dimensions,
  32691. // and there will be all sorts of maths errors when converting coordinates.
  32692. jassert (! newTransform.isSingularity());
  32693. if (newTransform.isIdentity())
  32694. {
  32695. if (affineTransform != 0)
  32696. {
  32697. repaint();
  32698. affineTransform = 0;
  32699. repaint();
  32700. sendMovedResizedMessages (false, false);
  32701. }
  32702. }
  32703. else if (affineTransform == 0)
  32704. {
  32705. repaint();
  32706. affineTransform = new AffineTransform (newTransform);
  32707. repaint();
  32708. sendMovedResizedMessages (false, false);
  32709. }
  32710. else if (*affineTransform != newTransform)
  32711. {
  32712. repaint();
  32713. *affineTransform = newTransform;
  32714. repaint();
  32715. sendMovedResizedMessages (false, false);
  32716. }
  32717. }
  32718. const AffineTransform Component::getTransform() const
  32719. {
  32720. return affineTransform != 0 ? *affineTransform : AffineTransform::identity;
  32721. }
  32722. bool Component::hitTest (int x, int y)
  32723. {
  32724. if (! flags.ignoresMouseClicksFlag)
  32725. return true;
  32726. if (flags.allowChildMouseClicksFlag)
  32727. {
  32728. for (int i = getNumChildComponents(); --i >= 0;)
  32729. {
  32730. Component& child = *getChildComponent (i);
  32731. if (child.isVisible()
  32732. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32733. return true;
  32734. }
  32735. }
  32736. return false;
  32737. }
  32738. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32739. const bool allowClicksOnChildComponents) throw()
  32740. {
  32741. flags.ignoresMouseClicksFlag = ! allowClicks;
  32742. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32743. }
  32744. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32745. bool& allowsClicksOnChildComponents) const throw()
  32746. {
  32747. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32748. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32749. }
  32750. bool Component::contains (const Point<int>& point)
  32751. {
  32752. if (ComponentHelpers::hitTest (*this, point))
  32753. {
  32754. if (parentComponent != 0)
  32755. {
  32756. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32757. }
  32758. else if (flags.hasHeavyweightPeerFlag)
  32759. {
  32760. const ComponentPeer* const peer = getPeer();
  32761. if (peer != 0)
  32762. return peer->contains (point, true);
  32763. }
  32764. }
  32765. return false;
  32766. }
  32767. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  32768. {
  32769. if (! contains (point))
  32770. return false;
  32771. Component* const top = getTopLevelComponent();
  32772. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  32773. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32774. }
  32775. Component* Component::getComponentAt (const Point<int>& position)
  32776. {
  32777. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32778. {
  32779. for (int i = childComponentList.size(); --i >= 0;)
  32780. {
  32781. Component* child = childComponentList.getUnchecked(i);
  32782. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32783. if (child != 0)
  32784. return child;
  32785. }
  32786. return this;
  32787. }
  32788. return 0;
  32789. }
  32790. Component* Component::getComponentAt (const int x, const int y)
  32791. {
  32792. return getComponentAt (Point<int> (x, y));
  32793. }
  32794. void Component::addChildComponent (Component* const child, int zOrder)
  32795. {
  32796. // if component methods are being called from threads other than the message
  32797. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32798. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32799. if (child != 0 && child->parentComponent != this)
  32800. {
  32801. if (child->parentComponent != 0)
  32802. child->parentComponent->removeChildComponent (child);
  32803. else
  32804. child->removeFromDesktop();
  32805. child->parentComponent = this;
  32806. if (child->isVisible())
  32807. child->repaintParent();
  32808. if (! child->isAlwaysOnTop())
  32809. {
  32810. if (zOrder < 0 || zOrder > childComponentList.size())
  32811. zOrder = childComponentList.size();
  32812. while (zOrder > 0)
  32813. {
  32814. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32815. break;
  32816. --zOrder;
  32817. }
  32818. }
  32819. childComponentList.insert (zOrder, child);
  32820. child->internalHierarchyChanged();
  32821. internalChildrenChanged();
  32822. }
  32823. }
  32824. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32825. {
  32826. if (child != 0)
  32827. {
  32828. child->setVisible (true);
  32829. addChildComponent (child, zOrder);
  32830. }
  32831. }
  32832. void Component::removeChildComponent (Component* const child)
  32833. {
  32834. removeChildComponent (childComponentList.indexOf (child), true, true);
  32835. }
  32836. Component* Component::removeChildComponent (const int index)
  32837. {
  32838. return removeChildComponent (index, true, true);
  32839. }
  32840. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  32841. {
  32842. // if component methods are being called from threads other than the message
  32843. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32844. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32845. Component* const child = childComponentList [index];
  32846. if (child != 0)
  32847. {
  32848. sendParentEvents = sendParentEvents && child->isShowing();
  32849. if (sendParentEvents)
  32850. {
  32851. sendFakeMouseMove();
  32852. child->repaintParent();
  32853. }
  32854. childComponentList.remove (index);
  32855. child->parentComponent = 0;
  32856. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  32857. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  32858. {
  32859. if (sendParentEvents)
  32860. {
  32861. const WeakReference<Component> thisPointer (this);
  32862. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32863. if (thisPointer == 0)
  32864. return child;
  32865. grabKeyboardFocus();
  32866. }
  32867. else
  32868. {
  32869. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32870. }
  32871. }
  32872. if (sendChildEvents)
  32873. child->internalHierarchyChanged();
  32874. if (sendParentEvents)
  32875. internalChildrenChanged();
  32876. }
  32877. return child;
  32878. }
  32879. void Component::removeAllChildren()
  32880. {
  32881. while (childComponentList.size() > 0)
  32882. removeChildComponent (childComponentList.size() - 1);
  32883. }
  32884. void Component::deleteAllChildren()
  32885. {
  32886. while (childComponentList.size() > 0)
  32887. delete (removeChildComponent (childComponentList.size() - 1));
  32888. }
  32889. int Component::getNumChildComponents() const throw()
  32890. {
  32891. return childComponentList.size();
  32892. }
  32893. Component* Component::getChildComponent (const int index) const throw()
  32894. {
  32895. return childComponentList [index];
  32896. }
  32897. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32898. {
  32899. return childComponentList.indexOf (const_cast <Component*> (child));
  32900. }
  32901. Component* Component::getTopLevelComponent() const throw()
  32902. {
  32903. const Component* comp = this;
  32904. while (comp->parentComponent != 0)
  32905. comp = comp->parentComponent;
  32906. return const_cast <Component*> (comp);
  32907. }
  32908. bool Component::isParentOf (const Component* possibleChild) const throw()
  32909. {
  32910. while (possibleChild != 0)
  32911. {
  32912. possibleChild = possibleChild->parentComponent;
  32913. if (possibleChild == this)
  32914. return true;
  32915. }
  32916. return false;
  32917. }
  32918. void Component::parentHierarchyChanged()
  32919. {
  32920. }
  32921. void Component::childrenChanged()
  32922. {
  32923. }
  32924. void Component::internalChildrenChanged()
  32925. {
  32926. if (componentListeners.isEmpty())
  32927. {
  32928. childrenChanged();
  32929. }
  32930. else
  32931. {
  32932. BailOutChecker checker (this);
  32933. childrenChanged();
  32934. if (! checker.shouldBailOut())
  32935. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32936. }
  32937. }
  32938. void Component::internalHierarchyChanged()
  32939. {
  32940. BailOutChecker checker (this);
  32941. parentHierarchyChanged();
  32942. if (checker.shouldBailOut())
  32943. return;
  32944. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32945. if (checker.shouldBailOut())
  32946. return;
  32947. for (int i = childComponentList.size(); --i >= 0;)
  32948. {
  32949. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  32950. if (checker.shouldBailOut())
  32951. {
  32952. // you really shouldn't delete the parent component during a callback telling you
  32953. // that it's changed..
  32954. jassertfalse;
  32955. return;
  32956. }
  32957. i = jmin (i, childComponentList.size());
  32958. }
  32959. }
  32960. int Component::runModalLoop()
  32961. {
  32962. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32963. {
  32964. // use a callback so this can be called from non-gui threads
  32965. return (int) (pointer_sized_int) MessageManager::getInstance()
  32966. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  32967. }
  32968. if (! isCurrentlyModal())
  32969. enterModalState (true);
  32970. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32971. }
  32972. void Component::enterModalState (const bool shouldTakeKeyboardFocus, ModalComponentManager::Callback* const callback)
  32973. {
  32974. // if component methods are being called from threads other than the message
  32975. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32976. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32977. // Check for an attempt to make a component modal when it already is!
  32978. // This can cause nasty problems..
  32979. jassert (! flags.currentlyModalFlag);
  32980. if (! isCurrentlyModal())
  32981. {
  32982. ModalComponentManager::getInstance()->startModal (this, callback);
  32983. flags.currentlyModalFlag = true;
  32984. setVisible (true);
  32985. if (shouldTakeKeyboardFocus)
  32986. grabKeyboardFocus();
  32987. }
  32988. }
  32989. void Component::exitModalState (const int returnValue)
  32990. {
  32991. if (flags.currentlyModalFlag)
  32992. {
  32993. if (MessageManager::getInstance()->isThisTheMessageThread())
  32994. {
  32995. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32996. flags.currentlyModalFlag = false;
  32997. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  32998. }
  32999. else
  33000. {
  33001. class ExitModalStateMessage : public CallbackMessage
  33002. {
  33003. public:
  33004. ExitModalStateMessage (Component* const target_, const int result_)
  33005. : target (target_), result (result_) {}
  33006. void messageCallback()
  33007. {
  33008. if (target.get() != 0) // (get() required for VS2003 bug)
  33009. target->exitModalState (result);
  33010. }
  33011. private:
  33012. WeakReference<Component> target;
  33013. int result;
  33014. };
  33015. (new ExitModalStateMessage (this, returnValue))->post();
  33016. }
  33017. }
  33018. }
  33019. bool Component::isCurrentlyModal() const throw()
  33020. {
  33021. return flags.currentlyModalFlag
  33022. && getCurrentlyModalComponent() == this;
  33023. }
  33024. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33025. {
  33026. Component* const mc = getCurrentlyModalComponent();
  33027. return mc != 0
  33028. && mc != this
  33029. && (! mc->isParentOf (this))
  33030. && ! mc->canModalEventBeSentToComponent (this);
  33031. }
  33032. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33033. {
  33034. return ModalComponentManager::getInstance()->getNumModalComponents();
  33035. }
  33036. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33037. {
  33038. return ModalComponentManager::getInstance()->getModalComponent (index);
  33039. }
  33040. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33041. {
  33042. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33043. }
  33044. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33045. {
  33046. return flags.bringToFrontOnClickFlag;
  33047. }
  33048. void Component::setMouseCursor (const MouseCursor& newCursor)
  33049. {
  33050. if (cursor != newCursor)
  33051. {
  33052. cursor = newCursor;
  33053. if (flags.visibleFlag)
  33054. updateMouseCursor();
  33055. }
  33056. }
  33057. const MouseCursor Component::getMouseCursor()
  33058. {
  33059. return cursor;
  33060. }
  33061. void Component::updateMouseCursor() const
  33062. {
  33063. sendFakeMouseMove();
  33064. }
  33065. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33066. {
  33067. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33068. }
  33069. void Component::setAlpha (const float newAlpha)
  33070. {
  33071. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  33072. if (componentTransparency != newIntAlpha)
  33073. {
  33074. componentTransparency = newIntAlpha;
  33075. if (flags.hasHeavyweightPeerFlag)
  33076. {
  33077. ComponentPeer* const peer = getPeer();
  33078. if (peer != 0)
  33079. peer->setAlpha (newAlpha);
  33080. }
  33081. else
  33082. {
  33083. repaint();
  33084. }
  33085. }
  33086. }
  33087. float Component::getAlpha() const
  33088. {
  33089. return (255 - componentTransparency) / 255.0f;
  33090. }
  33091. void Component::repaintParent()
  33092. {
  33093. if (flags.visibleFlag)
  33094. internalRepaint (0, 0, getWidth(), getHeight());
  33095. }
  33096. void Component::repaint()
  33097. {
  33098. repaint (0, 0, getWidth(), getHeight());
  33099. }
  33100. void Component::repaint (const int x, const int y,
  33101. const int w, const int h)
  33102. {
  33103. bufferedImage = Image::null;
  33104. if (flags.visibleFlag)
  33105. internalRepaint (x, y, w, h);
  33106. }
  33107. void Component::repaint (const Rectangle<int>& area)
  33108. {
  33109. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33110. }
  33111. void Component::internalRepaint (int x, int y, int w, int h)
  33112. {
  33113. // if component methods are being called from threads other than the message
  33114. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33115. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33116. if (x < 0)
  33117. {
  33118. w += x;
  33119. x = 0;
  33120. }
  33121. if (x + w > getWidth())
  33122. w = getWidth() - x;
  33123. if (w > 0)
  33124. {
  33125. if (y < 0)
  33126. {
  33127. h += y;
  33128. y = 0;
  33129. }
  33130. if (y + h > getHeight())
  33131. h = getHeight() - y;
  33132. if (h > 0)
  33133. {
  33134. if (parentComponent != 0)
  33135. {
  33136. if (parentComponent->flags.visibleFlag)
  33137. {
  33138. if (affineTransform == 0)
  33139. {
  33140. parentComponent->internalRepaint (x + getX(), y + getY(), w, h);
  33141. }
  33142. else
  33143. {
  33144. const Rectangle<int> r (ComponentHelpers::convertToParentSpace (*this, Rectangle<int> (x, y, w, h)));
  33145. parentComponent->internalRepaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  33146. }
  33147. }
  33148. }
  33149. else if (flags.hasHeavyweightPeerFlag)
  33150. {
  33151. ComponentPeer* const peer = getPeer();
  33152. if (peer != 0)
  33153. peer->repaint (Rectangle<int> (x, y, w, h));
  33154. }
  33155. }
  33156. }
  33157. }
  33158. void Component::paintComponent (Graphics& g)
  33159. {
  33160. if (flags.bufferToImageFlag)
  33161. {
  33162. if (bufferedImage.isNull())
  33163. {
  33164. bufferedImage = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33165. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33166. Graphics imG (bufferedImage);
  33167. paint (imG);
  33168. }
  33169. g.setColour (Colours::black.withAlpha (getAlpha()));
  33170. g.drawImageAt (bufferedImage, 0, 0);
  33171. }
  33172. else
  33173. {
  33174. paint (g);
  33175. }
  33176. }
  33177. void Component::paintWithinParentContext (Graphics& g)
  33178. {
  33179. g.setOrigin (getX(), getY());
  33180. paintEntireComponent (g, false);
  33181. }
  33182. void Component::paintComponentAndChildren (Graphics& g)
  33183. {
  33184. const Rectangle<int> clipBounds (g.getClipBounds());
  33185. if (flags.dontClipGraphicsFlag)
  33186. {
  33187. paintComponent (g);
  33188. }
  33189. else
  33190. {
  33191. g.saveState();
  33192. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  33193. if (! g.isClipEmpty())
  33194. paintComponent (g);
  33195. g.restoreState();
  33196. }
  33197. for (int i = 0; i < childComponentList.size(); ++i)
  33198. {
  33199. Component& child = *childComponentList.getUnchecked (i);
  33200. if (child.isVisible())
  33201. {
  33202. if (child.affineTransform != 0)
  33203. {
  33204. g.saveState();
  33205. g.addTransform (*child.affineTransform);
  33206. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  33207. child.paintWithinParentContext (g);
  33208. g.restoreState();
  33209. }
  33210. else if (clipBounds.intersects (child.getBounds()))
  33211. {
  33212. g.saveState();
  33213. if (child.flags.dontClipGraphicsFlag)
  33214. {
  33215. child.paintWithinParentContext (g);
  33216. }
  33217. else if (g.reduceClipRegion (child.getBounds()))
  33218. {
  33219. bool nothingClipped = true;
  33220. for (int j = i + 1; j < childComponentList.size(); ++j)
  33221. {
  33222. const Component& sibling = *childComponentList.getUnchecked (j);
  33223. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == 0)
  33224. {
  33225. nothingClipped = false;
  33226. g.excludeClipRegion (sibling.getBounds());
  33227. }
  33228. }
  33229. if (nothingClipped || ! g.isClipEmpty())
  33230. child.paintWithinParentContext (g);
  33231. }
  33232. g.restoreState();
  33233. }
  33234. }
  33235. }
  33236. g.saveState();
  33237. paintOverChildren (g);
  33238. g.restoreState();
  33239. }
  33240. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33241. {
  33242. jassert (! g.isClipEmpty());
  33243. #if JUCE_DEBUG
  33244. flags.isInsidePaintCall = true;
  33245. #endif
  33246. if (effect != 0)
  33247. {
  33248. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33249. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33250. {
  33251. Graphics g2 (effectImage);
  33252. paintComponentAndChildren (g2);
  33253. }
  33254. effect->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33255. }
  33256. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33257. {
  33258. if (componentTransparency < 255)
  33259. {
  33260. g.beginTransparencyLayer (getAlpha());
  33261. paintComponentAndChildren (g);
  33262. g.endTransparencyLayer();
  33263. }
  33264. }
  33265. else
  33266. {
  33267. paintComponentAndChildren (g);
  33268. }
  33269. #if JUCE_DEBUG
  33270. flags.isInsidePaintCall = false;
  33271. #endif
  33272. }
  33273. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33274. {
  33275. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33276. }
  33277. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33278. const bool clipImageToComponentBounds)
  33279. {
  33280. Rectangle<int> r (areaToGrab);
  33281. if (clipImageToComponentBounds)
  33282. r = r.getIntersection (getLocalBounds());
  33283. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33284. jmax (1, r.getWidth()),
  33285. jmax (1, r.getHeight()),
  33286. true);
  33287. Graphics imageContext (componentImage);
  33288. imageContext.setOrigin (-r.getX(), -r.getY());
  33289. paintEntireComponent (imageContext, true);
  33290. return componentImage;
  33291. }
  33292. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  33293. {
  33294. if (effect != newEffect)
  33295. {
  33296. effect = newEffect;
  33297. repaint();
  33298. }
  33299. }
  33300. LookAndFeel& Component::getLookAndFeel() const throw()
  33301. {
  33302. const Component* c = this;
  33303. do
  33304. {
  33305. if (c->lookAndFeel != 0)
  33306. return *(c->lookAndFeel);
  33307. c = c->parentComponent;
  33308. }
  33309. while (c != 0);
  33310. return LookAndFeel::getDefaultLookAndFeel();
  33311. }
  33312. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33313. {
  33314. if (lookAndFeel != newLookAndFeel)
  33315. {
  33316. lookAndFeel = newLookAndFeel;
  33317. sendLookAndFeelChange();
  33318. }
  33319. }
  33320. void Component::lookAndFeelChanged()
  33321. {
  33322. }
  33323. void Component::sendLookAndFeelChange()
  33324. {
  33325. repaint();
  33326. WeakReference<Component> safePointer (this);
  33327. lookAndFeelChanged();
  33328. if (safePointer != 0)
  33329. {
  33330. for (int i = childComponentList.size(); --i >= 0;)
  33331. {
  33332. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  33333. if (safePointer == 0)
  33334. return;
  33335. i = jmin (i, childComponentList.size());
  33336. }
  33337. }
  33338. }
  33339. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33340. {
  33341. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33342. if (v != 0)
  33343. return Colour ((int) *v);
  33344. if (inheritFromParent && parentComponent != 0)
  33345. return parentComponent->findColour (colourId, true);
  33346. return getLookAndFeel().findColour (colourId);
  33347. }
  33348. bool Component::isColourSpecified (const int colourId) const
  33349. {
  33350. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33351. }
  33352. void Component::removeColour (const int colourId)
  33353. {
  33354. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33355. colourChanged();
  33356. }
  33357. void Component::setColour (const int colourId, const Colour& colour)
  33358. {
  33359. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33360. colourChanged();
  33361. }
  33362. void Component::copyAllExplicitColoursTo (Component& target) const
  33363. {
  33364. bool changed = false;
  33365. for (int i = properties.size(); --i >= 0;)
  33366. {
  33367. const Identifier name (properties.getName(i));
  33368. if (name.toString().startsWith ("jcclr_"))
  33369. if (target.properties.set (name, properties [name]))
  33370. changed = true;
  33371. }
  33372. if (changed)
  33373. target.colourChanged();
  33374. }
  33375. void Component::colourChanged()
  33376. {
  33377. }
  33378. MarkerList* Component::getMarkers (bool /*xAxis*/)
  33379. {
  33380. return 0;
  33381. }
  33382. Component::Positioner::Positioner (Component& component_) throw()
  33383. : component (component_)
  33384. {
  33385. }
  33386. Component::Positioner* Component::getPositioner() const throw()
  33387. {
  33388. return positioner;
  33389. }
  33390. void Component::setPositioner (Positioner* newPositioner)
  33391. {
  33392. // You can only assign a positioner to the component that it was created for!
  33393. jassert (newPositioner == 0 || this == &(newPositioner->getComponent()));
  33394. positioner = newPositioner;
  33395. }
  33396. const Rectangle<int> Component::getLocalBounds() const throw()
  33397. {
  33398. return Rectangle<int> (getWidth(), getHeight());
  33399. }
  33400. const Rectangle<int> Component::getBoundsInParent() const throw()
  33401. {
  33402. return affineTransform == 0 ? bounds
  33403. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  33404. }
  33405. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33406. {
  33407. result.clear();
  33408. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33409. if (! unclipped.isEmpty())
  33410. {
  33411. result.add (unclipped);
  33412. if (includeSiblings)
  33413. {
  33414. const Component* const c = getTopLevelComponent();
  33415. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33416. c->getLocalBounds(), this);
  33417. }
  33418. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33419. result.consolidate();
  33420. }
  33421. }
  33422. void Component::mouseEnter (const MouseEvent&)
  33423. {
  33424. // base class does nothing
  33425. }
  33426. void Component::mouseExit (const MouseEvent&)
  33427. {
  33428. // base class does nothing
  33429. }
  33430. void Component::mouseDown (const MouseEvent&)
  33431. {
  33432. // base class does nothing
  33433. }
  33434. void Component::mouseUp (const MouseEvent&)
  33435. {
  33436. // base class does nothing
  33437. }
  33438. void Component::mouseDrag (const MouseEvent&)
  33439. {
  33440. // base class does nothing
  33441. }
  33442. void Component::mouseMove (const MouseEvent&)
  33443. {
  33444. // base class does nothing
  33445. }
  33446. void Component::mouseDoubleClick (const MouseEvent&)
  33447. {
  33448. // base class does nothing
  33449. }
  33450. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33451. {
  33452. // the base class just passes this event up to its parent..
  33453. if (parentComponent != 0)
  33454. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent),
  33455. wheelIncrementX, wheelIncrementY);
  33456. }
  33457. void Component::resized()
  33458. {
  33459. // base class does nothing
  33460. }
  33461. void Component::moved()
  33462. {
  33463. // base class does nothing
  33464. }
  33465. void Component::childBoundsChanged (Component*)
  33466. {
  33467. // base class does nothing
  33468. }
  33469. void Component::parentSizeChanged()
  33470. {
  33471. // base class does nothing
  33472. }
  33473. void Component::addComponentListener (ComponentListener* const newListener)
  33474. {
  33475. // if component methods are being called from threads other than the message
  33476. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33477. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33478. componentListeners.add (newListener);
  33479. }
  33480. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33481. {
  33482. componentListeners.remove (listenerToRemove);
  33483. }
  33484. void Component::inputAttemptWhenModal()
  33485. {
  33486. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33487. getLookAndFeel().playAlertSound();
  33488. }
  33489. bool Component::canModalEventBeSentToComponent (const Component*)
  33490. {
  33491. return false;
  33492. }
  33493. void Component::internalModalInputAttempt()
  33494. {
  33495. Component* const current = getCurrentlyModalComponent();
  33496. if (current != 0)
  33497. current->inputAttemptWhenModal();
  33498. }
  33499. void Component::paint (Graphics&)
  33500. {
  33501. // all painting is done in the subclasses
  33502. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33503. }
  33504. void Component::paintOverChildren (Graphics&)
  33505. {
  33506. // all painting is done in the subclasses
  33507. }
  33508. void Component::postCommandMessage (const int commandId)
  33509. {
  33510. class CustomCommandMessage : public CallbackMessage
  33511. {
  33512. public:
  33513. CustomCommandMessage (Component* const target_, const int commandId_)
  33514. : target (target_), commandId (commandId_) {}
  33515. void messageCallback()
  33516. {
  33517. if (target.get() != 0) // (get() required for VS2003 bug)
  33518. target->handleCommandMessage (commandId);
  33519. }
  33520. private:
  33521. WeakReference<Component> target;
  33522. int commandId;
  33523. };
  33524. (new CustomCommandMessage (this, commandId))->post();
  33525. }
  33526. void Component::handleCommandMessage (int)
  33527. {
  33528. // used by subclasses
  33529. }
  33530. void Component::addMouseListener (MouseListener* const newListener,
  33531. const bool wantsEventsForAllNestedChildComponents)
  33532. {
  33533. // if component methods are being called from threads other than the message
  33534. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33535. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33536. // If you register a component as a mouselistener for itself, it'll receive all the events
  33537. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33538. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33539. if (mouseListeners == 0)
  33540. mouseListeners = new MouseListenerList();
  33541. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33542. }
  33543. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33544. {
  33545. // if component methods are being called from threads other than the message
  33546. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33547. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33548. if (mouseListeners != 0)
  33549. mouseListeners->removeListener (listenerToRemove);
  33550. }
  33551. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33552. {
  33553. if (isCurrentlyBlockedByAnotherModalComponent())
  33554. {
  33555. // if something else is modal, always just show a normal mouse cursor
  33556. source.showMouseCursor (MouseCursor::NormalCursor);
  33557. return;
  33558. }
  33559. if (! flags.mouseInsideFlag)
  33560. {
  33561. flags.mouseInsideFlag = true;
  33562. flags.mouseOverFlag = true;
  33563. flags.mouseDownFlag = false;
  33564. BailOutChecker checker (this);
  33565. if (flags.repaintOnMouseActivityFlag)
  33566. repaint();
  33567. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33568. this, this, time, relativePos, time, 0, false);
  33569. mouseEnter (me);
  33570. if (checker.shouldBailOut())
  33571. return;
  33572. Desktop& desktop = Desktop::getInstance();
  33573. desktop.resetTimer();
  33574. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33575. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  33576. }
  33577. }
  33578. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33579. {
  33580. BailOutChecker checker (this);
  33581. if (flags.mouseDownFlag)
  33582. {
  33583. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33584. if (checker.shouldBailOut())
  33585. return;
  33586. }
  33587. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33588. {
  33589. flags.mouseInsideFlag = false;
  33590. flags.mouseOverFlag = false;
  33591. flags.mouseDownFlag = false;
  33592. if (flags.repaintOnMouseActivityFlag)
  33593. repaint();
  33594. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33595. this, this, time, relativePos, time, 0, false);
  33596. mouseExit (me);
  33597. if (checker.shouldBailOut())
  33598. return;
  33599. Desktop& desktop = Desktop::getInstance();
  33600. desktop.resetTimer();
  33601. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33602. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  33603. }
  33604. }
  33605. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33606. {
  33607. Desktop& desktop = Desktop::getInstance();
  33608. BailOutChecker checker (this);
  33609. if (isCurrentlyBlockedByAnotherModalComponent())
  33610. {
  33611. internalModalInputAttempt();
  33612. if (checker.shouldBailOut())
  33613. return;
  33614. // If processing the input attempt has exited the modal loop, we'll allow the event
  33615. // to be delivered..
  33616. if (isCurrentlyBlockedByAnotherModalComponent())
  33617. {
  33618. // allow blocked mouse-events to go to global listeners..
  33619. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33620. this, this, time, relativePos, time,
  33621. source.getNumberOfMultipleClicks(), false);
  33622. desktop.resetTimer();
  33623. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33624. return;
  33625. }
  33626. }
  33627. {
  33628. Component* c = this;
  33629. while (c != 0)
  33630. {
  33631. if (c->isBroughtToFrontOnMouseClick())
  33632. {
  33633. c->toFront (true);
  33634. if (checker.shouldBailOut())
  33635. return;
  33636. }
  33637. c = c->parentComponent;
  33638. }
  33639. }
  33640. if (! flags.dontFocusOnMouseClickFlag)
  33641. {
  33642. grabFocusInternal (focusChangedByMouseClick);
  33643. if (checker.shouldBailOut())
  33644. return;
  33645. }
  33646. flags.mouseDownFlag = true;
  33647. flags.mouseOverFlag = true;
  33648. if (flags.repaintOnMouseActivityFlag)
  33649. repaint();
  33650. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33651. this, this, time, relativePos, time,
  33652. source.getNumberOfMultipleClicks(), false);
  33653. mouseDown (me);
  33654. if (checker.shouldBailOut())
  33655. return;
  33656. desktop.resetTimer();
  33657. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33658. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  33659. }
  33660. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33661. {
  33662. if (flags.mouseDownFlag)
  33663. {
  33664. flags.mouseDownFlag = false;
  33665. BailOutChecker checker (this);
  33666. if (flags.repaintOnMouseActivityFlag)
  33667. repaint();
  33668. const MouseEvent me (source, relativePos,
  33669. oldModifiers, this, this, time,
  33670. getLocalPoint (0, source.getLastMouseDownPosition()),
  33671. source.getLastMouseDownTime(),
  33672. source.getNumberOfMultipleClicks(),
  33673. source.hasMouseMovedSignificantlySincePressed());
  33674. mouseUp (me);
  33675. if (checker.shouldBailOut())
  33676. return;
  33677. Desktop& desktop = Desktop::getInstance();
  33678. desktop.resetTimer();
  33679. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33680. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  33681. if (checker.shouldBailOut())
  33682. return;
  33683. // check for double-click
  33684. if (me.getNumberOfClicks() >= 2)
  33685. {
  33686. mouseDoubleClick (me);
  33687. if (checker.shouldBailOut())
  33688. return;
  33689. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33690. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  33691. }
  33692. }
  33693. }
  33694. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33695. {
  33696. if (flags.mouseDownFlag)
  33697. {
  33698. flags.mouseOverFlag = reallyContains (relativePos, false);
  33699. BailOutChecker checker (this);
  33700. const MouseEvent me (source, relativePos,
  33701. source.getCurrentModifiers(), this, this, time,
  33702. getLocalPoint (0, source.getLastMouseDownPosition()),
  33703. source.getLastMouseDownTime(),
  33704. source.getNumberOfMultipleClicks(),
  33705. source.hasMouseMovedSignificantlySincePressed());
  33706. mouseDrag (me);
  33707. if (checker.shouldBailOut())
  33708. return;
  33709. Desktop& desktop = Desktop::getInstance();
  33710. desktop.resetTimer();
  33711. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33712. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  33713. }
  33714. }
  33715. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33716. {
  33717. Desktop& desktop = Desktop::getInstance();
  33718. BailOutChecker checker (this);
  33719. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33720. this, this, time, relativePos, time, 0, false);
  33721. if (isCurrentlyBlockedByAnotherModalComponent())
  33722. {
  33723. // allow blocked mouse-events to go to global listeners..
  33724. desktop.sendMouseMove();
  33725. }
  33726. else
  33727. {
  33728. flags.mouseOverFlag = true;
  33729. mouseMove (me);
  33730. if (checker.shouldBailOut())
  33731. return;
  33732. desktop.resetTimer();
  33733. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33734. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  33735. }
  33736. }
  33737. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33738. const Time& time, const float amountX, const float amountY)
  33739. {
  33740. Desktop& desktop = Desktop::getInstance();
  33741. BailOutChecker checker (this);
  33742. const float wheelIncrementX = amountX / 256.0f;
  33743. const float wheelIncrementY = amountY / 256.0f;
  33744. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33745. this, this, time, relativePos, time, 0, false);
  33746. if (isCurrentlyBlockedByAnotherModalComponent())
  33747. {
  33748. // allow blocked mouse-events to go to global listeners..
  33749. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33750. }
  33751. else
  33752. {
  33753. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33754. if (checker.shouldBailOut())
  33755. return;
  33756. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33757. if (! checker.shouldBailOut())
  33758. MouseListenerList::sendWheelEvent (*this, checker, me, wheelIncrementX, wheelIncrementY);
  33759. }
  33760. }
  33761. void Component::sendFakeMouseMove() const
  33762. {
  33763. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  33764. if (! mainMouse.isDragging())
  33765. mainMouse.triggerFakeMove();
  33766. }
  33767. void Component::beginDragAutoRepeat (const int interval)
  33768. {
  33769. Desktop::getInstance().beginDragAutoRepeat (interval);
  33770. }
  33771. void Component::broughtToFront()
  33772. {
  33773. }
  33774. void Component::internalBroughtToFront()
  33775. {
  33776. if (flags.hasHeavyweightPeerFlag)
  33777. Desktop::getInstance().componentBroughtToFront (this);
  33778. BailOutChecker checker (this);
  33779. broughtToFront();
  33780. if (checker.shouldBailOut())
  33781. return;
  33782. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33783. if (checker.shouldBailOut())
  33784. return;
  33785. // When brought to the front and there's a modal component blocking this one,
  33786. // we need to bring the modal one to the front instead..
  33787. Component* const cm = getCurrentlyModalComponent();
  33788. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33789. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33790. }
  33791. void Component::focusGained (FocusChangeType)
  33792. {
  33793. // base class does nothing
  33794. }
  33795. void Component::internalFocusGain (const FocusChangeType cause)
  33796. {
  33797. internalFocusGain (cause, WeakReference<Component> (this));
  33798. }
  33799. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  33800. {
  33801. focusGained (cause);
  33802. if (safePointer != 0)
  33803. internalChildFocusChange (cause, safePointer);
  33804. }
  33805. void Component::focusLost (FocusChangeType)
  33806. {
  33807. // base class does nothing
  33808. }
  33809. void Component::internalFocusLoss (const FocusChangeType cause)
  33810. {
  33811. WeakReference<Component> safePointer (this);
  33812. focusLost (focusChangedDirectly);
  33813. if (safePointer != 0)
  33814. internalChildFocusChange (cause, safePointer);
  33815. }
  33816. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33817. {
  33818. // base class does nothing
  33819. }
  33820. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  33821. {
  33822. const bool childIsNowFocused = hasKeyboardFocus (true);
  33823. if (flags.childCompFocusedFlag != childIsNowFocused)
  33824. {
  33825. flags.childCompFocusedFlag = childIsNowFocused;
  33826. focusOfChildComponentChanged (cause);
  33827. if (safePointer == 0)
  33828. return;
  33829. }
  33830. if (parentComponent != 0)
  33831. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  33832. }
  33833. bool Component::isEnabled() const throw()
  33834. {
  33835. return (! flags.isDisabledFlag)
  33836. && (parentComponent == 0 || parentComponent->isEnabled());
  33837. }
  33838. void Component::setEnabled (const bool shouldBeEnabled)
  33839. {
  33840. if (flags.isDisabledFlag == shouldBeEnabled)
  33841. {
  33842. flags.isDisabledFlag = ! shouldBeEnabled;
  33843. // if any parent components are disabled, setting our flag won't make a difference,
  33844. // so no need to send a change message
  33845. if (parentComponent == 0 || parentComponent->isEnabled())
  33846. sendEnablementChangeMessage();
  33847. }
  33848. }
  33849. void Component::sendEnablementChangeMessage()
  33850. {
  33851. WeakReference<Component> safePointer (this);
  33852. enablementChanged();
  33853. if (safePointer == 0)
  33854. return;
  33855. for (int i = getNumChildComponents(); --i >= 0;)
  33856. {
  33857. Component* const c = getChildComponent (i);
  33858. if (c != 0)
  33859. {
  33860. c->sendEnablementChangeMessage();
  33861. if (safePointer == 0)
  33862. return;
  33863. }
  33864. }
  33865. }
  33866. void Component::enablementChanged()
  33867. {
  33868. }
  33869. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33870. {
  33871. flags.wantsFocusFlag = wantsFocus;
  33872. }
  33873. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33874. {
  33875. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33876. }
  33877. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33878. {
  33879. return ! flags.dontFocusOnMouseClickFlag;
  33880. }
  33881. bool Component::getWantsKeyboardFocus() const throw()
  33882. {
  33883. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33884. }
  33885. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33886. {
  33887. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33888. }
  33889. bool Component::isFocusContainer() const throw()
  33890. {
  33891. return flags.isFocusContainerFlag;
  33892. }
  33893. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33894. int Component::getExplicitFocusOrder() const
  33895. {
  33896. return properties [juce_explicitFocusOrderId];
  33897. }
  33898. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33899. {
  33900. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33901. }
  33902. KeyboardFocusTraverser* Component::createFocusTraverser()
  33903. {
  33904. if (flags.isFocusContainerFlag || parentComponent == 0)
  33905. return new KeyboardFocusTraverser();
  33906. return parentComponent->createFocusTraverser();
  33907. }
  33908. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33909. {
  33910. // give the focus to this component
  33911. if (currentlyFocusedComponent != this)
  33912. {
  33913. // get the focus onto our desktop window
  33914. ComponentPeer* const peer = getPeer();
  33915. if (peer != 0)
  33916. {
  33917. WeakReference<Component> safePointer (this);
  33918. peer->grabFocus();
  33919. if (peer->isFocused() && currentlyFocusedComponent != this)
  33920. {
  33921. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  33922. currentlyFocusedComponent = this;
  33923. Desktop::getInstance().triggerFocusCallback();
  33924. // call this after setting currentlyFocusedComponent so that the one that's
  33925. // losing it has a chance to see where focus is going
  33926. if (componentLosingFocus != 0)
  33927. componentLosingFocus->internalFocusLoss (cause);
  33928. if (currentlyFocusedComponent == this)
  33929. internalFocusGain (cause, safePointer);
  33930. }
  33931. }
  33932. }
  33933. }
  33934. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33935. {
  33936. if (isShowing())
  33937. {
  33938. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == 0))
  33939. {
  33940. takeKeyboardFocus (cause);
  33941. }
  33942. else
  33943. {
  33944. if (isParentOf (currentlyFocusedComponent)
  33945. && currentlyFocusedComponent->isShowing())
  33946. {
  33947. // do nothing if the focused component is actually a child of ours..
  33948. }
  33949. else
  33950. {
  33951. // find the default child component..
  33952. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33953. if (traverser != 0)
  33954. {
  33955. Component* const defaultComp = traverser->getDefaultComponent (this);
  33956. traverser = 0;
  33957. if (defaultComp != 0)
  33958. {
  33959. defaultComp->grabFocusInternal (cause, false);
  33960. return;
  33961. }
  33962. }
  33963. if (canTryParent && parentComponent != 0)
  33964. {
  33965. // if no children want it and we're allowed to try our parent comp,
  33966. // then pass up to parent, which will try our siblings.
  33967. parentComponent->grabFocusInternal (cause, true);
  33968. }
  33969. }
  33970. }
  33971. }
  33972. }
  33973. void Component::grabKeyboardFocus()
  33974. {
  33975. // if component methods are being called from threads other than the message
  33976. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33977. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33978. grabFocusInternal (focusChangedDirectly);
  33979. }
  33980. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33981. {
  33982. // if component methods are being called from threads other than the message
  33983. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33984. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33985. if (parentComponent != 0)
  33986. {
  33987. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33988. if (traverser != 0)
  33989. {
  33990. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33991. : traverser->getPreviousComponent (this);
  33992. traverser = 0;
  33993. if (nextComp != 0)
  33994. {
  33995. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33996. {
  33997. WeakReference<Component> nextCompPointer (nextComp);
  33998. internalModalInputAttempt();
  33999. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34000. return;
  34001. }
  34002. nextComp->grabFocusInternal (focusChangedByTabKey);
  34003. return;
  34004. }
  34005. }
  34006. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  34007. }
  34008. }
  34009. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34010. {
  34011. return (currentlyFocusedComponent == this)
  34012. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34013. }
  34014. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34015. {
  34016. return currentlyFocusedComponent;
  34017. }
  34018. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  34019. {
  34020. Component* const componentLosingFocus = currentlyFocusedComponent;
  34021. currentlyFocusedComponent = 0;
  34022. if (sendFocusLossEvent && componentLosingFocus != 0)
  34023. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34024. Desktop::getInstance().triggerFocusCallback();
  34025. }
  34026. bool Component::isMouseOver (const bool includeChildren) const
  34027. {
  34028. if (flags.mouseOverFlag)
  34029. return true;
  34030. if (includeChildren)
  34031. {
  34032. Desktop& desktop = Desktop::getInstance();
  34033. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34034. {
  34035. Component* const c = desktop.getMouseSource(i)->getComponentUnderMouse();
  34036. if (isParentOf (c) && c->flags.mouseOverFlag) // (mouseOverFlag checked in case it's being dragged outside the comp)
  34037. return true;
  34038. }
  34039. }
  34040. return false;
  34041. }
  34042. bool Component::isMouseButtonDown() const throw() { return flags.mouseDownFlag; }
  34043. bool Component::isMouseOverOrDragging() const throw() { return flags.mouseOverFlag || flags.mouseDownFlag; }
  34044. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34045. {
  34046. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34047. }
  34048. const Point<int> Component::getMouseXYRelative() const
  34049. {
  34050. return getLocalPoint (0, Desktop::getMousePosition());
  34051. }
  34052. const Rectangle<int> Component::getParentMonitorArea() const
  34053. {
  34054. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  34055. }
  34056. void Component::addKeyListener (KeyListener* const newListener)
  34057. {
  34058. if (keyListeners == 0)
  34059. keyListeners = new Array <KeyListener*>();
  34060. keyListeners->addIfNotAlreadyThere (newListener);
  34061. }
  34062. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34063. {
  34064. if (keyListeners != 0)
  34065. keyListeners->removeValue (listenerToRemove);
  34066. }
  34067. bool Component::keyPressed (const KeyPress&)
  34068. {
  34069. return false;
  34070. }
  34071. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34072. {
  34073. return false;
  34074. }
  34075. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34076. {
  34077. if (parentComponent != 0)
  34078. parentComponent->modifierKeysChanged (modifiers);
  34079. }
  34080. void Component::internalModifierKeysChanged()
  34081. {
  34082. sendFakeMouseMove();
  34083. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34084. }
  34085. ComponentPeer* Component::getPeer() const
  34086. {
  34087. if (flags.hasHeavyweightPeerFlag)
  34088. return ComponentPeer::getPeerFor (this);
  34089. else if (parentComponent == 0)
  34090. return 0;
  34091. return parentComponent->getPeer();
  34092. }
  34093. Component::BailOutChecker::BailOutChecker (Component* const component)
  34094. : safePointer (component)
  34095. {
  34096. jassert (component != 0);
  34097. }
  34098. bool Component::BailOutChecker::shouldBailOut() const throw()
  34099. {
  34100. return safePointer == 0;
  34101. }
  34102. END_JUCE_NAMESPACE
  34103. /*** End of inlined file: juce_Component.cpp ***/
  34104. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34105. BEGIN_JUCE_NAMESPACE
  34106. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34107. void ComponentListener::componentBroughtToFront (Component&) {}
  34108. void ComponentListener::componentVisibilityChanged (Component&) {}
  34109. void ComponentListener::componentChildrenChanged (Component&) {}
  34110. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34111. void ComponentListener::componentNameChanged (Component&) {}
  34112. void ComponentListener::componentBeingDeleted (Component&) {}
  34113. END_JUCE_NAMESPACE
  34114. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34115. /*** Start of inlined file: juce_Desktop.cpp ***/
  34116. BEGIN_JUCE_NAMESPACE
  34117. Desktop::Desktop()
  34118. : mouseClickCounter (0),
  34119. kioskModeComponent (0),
  34120. allowedOrientations (allOrientations)
  34121. {
  34122. createMouseInputSources();
  34123. refreshMonitorSizes();
  34124. }
  34125. Desktop::~Desktop()
  34126. {
  34127. jassert (instance == this);
  34128. instance = 0;
  34129. // doh! If you don't delete all your windows before exiting, you're going to
  34130. // be leaking memory!
  34131. jassert (desktopComponents.size() == 0);
  34132. }
  34133. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34134. {
  34135. if (instance == 0)
  34136. instance = new Desktop();
  34137. return *instance;
  34138. }
  34139. Desktop* Desktop::instance = 0;
  34140. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34141. const bool clipToWorkArea);
  34142. void Desktop::refreshMonitorSizes()
  34143. {
  34144. Array <Rectangle<int> > oldClipped, oldUnclipped;
  34145. oldClipped.swapWithArray (monitorCoordsClipped);
  34146. oldUnclipped.swapWithArray (monitorCoordsUnclipped);
  34147. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34148. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34149. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34150. if (oldClipped != monitorCoordsClipped
  34151. || oldUnclipped != monitorCoordsUnclipped)
  34152. {
  34153. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34154. {
  34155. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34156. if (p != 0)
  34157. p->handleScreenSizeChange();
  34158. }
  34159. }
  34160. }
  34161. int Desktop::getNumDisplayMonitors() const throw()
  34162. {
  34163. return monitorCoordsClipped.size();
  34164. }
  34165. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34166. {
  34167. return clippedToWorkArea ? monitorCoordsClipped [index]
  34168. : monitorCoordsUnclipped [index];
  34169. }
  34170. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34171. {
  34172. RectangleList rl;
  34173. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34174. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34175. return rl;
  34176. }
  34177. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34178. {
  34179. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34180. }
  34181. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34182. {
  34183. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34184. double bestDistance = 1.0e10;
  34185. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34186. {
  34187. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34188. if (rect.contains (position))
  34189. return rect;
  34190. const double distance = rect.getCentre().getDistanceFrom (position);
  34191. if (distance < bestDistance)
  34192. {
  34193. bestDistance = distance;
  34194. best = rect;
  34195. }
  34196. }
  34197. return best;
  34198. }
  34199. int Desktop::getNumComponents() const throw()
  34200. {
  34201. return desktopComponents.size();
  34202. }
  34203. Component* Desktop::getComponent (const int index) const throw()
  34204. {
  34205. return desktopComponents [index];
  34206. }
  34207. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34208. {
  34209. for (int i = desktopComponents.size(); --i >= 0;)
  34210. {
  34211. Component* const c = desktopComponents.getUnchecked(i);
  34212. if (c->isVisible())
  34213. {
  34214. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34215. if (c->contains (relative))
  34216. return c->getComponentAt (relative);
  34217. }
  34218. }
  34219. return 0;
  34220. }
  34221. void Desktop::addDesktopComponent (Component* const c)
  34222. {
  34223. jassert (c != 0);
  34224. jassert (! desktopComponents.contains (c));
  34225. desktopComponents.addIfNotAlreadyThere (c);
  34226. }
  34227. void Desktop::removeDesktopComponent (Component* const c)
  34228. {
  34229. desktopComponents.removeValue (c);
  34230. }
  34231. void Desktop::componentBroughtToFront (Component* const c)
  34232. {
  34233. const int index = desktopComponents.indexOf (c);
  34234. jassert (index >= 0);
  34235. if (index >= 0)
  34236. {
  34237. int newIndex = -1;
  34238. if (! c->isAlwaysOnTop())
  34239. {
  34240. newIndex = desktopComponents.size();
  34241. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34242. --newIndex;
  34243. --newIndex;
  34244. }
  34245. desktopComponents.move (index, newIndex);
  34246. }
  34247. }
  34248. const Point<int> Desktop::getMousePosition()
  34249. {
  34250. return getInstance().getMainMouseSource().getScreenPosition();
  34251. }
  34252. const Point<int> Desktop::getLastMouseDownPosition()
  34253. {
  34254. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34255. }
  34256. int Desktop::getMouseButtonClickCounter()
  34257. {
  34258. return getInstance().mouseClickCounter;
  34259. }
  34260. void Desktop::incrementMouseClickCounter() throw()
  34261. {
  34262. ++mouseClickCounter;
  34263. }
  34264. int Desktop::getNumDraggingMouseSources() const throw()
  34265. {
  34266. int num = 0;
  34267. for (int i = mouseSources.size(); --i >= 0;)
  34268. if (mouseSources.getUnchecked(i)->isDragging())
  34269. ++num;
  34270. return num;
  34271. }
  34272. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34273. {
  34274. int num = 0;
  34275. for (int i = mouseSources.size(); --i >= 0;)
  34276. {
  34277. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34278. if (mi->isDragging())
  34279. {
  34280. if (index == num)
  34281. return mi;
  34282. ++num;
  34283. }
  34284. }
  34285. return 0;
  34286. }
  34287. class MouseDragAutoRepeater : public Timer
  34288. {
  34289. public:
  34290. MouseDragAutoRepeater() {}
  34291. void timerCallback()
  34292. {
  34293. Desktop& desktop = Desktop::getInstance();
  34294. int numMiceDown = 0;
  34295. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34296. {
  34297. MouseInputSource* const source = desktop.getMouseSource(i);
  34298. if (source->isDragging())
  34299. {
  34300. source->triggerFakeMove();
  34301. ++numMiceDown;
  34302. }
  34303. }
  34304. if (numMiceDown == 0)
  34305. desktop.beginDragAutoRepeat (0);
  34306. }
  34307. private:
  34308. JUCE_DECLARE_NON_COPYABLE (MouseDragAutoRepeater);
  34309. };
  34310. void Desktop::beginDragAutoRepeat (const int interval)
  34311. {
  34312. if (interval > 0)
  34313. {
  34314. if (dragRepeater == 0)
  34315. dragRepeater = new MouseDragAutoRepeater();
  34316. if (dragRepeater->getTimerInterval() != interval)
  34317. dragRepeater->startTimer (interval);
  34318. }
  34319. else
  34320. {
  34321. dragRepeater = 0;
  34322. }
  34323. }
  34324. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34325. {
  34326. focusListeners.add (listener);
  34327. }
  34328. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34329. {
  34330. focusListeners.remove (listener);
  34331. }
  34332. void Desktop::triggerFocusCallback()
  34333. {
  34334. triggerAsyncUpdate();
  34335. }
  34336. void Desktop::handleAsyncUpdate()
  34337. {
  34338. // The component may be deleted during this operation, but we'll use a SafePointer rather than a
  34339. // BailOutChecker so that any remaining listeners will still get a callback (with a null pointer).
  34340. WeakReference<Component> currentFocus (Component::getCurrentlyFocusedComponent());
  34341. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34342. }
  34343. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34344. {
  34345. mouseListeners.add (listener);
  34346. resetTimer();
  34347. }
  34348. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34349. {
  34350. mouseListeners.remove (listener);
  34351. resetTimer();
  34352. }
  34353. void Desktop::timerCallback()
  34354. {
  34355. if (lastFakeMouseMove != getMousePosition())
  34356. sendMouseMove();
  34357. }
  34358. void Desktop::sendMouseMove()
  34359. {
  34360. if (! mouseListeners.isEmpty())
  34361. {
  34362. startTimer (20);
  34363. lastFakeMouseMove = getMousePosition();
  34364. Component* const target = findComponentAt (lastFakeMouseMove);
  34365. if (target != 0)
  34366. {
  34367. Component::BailOutChecker checker (target);
  34368. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34369. const Time now (Time::getCurrentTime());
  34370. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34371. target, target, now, pos, now, 0, false);
  34372. if (me.mods.isAnyMouseButtonDown())
  34373. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34374. else
  34375. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34376. }
  34377. }
  34378. }
  34379. void Desktop::resetTimer()
  34380. {
  34381. if (mouseListeners.size() == 0)
  34382. stopTimer();
  34383. else
  34384. startTimer (100);
  34385. lastFakeMouseMove = getMousePosition();
  34386. }
  34387. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34388. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34389. {
  34390. if (kioskModeComponent != componentToUse)
  34391. {
  34392. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34393. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34394. if (kioskModeComponent != 0)
  34395. {
  34396. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34397. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34398. }
  34399. kioskModeComponent = componentToUse;
  34400. if (kioskModeComponent != 0)
  34401. {
  34402. // Only components that are already on the desktop can be put into kiosk mode!
  34403. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34404. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34405. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34406. }
  34407. }
  34408. }
  34409. void Desktop::setOrientationsEnabled (const int newOrientations)
  34410. {
  34411. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34412. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34413. allowedOrientations = newOrientations;
  34414. }
  34415. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34416. {
  34417. // Make sure you only pass one valid flag in here...
  34418. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34419. return (allowedOrientations & orientation) != 0;
  34420. }
  34421. END_JUCE_NAMESPACE
  34422. /*** End of inlined file: juce_Desktop.cpp ***/
  34423. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34424. BEGIN_JUCE_NAMESPACE
  34425. class ModalComponentManager::ModalItem : public ComponentMovementWatcher
  34426. {
  34427. public:
  34428. ModalItem (Component* const comp, Callback* const callback)
  34429. : ComponentMovementWatcher (comp),
  34430. component (comp), returnValue (0), isActive (true)
  34431. {
  34432. jassert (comp != 0);
  34433. if (callback != 0)
  34434. callbacks.add (callback);
  34435. }
  34436. void componentMovedOrResized (bool, bool) {}
  34437. void componentPeerChanged()
  34438. {
  34439. if (! component->isShowing())
  34440. cancel();
  34441. }
  34442. void componentVisibilityChanged()
  34443. {
  34444. if (! component->isShowing())
  34445. cancel();
  34446. }
  34447. void componentBeingDeleted (Component& comp)
  34448. {
  34449. if (component == &comp || comp.isParentOf (component))
  34450. cancel();
  34451. }
  34452. void cancel()
  34453. {
  34454. if (isActive)
  34455. {
  34456. isActive = false;
  34457. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34458. }
  34459. }
  34460. Component* component;
  34461. OwnedArray<Callback> callbacks;
  34462. int returnValue;
  34463. bool isActive;
  34464. private:
  34465. JUCE_DECLARE_NON_COPYABLE (ModalItem);
  34466. };
  34467. ModalComponentManager::ModalComponentManager()
  34468. {
  34469. }
  34470. ModalComponentManager::~ModalComponentManager()
  34471. {
  34472. clearSingletonInstance();
  34473. }
  34474. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34475. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34476. {
  34477. if (component != 0)
  34478. stack.add (new ModalItem (component, callback));
  34479. }
  34480. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34481. {
  34482. if (callback != 0)
  34483. {
  34484. ScopedPointer<Callback> callbackDeleter (callback);
  34485. for (int i = stack.size(); --i >= 0;)
  34486. {
  34487. ModalItem* const item = stack.getUnchecked(i);
  34488. if (item->component == component)
  34489. {
  34490. item->callbacks.add (callback);
  34491. callbackDeleter.release();
  34492. break;
  34493. }
  34494. }
  34495. }
  34496. }
  34497. void ModalComponentManager::endModal (Component* component)
  34498. {
  34499. for (int i = stack.size(); --i >= 0;)
  34500. {
  34501. ModalItem* const item = stack.getUnchecked(i);
  34502. if (item->component == component)
  34503. item->cancel();
  34504. }
  34505. }
  34506. void ModalComponentManager::endModal (Component* component, int returnValue)
  34507. {
  34508. for (int i = stack.size(); --i >= 0;)
  34509. {
  34510. ModalItem* const item = stack.getUnchecked(i);
  34511. if (item->component == component)
  34512. {
  34513. item->returnValue = returnValue;
  34514. item->cancel();
  34515. }
  34516. }
  34517. }
  34518. int ModalComponentManager::getNumModalComponents() const
  34519. {
  34520. int n = 0;
  34521. for (int i = 0; i < stack.size(); ++i)
  34522. if (stack.getUnchecked(i)->isActive)
  34523. ++n;
  34524. return n;
  34525. }
  34526. Component* ModalComponentManager::getModalComponent (const int index) const
  34527. {
  34528. int n = 0;
  34529. for (int i = stack.size(); --i >= 0;)
  34530. {
  34531. const ModalItem* const item = stack.getUnchecked(i);
  34532. if (item->isActive)
  34533. if (n++ == index)
  34534. return item->component;
  34535. }
  34536. return 0;
  34537. }
  34538. bool ModalComponentManager::isModal (Component* const comp) const
  34539. {
  34540. for (int i = stack.size(); --i >= 0;)
  34541. {
  34542. const ModalItem* const item = stack.getUnchecked(i);
  34543. if (item->isActive && item->component == comp)
  34544. return true;
  34545. }
  34546. return false;
  34547. }
  34548. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34549. {
  34550. return comp == getModalComponent (0);
  34551. }
  34552. void ModalComponentManager::handleAsyncUpdate()
  34553. {
  34554. for (int i = stack.size(); --i >= 0;)
  34555. {
  34556. const ModalItem* const item = stack.getUnchecked(i);
  34557. if (! item->isActive)
  34558. {
  34559. for (int j = item->callbacks.size(); --j >= 0;)
  34560. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34561. stack.remove (i);
  34562. }
  34563. }
  34564. }
  34565. void ModalComponentManager::bringModalComponentsToFront()
  34566. {
  34567. ComponentPeer* lastOne = 0;
  34568. for (int i = 0; i < getNumModalComponents(); ++i)
  34569. {
  34570. Component* const c = getModalComponent (i);
  34571. if (c == 0)
  34572. break;
  34573. ComponentPeer* peer = c->getPeer();
  34574. if (peer != 0 && peer != lastOne)
  34575. {
  34576. if (lastOne == 0)
  34577. {
  34578. peer->toFront (true);
  34579. peer->grabFocus();
  34580. }
  34581. else
  34582. peer->toBehind (lastOne);
  34583. lastOne = peer;
  34584. }
  34585. }
  34586. }
  34587. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34588. {
  34589. public:
  34590. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34591. ~ReturnValueRetriever() {}
  34592. void modalStateFinished (int returnValue)
  34593. {
  34594. finished = true;
  34595. value = returnValue;
  34596. }
  34597. private:
  34598. int& value;
  34599. bool& finished;
  34600. JUCE_DECLARE_NON_COPYABLE (ReturnValueRetriever);
  34601. };
  34602. int ModalComponentManager::runEventLoopForCurrentComponent()
  34603. {
  34604. // This can only be run from the message thread!
  34605. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34606. Component* currentlyModal = getModalComponent (0);
  34607. if (currentlyModal == 0)
  34608. return 0;
  34609. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34610. int returnValue = 0;
  34611. bool finished = false;
  34612. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34613. JUCE_TRY
  34614. {
  34615. while (! finished)
  34616. {
  34617. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34618. break;
  34619. }
  34620. }
  34621. JUCE_CATCH_EXCEPTION
  34622. if (prevFocused != 0)
  34623. prevFocused->grabKeyboardFocus();
  34624. return returnValue;
  34625. }
  34626. END_JUCE_NAMESPACE
  34627. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34628. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34629. BEGIN_JUCE_NAMESPACE
  34630. ArrowButton::ArrowButton (const String& name,
  34631. float arrowDirectionInRadians,
  34632. const Colour& arrowColour)
  34633. : Button (name),
  34634. colour (arrowColour)
  34635. {
  34636. path.lineTo (0.0f, 1.0f);
  34637. path.lineTo (1.0f, 0.5f);
  34638. path.closeSubPath();
  34639. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34640. 0.5f, 0.5f));
  34641. setComponentEffect (&shadow);
  34642. buttonStateChanged();
  34643. }
  34644. ArrowButton::~ArrowButton()
  34645. {
  34646. }
  34647. void ArrowButton::paintButton (Graphics& g,
  34648. bool /*isMouseOverButton*/,
  34649. bool /*isButtonDown*/)
  34650. {
  34651. g.setColour (colour);
  34652. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34653. (float) offset,
  34654. (float) (getWidth() - 3),
  34655. (float) (getHeight() - 3),
  34656. false));
  34657. }
  34658. void ArrowButton::buttonStateChanged()
  34659. {
  34660. offset = (isDown()) ? 1 : 0;
  34661. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34662. 0.3f, -1, 0);
  34663. }
  34664. END_JUCE_NAMESPACE
  34665. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34666. /*** Start of inlined file: juce_Button.cpp ***/
  34667. BEGIN_JUCE_NAMESPACE
  34668. class Button::RepeatTimer : public Timer
  34669. {
  34670. public:
  34671. RepeatTimer (Button& owner_) : owner (owner_) {}
  34672. void timerCallback() { owner.repeatTimerCallback(); }
  34673. private:
  34674. Button& owner;
  34675. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RepeatTimer);
  34676. };
  34677. Button::Button (const String& name)
  34678. : Component (name),
  34679. text (name),
  34680. buttonPressTime (0),
  34681. lastRepeatTime (0),
  34682. commandManagerToUse (0),
  34683. autoRepeatDelay (-1),
  34684. autoRepeatSpeed (0),
  34685. autoRepeatMinimumDelay (-1),
  34686. radioGroupId (0),
  34687. commandID (0),
  34688. connectedEdgeFlags (0),
  34689. buttonState (buttonNormal),
  34690. lastToggleState (false),
  34691. clickTogglesState (false),
  34692. needsToRelease (false),
  34693. needsRepainting (false),
  34694. isKeyDown (false),
  34695. triggerOnMouseDown (false),
  34696. generateTooltip (false)
  34697. {
  34698. setWantsKeyboardFocus (true);
  34699. isOn.addListener (this);
  34700. }
  34701. Button::~Button()
  34702. {
  34703. isOn.removeListener (this);
  34704. if (commandManagerToUse != 0)
  34705. commandManagerToUse->removeListener (this);
  34706. repeatTimer = 0;
  34707. clearShortcuts();
  34708. }
  34709. void Button::setButtonText (const String& newText)
  34710. {
  34711. if (text != newText)
  34712. {
  34713. text = newText;
  34714. repaint();
  34715. }
  34716. }
  34717. void Button::setTooltip (const String& newTooltip)
  34718. {
  34719. SettableTooltipClient::setTooltip (newTooltip);
  34720. generateTooltip = false;
  34721. }
  34722. const String Button::getTooltip()
  34723. {
  34724. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34725. {
  34726. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34727. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34728. for (int i = 0; i < keyPresses.size(); ++i)
  34729. {
  34730. const String key (keyPresses.getReference(i).getTextDescription());
  34731. tt << " [";
  34732. if (key.length() == 1)
  34733. tt << TRANS("shortcut") << ": '" << key << "']";
  34734. else
  34735. tt << key << ']';
  34736. }
  34737. return tt;
  34738. }
  34739. return SettableTooltipClient::getTooltip();
  34740. }
  34741. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34742. {
  34743. if (connectedEdgeFlags != connectedEdgeFlags_)
  34744. {
  34745. connectedEdgeFlags = connectedEdgeFlags_;
  34746. repaint();
  34747. }
  34748. }
  34749. void Button::setToggleState (const bool shouldBeOn,
  34750. const bool sendChangeNotification)
  34751. {
  34752. if (shouldBeOn != lastToggleState)
  34753. {
  34754. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34755. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34756. lastToggleState = shouldBeOn;
  34757. repaint();
  34758. WeakReference<Component> deletionWatcher (this);
  34759. if (sendChangeNotification)
  34760. {
  34761. sendClickMessage (ModifierKeys());
  34762. if (deletionWatcher == 0)
  34763. return;
  34764. }
  34765. if (lastToggleState)
  34766. {
  34767. turnOffOtherButtonsInGroup (sendChangeNotification);
  34768. if (deletionWatcher == 0)
  34769. return;
  34770. }
  34771. sendStateMessage();
  34772. }
  34773. }
  34774. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34775. {
  34776. clickTogglesState = shouldToggle;
  34777. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34778. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34779. // it is that this button represents, and the button will update its state to reflect this
  34780. // in the applicationCommandListChanged() method.
  34781. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34782. }
  34783. bool Button::getClickingTogglesState() const throw()
  34784. {
  34785. return clickTogglesState;
  34786. }
  34787. void Button::valueChanged (Value& value)
  34788. {
  34789. if (value.refersToSameSourceAs (isOn))
  34790. setToggleState (isOn.getValue(), true);
  34791. }
  34792. void Button::setRadioGroupId (const int newGroupId)
  34793. {
  34794. if (radioGroupId != newGroupId)
  34795. {
  34796. radioGroupId = newGroupId;
  34797. if (lastToggleState)
  34798. turnOffOtherButtonsInGroup (true);
  34799. }
  34800. }
  34801. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34802. {
  34803. Component* const p = getParentComponent();
  34804. if (p != 0 && radioGroupId != 0)
  34805. {
  34806. WeakReference<Component> deletionWatcher (this);
  34807. for (int i = p->getNumChildComponents(); --i >= 0;)
  34808. {
  34809. Component* const c = p->getChildComponent (i);
  34810. if (c != this)
  34811. {
  34812. Button* const b = dynamic_cast <Button*> (c);
  34813. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34814. {
  34815. b->setToggleState (false, sendChangeNotification);
  34816. if (deletionWatcher == 0)
  34817. return;
  34818. }
  34819. }
  34820. }
  34821. }
  34822. }
  34823. void Button::enablementChanged()
  34824. {
  34825. updateState();
  34826. repaint();
  34827. }
  34828. Button::ButtonState Button::updateState()
  34829. {
  34830. return updateState (isMouseOver (true), isMouseButtonDown());
  34831. }
  34832. Button::ButtonState Button::updateState (const bool over, const bool down)
  34833. {
  34834. ButtonState newState = buttonNormal;
  34835. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34836. {
  34837. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34838. newState = buttonDown;
  34839. else if (over)
  34840. newState = buttonOver;
  34841. }
  34842. setState (newState);
  34843. return newState;
  34844. }
  34845. void Button::setState (const ButtonState newState)
  34846. {
  34847. if (buttonState != newState)
  34848. {
  34849. buttonState = newState;
  34850. repaint();
  34851. if (buttonState == buttonDown)
  34852. {
  34853. buttonPressTime = Time::getApproximateMillisecondCounter();
  34854. lastRepeatTime = 0;
  34855. }
  34856. sendStateMessage();
  34857. }
  34858. }
  34859. bool Button::isDown() const throw()
  34860. {
  34861. return buttonState == buttonDown;
  34862. }
  34863. bool Button::isOver() const throw()
  34864. {
  34865. return buttonState != buttonNormal;
  34866. }
  34867. void Button::buttonStateChanged()
  34868. {
  34869. }
  34870. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34871. {
  34872. const uint32 now = Time::getApproximateMillisecondCounter();
  34873. return now > buttonPressTime ? now - buttonPressTime : 0;
  34874. }
  34875. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34876. {
  34877. triggerOnMouseDown = isTriggeredOnMouseDown;
  34878. }
  34879. void Button::clicked()
  34880. {
  34881. }
  34882. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34883. {
  34884. clicked();
  34885. }
  34886. static const int clickMessageId = 0x2f3f4f99;
  34887. void Button::triggerClick()
  34888. {
  34889. postCommandMessage (clickMessageId);
  34890. }
  34891. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34892. {
  34893. if (clickTogglesState)
  34894. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34895. sendClickMessage (modifiers);
  34896. }
  34897. void Button::flashButtonState()
  34898. {
  34899. if (isEnabled())
  34900. {
  34901. needsToRelease = true;
  34902. setState (buttonDown);
  34903. getRepeatTimer().startTimer (100);
  34904. }
  34905. }
  34906. void Button::handleCommandMessage (int commandId)
  34907. {
  34908. if (commandId == clickMessageId)
  34909. {
  34910. if (isEnabled())
  34911. {
  34912. flashButtonState();
  34913. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34914. }
  34915. }
  34916. else
  34917. {
  34918. Component::handleCommandMessage (commandId);
  34919. }
  34920. }
  34921. void Button::addListener (ButtonListener* const newListener)
  34922. {
  34923. buttonListeners.add (newListener);
  34924. }
  34925. void Button::removeListener (ButtonListener* const listener)
  34926. {
  34927. buttonListeners.remove (listener);
  34928. }
  34929. void Button::addButtonListener (ButtonListener* l) { addListener (l); }
  34930. void Button::removeButtonListener (ButtonListener* l) { removeListener (l); }
  34931. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34932. {
  34933. Component::BailOutChecker checker (this);
  34934. if (commandManagerToUse != 0 && commandID != 0)
  34935. {
  34936. ApplicationCommandTarget::InvocationInfo info (commandID);
  34937. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34938. info.originatingComponent = this;
  34939. commandManagerToUse->invoke (info, true);
  34940. }
  34941. clicked (modifiers);
  34942. if (! checker.shouldBailOut())
  34943. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  34944. }
  34945. void Button::sendStateMessage()
  34946. {
  34947. Component::BailOutChecker checker (this);
  34948. buttonStateChanged();
  34949. if (! checker.shouldBailOut())
  34950. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34951. }
  34952. void Button::paint (Graphics& g)
  34953. {
  34954. if (needsToRelease && isEnabled())
  34955. {
  34956. needsToRelease = false;
  34957. needsRepainting = true;
  34958. }
  34959. paintButton (g, isOver(), isDown());
  34960. }
  34961. void Button::mouseEnter (const MouseEvent&)
  34962. {
  34963. updateState (true, false);
  34964. }
  34965. void Button::mouseExit (const MouseEvent&)
  34966. {
  34967. updateState (false, false);
  34968. }
  34969. void Button::mouseDown (const MouseEvent& e)
  34970. {
  34971. updateState (true, true);
  34972. if (isDown())
  34973. {
  34974. if (autoRepeatDelay >= 0)
  34975. getRepeatTimer().startTimer (autoRepeatDelay);
  34976. if (triggerOnMouseDown)
  34977. internalClickCallback (e.mods);
  34978. }
  34979. }
  34980. void Button::mouseUp (const MouseEvent& e)
  34981. {
  34982. const bool wasDown = isDown();
  34983. updateState (isMouseOver(), false);
  34984. if (wasDown && isOver() && ! triggerOnMouseDown)
  34985. internalClickCallback (e.mods);
  34986. }
  34987. void Button::mouseDrag (const MouseEvent&)
  34988. {
  34989. const ButtonState oldState = buttonState;
  34990. updateState (isMouseOver(), true);
  34991. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34992. getRepeatTimer().startTimer (autoRepeatSpeed);
  34993. }
  34994. void Button::focusGained (FocusChangeType)
  34995. {
  34996. updateState();
  34997. repaint();
  34998. }
  34999. void Button::focusLost (FocusChangeType)
  35000. {
  35001. updateState();
  35002. repaint();
  35003. }
  35004. void Button::visibilityChanged()
  35005. {
  35006. needsToRelease = false;
  35007. updateState();
  35008. }
  35009. void Button::parentHierarchyChanged()
  35010. {
  35011. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35012. if (newKeySource != keySource.get())
  35013. {
  35014. if (keySource != 0)
  35015. keySource->removeKeyListener (this);
  35016. keySource = newKeySource;
  35017. if (keySource != 0)
  35018. keySource->addKeyListener (this);
  35019. }
  35020. }
  35021. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35022. const int commandID_,
  35023. const bool generateTooltip_)
  35024. {
  35025. commandID = commandID_;
  35026. generateTooltip = generateTooltip_;
  35027. if (commandManagerToUse != commandManagerToUse_)
  35028. {
  35029. if (commandManagerToUse != 0)
  35030. commandManagerToUse->removeListener (this);
  35031. commandManagerToUse = commandManagerToUse_;
  35032. if (commandManagerToUse != 0)
  35033. commandManagerToUse->addListener (this);
  35034. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35035. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35036. // it is that this button represents, and the button will update its state to reflect this
  35037. // in the applicationCommandListChanged() method.
  35038. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35039. }
  35040. if (commandManagerToUse != 0)
  35041. applicationCommandListChanged();
  35042. else
  35043. setEnabled (true);
  35044. }
  35045. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35046. {
  35047. if (info.commandID == commandID
  35048. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35049. {
  35050. flashButtonState();
  35051. }
  35052. }
  35053. void Button::applicationCommandListChanged()
  35054. {
  35055. if (commandManagerToUse != 0)
  35056. {
  35057. ApplicationCommandInfo info (0);
  35058. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35059. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35060. if (target != 0)
  35061. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35062. }
  35063. }
  35064. void Button::addShortcut (const KeyPress& key)
  35065. {
  35066. if (key.isValid())
  35067. {
  35068. jassert (! isRegisteredForShortcut (key)); // already registered!
  35069. shortcuts.add (key);
  35070. parentHierarchyChanged();
  35071. }
  35072. }
  35073. void Button::clearShortcuts()
  35074. {
  35075. shortcuts.clear();
  35076. parentHierarchyChanged();
  35077. }
  35078. bool Button::isShortcutPressed() const
  35079. {
  35080. if (! isCurrentlyBlockedByAnotherModalComponent())
  35081. {
  35082. for (int i = shortcuts.size(); --i >= 0;)
  35083. if (shortcuts.getReference(i).isCurrentlyDown())
  35084. return true;
  35085. }
  35086. return false;
  35087. }
  35088. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35089. {
  35090. for (int i = shortcuts.size(); --i >= 0;)
  35091. if (key == shortcuts.getReference(i))
  35092. return true;
  35093. return false;
  35094. }
  35095. bool Button::keyStateChanged (const bool, Component*)
  35096. {
  35097. if (! isEnabled())
  35098. return false;
  35099. const bool wasDown = isKeyDown;
  35100. isKeyDown = isShortcutPressed();
  35101. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35102. getRepeatTimer().startTimer (autoRepeatDelay);
  35103. updateState();
  35104. if (isEnabled() && wasDown && ! isKeyDown)
  35105. {
  35106. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35107. // (return immediately - this button may now have been deleted)
  35108. return true;
  35109. }
  35110. return wasDown || isKeyDown;
  35111. }
  35112. bool Button::keyPressed (const KeyPress&, Component*)
  35113. {
  35114. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35115. return isShortcutPressed();
  35116. }
  35117. bool Button::keyPressed (const KeyPress& key)
  35118. {
  35119. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35120. {
  35121. triggerClick();
  35122. return true;
  35123. }
  35124. return false;
  35125. }
  35126. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35127. const int repeatMillisecs,
  35128. const int minimumDelayInMillisecs) throw()
  35129. {
  35130. autoRepeatDelay = initialDelayMillisecs;
  35131. autoRepeatSpeed = repeatMillisecs;
  35132. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35133. }
  35134. void Button::repeatTimerCallback()
  35135. {
  35136. if (needsRepainting)
  35137. {
  35138. getRepeatTimer().stopTimer();
  35139. updateState();
  35140. needsRepainting = false;
  35141. }
  35142. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  35143. {
  35144. int repeatSpeed = autoRepeatSpeed;
  35145. if (autoRepeatMinimumDelay >= 0)
  35146. {
  35147. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35148. timeHeldDown *= timeHeldDown;
  35149. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35150. }
  35151. repeatSpeed = jmax (1, repeatSpeed);
  35152. const uint32 now = Time::getMillisecondCounter();
  35153. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  35154. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  35155. repeatSpeed = jmax (1, repeatSpeed / 2);
  35156. lastRepeatTime = now;
  35157. getRepeatTimer().startTimer (repeatSpeed);
  35158. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35159. }
  35160. else if (! needsToRelease)
  35161. {
  35162. getRepeatTimer().stopTimer();
  35163. }
  35164. }
  35165. Button::RepeatTimer& Button::getRepeatTimer()
  35166. {
  35167. if (repeatTimer == 0)
  35168. repeatTimer = new RepeatTimer (*this);
  35169. return *repeatTimer;
  35170. }
  35171. END_JUCE_NAMESPACE
  35172. /*** End of inlined file: juce_Button.cpp ***/
  35173. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35174. BEGIN_JUCE_NAMESPACE
  35175. DrawableButton::DrawableButton (const String& name,
  35176. const DrawableButton::ButtonStyle buttonStyle)
  35177. : Button (name),
  35178. style (buttonStyle),
  35179. currentImage (0),
  35180. edgeIndent (3)
  35181. {
  35182. if (buttonStyle == ImageOnButtonBackground)
  35183. {
  35184. backgroundOff = Colour (0xffbbbbff);
  35185. backgroundOn = Colour (0xff3333ff);
  35186. }
  35187. else
  35188. {
  35189. backgroundOff = Colours::transparentBlack;
  35190. backgroundOn = Colour (0xaabbbbff);
  35191. }
  35192. }
  35193. DrawableButton::~DrawableButton()
  35194. {
  35195. }
  35196. void DrawableButton::setImages (const Drawable* normal,
  35197. const Drawable* over,
  35198. const Drawable* down,
  35199. const Drawable* disabled,
  35200. const Drawable* normalOn,
  35201. const Drawable* overOn,
  35202. const Drawable* downOn,
  35203. const Drawable* disabledOn)
  35204. {
  35205. jassert (normal != 0); // you really need to give it at least a normal image..
  35206. if (normal != 0) normalImage = normal->createCopy();
  35207. if (over != 0) overImage = over->createCopy();
  35208. if (down != 0) downImage = down->createCopy();
  35209. if (disabled != 0) disabledImage = disabled->createCopy();
  35210. if (normalOn != 0) normalImageOn = normalOn->createCopy();
  35211. if (overOn != 0) overImageOn = overOn->createCopy();
  35212. if (downOn != 0) downImageOn = downOn->createCopy();
  35213. if (disabledOn != 0) disabledImageOn = disabledOn->createCopy();
  35214. buttonStateChanged();
  35215. }
  35216. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35217. {
  35218. if (style != newStyle)
  35219. {
  35220. style = newStyle;
  35221. buttonStateChanged();
  35222. }
  35223. }
  35224. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35225. const Colour& toggledOnColour)
  35226. {
  35227. if (backgroundOff != toggledOffColour
  35228. || backgroundOn != toggledOnColour)
  35229. {
  35230. backgroundOff = toggledOffColour;
  35231. backgroundOn = toggledOnColour;
  35232. repaint();
  35233. }
  35234. }
  35235. const Colour& DrawableButton::getBackgroundColour() const throw()
  35236. {
  35237. return getToggleState() ? backgroundOn
  35238. : backgroundOff;
  35239. }
  35240. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35241. {
  35242. edgeIndent = numPixelsIndent;
  35243. repaint();
  35244. resized();
  35245. }
  35246. void DrawableButton::resized()
  35247. {
  35248. Button::resized();
  35249. if (currentImage != 0)
  35250. {
  35251. if (style == ImageRaw)
  35252. {
  35253. currentImage->setOriginWithOriginalSize (Point<float>());
  35254. }
  35255. else
  35256. {
  35257. Rectangle<int> imageSpace;
  35258. if (style == ImageOnButtonBackground)
  35259. {
  35260. imageSpace = getLocalBounds().reduced (getWidth() / 4, getHeight() / 4);
  35261. }
  35262. else
  35263. {
  35264. const int textH = (style == ImageAboveTextLabel) ? jmin (16, proportionOfHeight (0.25f)) : 0;
  35265. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35266. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35267. imageSpace.setBounds (indentX, indentY,
  35268. getWidth() - indentX * 2,
  35269. getHeight() - indentY * 2 - textH);
  35270. }
  35271. currentImage->setTransformToFit (imageSpace.toFloat(), RectanglePlacement::centred);
  35272. }
  35273. }
  35274. }
  35275. void DrawableButton::buttonStateChanged()
  35276. {
  35277. repaint();
  35278. Drawable* imageToDraw = 0;
  35279. float opacity = 1.0f;
  35280. if (isEnabled())
  35281. {
  35282. imageToDraw = getCurrentImage();
  35283. }
  35284. else
  35285. {
  35286. imageToDraw = getToggleState() ? disabledImageOn
  35287. : disabledImage;
  35288. if (imageToDraw == 0)
  35289. {
  35290. opacity = 0.4f;
  35291. imageToDraw = getNormalImage();
  35292. }
  35293. }
  35294. if (imageToDraw != currentImage)
  35295. {
  35296. removeChildComponent (currentImage);
  35297. currentImage = imageToDraw;
  35298. if (currentImage != 0)
  35299. {
  35300. addAndMakeVisible (currentImage);
  35301. DrawableButton::resized();
  35302. }
  35303. }
  35304. if (currentImage != 0)
  35305. currentImage->setAlpha (opacity);
  35306. }
  35307. void DrawableButton::paintButton (Graphics& g,
  35308. bool isMouseOverButton,
  35309. bool isButtonDown)
  35310. {
  35311. if (style == ImageOnButtonBackground)
  35312. {
  35313. getLookAndFeel().drawButtonBackground (g, *this,
  35314. getBackgroundColour(),
  35315. isMouseOverButton,
  35316. isButtonDown);
  35317. }
  35318. else
  35319. {
  35320. g.fillAll (getBackgroundColour());
  35321. const int textH = (style == ImageAboveTextLabel)
  35322. ? jmin (16, proportionOfHeight (0.25f))
  35323. : 0;
  35324. if (textH > 0)
  35325. {
  35326. g.setFont ((float) textH);
  35327. g.setColour (findColour (DrawableButton::textColourId)
  35328. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35329. g.drawFittedText (getButtonText(),
  35330. 2, getHeight() - textH - 1,
  35331. getWidth() - 4, textH,
  35332. Justification::centred, 1);
  35333. }
  35334. }
  35335. }
  35336. Drawable* DrawableButton::getCurrentImage() const throw()
  35337. {
  35338. if (isDown())
  35339. return getDownImage();
  35340. if (isOver())
  35341. return getOverImage();
  35342. return getNormalImage();
  35343. }
  35344. Drawable* DrawableButton::getNormalImage() const throw()
  35345. {
  35346. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35347. : normalImage;
  35348. }
  35349. Drawable* DrawableButton::getOverImage() const throw()
  35350. {
  35351. Drawable* d = normalImage;
  35352. if (getToggleState())
  35353. {
  35354. if (overImageOn != 0)
  35355. d = overImageOn;
  35356. else if (normalImageOn != 0)
  35357. d = normalImageOn;
  35358. else if (overImage != 0)
  35359. d = overImage;
  35360. }
  35361. else
  35362. {
  35363. if (overImage != 0)
  35364. d = overImage;
  35365. }
  35366. return d;
  35367. }
  35368. Drawable* DrawableButton::getDownImage() const throw()
  35369. {
  35370. Drawable* d = normalImage;
  35371. if (getToggleState())
  35372. {
  35373. if (downImageOn != 0)
  35374. d = downImageOn;
  35375. else if (overImageOn != 0)
  35376. d = overImageOn;
  35377. else if (normalImageOn != 0)
  35378. d = normalImageOn;
  35379. else if (downImage != 0)
  35380. d = downImage;
  35381. else
  35382. d = getOverImage();
  35383. }
  35384. else
  35385. {
  35386. if (downImage != 0)
  35387. d = downImage;
  35388. else
  35389. d = getOverImage();
  35390. }
  35391. return d;
  35392. }
  35393. END_JUCE_NAMESPACE
  35394. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35395. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35396. BEGIN_JUCE_NAMESPACE
  35397. HyperlinkButton::HyperlinkButton (const String& linkText,
  35398. const URL& linkURL)
  35399. : Button (linkText),
  35400. url (linkURL),
  35401. font (14.0f, Font::underlined),
  35402. resizeFont (true),
  35403. justification (Justification::centred)
  35404. {
  35405. setMouseCursor (MouseCursor::PointingHandCursor);
  35406. setTooltip (linkURL.toString (false));
  35407. }
  35408. HyperlinkButton::~HyperlinkButton()
  35409. {
  35410. }
  35411. void HyperlinkButton::setFont (const Font& newFont,
  35412. const bool resizeToMatchComponentHeight,
  35413. const Justification& justificationType)
  35414. {
  35415. font = newFont;
  35416. resizeFont = resizeToMatchComponentHeight;
  35417. justification = justificationType;
  35418. repaint();
  35419. }
  35420. void HyperlinkButton::setURL (const URL& newURL) throw()
  35421. {
  35422. url = newURL;
  35423. setTooltip (newURL.toString (false));
  35424. }
  35425. const Font HyperlinkButton::getFontToUse() const
  35426. {
  35427. Font f (font);
  35428. if (resizeFont)
  35429. f.setHeight (getHeight() * 0.7f);
  35430. return f;
  35431. }
  35432. void HyperlinkButton::changeWidthToFitText()
  35433. {
  35434. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35435. }
  35436. void HyperlinkButton::colourChanged()
  35437. {
  35438. repaint();
  35439. }
  35440. void HyperlinkButton::clicked()
  35441. {
  35442. if (url.isWellFormed())
  35443. url.launchInDefaultBrowser();
  35444. }
  35445. void HyperlinkButton::paintButton (Graphics& g,
  35446. bool isMouseOverButton,
  35447. bool isButtonDown)
  35448. {
  35449. const Colour textColour (findColour (textColourId));
  35450. if (isEnabled())
  35451. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35452. : textColour);
  35453. else
  35454. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35455. g.setFont (getFontToUse());
  35456. g.drawText (getButtonText(),
  35457. 2, 0, getWidth() - 2, getHeight(),
  35458. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35459. true);
  35460. }
  35461. END_JUCE_NAMESPACE
  35462. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35463. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35464. BEGIN_JUCE_NAMESPACE
  35465. ImageButton::ImageButton (const String& text_)
  35466. : Button (text_),
  35467. scaleImageToFit (true),
  35468. preserveProportions (true),
  35469. alphaThreshold (0),
  35470. imageX (0),
  35471. imageY (0),
  35472. imageW (0),
  35473. imageH (0),
  35474. normalImage (0),
  35475. overImage (0),
  35476. downImage (0)
  35477. {
  35478. }
  35479. ImageButton::~ImageButton()
  35480. {
  35481. }
  35482. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35483. const bool rescaleImagesWhenButtonSizeChanges,
  35484. const bool preserveImageProportions,
  35485. const Image& normalImage_,
  35486. const float imageOpacityWhenNormal,
  35487. const Colour& overlayColourWhenNormal,
  35488. const Image& overImage_,
  35489. const float imageOpacityWhenOver,
  35490. const Colour& overlayColourWhenOver,
  35491. const Image& downImage_,
  35492. const float imageOpacityWhenDown,
  35493. const Colour& overlayColourWhenDown,
  35494. const float hitTestAlphaThreshold)
  35495. {
  35496. normalImage = normalImage_;
  35497. overImage = overImage_;
  35498. downImage = downImage_;
  35499. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35500. {
  35501. imageW = normalImage.getWidth();
  35502. imageH = normalImage.getHeight();
  35503. setSize (imageW, imageH);
  35504. }
  35505. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35506. preserveProportions = preserveImageProportions;
  35507. normalOpacity = imageOpacityWhenNormal;
  35508. normalOverlay = overlayColourWhenNormal;
  35509. overOpacity = imageOpacityWhenOver;
  35510. overOverlay = overlayColourWhenOver;
  35511. downOpacity = imageOpacityWhenDown;
  35512. downOverlay = overlayColourWhenDown;
  35513. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35514. repaint();
  35515. }
  35516. const Image ImageButton::getCurrentImage() const
  35517. {
  35518. if (isDown() || getToggleState())
  35519. return getDownImage();
  35520. if (isOver())
  35521. return getOverImage();
  35522. return getNormalImage();
  35523. }
  35524. const Image ImageButton::getNormalImage() const
  35525. {
  35526. return normalImage;
  35527. }
  35528. const Image ImageButton::getOverImage() const
  35529. {
  35530. return overImage.isValid() ? overImage
  35531. : normalImage;
  35532. }
  35533. const Image ImageButton::getDownImage() const
  35534. {
  35535. return downImage.isValid() ? downImage
  35536. : getOverImage();
  35537. }
  35538. void ImageButton::paintButton (Graphics& g,
  35539. bool isMouseOverButton,
  35540. bool isButtonDown)
  35541. {
  35542. if (! isEnabled())
  35543. {
  35544. isMouseOverButton = false;
  35545. isButtonDown = false;
  35546. }
  35547. Image im (getCurrentImage());
  35548. if (im.isValid())
  35549. {
  35550. const int iw = im.getWidth();
  35551. const int ih = im.getHeight();
  35552. imageW = getWidth();
  35553. imageH = getHeight();
  35554. imageX = (imageW - iw) >> 1;
  35555. imageY = (imageH - ih) >> 1;
  35556. if (scaleImageToFit)
  35557. {
  35558. if (preserveProportions)
  35559. {
  35560. int newW, newH;
  35561. const float imRatio = ih / (float)iw;
  35562. const float destRatio = imageH / (float)imageW;
  35563. if (imRatio > destRatio)
  35564. {
  35565. newW = roundToInt (imageH / imRatio);
  35566. newH = imageH;
  35567. }
  35568. else
  35569. {
  35570. newW = imageW;
  35571. newH = roundToInt (imageW * imRatio);
  35572. }
  35573. imageX = (imageW - newW) / 2;
  35574. imageY = (imageH - newH) / 2;
  35575. imageW = newW;
  35576. imageH = newH;
  35577. }
  35578. else
  35579. {
  35580. imageX = 0;
  35581. imageY = 0;
  35582. }
  35583. }
  35584. if (! scaleImageToFit)
  35585. {
  35586. imageW = iw;
  35587. imageH = ih;
  35588. }
  35589. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35590. isButtonDown ? downOverlay
  35591. : (isMouseOverButton ? overOverlay
  35592. : normalOverlay),
  35593. isButtonDown ? downOpacity
  35594. : (isMouseOverButton ? overOpacity
  35595. : normalOpacity),
  35596. *this);
  35597. }
  35598. }
  35599. bool ImageButton::hitTest (int x, int y)
  35600. {
  35601. if (alphaThreshold == 0)
  35602. return true;
  35603. Image im (getCurrentImage());
  35604. return im.isNull() || (imageW > 0 && imageH > 0
  35605. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35606. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35607. }
  35608. END_JUCE_NAMESPACE
  35609. /*** End of inlined file: juce_ImageButton.cpp ***/
  35610. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35611. BEGIN_JUCE_NAMESPACE
  35612. ShapeButton::ShapeButton (const String& text_,
  35613. const Colour& normalColour_,
  35614. const Colour& overColour_,
  35615. const Colour& downColour_)
  35616. : Button (text_),
  35617. normalColour (normalColour_),
  35618. overColour (overColour_),
  35619. downColour (downColour_),
  35620. maintainShapeProportions (false),
  35621. outlineWidth (0.0f)
  35622. {
  35623. }
  35624. ShapeButton::~ShapeButton()
  35625. {
  35626. }
  35627. void ShapeButton::setColours (const Colour& newNormalColour,
  35628. const Colour& newOverColour,
  35629. const Colour& newDownColour)
  35630. {
  35631. normalColour = newNormalColour;
  35632. overColour = newOverColour;
  35633. downColour = newDownColour;
  35634. }
  35635. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35636. const float newOutlineWidth)
  35637. {
  35638. outlineColour = newOutlineColour;
  35639. outlineWidth = newOutlineWidth;
  35640. }
  35641. void ShapeButton::setShape (const Path& newShape,
  35642. const bool resizeNowToFitThisShape,
  35643. const bool maintainShapeProportions_,
  35644. const bool hasShadow)
  35645. {
  35646. shape = newShape;
  35647. maintainShapeProportions = maintainShapeProportions_;
  35648. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35649. setComponentEffect ((hasShadow) ? &shadow : 0);
  35650. if (resizeNowToFitThisShape)
  35651. {
  35652. Rectangle<float> bounds (shape.getBounds());
  35653. if (hasShadow)
  35654. bounds.expand (4.0f, 4.0f);
  35655. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35656. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35657. 1 + (int) (bounds.getHeight() + outlineWidth));
  35658. }
  35659. }
  35660. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35661. {
  35662. if (! isEnabled())
  35663. {
  35664. isMouseOverButton = false;
  35665. isButtonDown = false;
  35666. }
  35667. g.setColour ((isButtonDown) ? downColour
  35668. : (isMouseOverButton) ? overColour
  35669. : normalColour);
  35670. int w = getWidth();
  35671. int h = getHeight();
  35672. if (getComponentEffect() != 0)
  35673. {
  35674. w -= 4;
  35675. h -= 4;
  35676. }
  35677. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35678. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35679. w - offset - outlineWidth,
  35680. h - offset - outlineWidth,
  35681. maintainShapeProportions));
  35682. g.fillPath (shape, trans);
  35683. if (outlineWidth > 0.0f)
  35684. {
  35685. g.setColour (outlineColour);
  35686. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35687. }
  35688. }
  35689. END_JUCE_NAMESPACE
  35690. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35691. /*** Start of inlined file: juce_TextButton.cpp ***/
  35692. BEGIN_JUCE_NAMESPACE
  35693. TextButton::TextButton (const String& name,
  35694. const String& toolTip)
  35695. : Button (name)
  35696. {
  35697. setTooltip (toolTip);
  35698. }
  35699. TextButton::~TextButton()
  35700. {
  35701. }
  35702. void TextButton::paintButton (Graphics& g,
  35703. bool isMouseOverButton,
  35704. bool isButtonDown)
  35705. {
  35706. getLookAndFeel().drawButtonBackground (g, *this,
  35707. findColour (getToggleState() ? buttonOnColourId
  35708. : buttonColourId),
  35709. isMouseOverButton,
  35710. isButtonDown);
  35711. getLookAndFeel().drawButtonText (g, *this,
  35712. isMouseOverButton,
  35713. isButtonDown);
  35714. }
  35715. void TextButton::colourChanged()
  35716. {
  35717. repaint();
  35718. }
  35719. const Font TextButton::getFont()
  35720. {
  35721. return Font (jmin (15.0f, getHeight() * 0.6f));
  35722. }
  35723. void TextButton::changeWidthToFitText (const int newHeight)
  35724. {
  35725. if (newHeight >= 0)
  35726. setSize (jmax (1, getWidth()), newHeight);
  35727. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35728. getHeight());
  35729. }
  35730. END_JUCE_NAMESPACE
  35731. /*** End of inlined file: juce_TextButton.cpp ***/
  35732. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35733. BEGIN_JUCE_NAMESPACE
  35734. ToggleButton::ToggleButton (const String& buttonText)
  35735. : Button (buttonText)
  35736. {
  35737. setClickingTogglesState (true);
  35738. }
  35739. ToggleButton::~ToggleButton()
  35740. {
  35741. }
  35742. void ToggleButton::paintButton (Graphics& g,
  35743. bool isMouseOverButton,
  35744. bool isButtonDown)
  35745. {
  35746. getLookAndFeel().drawToggleButton (g, *this,
  35747. isMouseOverButton,
  35748. isButtonDown);
  35749. }
  35750. void ToggleButton::changeWidthToFitText()
  35751. {
  35752. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35753. }
  35754. void ToggleButton::colourChanged()
  35755. {
  35756. repaint();
  35757. }
  35758. END_JUCE_NAMESPACE
  35759. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35760. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35761. BEGIN_JUCE_NAMESPACE
  35762. ToolbarButton::ToolbarButton (const int itemId_, const String& buttonText,
  35763. Drawable* const normalImage_, Drawable* const toggledOnImage_)
  35764. : ToolbarItemComponent (itemId_, buttonText, true),
  35765. normalImage (normalImage_),
  35766. toggledOnImage (toggledOnImage_),
  35767. currentImage (0)
  35768. {
  35769. jassert (normalImage_ != 0);
  35770. }
  35771. ToolbarButton::~ToolbarButton()
  35772. {
  35773. }
  35774. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize)
  35775. {
  35776. preferredSize = minSize = maxSize = toolbarDepth;
  35777. return true;
  35778. }
  35779. void ToolbarButton::paintButtonArea (Graphics&, int /*width*/, int /*height*/, bool /*isMouseOver*/, bool /*isMouseDown*/)
  35780. {
  35781. }
  35782. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35783. {
  35784. buttonStateChanged();
  35785. }
  35786. void ToolbarButton::updateDrawable()
  35787. {
  35788. if (currentImage != 0)
  35789. {
  35790. currentImage->setTransformToFit (getContentArea().toFloat(), RectanglePlacement::centred);
  35791. currentImage->setAlpha (isEnabled() ? 1.0f : 0.5f);
  35792. }
  35793. }
  35794. void ToolbarButton::resized()
  35795. {
  35796. ToolbarItemComponent::resized();
  35797. updateDrawable();
  35798. }
  35799. void ToolbarButton::enablementChanged()
  35800. {
  35801. ToolbarItemComponent::enablementChanged();
  35802. updateDrawable();
  35803. }
  35804. void ToolbarButton::buttonStateChanged()
  35805. {
  35806. Drawable* d = normalImage;
  35807. if (getToggleState() && toggledOnImage != 0)
  35808. d = toggledOnImage;
  35809. if (d != currentImage)
  35810. {
  35811. removeChildComponent (currentImage);
  35812. currentImage = d;
  35813. if (d != 0)
  35814. {
  35815. enablementChanged();
  35816. addAndMakeVisible (d);
  35817. updateDrawable();
  35818. }
  35819. }
  35820. }
  35821. END_JUCE_NAMESPACE
  35822. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35823. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35824. BEGIN_JUCE_NAMESPACE
  35825. class CodeDocumentLine
  35826. {
  35827. public:
  35828. CodeDocumentLine (const juce_wchar* const line_,
  35829. const int lineLength_,
  35830. const int numNewLineChars,
  35831. const int lineStartInFile_)
  35832. : line (line_, lineLength_),
  35833. lineStartInFile (lineStartInFile_),
  35834. lineLength (lineLength_),
  35835. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35836. {
  35837. }
  35838. ~CodeDocumentLine()
  35839. {
  35840. }
  35841. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35842. {
  35843. const juce_wchar* const t = text;
  35844. int pos = 0;
  35845. while (t [pos] != 0)
  35846. {
  35847. const int startOfLine = pos;
  35848. int numNewLineChars = 0;
  35849. while (t[pos] != 0)
  35850. {
  35851. if (t[pos] == '\r')
  35852. {
  35853. ++numNewLineChars;
  35854. ++pos;
  35855. if (t[pos] == '\n')
  35856. {
  35857. ++numNewLineChars;
  35858. ++pos;
  35859. }
  35860. break;
  35861. }
  35862. if (t[pos] == '\n')
  35863. {
  35864. ++numNewLineChars;
  35865. ++pos;
  35866. break;
  35867. }
  35868. ++pos;
  35869. }
  35870. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35871. numNewLineChars, startOfLine));
  35872. }
  35873. jassert (pos == text.length());
  35874. }
  35875. bool endsWithLineBreak() const throw()
  35876. {
  35877. return lineLengthWithoutNewLines != lineLength;
  35878. }
  35879. void updateLength() throw()
  35880. {
  35881. lineLengthWithoutNewLines = lineLength = line.length();
  35882. while (lineLengthWithoutNewLines > 0
  35883. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35884. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35885. {
  35886. --lineLengthWithoutNewLines;
  35887. }
  35888. }
  35889. String line;
  35890. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35891. };
  35892. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35893. : document (document_),
  35894. currentLine (document_->lines[0]),
  35895. line (0),
  35896. position (0)
  35897. {
  35898. }
  35899. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35900. : document (other.document),
  35901. currentLine (other.currentLine),
  35902. line (other.line),
  35903. position (other.position)
  35904. {
  35905. }
  35906. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35907. {
  35908. document = other.document;
  35909. currentLine = other.currentLine;
  35910. line = other.line;
  35911. position = other.position;
  35912. return *this;
  35913. }
  35914. CodeDocument::Iterator::~Iterator() throw()
  35915. {
  35916. }
  35917. juce_wchar CodeDocument::Iterator::nextChar()
  35918. {
  35919. if (currentLine == 0)
  35920. return 0;
  35921. jassert (currentLine == document->lines.getUnchecked (line));
  35922. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35923. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35924. {
  35925. ++line;
  35926. currentLine = document->lines [line];
  35927. }
  35928. return result;
  35929. }
  35930. void CodeDocument::Iterator::skip()
  35931. {
  35932. if (currentLine != 0)
  35933. {
  35934. jassert (currentLine == document->lines.getUnchecked (line));
  35935. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35936. {
  35937. ++line;
  35938. currentLine = document->lines [line];
  35939. }
  35940. }
  35941. }
  35942. void CodeDocument::Iterator::skipToEndOfLine()
  35943. {
  35944. if (currentLine != 0)
  35945. {
  35946. jassert (currentLine == document->lines.getUnchecked (line));
  35947. ++line;
  35948. currentLine = document->lines [line];
  35949. if (currentLine != 0)
  35950. position = currentLine->lineStartInFile;
  35951. else
  35952. position = document->getNumCharacters();
  35953. }
  35954. }
  35955. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35956. {
  35957. if (currentLine == 0)
  35958. return 0;
  35959. jassert (currentLine == document->lines.getUnchecked (line));
  35960. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35961. }
  35962. void CodeDocument::Iterator::skipWhitespace()
  35963. {
  35964. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35965. skip();
  35966. }
  35967. bool CodeDocument::Iterator::isEOF() const throw()
  35968. {
  35969. return currentLine == 0;
  35970. }
  35971. CodeDocument::Position::Position() throw()
  35972. : owner (0), characterPos (0), line (0),
  35973. indexInLine (0), positionMaintained (false)
  35974. {
  35975. }
  35976. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35977. const int line_, const int indexInLine_) throw()
  35978. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35979. characterPos (0), line (line_),
  35980. indexInLine (indexInLine_), positionMaintained (false)
  35981. {
  35982. setLineAndIndex (line_, indexInLine_);
  35983. }
  35984. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35985. const int characterPos_) throw()
  35986. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35987. positionMaintained (false)
  35988. {
  35989. setPosition (characterPos_);
  35990. }
  35991. CodeDocument::Position::Position (const Position& other) throw()
  35992. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35993. indexInLine (other.indexInLine), positionMaintained (false)
  35994. {
  35995. jassert (*this == other);
  35996. }
  35997. CodeDocument::Position::~Position()
  35998. {
  35999. setPositionMaintained (false);
  36000. }
  36001. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36002. {
  36003. if (this != &other)
  36004. {
  36005. const bool wasPositionMaintained = positionMaintained;
  36006. if (owner != other.owner)
  36007. setPositionMaintained (false);
  36008. owner = other.owner;
  36009. line = other.line;
  36010. indexInLine = other.indexInLine;
  36011. characterPos = other.characterPos;
  36012. setPositionMaintained (wasPositionMaintained);
  36013. jassert (*this == other);
  36014. }
  36015. return *this;
  36016. }
  36017. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36018. {
  36019. jassert ((characterPos == other.characterPos)
  36020. == (line == other.line && indexInLine == other.indexInLine));
  36021. return characterPos == other.characterPos
  36022. && line == other.line
  36023. && indexInLine == other.indexInLine
  36024. && owner == other.owner;
  36025. }
  36026. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36027. {
  36028. return ! operator== (other);
  36029. }
  36030. void CodeDocument::Position::setLineAndIndex (const int newLineNum, const int newIndexInLine)
  36031. {
  36032. jassert (owner != 0);
  36033. if (owner->lines.size() == 0)
  36034. {
  36035. line = 0;
  36036. indexInLine = 0;
  36037. characterPos = 0;
  36038. }
  36039. else
  36040. {
  36041. if (newLineNum >= owner->lines.size())
  36042. {
  36043. line = owner->lines.size() - 1;
  36044. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36045. jassert (l != 0);
  36046. indexInLine = l->lineLengthWithoutNewLines;
  36047. characterPos = l->lineStartInFile + indexInLine;
  36048. }
  36049. else
  36050. {
  36051. line = jmax (0, newLineNum);
  36052. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36053. jassert (l != 0);
  36054. if (l->lineLengthWithoutNewLines > 0)
  36055. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36056. else
  36057. indexInLine = 0;
  36058. characterPos = l->lineStartInFile + indexInLine;
  36059. }
  36060. }
  36061. }
  36062. void CodeDocument::Position::setPosition (const int newPosition)
  36063. {
  36064. jassert (owner != 0);
  36065. line = 0;
  36066. indexInLine = 0;
  36067. characterPos = 0;
  36068. if (newPosition > 0)
  36069. {
  36070. int lineStart = 0;
  36071. int lineEnd = owner->lines.size();
  36072. for (;;)
  36073. {
  36074. if (lineEnd - lineStart < 4)
  36075. {
  36076. for (int i = lineStart; i < lineEnd; ++i)
  36077. {
  36078. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36079. int index = newPosition - l->lineStartInFile;
  36080. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36081. {
  36082. line = i;
  36083. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36084. characterPos = l->lineStartInFile + indexInLine;
  36085. }
  36086. }
  36087. break;
  36088. }
  36089. else
  36090. {
  36091. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36092. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36093. if (newPosition >= mid->lineStartInFile)
  36094. lineStart = midIndex;
  36095. else
  36096. lineEnd = midIndex;
  36097. }
  36098. }
  36099. }
  36100. }
  36101. void CodeDocument::Position::moveBy (int characterDelta)
  36102. {
  36103. jassert (owner != 0);
  36104. if (characterDelta == 1)
  36105. {
  36106. setPosition (getPosition());
  36107. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36108. if (line < owner->lines.size())
  36109. {
  36110. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36111. if (indexInLine + characterDelta < l->lineLength
  36112. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36113. ++characterDelta;
  36114. }
  36115. }
  36116. setPosition (characterPos + characterDelta);
  36117. }
  36118. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36119. {
  36120. CodeDocument::Position p (*this);
  36121. p.moveBy (characterDelta);
  36122. return p;
  36123. }
  36124. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36125. {
  36126. CodeDocument::Position p (*this);
  36127. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36128. return p;
  36129. }
  36130. const juce_wchar CodeDocument::Position::getCharacter() const
  36131. {
  36132. const CodeDocumentLine* const l = owner->lines [line];
  36133. return l == 0 ? 0 : l->line [getIndexInLine()];
  36134. }
  36135. const String CodeDocument::Position::getLineText() const
  36136. {
  36137. const CodeDocumentLine* const l = owner->lines [line];
  36138. return l == 0 ? String::empty : l->line;
  36139. }
  36140. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36141. {
  36142. if (isMaintained != positionMaintained)
  36143. {
  36144. positionMaintained = isMaintained;
  36145. if (owner != 0)
  36146. {
  36147. if (isMaintained)
  36148. {
  36149. jassert (! owner->positionsToMaintain.contains (this));
  36150. owner->positionsToMaintain.add (this);
  36151. }
  36152. else
  36153. {
  36154. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36155. jassert (owner->positionsToMaintain.contains (this));
  36156. owner->positionsToMaintain.removeValue (this);
  36157. }
  36158. }
  36159. }
  36160. }
  36161. CodeDocument::CodeDocument()
  36162. : undoManager (std::numeric_limits<int>::max(), 10000),
  36163. currentActionIndex (0),
  36164. indexOfSavedState (-1),
  36165. maximumLineLength (-1),
  36166. newLineChars ("\r\n")
  36167. {
  36168. }
  36169. CodeDocument::~CodeDocument()
  36170. {
  36171. }
  36172. const String CodeDocument::getAllContent() const
  36173. {
  36174. return getTextBetween (Position (this, 0),
  36175. Position (this, lines.size(), 0));
  36176. }
  36177. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36178. {
  36179. if (end.getPosition() <= start.getPosition())
  36180. return String::empty;
  36181. const int startLine = start.getLineNumber();
  36182. const int endLine = end.getLineNumber();
  36183. if (startLine == endLine)
  36184. {
  36185. CodeDocumentLine* const line = lines [startLine];
  36186. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36187. }
  36188. String result;
  36189. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36190. String::Concatenator concatenator (result);
  36191. const int maxLine = jmin (lines.size() - 1, endLine);
  36192. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36193. {
  36194. const CodeDocumentLine* line = lines.getUnchecked(i);
  36195. int len = line->lineLength;
  36196. if (i == startLine)
  36197. {
  36198. const int index = start.getIndexInLine();
  36199. concatenator.append (line->line.substring (index, len));
  36200. }
  36201. else if (i == endLine)
  36202. {
  36203. len = end.getIndexInLine();
  36204. concatenator.append (line->line.substring (0, len));
  36205. }
  36206. else
  36207. {
  36208. concatenator.append (line->line);
  36209. }
  36210. }
  36211. return result;
  36212. }
  36213. int CodeDocument::getNumCharacters() const throw()
  36214. {
  36215. const CodeDocumentLine* const lastLine = lines.getLast();
  36216. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36217. }
  36218. const String CodeDocument::getLine (const int lineIndex) const throw()
  36219. {
  36220. const CodeDocumentLine* const line = lines [lineIndex];
  36221. return (line == 0) ? String::empty : line->line;
  36222. }
  36223. int CodeDocument::getMaximumLineLength() throw()
  36224. {
  36225. if (maximumLineLength < 0)
  36226. {
  36227. maximumLineLength = 0;
  36228. for (int i = lines.size(); --i >= 0;)
  36229. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36230. }
  36231. return maximumLineLength;
  36232. }
  36233. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36234. {
  36235. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36236. }
  36237. void CodeDocument::insertText (const Position& position, const String& text)
  36238. {
  36239. insert (text, position.getPosition(), true);
  36240. }
  36241. void CodeDocument::replaceAllContent (const String& newContent)
  36242. {
  36243. remove (0, getNumCharacters(), true);
  36244. insert (newContent, 0, true);
  36245. }
  36246. bool CodeDocument::loadFromStream (InputStream& stream)
  36247. {
  36248. replaceAllContent (stream.readEntireStreamAsString());
  36249. setSavePoint();
  36250. clearUndoHistory();
  36251. return true;
  36252. }
  36253. bool CodeDocument::writeToStream (OutputStream& stream)
  36254. {
  36255. for (int i = 0; i < lines.size(); ++i)
  36256. {
  36257. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36258. const char* utf8 = temp.toUTF8();
  36259. if (! stream.write (utf8, (int) strlen (utf8)))
  36260. return false;
  36261. }
  36262. return true;
  36263. }
  36264. void CodeDocument::setNewLineCharacters (const String& newLineChars_) throw()
  36265. {
  36266. jassert (newLineChars_ == "\r\n" || newLineChars_ == "\n" || newLineChars_ == "\r");
  36267. newLineChars = newLineChars_;
  36268. }
  36269. void CodeDocument::newTransaction()
  36270. {
  36271. undoManager.beginNewTransaction (String::empty);
  36272. }
  36273. void CodeDocument::undo()
  36274. {
  36275. newTransaction();
  36276. undoManager.undo();
  36277. }
  36278. void CodeDocument::redo()
  36279. {
  36280. undoManager.redo();
  36281. }
  36282. void CodeDocument::clearUndoHistory()
  36283. {
  36284. undoManager.clearUndoHistory();
  36285. }
  36286. void CodeDocument::setSavePoint() throw()
  36287. {
  36288. indexOfSavedState = currentActionIndex;
  36289. }
  36290. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36291. {
  36292. return currentActionIndex != indexOfSavedState;
  36293. }
  36294. namespace CodeDocumentHelpers
  36295. {
  36296. int getCharacterType (const juce_wchar character) throw()
  36297. {
  36298. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36299. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36300. }
  36301. }
  36302. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36303. {
  36304. Position p (position);
  36305. const int maxDistance = 256;
  36306. int i = 0;
  36307. while (i < maxDistance
  36308. && CharacterFunctions::isWhitespace (p.getCharacter())
  36309. && (i == 0 || (p.getCharacter() != '\n'
  36310. && p.getCharacter() != '\r')))
  36311. {
  36312. ++i;
  36313. p.moveBy (1);
  36314. }
  36315. if (i == 0)
  36316. {
  36317. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36318. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36319. {
  36320. ++i;
  36321. p.moveBy (1);
  36322. }
  36323. while (i < maxDistance
  36324. && CharacterFunctions::isWhitespace (p.getCharacter())
  36325. && (i == 0 || (p.getCharacter() != '\n'
  36326. && p.getCharacter() != '\r')))
  36327. {
  36328. ++i;
  36329. p.moveBy (1);
  36330. }
  36331. }
  36332. return p;
  36333. }
  36334. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36335. {
  36336. Position p (position);
  36337. const int maxDistance = 256;
  36338. int i = 0;
  36339. bool stoppedAtLineStart = false;
  36340. while (i < maxDistance)
  36341. {
  36342. const juce_wchar c = p.movedBy (-1).getCharacter();
  36343. if (c == '\r' || c == '\n')
  36344. {
  36345. stoppedAtLineStart = true;
  36346. if (i > 0)
  36347. break;
  36348. }
  36349. if (! CharacterFunctions::isWhitespace (c))
  36350. break;
  36351. p.moveBy (-1);
  36352. ++i;
  36353. }
  36354. if (i < maxDistance && ! stoppedAtLineStart)
  36355. {
  36356. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36357. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36358. {
  36359. p.moveBy (-1);
  36360. ++i;
  36361. }
  36362. }
  36363. return p;
  36364. }
  36365. void CodeDocument::checkLastLineStatus()
  36366. {
  36367. while (lines.size() > 0
  36368. && lines.getLast()->lineLength == 0
  36369. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36370. {
  36371. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36372. lines.removeLast();
  36373. }
  36374. const CodeDocumentLine* const lastLine = lines.getLast();
  36375. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36376. {
  36377. // check that there's an empty line at the end if the preceding one ends in a newline..
  36378. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36379. }
  36380. }
  36381. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36382. {
  36383. listeners.add (listener);
  36384. }
  36385. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36386. {
  36387. listeners.remove (listener);
  36388. }
  36389. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36390. {
  36391. Position startPos (this, startLine, 0);
  36392. Position endPos (this, endLine, 0);
  36393. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36394. }
  36395. class CodeDocumentInsertAction : public UndoableAction
  36396. {
  36397. public:
  36398. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36399. : owner (owner_),
  36400. text (text_),
  36401. insertPos (insertPos_)
  36402. {
  36403. }
  36404. bool perform()
  36405. {
  36406. owner.currentActionIndex++;
  36407. owner.insert (text, insertPos, false);
  36408. return true;
  36409. }
  36410. bool undo()
  36411. {
  36412. owner.currentActionIndex--;
  36413. owner.remove (insertPos, insertPos + text.length(), false);
  36414. return true;
  36415. }
  36416. int getSizeInUnits() { return text.length() + 32; }
  36417. private:
  36418. CodeDocument& owner;
  36419. const String text;
  36420. int insertPos;
  36421. JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction);
  36422. };
  36423. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36424. {
  36425. if (text.isEmpty())
  36426. return;
  36427. if (undoable)
  36428. {
  36429. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36430. }
  36431. else
  36432. {
  36433. Position pos (this, insertPos);
  36434. const int firstAffectedLine = pos.getLineNumber();
  36435. int lastAffectedLine = firstAffectedLine + 1;
  36436. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36437. String textInsideOriginalLine (text);
  36438. if (firstLine != 0)
  36439. {
  36440. const int index = pos.getIndexInLine();
  36441. textInsideOriginalLine = firstLine->line.substring (0, index)
  36442. + textInsideOriginalLine
  36443. + firstLine->line.substring (index);
  36444. }
  36445. maximumLineLength = -1;
  36446. Array <CodeDocumentLine*> newLines;
  36447. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36448. jassert (newLines.size() > 0);
  36449. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36450. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36451. lines.set (firstAffectedLine, newFirstLine);
  36452. if (newLines.size() > 1)
  36453. {
  36454. for (int i = 1; i < newLines.size(); ++i)
  36455. {
  36456. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36457. lines.insert (firstAffectedLine + i, l);
  36458. }
  36459. lastAffectedLine = lines.size();
  36460. }
  36461. int i, lineStart = newFirstLine->lineStartInFile;
  36462. for (i = firstAffectedLine; i < lines.size(); ++i)
  36463. {
  36464. CodeDocumentLine* const l = lines.getUnchecked (i);
  36465. l->lineStartInFile = lineStart;
  36466. lineStart += l->lineLength;
  36467. }
  36468. checkLastLineStatus();
  36469. const int newTextLength = text.length();
  36470. for (i = 0; i < positionsToMaintain.size(); ++i)
  36471. {
  36472. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36473. if (p->getPosition() >= insertPos)
  36474. p->setPosition (p->getPosition() + newTextLength);
  36475. }
  36476. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36477. }
  36478. }
  36479. class CodeDocumentDeleteAction : public UndoableAction
  36480. {
  36481. public:
  36482. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36483. : owner (owner_),
  36484. startPos (startPos_),
  36485. endPos (endPos_)
  36486. {
  36487. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36488. CodeDocument::Position (&owner, endPos));
  36489. }
  36490. bool perform()
  36491. {
  36492. owner.currentActionIndex++;
  36493. owner.remove (startPos, endPos, false);
  36494. return true;
  36495. }
  36496. bool undo()
  36497. {
  36498. owner.currentActionIndex--;
  36499. owner.insert (removedText, startPos, false);
  36500. return true;
  36501. }
  36502. int getSizeInUnits() { return removedText.length() + 32; }
  36503. private:
  36504. CodeDocument& owner;
  36505. int startPos, endPos;
  36506. String removedText;
  36507. JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction);
  36508. };
  36509. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36510. {
  36511. if (endPos <= startPos)
  36512. return;
  36513. if (undoable)
  36514. {
  36515. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36516. }
  36517. else
  36518. {
  36519. Position startPosition (this, startPos);
  36520. Position endPosition (this, endPos);
  36521. maximumLineLength = -1;
  36522. const int firstAffectedLine = startPosition.getLineNumber();
  36523. const int endLine = endPosition.getLineNumber();
  36524. int lastAffectedLine = firstAffectedLine + 1;
  36525. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36526. if (firstAffectedLine == endLine)
  36527. {
  36528. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36529. + firstLine->line.substring (endPosition.getIndexInLine());
  36530. firstLine->updateLength();
  36531. }
  36532. else
  36533. {
  36534. lastAffectedLine = lines.size();
  36535. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36536. jassert (lastLine != 0);
  36537. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36538. + lastLine->line.substring (endPosition.getIndexInLine());
  36539. firstLine->updateLength();
  36540. int numLinesToRemove = endLine - firstAffectedLine;
  36541. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36542. }
  36543. int i;
  36544. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36545. {
  36546. CodeDocumentLine* const l = lines.getUnchecked (i);
  36547. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36548. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36549. }
  36550. checkLastLineStatus();
  36551. const int totalChars = getNumCharacters();
  36552. for (i = 0; i < positionsToMaintain.size(); ++i)
  36553. {
  36554. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36555. if (p->getPosition() > startPosition.getPosition())
  36556. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36557. if (p->getPosition() > totalChars)
  36558. p->setPosition (totalChars);
  36559. }
  36560. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36561. }
  36562. }
  36563. END_JUCE_NAMESPACE
  36564. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36565. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36566. BEGIN_JUCE_NAMESPACE
  36567. class CodeEditorComponent::CaretComponent : public Component,
  36568. public Timer
  36569. {
  36570. public:
  36571. CaretComponent (CodeEditorComponent& owner_)
  36572. : owner (owner_)
  36573. {
  36574. setAlwaysOnTop (true);
  36575. setInterceptsMouseClicks (false, false);
  36576. }
  36577. void paint (Graphics& g)
  36578. {
  36579. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36580. }
  36581. void timerCallback()
  36582. {
  36583. setVisible (shouldBeShown() && ! isVisible());
  36584. }
  36585. void updatePosition()
  36586. {
  36587. startTimer (400);
  36588. setVisible (shouldBeShown());
  36589. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36590. }
  36591. private:
  36592. CodeEditorComponent& owner;
  36593. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36594. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  36595. };
  36596. class CodeEditorComponent::CodeEditorLine
  36597. {
  36598. public:
  36599. CodeEditorLine() throw()
  36600. : highlightColumnStart (0), highlightColumnEnd (0)
  36601. {
  36602. }
  36603. bool update (CodeDocument& document, int lineNum,
  36604. CodeDocument::Iterator& source,
  36605. CodeTokeniser* analyser, const int spacesPerTab,
  36606. const CodeDocument::Position& selectionStart,
  36607. const CodeDocument::Position& selectionEnd)
  36608. {
  36609. Array <SyntaxToken> newTokens;
  36610. newTokens.ensureStorageAllocated (8);
  36611. if (analyser == 0)
  36612. {
  36613. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36614. }
  36615. else if (lineNum < document.getNumLines())
  36616. {
  36617. const CodeDocument::Position pos (&document, lineNum, 0);
  36618. createTokens (pos.getPosition(), pos.getLineText(),
  36619. source, analyser, newTokens);
  36620. }
  36621. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36622. int newHighlightStart = 0;
  36623. int newHighlightEnd = 0;
  36624. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36625. {
  36626. const String line (document.getLine (lineNum));
  36627. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36628. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36629. line, spacesPerTab);
  36630. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36631. line, spacesPerTab);
  36632. }
  36633. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36634. {
  36635. highlightColumnStart = newHighlightStart;
  36636. highlightColumnEnd = newHighlightEnd;
  36637. }
  36638. else
  36639. {
  36640. if (tokens.size() == newTokens.size())
  36641. {
  36642. bool allTheSame = true;
  36643. for (int i = newTokens.size(); --i >= 0;)
  36644. {
  36645. if (tokens.getReference(i) != newTokens.getReference(i))
  36646. {
  36647. allTheSame = false;
  36648. break;
  36649. }
  36650. }
  36651. if (allTheSame)
  36652. return false;
  36653. }
  36654. }
  36655. tokens.swapWithArray (newTokens);
  36656. return true;
  36657. }
  36658. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36659. float x, const int y, const int baselineOffset, const int lineHeight,
  36660. const Colour& highlightColour) const
  36661. {
  36662. if (highlightColumnStart < highlightColumnEnd)
  36663. {
  36664. g.setColour (highlightColour);
  36665. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36666. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36667. }
  36668. int lastType = std::numeric_limits<int>::min();
  36669. for (int i = 0; i < tokens.size(); ++i)
  36670. {
  36671. SyntaxToken& token = tokens.getReference(i);
  36672. if (lastType != token.tokenType)
  36673. {
  36674. lastType = token.tokenType;
  36675. g.setColour (owner.getColourForTokenType (lastType));
  36676. }
  36677. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36678. if (i < tokens.size() - 1)
  36679. {
  36680. if (token.width < 0)
  36681. token.width = font.getStringWidthFloat (token.text);
  36682. x += token.width;
  36683. }
  36684. }
  36685. }
  36686. private:
  36687. struct SyntaxToken
  36688. {
  36689. SyntaxToken (const String& text_, const int type) throw()
  36690. : text (text_), tokenType (type), width (-1.0f)
  36691. {
  36692. }
  36693. bool operator!= (const SyntaxToken& other) const throw()
  36694. {
  36695. return text != other.text || tokenType != other.tokenType;
  36696. }
  36697. String text;
  36698. int tokenType;
  36699. float width;
  36700. };
  36701. Array <SyntaxToken> tokens;
  36702. int highlightColumnStart, highlightColumnEnd;
  36703. static void createTokens (int startPosition, const String& lineText,
  36704. CodeDocument::Iterator& source,
  36705. CodeTokeniser* analyser,
  36706. Array <SyntaxToken>& newTokens)
  36707. {
  36708. CodeDocument::Iterator lastIterator (source);
  36709. const int lineLength = lineText.length();
  36710. for (;;)
  36711. {
  36712. int tokenType = analyser->readNextToken (source);
  36713. int tokenStart = lastIterator.getPosition();
  36714. int tokenEnd = source.getPosition();
  36715. if (tokenEnd <= tokenStart)
  36716. break;
  36717. tokenEnd -= startPosition;
  36718. if (tokenEnd > 0)
  36719. {
  36720. tokenStart -= startPosition;
  36721. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36722. tokenType));
  36723. if (tokenEnd >= lineLength)
  36724. break;
  36725. }
  36726. lastIterator = source;
  36727. }
  36728. source = lastIterator;
  36729. }
  36730. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36731. {
  36732. int x = 0;
  36733. for (int i = 0; i < tokens.size(); ++i)
  36734. {
  36735. SyntaxToken& t = tokens.getReference(i);
  36736. for (;;)
  36737. {
  36738. int tabPos = t.text.indexOfChar ('\t');
  36739. if (tabPos < 0)
  36740. break;
  36741. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36742. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36743. }
  36744. x += t.text.length();
  36745. }
  36746. }
  36747. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36748. {
  36749. jassert (index <= line.length());
  36750. int col = 0;
  36751. for (int i = 0; i < index; ++i)
  36752. {
  36753. if (line[i] != '\t')
  36754. ++col;
  36755. else
  36756. col += spacesPerTab - (col % spacesPerTab);
  36757. }
  36758. return col;
  36759. }
  36760. };
  36761. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36762. CodeTokeniser* const codeTokeniser_)
  36763. : document (document_),
  36764. firstLineOnScreen (0),
  36765. gutter (5),
  36766. spacesPerTab (4),
  36767. lineHeight (0),
  36768. linesOnScreen (0),
  36769. columnsOnScreen (0),
  36770. scrollbarThickness (16),
  36771. columnToTryToMaintain (-1),
  36772. useSpacesForTabs (false),
  36773. xOffset (0),
  36774. verticalScrollBar (true),
  36775. horizontalScrollBar (false),
  36776. codeTokeniser (codeTokeniser_)
  36777. {
  36778. caretPos = CodeDocument::Position (&document_, 0, 0);
  36779. caretPos.setPositionMaintained (true);
  36780. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36781. selectionStart.setPositionMaintained (true);
  36782. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36783. selectionEnd.setPositionMaintained (true);
  36784. setOpaque (true);
  36785. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36786. setWantsKeyboardFocus (true);
  36787. addAndMakeVisible (&verticalScrollBar);
  36788. verticalScrollBar.setSingleStepSize (1.0);
  36789. addAndMakeVisible (&horizontalScrollBar);
  36790. horizontalScrollBar.setSingleStepSize (1.0);
  36791. addAndMakeVisible (caret = new CaretComponent (*this));
  36792. Font f (12.0f);
  36793. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36794. setFont (f);
  36795. resetToDefaultColours();
  36796. verticalScrollBar.addListener (this);
  36797. horizontalScrollBar.addListener (this);
  36798. document.addListener (this);
  36799. }
  36800. CodeEditorComponent::~CodeEditorComponent()
  36801. {
  36802. document.removeListener (this);
  36803. }
  36804. void CodeEditorComponent::loadContent (const String& newContent)
  36805. {
  36806. clearCachedIterators (0);
  36807. document.replaceAllContent (newContent);
  36808. document.clearUndoHistory();
  36809. document.setSavePoint();
  36810. caretPos.setPosition (0);
  36811. selectionStart.setPosition (0);
  36812. selectionEnd.setPosition (0);
  36813. scrollToLine (0);
  36814. }
  36815. bool CodeEditorComponent::isTextInputActive() const
  36816. {
  36817. return true;
  36818. }
  36819. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36820. const CodeDocument::Position& affectedTextEnd)
  36821. {
  36822. clearCachedIterators (affectedTextStart.getLineNumber());
  36823. triggerAsyncUpdate();
  36824. caret->updatePosition();
  36825. columnToTryToMaintain = -1;
  36826. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36827. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36828. deselectAll();
  36829. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36830. || caretPos.getPosition() < affectedTextStart.getPosition())
  36831. moveCaretTo (affectedTextStart, false);
  36832. updateScrollBars();
  36833. }
  36834. void CodeEditorComponent::resized()
  36835. {
  36836. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36837. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36838. lines.clear();
  36839. rebuildLineTokens();
  36840. caret->updatePosition();
  36841. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36842. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36843. updateScrollBars();
  36844. }
  36845. void CodeEditorComponent::paint (Graphics& g)
  36846. {
  36847. handleUpdateNowIfNeeded();
  36848. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36849. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  36850. g.setFont (font);
  36851. const int baselineOffset = (int) font.getAscent();
  36852. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36853. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36854. const Rectangle<int> clip (g.getClipBounds());
  36855. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36856. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36857. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36858. {
  36859. lines.getUnchecked(j)->draw (*this, g, font,
  36860. (float) (gutter - xOffset * charWidth),
  36861. lineHeight * j, baselineOffset, lineHeight,
  36862. highlightColour);
  36863. }
  36864. }
  36865. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36866. {
  36867. if (scrollbarThickness != thickness)
  36868. {
  36869. scrollbarThickness = thickness;
  36870. resized();
  36871. }
  36872. }
  36873. void CodeEditorComponent::handleAsyncUpdate()
  36874. {
  36875. rebuildLineTokens();
  36876. }
  36877. void CodeEditorComponent::rebuildLineTokens()
  36878. {
  36879. cancelPendingUpdate();
  36880. const int numNeeded = linesOnScreen + 1;
  36881. int minLineToRepaint = numNeeded;
  36882. int maxLineToRepaint = 0;
  36883. if (numNeeded != lines.size())
  36884. {
  36885. lines.clear();
  36886. for (int i = numNeeded; --i >= 0;)
  36887. lines.add (new CodeEditorLine());
  36888. minLineToRepaint = 0;
  36889. maxLineToRepaint = numNeeded;
  36890. }
  36891. jassert (numNeeded == lines.size());
  36892. CodeDocument::Iterator source (&document);
  36893. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36894. for (int i = 0; i < numNeeded; ++i)
  36895. {
  36896. CodeEditorLine* const line = lines.getUnchecked(i);
  36897. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36898. selectionStart, selectionEnd))
  36899. {
  36900. minLineToRepaint = jmin (minLineToRepaint, i);
  36901. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36902. }
  36903. }
  36904. if (minLineToRepaint <= maxLineToRepaint)
  36905. {
  36906. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36907. verticalScrollBar.getX() - gutter,
  36908. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36909. }
  36910. }
  36911. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36912. {
  36913. caretPos = newPos;
  36914. columnToTryToMaintain = -1;
  36915. if (highlighting)
  36916. {
  36917. if (dragType == notDragging)
  36918. {
  36919. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36920. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36921. dragType = draggingSelectionStart;
  36922. else
  36923. dragType = draggingSelectionEnd;
  36924. }
  36925. if (dragType == draggingSelectionStart)
  36926. {
  36927. selectionStart = caretPos;
  36928. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36929. {
  36930. const CodeDocument::Position temp (selectionStart);
  36931. selectionStart = selectionEnd;
  36932. selectionEnd = temp;
  36933. dragType = draggingSelectionEnd;
  36934. }
  36935. }
  36936. else
  36937. {
  36938. selectionEnd = caretPos;
  36939. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36940. {
  36941. const CodeDocument::Position temp (selectionStart);
  36942. selectionStart = selectionEnd;
  36943. selectionEnd = temp;
  36944. dragType = draggingSelectionStart;
  36945. }
  36946. }
  36947. triggerAsyncUpdate();
  36948. }
  36949. else
  36950. {
  36951. deselectAll();
  36952. }
  36953. caret->updatePosition();
  36954. scrollToKeepCaretOnScreen();
  36955. updateScrollBars();
  36956. }
  36957. void CodeEditorComponent::deselectAll()
  36958. {
  36959. if (selectionStart != selectionEnd)
  36960. triggerAsyncUpdate();
  36961. selectionStart = caretPos;
  36962. selectionEnd = caretPos;
  36963. }
  36964. void CodeEditorComponent::updateScrollBars()
  36965. {
  36966. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36967. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  36968. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36969. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  36970. }
  36971. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36972. {
  36973. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36974. newFirstLineOnScreen);
  36975. if (newFirstLineOnScreen != firstLineOnScreen)
  36976. {
  36977. firstLineOnScreen = newFirstLineOnScreen;
  36978. caret->updatePosition();
  36979. updateCachedIterators (firstLineOnScreen);
  36980. triggerAsyncUpdate();
  36981. }
  36982. }
  36983. void CodeEditorComponent::scrollToColumnInternal (double column)
  36984. {
  36985. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36986. if (xOffset != newOffset)
  36987. {
  36988. xOffset = newOffset;
  36989. caret->updatePosition();
  36990. repaint();
  36991. }
  36992. }
  36993. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36994. {
  36995. scrollToLineInternal (newFirstLineOnScreen);
  36996. updateScrollBars();
  36997. }
  36998. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36999. {
  37000. scrollToColumnInternal (newFirstColumnOnScreen);
  37001. updateScrollBars();
  37002. }
  37003. void CodeEditorComponent::scrollBy (int deltaLines)
  37004. {
  37005. scrollToLine (firstLineOnScreen + deltaLines);
  37006. }
  37007. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37008. {
  37009. if (caretPos.getLineNumber() < firstLineOnScreen)
  37010. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37011. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37012. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37013. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37014. if (column >= xOffset + columnsOnScreen - 1)
  37015. scrollToColumn (column + 1 - columnsOnScreen);
  37016. else if (column < xOffset)
  37017. scrollToColumn (column);
  37018. }
  37019. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37020. {
  37021. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37022. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37023. roundToInt (charWidth),
  37024. lineHeight);
  37025. }
  37026. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37027. {
  37028. const int line = y / lineHeight + firstLineOnScreen;
  37029. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37030. const int index = columnToIndex (line, column);
  37031. return CodeDocument::Position (&document, line, index);
  37032. }
  37033. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37034. {
  37035. document.deleteSection (selectionStart, selectionEnd);
  37036. if (newText.isNotEmpty())
  37037. document.insertText (caretPos, newText);
  37038. scrollToKeepCaretOnScreen();
  37039. }
  37040. void CodeEditorComponent::insertTabAtCaret()
  37041. {
  37042. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37043. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37044. {
  37045. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37046. }
  37047. if (useSpacesForTabs)
  37048. {
  37049. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37050. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37051. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37052. }
  37053. else
  37054. {
  37055. insertTextAtCaret ("\t");
  37056. }
  37057. }
  37058. void CodeEditorComponent::cut()
  37059. {
  37060. insertTextAtCaret (String::empty);
  37061. }
  37062. void CodeEditorComponent::copy()
  37063. {
  37064. newTransaction();
  37065. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37066. if (selection.isNotEmpty())
  37067. SystemClipboard::copyTextToClipboard (selection);
  37068. }
  37069. void CodeEditorComponent::copyThenCut()
  37070. {
  37071. copy();
  37072. cut();
  37073. newTransaction();
  37074. }
  37075. void CodeEditorComponent::paste()
  37076. {
  37077. newTransaction();
  37078. const String clip (SystemClipboard::getTextFromClipboard());
  37079. if (clip.isNotEmpty())
  37080. insertTextAtCaret (clip);
  37081. newTransaction();
  37082. }
  37083. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37084. {
  37085. newTransaction();
  37086. if (moveInWholeWordSteps)
  37087. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37088. else
  37089. moveCaretTo (caretPos.movedBy (-1), selecting);
  37090. }
  37091. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37092. {
  37093. newTransaction();
  37094. if (moveInWholeWordSteps)
  37095. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37096. else
  37097. moveCaretTo (caretPos.movedBy (1), selecting);
  37098. }
  37099. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37100. {
  37101. CodeDocument::Position pos (caretPos);
  37102. const int newLineNum = pos.getLineNumber() + delta;
  37103. if (columnToTryToMaintain < 0)
  37104. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37105. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37106. const int colToMaintain = columnToTryToMaintain;
  37107. moveCaretTo (pos, selecting);
  37108. columnToTryToMaintain = colToMaintain;
  37109. }
  37110. void CodeEditorComponent::cursorDown (const bool selecting)
  37111. {
  37112. newTransaction();
  37113. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37114. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37115. else
  37116. moveLineDelta (1, selecting);
  37117. }
  37118. void CodeEditorComponent::cursorUp (const bool selecting)
  37119. {
  37120. newTransaction();
  37121. if (caretPos.getLineNumber() == 0)
  37122. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37123. else
  37124. moveLineDelta (-1, selecting);
  37125. }
  37126. void CodeEditorComponent::pageDown (const bool selecting)
  37127. {
  37128. newTransaction();
  37129. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37130. moveLineDelta (linesOnScreen, selecting);
  37131. }
  37132. void CodeEditorComponent::pageUp (const bool selecting)
  37133. {
  37134. newTransaction();
  37135. scrollBy (-linesOnScreen);
  37136. moveLineDelta (-linesOnScreen, selecting);
  37137. }
  37138. void CodeEditorComponent::scrollUp()
  37139. {
  37140. newTransaction();
  37141. scrollBy (1);
  37142. if (caretPos.getLineNumber() < firstLineOnScreen)
  37143. moveLineDelta (1, false);
  37144. }
  37145. void CodeEditorComponent::scrollDown()
  37146. {
  37147. newTransaction();
  37148. scrollBy (-1);
  37149. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37150. moveLineDelta (-1, false);
  37151. }
  37152. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37153. {
  37154. newTransaction();
  37155. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37156. }
  37157. namespace CodeEditorHelpers
  37158. {
  37159. int findFirstNonWhitespaceChar (const String& line) throw()
  37160. {
  37161. const int len = line.length();
  37162. for (int i = 0; i < len; ++i)
  37163. if (! CharacterFunctions::isWhitespace (line [i]))
  37164. return i;
  37165. return 0;
  37166. }
  37167. }
  37168. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37169. {
  37170. newTransaction();
  37171. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37172. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37173. index = 0;
  37174. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37175. }
  37176. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37177. {
  37178. newTransaction();
  37179. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37180. }
  37181. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37182. {
  37183. newTransaction();
  37184. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37185. }
  37186. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37187. {
  37188. if (moveInWholeWordSteps)
  37189. {
  37190. cut(); // in case something is already highlighted
  37191. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37192. }
  37193. else
  37194. {
  37195. if (selectionStart == selectionEnd)
  37196. selectionStart.moveBy (-1);
  37197. }
  37198. cut();
  37199. }
  37200. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37201. {
  37202. if (moveInWholeWordSteps)
  37203. {
  37204. cut(); // in case something is already highlighted
  37205. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37206. }
  37207. else
  37208. {
  37209. if (selectionStart == selectionEnd)
  37210. selectionEnd.moveBy (1);
  37211. else
  37212. newTransaction();
  37213. }
  37214. cut();
  37215. }
  37216. void CodeEditorComponent::selectAll()
  37217. {
  37218. newTransaction();
  37219. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37220. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37221. }
  37222. void CodeEditorComponent::undo()
  37223. {
  37224. document.undo();
  37225. scrollToKeepCaretOnScreen();
  37226. }
  37227. void CodeEditorComponent::redo()
  37228. {
  37229. document.redo();
  37230. scrollToKeepCaretOnScreen();
  37231. }
  37232. void CodeEditorComponent::newTransaction()
  37233. {
  37234. document.newTransaction();
  37235. startTimer (600);
  37236. }
  37237. void CodeEditorComponent::timerCallback()
  37238. {
  37239. newTransaction();
  37240. }
  37241. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37242. {
  37243. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37244. }
  37245. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37246. {
  37247. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37248. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37249. }
  37250. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37251. {
  37252. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37253. CodeDocument::Position (&document, range.getEnd()));
  37254. }
  37255. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37256. {
  37257. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37258. const bool shiftDown = key.getModifiers().isShiftDown();
  37259. if (key.isKeyCode (KeyPress::leftKey))
  37260. {
  37261. cursorLeft (moveInWholeWordSteps, shiftDown);
  37262. }
  37263. else if (key.isKeyCode (KeyPress::rightKey))
  37264. {
  37265. cursorRight (moveInWholeWordSteps, shiftDown);
  37266. }
  37267. else if (key.isKeyCode (KeyPress::upKey))
  37268. {
  37269. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37270. scrollDown();
  37271. #if JUCE_MAC
  37272. else if (key.getModifiers().isCommandDown())
  37273. goToStartOfDocument (shiftDown);
  37274. #endif
  37275. else
  37276. cursorUp (shiftDown);
  37277. }
  37278. else if (key.isKeyCode (KeyPress::downKey))
  37279. {
  37280. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37281. scrollUp();
  37282. #if JUCE_MAC
  37283. else if (key.getModifiers().isCommandDown())
  37284. goToEndOfDocument (shiftDown);
  37285. #endif
  37286. else
  37287. cursorDown (shiftDown);
  37288. }
  37289. else if (key.isKeyCode (KeyPress::pageDownKey))
  37290. {
  37291. pageDown (shiftDown);
  37292. }
  37293. else if (key.isKeyCode (KeyPress::pageUpKey))
  37294. {
  37295. pageUp (shiftDown);
  37296. }
  37297. else if (key.isKeyCode (KeyPress::homeKey))
  37298. {
  37299. if (moveInWholeWordSteps)
  37300. goToStartOfDocument (shiftDown);
  37301. else
  37302. goToStartOfLine (shiftDown);
  37303. }
  37304. else if (key.isKeyCode (KeyPress::endKey))
  37305. {
  37306. if (moveInWholeWordSteps)
  37307. goToEndOfDocument (shiftDown);
  37308. else
  37309. goToEndOfLine (shiftDown);
  37310. }
  37311. else if (key.isKeyCode (KeyPress::backspaceKey))
  37312. {
  37313. backspace (moveInWholeWordSteps);
  37314. }
  37315. else if (key.isKeyCode (KeyPress::deleteKey))
  37316. {
  37317. deleteForward (moveInWholeWordSteps);
  37318. }
  37319. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37320. {
  37321. copy();
  37322. }
  37323. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37324. {
  37325. copyThenCut();
  37326. }
  37327. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37328. {
  37329. paste();
  37330. }
  37331. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37332. {
  37333. undo();
  37334. }
  37335. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37336. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37337. {
  37338. redo();
  37339. }
  37340. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37341. {
  37342. selectAll();
  37343. }
  37344. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37345. {
  37346. insertTabAtCaret();
  37347. }
  37348. else if (key == KeyPress::returnKey)
  37349. {
  37350. newTransaction();
  37351. insertTextAtCaret (document.getNewLineCharacters());
  37352. }
  37353. else if (key.isKeyCode (KeyPress::escapeKey))
  37354. {
  37355. newTransaction();
  37356. }
  37357. else if (key.getTextCharacter() >= ' ')
  37358. {
  37359. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37360. }
  37361. else
  37362. {
  37363. return false;
  37364. }
  37365. return true;
  37366. }
  37367. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37368. {
  37369. newTransaction();
  37370. dragType = notDragging;
  37371. if (! e.mods.isPopupMenu())
  37372. {
  37373. beginDragAutoRepeat (100);
  37374. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37375. }
  37376. else
  37377. {
  37378. /*PopupMenu m;
  37379. addPopupMenuItems (m, &e);
  37380. const int result = m.show();
  37381. if (result != 0)
  37382. performPopupMenuAction (result);
  37383. */
  37384. }
  37385. }
  37386. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37387. {
  37388. if (! e.mods.isPopupMenu())
  37389. moveCaretTo (getPositionAt (e.x, e.y), true);
  37390. }
  37391. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37392. {
  37393. newTransaction();
  37394. beginDragAutoRepeat (0);
  37395. dragType = notDragging;
  37396. }
  37397. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37398. {
  37399. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37400. CodeDocument::Position tokenEnd (tokenStart);
  37401. if (e.getNumberOfClicks() > 2)
  37402. {
  37403. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37404. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37405. }
  37406. else
  37407. {
  37408. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37409. tokenEnd.moveBy (1);
  37410. tokenStart = tokenEnd;
  37411. while (tokenStart.getIndexInLine() > 0
  37412. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37413. tokenStart.moveBy (-1);
  37414. }
  37415. moveCaretTo (tokenEnd, false);
  37416. moveCaretTo (tokenStart, true);
  37417. }
  37418. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37419. {
  37420. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37421. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37422. {
  37423. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37424. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37425. }
  37426. else
  37427. {
  37428. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37429. }
  37430. }
  37431. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37432. {
  37433. if (scrollBarThatHasMoved == &verticalScrollBar)
  37434. scrollToLineInternal ((int) newRangeStart);
  37435. else
  37436. scrollToColumnInternal (newRangeStart);
  37437. }
  37438. void CodeEditorComponent::focusGained (FocusChangeType)
  37439. {
  37440. caret->updatePosition();
  37441. }
  37442. void CodeEditorComponent::focusLost (FocusChangeType)
  37443. {
  37444. caret->updatePosition();
  37445. }
  37446. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37447. {
  37448. useSpacesForTabs = insertSpaces;
  37449. if (spacesPerTab != numSpaces)
  37450. {
  37451. spacesPerTab = numSpaces;
  37452. triggerAsyncUpdate();
  37453. }
  37454. }
  37455. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37456. {
  37457. const String line (document.getLine (lineNum));
  37458. jassert (index <= line.length());
  37459. int col = 0;
  37460. for (int i = 0; i < index; ++i)
  37461. {
  37462. if (line[i] != '\t')
  37463. ++col;
  37464. else
  37465. col += getTabSize() - (col % getTabSize());
  37466. }
  37467. return col;
  37468. }
  37469. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37470. {
  37471. const String line (document.getLine (lineNum));
  37472. const int lineLength = line.length();
  37473. int i, col = 0;
  37474. for (i = 0; i < lineLength; ++i)
  37475. {
  37476. if (line[i] != '\t')
  37477. ++col;
  37478. else
  37479. col += getTabSize() - (col % getTabSize());
  37480. if (col > column)
  37481. break;
  37482. }
  37483. return i;
  37484. }
  37485. void CodeEditorComponent::setFont (const Font& newFont)
  37486. {
  37487. font = newFont;
  37488. charWidth = font.getStringWidthFloat ("0");
  37489. lineHeight = roundToInt (font.getHeight());
  37490. resized();
  37491. }
  37492. void CodeEditorComponent::resetToDefaultColours()
  37493. {
  37494. coloursForTokenCategories.clear();
  37495. if (codeTokeniser != 0)
  37496. {
  37497. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37498. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37499. }
  37500. }
  37501. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37502. {
  37503. jassert (tokenType < 256);
  37504. while (coloursForTokenCategories.size() < tokenType)
  37505. coloursForTokenCategories.add (Colours::black);
  37506. coloursForTokenCategories.set (tokenType, colour);
  37507. repaint();
  37508. }
  37509. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37510. {
  37511. if (! isPositiveAndBelow (tokenType, coloursForTokenCategories.size()))
  37512. return findColour (CodeEditorComponent::defaultTextColourId);
  37513. return coloursForTokenCategories.getReference (tokenType);
  37514. }
  37515. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37516. {
  37517. int i;
  37518. for (i = cachedIterators.size(); --i >= 0;)
  37519. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37520. break;
  37521. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37522. }
  37523. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37524. {
  37525. const int maxNumCachedPositions = 5000;
  37526. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37527. if (cachedIterators.size() == 0)
  37528. cachedIterators.add (new CodeDocument::Iterator (&document));
  37529. if (codeTokeniser == 0)
  37530. return;
  37531. for (;;)
  37532. {
  37533. CodeDocument::Iterator* last = cachedIterators.getLast();
  37534. if (last->getLine() >= maxLineNum)
  37535. break;
  37536. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37537. cachedIterators.add (t);
  37538. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37539. for (;;)
  37540. {
  37541. codeTokeniser->readNextToken (*t);
  37542. if (t->getLine() >= targetLine)
  37543. break;
  37544. if (t->isEOF())
  37545. return;
  37546. }
  37547. }
  37548. }
  37549. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37550. {
  37551. if (codeTokeniser == 0)
  37552. return;
  37553. for (int i = cachedIterators.size(); --i >= 0;)
  37554. {
  37555. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37556. if (t->getPosition() <= position)
  37557. {
  37558. source = *t;
  37559. break;
  37560. }
  37561. }
  37562. while (source.getPosition() < position)
  37563. {
  37564. const CodeDocument::Iterator original (source);
  37565. codeTokeniser->readNextToken (source);
  37566. if (source.getPosition() > position || source.isEOF())
  37567. {
  37568. source = original;
  37569. break;
  37570. }
  37571. }
  37572. }
  37573. END_JUCE_NAMESPACE
  37574. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37575. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37576. BEGIN_JUCE_NAMESPACE
  37577. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37578. {
  37579. }
  37580. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37581. {
  37582. }
  37583. namespace CppTokeniser
  37584. {
  37585. bool isIdentifierStart (const juce_wchar c) throw()
  37586. {
  37587. return CharacterFunctions::isLetter (c)
  37588. || c == '_' || c == '@';
  37589. }
  37590. bool isIdentifierBody (const juce_wchar c) throw()
  37591. {
  37592. return CharacterFunctions::isLetterOrDigit (c)
  37593. || c == '_' || c == '@';
  37594. }
  37595. bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37596. {
  37597. static const juce_wchar* const keywords2Char[] =
  37598. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37599. static const juce_wchar* const keywords3Char[] =
  37600. { 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 };
  37601. static const juce_wchar* const keywords4Char[] =
  37602. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37603. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37604. static const juce_wchar* const keywords5Char[] =
  37605. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37606. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37607. static const juce_wchar* const keywords6Char[] =
  37608. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37609. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37610. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37611. static const juce_wchar* const keywordsOther[] =
  37612. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37613. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37614. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37615. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37616. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37617. const juce_wchar* const* k;
  37618. switch (tokenLength)
  37619. {
  37620. case 2: k = keywords2Char; break;
  37621. case 3: k = keywords3Char; break;
  37622. case 4: k = keywords4Char; break;
  37623. case 5: k = keywords5Char; break;
  37624. case 6: k = keywords6Char; break;
  37625. default:
  37626. if (tokenLength < 2 || tokenLength > 16)
  37627. return false;
  37628. k = keywordsOther;
  37629. break;
  37630. }
  37631. int i = 0;
  37632. while (k[i] != 0)
  37633. {
  37634. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37635. return true;
  37636. ++i;
  37637. }
  37638. return false;
  37639. }
  37640. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37641. {
  37642. int tokenLength = 0;
  37643. juce_wchar possibleIdentifier [19];
  37644. while (isIdentifierBody (source.peekNextChar()))
  37645. {
  37646. const juce_wchar c = source.nextChar();
  37647. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37648. possibleIdentifier [tokenLength] = c;
  37649. ++tokenLength;
  37650. }
  37651. if (tokenLength > 1 && tokenLength <= 16)
  37652. {
  37653. possibleIdentifier [tokenLength] = 0;
  37654. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37655. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37656. }
  37657. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37658. }
  37659. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37660. {
  37661. const juce_wchar c = source.peekNextChar();
  37662. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37663. source.skip();
  37664. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37665. return false;
  37666. return true;
  37667. }
  37668. bool isHexDigit (const juce_wchar c) throw()
  37669. {
  37670. return (c >= '0' && c <= '9')
  37671. || (c >= 'a' && c <= 'f')
  37672. || (c >= 'A' && c <= 'F');
  37673. }
  37674. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37675. {
  37676. if (source.nextChar() != '0')
  37677. return false;
  37678. juce_wchar c = source.nextChar();
  37679. if (c != 'x' && c != 'X')
  37680. return false;
  37681. int numDigits = 0;
  37682. while (isHexDigit (source.peekNextChar()))
  37683. {
  37684. ++numDigits;
  37685. source.skip();
  37686. }
  37687. if (numDigits == 0)
  37688. return false;
  37689. return skipNumberSuffix (source);
  37690. }
  37691. bool isOctalDigit (const juce_wchar c) throw()
  37692. {
  37693. return c >= '0' && c <= '7';
  37694. }
  37695. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37696. {
  37697. if (source.nextChar() != '0')
  37698. return false;
  37699. if (! isOctalDigit (source.nextChar()))
  37700. return false;
  37701. while (isOctalDigit (source.peekNextChar()))
  37702. source.skip();
  37703. return skipNumberSuffix (source);
  37704. }
  37705. bool isDecimalDigit (const juce_wchar c) throw()
  37706. {
  37707. return c >= '0' && c <= '9';
  37708. }
  37709. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37710. {
  37711. int numChars = 0;
  37712. while (isDecimalDigit (source.peekNextChar()))
  37713. {
  37714. ++numChars;
  37715. source.skip();
  37716. }
  37717. if (numChars == 0)
  37718. return false;
  37719. return skipNumberSuffix (source);
  37720. }
  37721. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37722. {
  37723. int numDigits = 0;
  37724. while (isDecimalDigit (source.peekNextChar()))
  37725. {
  37726. source.skip();
  37727. ++numDigits;
  37728. }
  37729. const bool hasPoint = (source.peekNextChar() == '.');
  37730. if (hasPoint)
  37731. {
  37732. source.skip();
  37733. while (isDecimalDigit (source.peekNextChar()))
  37734. {
  37735. source.skip();
  37736. ++numDigits;
  37737. }
  37738. }
  37739. if (numDigits == 0)
  37740. return false;
  37741. juce_wchar c = source.peekNextChar();
  37742. const bool hasExponent = (c == 'e' || c == 'E');
  37743. if (hasExponent)
  37744. {
  37745. source.skip();
  37746. c = source.peekNextChar();
  37747. if (c == '+' || c == '-')
  37748. source.skip();
  37749. int numExpDigits = 0;
  37750. while (isDecimalDigit (source.peekNextChar()))
  37751. {
  37752. source.skip();
  37753. ++numExpDigits;
  37754. }
  37755. if (numExpDigits == 0)
  37756. return false;
  37757. }
  37758. c = source.peekNextChar();
  37759. if (c == 'f' || c == 'F')
  37760. source.skip();
  37761. else if (! (hasExponent || hasPoint))
  37762. return false;
  37763. return true;
  37764. }
  37765. int parseNumber (CodeDocument::Iterator& source)
  37766. {
  37767. const CodeDocument::Iterator original (source);
  37768. if (parseFloatLiteral (source))
  37769. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37770. source = original;
  37771. if (parseHexLiteral (source))
  37772. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37773. source = original;
  37774. if (parseOctalLiteral (source))
  37775. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37776. source = original;
  37777. if (parseDecimalLiteral (source))
  37778. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37779. source = original;
  37780. source.skip();
  37781. return CPlusPlusCodeTokeniser::tokenType_error;
  37782. }
  37783. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37784. {
  37785. const juce_wchar quote = source.nextChar();
  37786. for (;;)
  37787. {
  37788. const juce_wchar c = source.nextChar();
  37789. if (c == quote || c == 0)
  37790. break;
  37791. if (c == '\\')
  37792. source.skip();
  37793. }
  37794. }
  37795. void skipComment (CodeDocument::Iterator& source) throw()
  37796. {
  37797. bool lastWasStar = false;
  37798. for (;;)
  37799. {
  37800. const juce_wchar c = source.nextChar();
  37801. if (c == 0 || (c == '/' && lastWasStar))
  37802. break;
  37803. lastWasStar = (c == '*');
  37804. }
  37805. }
  37806. }
  37807. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37808. {
  37809. int result = tokenType_error;
  37810. source.skipWhitespace();
  37811. juce_wchar firstChar = source.peekNextChar();
  37812. switch (firstChar)
  37813. {
  37814. case 0:
  37815. source.skip();
  37816. break;
  37817. case '0':
  37818. case '1':
  37819. case '2':
  37820. case '3':
  37821. case '4':
  37822. case '5':
  37823. case '6':
  37824. case '7':
  37825. case '8':
  37826. case '9':
  37827. result = CppTokeniser::parseNumber (source);
  37828. break;
  37829. case '.':
  37830. result = CppTokeniser::parseNumber (source);
  37831. if (result == tokenType_error)
  37832. result = tokenType_punctuation;
  37833. break;
  37834. case ',':
  37835. case ';':
  37836. case ':':
  37837. source.skip();
  37838. result = tokenType_punctuation;
  37839. break;
  37840. case '(':
  37841. case ')':
  37842. case '{':
  37843. case '}':
  37844. case '[':
  37845. case ']':
  37846. source.skip();
  37847. result = tokenType_bracket;
  37848. break;
  37849. case '"':
  37850. case '\'':
  37851. CppTokeniser::skipQuotedString (source);
  37852. result = tokenType_stringLiteral;
  37853. break;
  37854. case '+':
  37855. result = tokenType_operator;
  37856. source.skip();
  37857. if (source.peekNextChar() == '+')
  37858. source.skip();
  37859. else if (source.peekNextChar() == '=')
  37860. source.skip();
  37861. break;
  37862. case '-':
  37863. source.skip();
  37864. result = CppTokeniser::parseNumber (source);
  37865. if (result == tokenType_error)
  37866. {
  37867. result = tokenType_operator;
  37868. if (source.peekNextChar() == '-')
  37869. source.skip();
  37870. else if (source.peekNextChar() == '=')
  37871. source.skip();
  37872. }
  37873. break;
  37874. case '*':
  37875. case '%':
  37876. case '=':
  37877. case '!':
  37878. result = tokenType_operator;
  37879. source.skip();
  37880. if (source.peekNextChar() == '=')
  37881. source.skip();
  37882. break;
  37883. case '/':
  37884. result = tokenType_operator;
  37885. source.skip();
  37886. if (source.peekNextChar() == '=')
  37887. {
  37888. source.skip();
  37889. }
  37890. else if (source.peekNextChar() == '/')
  37891. {
  37892. result = tokenType_comment;
  37893. source.skipToEndOfLine();
  37894. }
  37895. else if (source.peekNextChar() == '*')
  37896. {
  37897. source.skip();
  37898. result = tokenType_comment;
  37899. CppTokeniser::skipComment (source);
  37900. }
  37901. break;
  37902. case '?':
  37903. case '~':
  37904. source.skip();
  37905. result = tokenType_operator;
  37906. break;
  37907. case '<':
  37908. source.skip();
  37909. result = tokenType_operator;
  37910. if (source.peekNextChar() == '=')
  37911. {
  37912. source.skip();
  37913. }
  37914. else if (source.peekNextChar() == '<')
  37915. {
  37916. source.skip();
  37917. if (source.peekNextChar() == '=')
  37918. source.skip();
  37919. }
  37920. break;
  37921. case '>':
  37922. source.skip();
  37923. result = tokenType_operator;
  37924. if (source.peekNextChar() == '=')
  37925. {
  37926. source.skip();
  37927. }
  37928. else if (source.peekNextChar() == '<')
  37929. {
  37930. source.skip();
  37931. if (source.peekNextChar() == '=')
  37932. source.skip();
  37933. }
  37934. break;
  37935. case '|':
  37936. source.skip();
  37937. result = tokenType_operator;
  37938. if (source.peekNextChar() == '=')
  37939. {
  37940. source.skip();
  37941. }
  37942. else if (source.peekNextChar() == '|')
  37943. {
  37944. source.skip();
  37945. if (source.peekNextChar() == '=')
  37946. source.skip();
  37947. }
  37948. break;
  37949. case '&':
  37950. source.skip();
  37951. result = tokenType_operator;
  37952. if (source.peekNextChar() == '=')
  37953. {
  37954. source.skip();
  37955. }
  37956. else if (source.peekNextChar() == '&')
  37957. {
  37958. source.skip();
  37959. if (source.peekNextChar() == '=')
  37960. source.skip();
  37961. }
  37962. break;
  37963. case '^':
  37964. source.skip();
  37965. result = tokenType_operator;
  37966. if (source.peekNextChar() == '=')
  37967. {
  37968. source.skip();
  37969. }
  37970. else if (source.peekNextChar() == '^')
  37971. {
  37972. source.skip();
  37973. if (source.peekNextChar() == '=')
  37974. source.skip();
  37975. }
  37976. break;
  37977. case '#':
  37978. result = tokenType_preprocessor;
  37979. source.skipToEndOfLine();
  37980. break;
  37981. default:
  37982. if (CppTokeniser::isIdentifierStart (firstChar))
  37983. result = CppTokeniser::parseIdentifier (source);
  37984. else
  37985. source.skip();
  37986. break;
  37987. }
  37988. return result;
  37989. }
  37990. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37991. {
  37992. const char* const types[] =
  37993. {
  37994. "Error",
  37995. "Comment",
  37996. "C++ keyword",
  37997. "Identifier",
  37998. "Integer literal",
  37999. "Float literal",
  38000. "String literal",
  38001. "Operator",
  38002. "Bracket",
  38003. "Punctuation",
  38004. "Preprocessor line",
  38005. 0
  38006. };
  38007. return StringArray (types);
  38008. }
  38009. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38010. {
  38011. const uint32 colours[] =
  38012. {
  38013. 0xffcc0000, // error
  38014. 0xff00aa00, // comment
  38015. 0xff0000cc, // keyword
  38016. 0xff000000, // identifier
  38017. 0xff880000, // int literal
  38018. 0xff885500, // float literal
  38019. 0xff990099, // string literal
  38020. 0xff225500, // operator
  38021. 0xff000055, // bracket
  38022. 0xff004400, // punctuation
  38023. 0xff660000 // preprocessor
  38024. };
  38025. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38026. return Colour (colours [tokenType]);
  38027. return Colours::black;
  38028. }
  38029. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38030. {
  38031. return CppTokeniser::isReservedKeyword (token, token.length());
  38032. }
  38033. END_JUCE_NAMESPACE
  38034. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38035. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38036. BEGIN_JUCE_NAMESPACE
  38037. ComboBox::ItemInfo::ItemInfo (const String& name_, int itemId_, bool isEnabled_, bool isHeading_)
  38038. : name (name_), itemId (itemId_), isEnabled (isEnabled_), isHeading (isHeading_)
  38039. {
  38040. }
  38041. bool ComboBox::ItemInfo::isSeparator() const throw()
  38042. {
  38043. return name.isEmpty();
  38044. }
  38045. bool ComboBox::ItemInfo::isRealItem() const throw()
  38046. {
  38047. return ! (isHeading || name.isEmpty());
  38048. }
  38049. ComboBox::ComboBox (const String& name)
  38050. : Component (name),
  38051. lastCurrentId (0),
  38052. isButtonDown (false),
  38053. separatorPending (false),
  38054. menuActive (false),
  38055. noChoicesMessage (TRANS("(no choices)"))
  38056. {
  38057. setRepaintsOnMouseActivity (true);
  38058. lookAndFeelChanged();
  38059. currentId.addListener (this);
  38060. }
  38061. ComboBox::~ComboBox()
  38062. {
  38063. currentId.removeListener (this);
  38064. if (menuActive)
  38065. PopupMenu::dismissAllActiveMenus();
  38066. label = 0;
  38067. }
  38068. void ComboBox::setEditableText (const bool isEditable)
  38069. {
  38070. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38071. {
  38072. label->setEditable (isEditable, isEditable, false);
  38073. setWantsKeyboardFocus (! isEditable);
  38074. resized();
  38075. }
  38076. }
  38077. bool ComboBox::isTextEditable() const throw()
  38078. {
  38079. return label->isEditable();
  38080. }
  38081. void ComboBox::setJustificationType (const Justification& justification)
  38082. {
  38083. label->setJustificationType (justification);
  38084. }
  38085. const Justification ComboBox::getJustificationType() const throw()
  38086. {
  38087. return label->getJustificationType();
  38088. }
  38089. void ComboBox::setTooltip (const String& newTooltip)
  38090. {
  38091. SettableTooltipClient::setTooltip (newTooltip);
  38092. label->setTooltip (newTooltip);
  38093. }
  38094. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38095. {
  38096. // you can't add empty strings to the list..
  38097. jassert (newItemText.isNotEmpty());
  38098. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38099. jassert (newItemId != 0);
  38100. // you shouldn't use duplicate item IDs!
  38101. jassert (getItemForId (newItemId) == 0);
  38102. if (newItemText.isNotEmpty() && newItemId != 0)
  38103. {
  38104. if (separatorPending)
  38105. {
  38106. separatorPending = false;
  38107. items.add (new ItemInfo (String::empty, 0, false, false));
  38108. }
  38109. items.add (new ItemInfo (newItemText, newItemId, true, false));
  38110. }
  38111. }
  38112. void ComboBox::addSeparator()
  38113. {
  38114. separatorPending = (items.size() > 0);
  38115. }
  38116. void ComboBox::addSectionHeading (const String& headingName)
  38117. {
  38118. // you can't add empty strings to the list..
  38119. jassert (headingName.isNotEmpty());
  38120. if (headingName.isNotEmpty())
  38121. {
  38122. if (separatorPending)
  38123. {
  38124. separatorPending = false;
  38125. items.add (new ItemInfo (String::empty, 0, false, false));
  38126. }
  38127. items.add (new ItemInfo (headingName, 0, true, true));
  38128. }
  38129. }
  38130. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38131. {
  38132. ItemInfo* const item = getItemForId (itemId);
  38133. if (item != 0)
  38134. item->isEnabled = shouldBeEnabled;
  38135. }
  38136. void ComboBox::changeItemText (const int itemId, const String& newText)
  38137. {
  38138. ItemInfo* const item = getItemForId (itemId);
  38139. jassert (item != 0);
  38140. if (item != 0)
  38141. item->name = newText;
  38142. }
  38143. void ComboBox::clear (const bool dontSendChangeMessage)
  38144. {
  38145. items.clear();
  38146. separatorPending = false;
  38147. if (! label->isEditable())
  38148. setSelectedItemIndex (-1, dontSendChangeMessage);
  38149. }
  38150. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38151. {
  38152. if (itemId != 0)
  38153. {
  38154. for (int i = items.size(); --i >= 0;)
  38155. if (items.getUnchecked(i)->itemId == itemId)
  38156. return items.getUnchecked(i);
  38157. }
  38158. return 0;
  38159. }
  38160. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38161. {
  38162. for (int n = 0, i = 0; i < items.size(); ++i)
  38163. {
  38164. ItemInfo* const item = items.getUnchecked(i);
  38165. if (item->isRealItem())
  38166. if (n++ == index)
  38167. return item;
  38168. }
  38169. return 0;
  38170. }
  38171. int ComboBox::getNumItems() const throw()
  38172. {
  38173. int n = 0;
  38174. for (int i = items.size(); --i >= 0;)
  38175. if (items.getUnchecked(i)->isRealItem())
  38176. ++n;
  38177. return n;
  38178. }
  38179. const String ComboBox::getItemText (const int index) const
  38180. {
  38181. const ItemInfo* const item = getItemForIndex (index);
  38182. return item != 0 ? item->name : String::empty;
  38183. }
  38184. int ComboBox::getItemId (const int index) const throw()
  38185. {
  38186. const ItemInfo* const item = getItemForIndex (index);
  38187. return item != 0 ? item->itemId : 0;
  38188. }
  38189. int ComboBox::indexOfItemId (const int itemId) const throw()
  38190. {
  38191. for (int n = 0, i = 0; i < items.size(); ++i)
  38192. {
  38193. const ItemInfo* const item = items.getUnchecked(i);
  38194. if (item->isRealItem())
  38195. {
  38196. if (item->itemId == itemId)
  38197. return n;
  38198. ++n;
  38199. }
  38200. }
  38201. return -1;
  38202. }
  38203. int ComboBox::getSelectedItemIndex() const
  38204. {
  38205. int index = indexOfItemId (currentId.getValue());
  38206. if (getText() != getItemText (index))
  38207. index = -1;
  38208. return index;
  38209. }
  38210. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38211. {
  38212. setSelectedId (getItemId (index), dontSendChangeMessage);
  38213. }
  38214. int ComboBox::getSelectedId() const throw()
  38215. {
  38216. const ItemInfo* const item = getItemForId (currentId.getValue());
  38217. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38218. }
  38219. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38220. {
  38221. const ItemInfo* const item = getItemForId (newItemId);
  38222. const String newItemText (item != 0 ? item->name : String::empty);
  38223. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38224. {
  38225. if (! dontSendChangeMessage)
  38226. triggerAsyncUpdate();
  38227. label->setText (newItemText, false);
  38228. lastCurrentId = newItemId;
  38229. currentId = newItemId;
  38230. repaint(); // for the benefit of the 'none selected' text
  38231. }
  38232. }
  38233. bool ComboBox::selectIfEnabled (const int index)
  38234. {
  38235. const ItemInfo* const item = getItemForIndex (index);
  38236. if (item != 0 && item->isEnabled)
  38237. {
  38238. setSelectedItemIndex (index);
  38239. return true;
  38240. }
  38241. return false;
  38242. }
  38243. void ComboBox::valueChanged (Value&)
  38244. {
  38245. if (lastCurrentId != (int) currentId.getValue())
  38246. setSelectedId (currentId.getValue(), false);
  38247. }
  38248. const String ComboBox::getText() const
  38249. {
  38250. return label->getText();
  38251. }
  38252. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38253. {
  38254. for (int i = items.size(); --i >= 0;)
  38255. {
  38256. const ItemInfo* const item = items.getUnchecked(i);
  38257. if (item->isRealItem()
  38258. && item->name == newText)
  38259. {
  38260. setSelectedId (item->itemId, dontSendChangeMessage);
  38261. return;
  38262. }
  38263. }
  38264. lastCurrentId = 0;
  38265. currentId = 0;
  38266. if (label->getText() != newText)
  38267. {
  38268. label->setText (newText, false);
  38269. if (! dontSendChangeMessage)
  38270. triggerAsyncUpdate();
  38271. }
  38272. repaint();
  38273. }
  38274. void ComboBox::showEditor()
  38275. {
  38276. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38277. label->showEditor();
  38278. }
  38279. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38280. {
  38281. if (textWhenNothingSelected != newMessage)
  38282. {
  38283. textWhenNothingSelected = newMessage;
  38284. repaint();
  38285. }
  38286. }
  38287. const String ComboBox::getTextWhenNothingSelected() const
  38288. {
  38289. return textWhenNothingSelected;
  38290. }
  38291. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38292. {
  38293. noChoicesMessage = newMessage;
  38294. }
  38295. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38296. {
  38297. return noChoicesMessage;
  38298. }
  38299. void ComboBox::paint (Graphics& g)
  38300. {
  38301. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  38302. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  38303. *this);
  38304. if (textWhenNothingSelected.isNotEmpty()
  38305. && label->getText().isEmpty()
  38306. && ! label->isBeingEdited())
  38307. {
  38308. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38309. g.setFont (label->getFont());
  38310. g.drawFittedText (textWhenNothingSelected,
  38311. label->getX() + 2, label->getY() + 1,
  38312. label->getWidth() - 4, label->getHeight() - 2,
  38313. label->getJustificationType(),
  38314. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38315. }
  38316. }
  38317. void ComboBox::resized()
  38318. {
  38319. if (getHeight() > 0 && getWidth() > 0)
  38320. getLookAndFeel().positionComboBoxText (*this, *label);
  38321. }
  38322. void ComboBox::enablementChanged()
  38323. {
  38324. repaint();
  38325. }
  38326. void ComboBox::lookAndFeelChanged()
  38327. {
  38328. repaint();
  38329. {
  38330. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38331. jassert (newLabel != 0);
  38332. if (label != 0)
  38333. {
  38334. newLabel->setEditable (label->isEditable());
  38335. newLabel->setJustificationType (label->getJustificationType());
  38336. newLabel->setTooltip (label->getTooltip());
  38337. newLabel->setText (label->getText(), false);
  38338. }
  38339. label = newLabel;
  38340. }
  38341. addAndMakeVisible (label);
  38342. label->addListener (this);
  38343. label->addMouseListener (this, false);
  38344. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38345. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38346. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38347. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38348. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38349. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38350. resized();
  38351. }
  38352. void ComboBox::colourChanged()
  38353. {
  38354. lookAndFeelChanged();
  38355. }
  38356. bool ComboBox::keyPressed (const KeyPress& key)
  38357. {
  38358. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38359. {
  38360. int index = getSelectedItemIndex() - 1;
  38361. while (index >= 0 && ! selectIfEnabled (index))
  38362. --index;
  38363. return true;
  38364. }
  38365. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38366. {
  38367. int index = getSelectedItemIndex() + 1;
  38368. while (index < getNumItems() && ! selectIfEnabled (index))
  38369. ++index;
  38370. return true;
  38371. }
  38372. else if (key.isKeyCode (KeyPress::returnKey))
  38373. {
  38374. showPopup();
  38375. return true;
  38376. }
  38377. return false;
  38378. }
  38379. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38380. {
  38381. // only forward key events that aren't used by this component
  38382. return isKeyDown
  38383. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38384. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38385. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38386. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38387. }
  38388. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38389. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38390. void ComboBox::labelTextChanged (Label*)
  38391. {
  38392. triggerAsyncUpdate();
  38393. }
  38394. class ComboBox::Callback : public ModalComponentManager::Callback
  38395. {
  38396. public:
  38397. Callback (ComboBox* const box_)
  38398. : box (box_)
  38399. {
  38400. }
  38401. void modalStateFinished (int returnValue)
  38402. {
  38403. if (box != 0)
  38404. {
  38405. box->menuActive = false;
  38406. if (returnValue != 0)
  38407. box->setSelectedId (returnValue);
  38408. }
  38409. }
  38410. private:
  38411. Component::SafePointer<ComboBox> box;
  38412. JUCE_DECLARE_NON_COPYABLE (Callback);
  38413. };
  38414. void ComboBox::showPopup()
  38415. {
  38416. if (! menuActive)
  38417. {
  38418. const int selectedId = getSelectedId();
  38419. PopupMenu menu;
  38420. menu.setLookAndFeel (&getLookAndFeel());
  38421. for (int i = 0; i < items.size(); ++i)
  38422. {
  38423. const ItemInfo* const item = items.getUnchecked(i);
  38424. if (item->isSeparator())
  38425. menu.addSeparator();
  38426. else if (item->isHeading)
  38427. menu.addSectionHeader (item->name);
  38428. else
  38429. menu.addItem (item->itemId, item->name,
  38430. item->isEnabled, item->itemId == selectedId);
  38431. }
  38432. if (items.size() == 0)
  38433. menu.addItem (1, noChoicesMessage, false);
  38434. menuActive = true;
  38435. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38436. new Callback (this));
  38437. }
  38438. }
  38439. void ComboBox::mouseDown (const MouseEvent& e)
  38440. {
  38441. beginDragAutoRepeat (300);
  38442. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  38443. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38444. showPopup();
  38445. }
  38446. void ComboBox::mouseDrag (const MouseEvent& e)
  38447. {
  38448. beginDragAutoRepeat (50);
  38449. if (isButtonDown && ! e.mouseWasClicked())
  38450. showPopup();
  38451. }
  38452. void ComboBox::mouseUp (const MouseEvent& e2)
  38453. {
  38454. if (isButtonDown)
  38455. {
  38456. isButtonDown = false;
  38457. repaint();
  38458. const MouseEvent e (e2.getEventRelativeTo (this));
  38459. if (reallyContains (e.getPosition(), true)
  38460. && (e2.eventComponent == this || ! label->isEditable()))
  38461. {
  38462. showPopup();
  38463. }
  38464. }
  38465. }
  38466. void ComboBox::addListener (ComboBoxListener* const listener)
  38467. {
  38468. listeners.add (listener);
  38469. }
  38470. void ComboBox::removeListener (ComboBoxListener* const listener)
  38471. {
  38472. listeners.remove (listener);
  38473. }
  38474. void ComboBox::handleAsyncUpdate()
  38475. {
  38476. Component::BailOutChecker checker (this);
  38477. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38478. }
  38479. END_JUCE_NAMESPACE
  38480. /*** End of inlined file: juce_ComboBox.cpp ***/
  38481. /*** Start of inlined file: juce_Label.cpp ***/
  38482. BEGIN_JUCE_NAMESPACE
  38483. Label::Label (const String& componentName,
  38484. const String& labelText)
  38485. : Component (componentName),
  38486. textValue (labelText),
  38487. lastTextValue (labelText),
  38488. font (15.0f),
  38489. justification (Justification::centredLeft),
  38490. ownerComponent (0),
  38491. horizontalBorderSize (5),
  38492. verticalBorderSize (1),
  38493. minimumHorizontalScale (0.7f),
  38494. editSingleClick (false),
  38495. editDoubleClick (false),
  38496. lossOfFocusDiscardsChanges (false)
  38497. {
  38498. setColour (TextEditor::textColourId, Colours::black);
  38499. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38500. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38501. textValue.addListener (this);
  38502. }
  38503. Label::~Label()
  38504. {
  38505. textValue.removeListener (this);
  38506. if (ownerComponent != 0)
  38507. ownerComponent->removeComponentListener (this);
  38508. editor = 0;
  38509. }
  38510. void Label::setText (const String& newText,
  38511. const bool broadcastChangeMessage)
  38512. {
  38513. hideEditor (true);
  38514. if (lastTextValue != newText)
  38515. {
  38516. lastTextValue = newText;
  38517. textValue = newText;
  38518. repaint();
  38519. textWasChanged();
  38520. if (ownerComponent != 0)
  38521. componentMovedOrResized (*ownerComponent, true, true);
  38522. if (broadcastChangeMessage)
  38523. callChangeListeners();
  38524. }
  38525. }
  38526. const String Label::getText (const bool returnActiveEditorContents) const
  38527. {
  38528. return (returnActiveEditorContents && isBeingEdited())
  38529. ? editor->getText()
  38530. : textValue.toString();
  38531. }
  38532. void Label::valueChanged (Value&)
  38533. {
  38534. if (lastTextValue != textValue.toString())
  38535. setText (textValue.toString(), true);
  38536. }
  38537. void Label::setFont (const Font& newFont)
  38538. {
  38539. if (font != newFont)
  38540. {
  38541. font = newFont;
  38542. repaint();
  38543. }
  38544. }
  38545. const Font& Label::getFont() const throw()
  38546. {
  38547. return font;
  38548. }
  38549. void Label::setEditable (const bool editOnSingleClick,
  38550. const bool editOnDoubleClick,
  38551. const bool lossOfFocusDiscardsChanges_)
  38552. {
  38553. editSingleClick = editOnSingleClick;
  38554. editDoubleClick = editOnDoubleClick;
  38555. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38556. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38557. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38558. }
  38559. void Label::setJustificationType (const Justification& newJustification)
  38560. {
  38561. if (justification != newJustification)
  38562. {
  38563. justification = newJustification;
  38564. repaint();
  38565. }
  38566. }
  38567. void Label::setBorderSize (int h, int v)
  38568. {
  38569. if (horizontalBorderSize != h || verticalBorderSize != v)
  38570. {
  38571. horizontalBorderSize = h;
  38572. verticalBorderSize = v;
  38573. repaint();
  38574. }
  38575. }
  38576. Component* Label::getAttachedComponent() const
  38577. {
  38578. return static_cast<Component*> (ownerComponent);
  38579. }
  38580. void Label::attachToComponent (Component* owner,
  38581. const bool onLeft)
  38582. {
  38583. if (ownerComponent != 0)
  38584. ownerComponent->removeComponentListener (this);
  38585. ownerComponent = owner;
  38586. leftOfOwnerComp = onLeft;
  38587. if (ownerComponent != 0)
  38588. {
  38589. setVisible (owner->isVisible());
  38590. ownerComponent->addComponentListener (this);
  38591. componentParentHierarchyChanged (*ownerComponent);
  38592. componentMovedOrResized (*ownerComponent, true, true);
  38593. }
  38594. }
  38595. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38596. {
  38597. if (leftOfOwnerComp)
  38598. {
  38599. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38600. component.getHeight());
  38601. setTopRightPosition (component.getX(), component.getY());
  38602. }
  38603. else
  38604. {
  38605. setSize (component.getWidth(),
  38606. 8 + roundToInt (getFont().getHeight()));
  38607. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38608. }
  38609. }
  38610. void Label::componentParentHierarchyChanged (Component& component)
  38611. {
  38612. if (component.getParentComponent() != 0)
  38613. component.getParentComponent()->addChildComponent (this);
  38614. }
  38615. void Label::componentVisibilityChanged (Component& component)
  38616. {
  38617. setVisible (component.isVisible());
  38618. }
  38619. void Label::textWasEdited()
  38620. {
  38621. }
  38622. void Label::textWasChanged()
  38623. {
  38624. }
  38625. void Label::showEditor()
  38626. {
  38627. if (editor == 0)
  38628. {
  38629. addAndMakeVisible (editor = createEditorComponent());
  38630. editor->setText (getText(), false);
  38631. editor->addListener (this);
  38632. editor->grabKeyboardFocus();
  38633. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38634. editor->addListener (this);
  38635. resized();
  38636. repaint();
  38637. editorShown (editor);
  38638. enterModalState (false);
  38639. editor->grabKeyboardFocus();
  38640. }
  38641. }
  38642. void Label::editorShown (TextEditor* /*editorComponent*/)
  38643. {
  38644. }
  38645. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38646. {
  38647. }
  38648. bool Label::updateFromTextEditorContents()
  38649. {
  38650. jassert (editor != 0);
  38651. const String newText (editor->getText());
  38652. if (textValue.toString() != newText)
  38653. {
  38654. lastTextValue = newText;
  38655. textValue = newText;
  38656. repaint();
  38657. textWasChanged();
  38658. if (ownerComponent != 0)
  38659. componentMovedOrResized (*ownerComponent, true, true);
  38660. return true;
  38661. }
  38662. return false;
  38663. }
  38664. void Label::hideEditor (const bool discardCurrentEditorContents)
  38665. {
  38666. if (editor != 0)
  38667. {
  38668. WeakReference<Component> deletionChecker (this);
  38669. editorAboutToBeHidden (editor);
  38670. const bool changed = (! discardCurrentEditorContents)
  38671. && updateFromTextEditorContents();
  38672. editor = 0;
  38673. repaint();
  38674. if (changed)
  38675. textWasEdited();
  38676. if (deletionChecker != 0)
  38677. exitModalState (0);
  38678. if (changed && deletionChecker != 0)
  38679. callChangeListeners();
  38680. }
  38681. }
  38682. void Label::inputAttemptWhenModal()
  38683. {
  38684. if (editor != 0)
  38685. {
  38686. if (lossOfFocusDiscardsChanges)
  38687. textEditorEscapeKeyPressed (*editor);
  38688. else
  38689. textEditorReturnKeyPressed (*editor);
  38690. }
  38691. }
  38692. bool Label::isBeingEdited() const throw()
  38693. {
  38694. return editor != 0;
  38695. }
  38696. TextEditor* Label::createEditorComponent()
  38697. {
  38698. TextEditor* const ed = new TextEditor (getName());
  38699. ed->setFont (font);
  38700. // copy these colours from our own settings..
  38701. const int cols[] = { TextEditor::backgroundColourId,
  38702. TextEditor::textColourId,
  38703. TextEditor::highlightColourId,
  38704. TextEditor::highlightedTextColourId,
  38705. TextEditor::caretColourId,
  38706. TextEditor::outlineColourId,
  38707. TextEditor::focusedOutlineColourId,
  38708. TextEditor::shadowColourId };
  38709. for (int i = 0; i < numElementsInArray (cols); ++i)
  38710. ed->setColour (cols[i], findColour (cols[i]));
  38711. return ed;
  38712. }
  38713. void Label::paint (Graphics& g)
  38714. {
  38715. getLookAndFeel().drawLabel (g, *this);
  38716. }
  38717. void Label::mouseUp (const MouseEvent& e)
  38718. {
  38719. if (editSingleClick
  38720. && e.mouseWasClicked()
  38721. && contains (e.getPosition())
  38722. && ! e.mods.isPopupMenu())
  38723. {
  38724. showEditor();
  38725. }
  38726. }
  38727. void Label::mouseDoubleClick (const MouseEvent& e)
  38728. {
  38729. if (editDoubleClick && ! e.mods.isPopupMenu())
  38730. showEditor();
  38731. }
  38732. void Label::resized()
  38733. {
  38734. if (editor != 0)
  38735. editor->setBoundsInset (BorderSize (0));
  38736. }
  38737. void Label::focusGained (FocusChangeType cause)
  38738. {
  38739. if (editSingleClick && cause == focusChangedByTabKey)
  38740. showEditor();
  38741. }
  38742. void Label::enablementChanged()
  38743. {
  38744. repaint();
  38745. }
  38746. void Label::colourChanged()
  38747. {
  38748. repaint();
  38749. }
  38750. void Label::setMinimumHorizontalScale (const float newScale)
  38751. {
  38752. if (minimumHorizontalScale != newScale)
  38753. {
  38754. minimumHorizontalScale = newScale;
  38755. repaint();
  38756. }
  38757. }
  38758. // We'll use a custom focus traverser here to make sure focus goes from the
  38759. // text editor to another component rather than back to the label itself.
  38760. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38761. {
  38762. public:
  38763. LabelKeyboardFocusTraverser() {}
  38764. Component* getNextComponent (Component* current)
  38765. {
  38766. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38767. ? current->getParentComponent() : current);
  38768. }
  38769. Component* getPreviousComponent (Component* current)
  38770. {
  38771. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38772. ? current->getParentComponent() : current);
  38773. }
  38774. };
  38775. KeyboardFocusTraverser* Label::createFocusTraverser()
  38776. {
  38777. return new LabelKeyboardFocusTraverser();
  38778. }
  38779. void Label::addListener (LabelListener* const listener)
  38780. {
  38781. listeners.add (listener);
  38782. }
  38783. void Label::removeListener (LabelListener* const listener)
  38784. {
  38785. listeners.remove (listener);
  38786. }
  38787. void Label::callChangeListeners()
  38788. {
  38789. Component::BailOutChecker checker (this);
  38790. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38791. }
  38792. void Label::textEditorTextChanged (TextEditor& ed)
  38793. {
  38794. if (editor != 0)
  38795. {
  38796. jassert (&ed == editor);
  38797. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38798. {
  38799. if (lossOfFocusDiscardsChanges)
  38800. textEditorEscapeKeyPressed (ed);
  38801. else
  38802. textEditorReturnKeyPressed (ed);
  38803. }
  38804. }
  38805. }
  38806. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38807. {
  38808. if (editor != 0)
  38809. {
  38810. jassert (&ed == editor);
  38811. (void) ed;
  38812. const bool changed = updateFromTextEditorContents();
  38813. hideEditor (true);
  38814. if (changed)
  38815. {
  38816. WeakReference<Component> deletionChecker (this);
  38817. textWasEdited();
  38818. if (deletionChecker != 0)
  38819. callChangeListeners();
  38820. }
  38821. }
  38822. }
  38823. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38824. {
  38825. if (editor != 0)
  38826. {
  38827. jassert (&ed == editor);
  38828. (void) ed;
  38829. editor->setText (textValue.toString(), false);
  38830. hideEditor (true);
  38831. }
  38832. }
  38833. void Label::textEditorFocusLost (TextEditor& ed)
  38834. {
  38835. textEditorTextChanged (ed);
  38836. }
  38837. END_JUCE_NAMESPACE
  38838. /*** End of inlined file: juce_Label.cpp ***/
  38839. /*** Start of inlined file: juce_ListBox.cpp ***/
  38840. BEGIN_JUCE_NAMESPACE
  38841. class ListBoxRowComponent : public Component,
  38842. public TooltipClient
  38843. {
  38844. public:
  38845. ListBoxRowComponent (ListBox& owner_)
  38846. : owner (owner_), row (-1),
  38847. selected (false), isDragging (false), selectRowOnMouseUp (false)
  38848. {
  38849. }
  38850. void paint (Graphics& g)
  38851. {
  38852. if (owner.getModel() != 0)
  38853. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38854. }
  38855. void update (const int row_, const bool selected_)
  38856. {
  38857. if (row != row_ || selected != selected_)
  38858. {
  38859. repaint();
  38860. row = row_;
  38861. selected = selected_;
  38862. }
  38863. if (owner.getModel() != 0)
  38864. {
  38865. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  38866. if (customComponent != 0)
  38867. {
  38868. addAndMakeVisible (customComponent);
  38869. customComponent->setBounds (getLocalBounds());
  38870. }
  38871. }
  38872. }
  38873. void mouseDown (const MouseEvent& e)
  38874. {
  38875. isDragging = false;
  38876. selectRowOnMouseUp = false;
  38877. if (isEnabled())
  38878. {
  38879. if (! selected)
  38880. {
  38881. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  38882. if (owner.getModel() != 0)
  38883. owner.getModel()->listBoxItemClicked (row, e);
  38884. }
  38885. else
  38886. {
  38887. selectRowOnMouseUp = true;
  38888. }
  38889. }
  38890. }
  38891. void mouseUp (const MouseEvent& e)
  38892. {
  38893. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38894. {
  38895. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  38896. if (owner.getModel() != 0)
  38897. owner.getModel()->listBoxItemClicked (row, e);
  38898. }
  38899. }
  38900. void mouseDoubleClick (const MouseEvent& e)
  38901. {
  38902. if (owner.getModel() != 0 && isEnabled())
  38903. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38904. }
  38905. void mouseDrag (const MouseEvent& e)
  38906. {
  38907. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38908. {
  38909. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38910. if (selectedRows.size() > 0)
  38911. {
  38912. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38913. if (dragDescription.isNotEmpty())
  38914. {
  38915. isDragging = true;
  38916. owner.startDragAndDrop (e, dragDescription);
  38917. }
  38918. }
  38919. }
  38920. }
  38921. void resized()
  38922. {
  38923. if (customComponent != 0)
  38924. customComponent->setBounds (getLocalBounds());
  38925. }
  38926. const String getTooltip()
  38927. {
  38928. if (owner.getModel() != 0)
  38929. return owner.getModel()->getTooltipForRow (row);
  38930. return String::empty;
  38931. }
  38932. ScopedPointer<Component> customComponent;
  38933. private:
  38934. ListBox& owner;
  38935. int row;
  38936. bool selected, isDragging, selectRowOnMouseUp;
  38937. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxRowComponent);
  38938. };
  38939. class ListViewport : public Viewport
  38940. {
  38941. public:
  38942. ListViewport (ListBox& owner_)
  38943. : owner (owner_)
  38944. {
  38945. setWantsKeyboardFocus (false);
  38946. Component* const content = new Component();
  38947. setViewedComponent (content);
  38948. content->addMouseListener (this, false);
  38949. content->setWantsKeyboardFocus (false);
  38950. }
  38951. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38952. {
  38953. return rows [row % jmax (1, rows.size())];
  38954. }
  38955. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  38956. {
  38957. return (row >= firstIndex && row < firstIndex + rows.size())
  38958. ? getComponentForRow (row) : 0;
  38959. }
  38960. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38961. {
  38962. const int index = getIndexOfChildComponent (rowComponent);
  38963. const int num = rows.size();
  38964. for (int i = num; --i >= 0;)
  38965. if (((firstIndex + i) % jmax (1, num)) == index)
  38966. return firstIndex + i;
  38967. return -1;
  38968. }
  38969. void visibleAreaChanged (const Rectangle<int>&)
  38970. {
  38971. updateVisibleArea (true);
  38972. if (owner.getModel() != 0)
  38973. owner.getModel()->listWasScrolled();
  38974. }
  38975. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38976. {
  38977. hasUpdated = false;
  38978. const int newX = getViewedComponent()->getX();
  38979. int newY = getViewedComponent()->getY();
  38980. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38981. const int newH = owner.totalItems * owner.getRowHeight();
  38982. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38983. newY = getMaximumVisibleHeight() - newH;
  38984. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38985. if (makeSureItUpdatesContent && ! hasUpdated)
  38986. updateContents();
  38987. }
  38988. void updateContents()
  38989. {
  38990. hasUpdated = true;
  38991. const int rowHeight = owner.getRowHeight();
  38992. if (rowHeight > 0)
  38993. {
  38994. const int y = getViewPositionY();
  38995. const int w = getViewedComponent()->getWidth();
  38996. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38997. rows.removeRange (numNeeded, rows.size());
  38998. while (numNeeded > rows.size())
  38999. {
  39000. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  39001. rows.add (newRow);
  39002. getViewedComponent()->addAndMakeVisible (newRow);
  39003. }
  39004. firstIndex = y / rowHeight;
  39005. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39006. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39007. for (int i = 0; i < numNeeded; ++i)
  39008. {
  39009. const int row = i + firstIndex;
  39010. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39011. if (rowComp != 0)
  39012. {
  39013. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39014. rowComp->update (row, owner.isRowSelected (row));
  39015. }
  39016. }
  39017. }
  39018. if (owner.headerComponent != 0)
  39019. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39020. owner.outlineThickness,
  39021. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39022. getViewedComponent()->getWidth()),
  39023. owner.headerComponent->getHeight());
  39024. }
  39025. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  39026. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  39027. {
  39028. hasUpdated = false;
  39029. if (row < firstWholeIndex && ! dontScroll)
  39030. {
  39031. setViewPosition (getViewPositionX(), row * rowHeight);
  39032. }
  39033. else if (row >= lastWholeIndex && ! dontScroll)
  39034. {
  39035. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  39036. if (row >= lastRowSelected + rowsOnScreen
  39037. && rowsOnScreen < totalItems - 1
  39038. && ! isMouseClick)
  39039. {
  39040. setViewPosition (getViewPositionX(),
  39041. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  39042. }
  39043. else
  39044. {
  39045. setViewPosition (getViewPositionX(),
  39046. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39047. }
  39048. }
  39049. if (! hasUpdated)
  39050. updateContents();
  39051. }
  39052. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  39053. {
  39054. if (row < firstWholeIndex)
  39055. {
  39056. setViewPosition (getViewPositionX(), row * rowHeight);
  39057. }
  39058. else if (row >= lastWholeIndex)
  39059. {
  39060. setViewPosition (getViewPositionX(),
  39061. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39062. }
  39063. }
  39064. void paint (Graphics& g)
  39065. {
  39066. if (isOpaque())
  39067. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39068. }
  39069. bool keyPressed (const KeyPress& key)
  39070. {
  39071. if (key.isKeyCode (KeyPress::upKey)
  39072. || key.isKeyCode (KeyPress::downKey)
  39073. || key.isKeyCode (KeyPress::pageUpKey)
  39074. || key.isKeyCode (KeyPress::pageDownKey)
  39075. || key.isKeyCode (KeyPress::homeKey)
  39076. || key.isKeyCode (KeyPress::endKey))
  39077. {
  39078. // we want to avoid these keypresses going to the viewport, and instead allow
  39079. // them to pass up to our listbox..
  39080. return false;
  39081. }
  39082. return Viewport::keyPressed (key);
  39083. }
  39084. private:
  39085. ListBox& owner;
  39086. OwnedArray<ListBoxRowComponent> rows;
  39087. int firstIndex, firstWholeIndex, lastWholeIndex;
  39088. bool hasUpdated;
  39089. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport);
  39090. };
  39091. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39092. : Component (name),
  39093. model (model_),
  39094. totalItems (0),
  39095. rowHeight (22),
  39096. minimumRowWidth (0),
  39097. outlineThickness (0),
  39098. lastRowSelected (-1),
  39099. mouseMoveSelects (false),
  39100. multipleSelection (false),
  39101. hasDoneInitialUpdate (false)
  39102. {
  39103. addAndMakeVisible (viewport = new ListViewport (*this));
  39104. setWantsKeyboardFocus (true);
  39105. colourChanged();
  39106. }
  39107. ListBox::~ListBox()
  39108. {
  39109. headerComponent = 0;
  39110. viewport = 0;
  39111. }
  39112. void ListBox::setModel (ListBoxModel* const newModel)
  39113. {
  39114. if (model != newModel)
  39115. {
  39116. model = newModel;
  39117. repaint();
  39118. updateContent();
  39119. }
  39120. }
  39121. void ListBox::setMultipleSelectionEnabled (bool b)
  39122. {
  39123. multipleSelection = b;
  39124. }
  39125. void ListBox::setMouseMoveSelectsRows (bool b)
  39126. {
  39127. mouseMoveSelects = b;
  39128. if (b)
  39129. addMouseListener (this, true);
  39130. }
  39131. void ListBox::paint (Graphics& g)
  39132. {
  39133. if (! hasDoneInitialUpdate)
  39134. updateContent();
  39135. g.fillAll (findColour (backgroundColourId));
  39136. }
  39137. void ListBox::paintOverChildren (Graphics& g)
  39138. {
  39139. if (outlineThickness > 0)
  39140. {
  39141. g.setColour (findColour (outlineColourId));
  39142. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39143. }
  39144. }
  39145. void ListBox::resized()
  39146. {
  39147. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39148. outlineThickness,
  39149. outlineThickness,
  39150. outlineThickness));
  39151. viewport->setSingleStepSizes (20, getRowHeight());
  39152. viewport->updateVisibleArea (false);
  39153. }
  39154. void ListBox::visibilityChanged()
  39155. {
  39156. viewport->updateVisibleArea (true);
  39157. }
  39158. Viewport* ListBox::getViewport() const throw()
  39159. {
  39160. return viewport;
  39161. }
  39162. void ListBox::updateContent()
  39163. {
  39164. hasDoneInitialUpdate = true;
  39165. totalItems = (model != 0) ? model->getNumRows() : 0;
  39166. bool selectionChanged = false;
  39167. if (selected [selected.size() - 1] >= totalItems)
  39168. {
  39169. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39170. lastRowSelected = getSelectedRow (0);
  39171. selectionChanged = true;
  39172. }
  39173. viewport->updateVisibleArea (isVisible());
  39174. viewport->resized();
  39175. if (selectionChanged && model != 0)
  39176. model->selectedRowsChanged (lastRowSelected);
  39177. }
  39178. void ListBox::selectRow (const int row,
  39179. bool dontScroll,
  39180. bool deselectOthersFirst)
  39181. {
  39182. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39183. }
  39184. void ListBox::selectRowInternal (const int row,
  39185. bool dontScroll,
  39186. bool deselectOthersFirst,
  39187. bool isMouseClick)
  39188. {
  39189. if (! multipleSelection)
  39190. deselectOthersFirst = true;
  39191. if ((! isRowSelected (row))
  39192. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39193. {
  39194. if (isPositiveAndBelow (row, totalItems))
  39195. {
  39196. if (deselectOthersFirst)
  39197. selected.clear();
  39198. selected.addRange (Range<int> (row, row + 1));
  39199. if (getHeight() == 0 || getWidth() == 0)
  39200. dontScroll = true;
  39201. viewport->selectRow (row, getRowHeight(), dontScroll,
  39202. lastRowSelected, totalItems, isMouseClick);
  39203. lastRowSelected = row;
  39204. model->selectedRowsChanged (row);
  39205. }
  39206. else
  39207. {
  39208. if (deselectOthersFirst)
  39209. deselectAllRows();
  39210. }
  39211. }
  39212. }
  39213. void ListBox::deselectRow (const int row)
  39214. {
  39215. if (selected.contains (row))
  39216. {
  39217. selected.removeRange (Range <int> (row, row + 1));
  39218. if (row == lastRowSelected)
  39219. lastRowSelected = getSelectedRow (0);
  39220. viewport->updateContents();
  39221. model->selectedRowsChanged (lastRowSelected);
  39222. }
  39223. }
  39224. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39225. const bool sendNotificationEventToModel)
  39226. {
  39227. selected = setOfRowsToBeSelected;
  39228. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39229. if (! isRowSelected (lastRowSelected))
  39230. lastRowSelected = getSelectedRow (0);
  39231. viewport->updateContents();
  39232. if ((model != 0) && sendNotificationEventToModel)
  39233. model->selectedRowsChanged (lastRowSelected);
  39234. }
  39235. const SparseSet<int> ListBox::getSelectedRows() const
  39236. {
  39237. return selected;
  39238. }
  39239. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39240. {
  39241. if (multipleSelection && (firstRow != lastRow))
  39242. {
  39243. const int numRows = totalItems - 1;
  39244. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39245. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39246. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39247. jmax (firstRow, lastRow) + 1));
  39248. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39249. }
  39250. selectRowInternal (lastRow, false, false, true);
  39251. }
  39252. void ListBox::flipRowSelection (const int row)
  39253. {
  39254. if (isRowSelected (row))
  39255. deselectRow (row);
  39256. else
  39257. selectRowInternal (row, false, false, true);
  39258. }
  39259. void ListBox::deselectAllRows()
  39260. {
  39261. if (! selected.isEmpty())
  39262. {
  39263. selected.clear();
  39264. lastRowSelected = -1;
  39265. viewport->updateContents();
  39266. if (model != 0)
  39267. model->selectedRowsChanged (lastRowSelected);
  39268. }
  39269. }
  39270. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39271. const ModifierKeys& mods,
  39272. const bool isMouseUpEvent)
  39273. {
  39274. if (multipleSelection && mods.isCommandDown())
  39275. {
  39276. flipRowSelection (row);
  39277. }
  39278. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39279. {
  39280. selectRangeOfRows (lastRowSelected, row);
  39281. }
  39282. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39283. {
  39284. selectRowInternal (row, false, ! (multipleSelection && (! isMouseUpEvent) && isRowSelected (row)), true);
  39285. }
  39286. }
  39287. int ListBox::getNumSelectedRows() const
  39288. {
  39289. return selected.size();
  39290. }
  39291. int ListBox::getSelectedRow (const int index) const
  39292. {
  39293. return (isPositiveAndBelow (index, selected.size()))
  39294. ? selected [index] : -1;
  39295. }
  39296. bool ListBox::isRowSelected (const int row) const
  39297. {
  39298. return selected.contains (row);
  39299. }
  39300. int ListBox::getLastRowSelected() const
  39301. {
  39302. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39303. }
  39304. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39305. {
  39306. if (isPositiveAndBelow (x, getWidth()))
  39307. {
  39308. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39309. if (isPositiveAndBelow (row, totalItems))
  39310. return row;
  39311. }
  39312. return -1;
  39313. }
  39314. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39315. {
  39316. if (isPositiveAndBelow (x, getWidth()))
  39317. {
  39318. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39319. return jlimit (0, totalItems, row);
  39320. }
  39321. return -1;
  39322. }
  39323. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39324. {
  39325. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39326. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39327. }
  39328. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39329. {
  39330. return viewport->getRowNumberOfComponent (rowComponent);
  39331. }
  39332. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39333. const bool relativeToComponentTopLeft) const throw()
  39334. {
  39335. int y = viewport->getY() + rowHeight * rowNumber;
  39336. if (relativeToComponentTopLeft)
  39337. y -= viewport->getViewPositionY();
  39338. return Rectangle<int> (viewport->getX(), y,
  39339. viewport->getViewedComponent()->getWidth(), rowHeight);
  39340. }
  39341. void ListBox::setVerticalPosition (const double proportion)
  39342. {
  39343. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39344. viewport->setViewPosition (viewport->getViewPositionX(),
  39345. jmax (0, roundToInt (proportion * offscreen)));
  39346. }
  39347. double ListBox::getVerticalPosition() const
  39348. {
  39349. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39350. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39351. : 0;
  39352. }
  39353. int ListBox::getVisibleRowWidth() const throw()
  39354. {
  39355. return viewport->getViewWidth();
  39356. }
  39357. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39358. {
  39359. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39360. }
  39361. bool ListBox::keyPressed (const KeyPress& key)
  39362. {
  39363. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39364. const bool multiple = multipleSelection
  39365. && (lastRowSelected >= 0)
  39366. && (key.getModifiers().isShiftDown()
  39367. || key.getModifiers().isCtrlDown()
  39368. || key.getModifiers().isCommandDown());
  39369. if (key.isKeyCode (KeyPress::upKey))
  39370. {
  39371. if (multiple)
  39372. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39373. else
  39374. selectRow (jmax (0, lastRowSelected - 1));
  39375. }
  39376. else if (key.isKeyCode (KeyPress::returnKey)
  39377. && isRowSelected (lastRowSelected))
  39378. {
  39379. if (model != 0)
  39380. model->returnKeyPressed (lastRowSelected);
  39381. }
  39382. else if (key.isKeyCode (KeyPress::pageUpKey))
  39383. {
  39384. if (multiple)
  39385. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39386. else
  39387. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39388. }
  39389. else if (key.isKeyCode (KeyPress::pageDownKey))
  39390. {
  39391. if (multiple)
  39392. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39393. else
  39394. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39395. }
  39396. else if (key.isKeyCode (KeyPress::homeKey))
  39397. {
  39398. if (multiple && key.getModifiers().isShiftDown())
  39399. selectRangeOfRows (lastRowSelected, 0);
  39400. else
  39401. selectRow (0);
  39402. }
  39403. else if (key.isKeyCode (KeyPress::endKey))
  39404. {
  39405. if (multiple && key.getModifiers().isShiftDown())
  39406. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39407. else
  39408. selectRow (totalItems - 1);
  39409. }
  39410. else if (key.isKeyCode (KeyPress::downKey))
  39411. {
  39412. if (multiple)
  39413. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39414. else
  39415. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39416. }
  39417. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39418. && isRowSelected (lastRowSelected))
  39419. {
  39420. if (model != 0)
  39421. model->deleteKeyPressed (lastRowSelected);
  39422. }
  39423. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39424. {
  39425. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39426. }
  39427. else
  39428. {
  39429. return false;
  39430. }
  39431. return true;
  39432. }
  39433. bool ListBox::keyStateChanged (const bool isKeyDown)
  39434. {
  39435. return isKeyDown
  39436. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39437. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39438. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39439. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39440. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39441. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39442. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39443. }
  39444. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39445. {
  39446. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39447. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39448. }
  39449. void ListBox::mouseMove (const MouseEvent& e)
  39450. {
  39451. if (mouseMoveSelects)
  39452. {
  39453. const MouseEvent e2 (e.getEventRelativeTo (this));
  39454. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39455. }
  39456. }
  39457. void ListBox::mouseExit (const MouseEvent& e)
  39458. {
  39459. mouseMove (e);
  39460. }
  39461. void ListBox::mouseUp (const MouseEvent& e)
  39462. {
  39463. if (e.mouseWasClicked() && model != 0)
  39464. model->backgroundClicked();
  39465. }
  39466. void ListBox::setRowHeight (const int newHeight)
  39467. {
  39468. rowHeight = jmax (1, newHeight);
  39469. viewport->setSingleStepSizes (20, rowHeight);
  39470. updateContent();
  39471. }
  39472. int ListBox::getNumRowsOnScreen() const throw()
  39473. {
  39474. return viewport->getMaximumVisibleHeight() / rowHeight;
  39475. }
  39476. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39477. {
  39478. minimumRowWidth = newMinimumWidth;
  39479. updateContent();
  39480. }
  39481. int ListBox::getVisibleContentWidth() const throw()
  39482. {
  39483. return viewport->getMaximumVisibleWidth();
  39484. }
  39485. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39486. {
  39487. return viewport->getVerticalScrollBar();
  39488. }
  39489. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39490. {
  39491. return viewport->getHorizontalScrollBar();
  39492. }
  39493. void ListBox::colourChanged()
  39494. {
  39495. setOpaque (findColour (backgroundColourId).isOpaque());
  39496. viewport->setOpaque (isOpaque());
  39497. repaint();
  39498. }
  39499. void ListBox::setOutlineThickness (const int outlineThickness_)
  39500. {
  39501. outlineThickness = outlineThickness_;
  39502. resized();
  39503. }
  39504. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39505. {
  39506. if (headerComponent != newHeaderComponent)
  39507. {
  39508. headerComponent = newHeaderComponent;
  39509. addAndMakeVisible (newHeaderComponent);
  39510. ListBox::resized();
  39511. }
  39512. }
  39513. void ListBox::repaintRow (const int rowNumber) throw()
  39514. {
  39515. repaint (getRowPosition (rowNumber, true));
  39516. }
  39517. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39518. {
  39519. Rectangle<int> imageArea;
  39520. const int firstRow = getRowContainingPosition (0, 0);
  39521. int i;
  39522. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39523. {
  39524. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39525. if (rowComp != 0 && isRowSelected (firstRow + i))
  39526. {
  39527. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39528. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39529. imageArea = imageArea.getUnion (rowRect);
  39530. }
  39531. }
  39532. imageArea = imageArea.getIntersection (getLocalBounds());
  39533. imageX = imageArea.getX();
  39534. imageY = imageArea.getY();
  39535. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39536. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39537. {
  39538. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39539. if (rowComp != 0 && isRowSelected (firstRow + i))
  39540. {
  39541. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39542. Graphics g (snapshot);
  39543. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39544. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39545. rowComp->paintEntireComponent (g, false);
  39546. }
  39547. }
  39548. return snapshot;
  39549. }
  39550. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39551. {
  39552. DragAndDropContainer* const dragContainer
  39553. = DragAndDropContainer::findParentDragContainerFor (this);
  39554. if (dragContainer != 0)
  39555. {
  39556. int x, y;
  39557. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39558. dragImage.multiplyAllAlphas (0.6f);
  39559. MouseEvent e2 (e.getEventRelativeTo (this));
  39560. const Point<int> p (x - e2.x, y - e2.y);
  39561. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39562. }
  39563. else
  39564. {
  39565. // to be able to do a drag-and-drop operation, the listbox needs to
  39566. // be inside a component which is also a DragAndDropContainer.
  39567. jassertfalse;
  39568. }
  39569. }
  39570. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39571. {
  39572. (void) existingComponentToUpdate;
  39573. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39574. return 0;
  39575. }
  39576. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39577. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39578. void ListBoxModel::backgroundClicked() {}
  39579. void ListBoxModel::selectedRowsChanged (int) {}
  39580. void ListBoxModel::deleteKeyPressed (int) {}
  39581. void ListBoxModel::returnKeyPressed (int) {}
  39582. void ListBoxModel::listWasScrolled() {}
  39583. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39584. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39585. END_JUCE_NAMESPACE
  39586. /*** End of inlined file: juce_ListBox.cpp ***/
  39587. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39588. BEGIN_JUCE_NAMESPACE
  39589. ProgressBar::ProgressBar (double& progress_)
  39590. : progress (progress_),
  39591. displayPercentage (true),
  39592. lastCallbackTime (0)
  39593. {
  39594. currentValue = jlimit (0.0, 1.0, progress);
  39595. }
  39596. ProgressBar::~ProgressBar()
  39597. {
  39598. }
  39599. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39600. {
  39601. displayPercentage = shouldDisplayPercentage;
  39602. repaint();
  39603. }
  39604. void ProgressBar::setTextToDisplay (const String& text)
  39605. {
  39606. displayPercentage = false;
  39607. displayedMessage = text;
  39608. }
  39609. void ProgressBar::lookAndFeelChanged()
  39610. {
  39611. setOpaque (findColour (backgroundColourId).isOpaque());
  39612. }
  39613. void ProgressBar::colourChanged()
  39614. {
  39615. lookAndFeelChanged();
  39616. }
  39617. void ProgressBar::paint (Graphics& g)
  39618. {
  39619. String text;
  39620. if (displayPercentage)
  39621. {
  39622. if (currentValue >= 0 && currentValue <= 1.0)
  39623. text << roundToInt (currentValue * 100.0) << '%';
  39624. }
  39625. else
  39626. {
  39627. text = displayedMessage;
  39628. }
  39629. getLookAndFeel().drawProgressBar (g, *this,
  39630. getWidth(), getHeight(),
  39631. currentValue, text);
  39632. }
  39633. void ProgressBar::visibilityChanged()
  39634. {
  39635. if (isVisible())
  39636. startTimer (30);
  39637. else
  39638. stopTimer();
  39639. }
  39640. void ProgressBar::timerCallback()
  39641. {
  39642. double newProgress = progress;
  39643. const uint32 now = Time::getMillisecondCounter();
  39644. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39645. lastCallbackTime = now;
  39646. if (currentValue != newProgress
  39647. || newProgress < 0 || newProgress >= 1.0
  39648. || currentMessage != displayedMessage)
  39649. {
  39650. if (currentValue < newProgress
  39651. && newProgress >= 0 && newProgress < 1.0
  39652. && currentValue >= 0 && currentValue < 1.0)
  39653. {
  39654. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39655. newProgress);
  39656. }
  39657. currentValue = newProgress;
  39658. currentMessage = displayedMessage;
  39659. repaint();
  39660. }
  39661. }
  39662. END_JUCE_NAMESPACE
  39663. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39664. /*** Start of inlined file: juce_Slider.cpp ***/
  39665. BEGIN_JUCE_NAMESPACE
  39666. class SliderPopupDisplayComponent : public BubbleComponent
  39667. {
  39668. public:
  39669. SliderPopupDisplayComponent (Slider* const owner_)
  39670. : owner (owner_),
  39671. font (15.0f, Font::bold)
  39672. {
  39673. setAlwaysOnTop (true);
  39674. }
  39675. ~SliderPopupDisplayComponent()
  39676. {
  39677. }
  39678. void paintContent (Graphics& g, int w, int h)
  39679. {
  39680. g.setFont (font);
  39681. g.setColour (Colours::black);
  39682. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39683. }
  39684. void getContentSize (int& w, int& h)
  39685. {
  39686. w = font.getStringWidth (text) + 18;
  39687. h = (int) (font.getHeight() * 1.6f);
  39688. }
  39689. void updatePosition (const String& newText)
  39690. {
  39691. if (text != newText)
  39692. {
  39693. text = newText;
  39694. repaint();
  39695. }
  39696. BubbleComponent::setPosition (owner);
  39697. }
  39698. private:
  39699. Slider* owner;
  39700. Font font;
  39701. String text;
  39702. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPopupDisplayComponent);
  39703. };
  39704. Slider::Slider (const String& name)
  39705. : Component (name),
  39706. lastCurrentValue (0),
  39707. lastValueMin (0),
  39708. lastValueMax (0),
  39709. minimum (0),
  39710. maximum (10),
  39711. interval (0),
  39712. skewFactor (1.0),
  39713. velocityModeSensitivity (1.0),
  39714. velocityModeOffset (0.0),
  39715. velocityModeThreshold (1),
  39716. rotaryStart (float_Pi * 1.2f),
  39717. rotaryEnd (float_Pi * 2.8f),
  39718. numDecimalPlaces (7),
  39719. sliderRegionStart (0),
  39720. sliderRegionSize (1),
  39721. sliderBeingDragged (-1),
  39722. pixelsForFullDragExtent (250),
  39723. style (LinearHorizontal),
  39724. textBoxPos (TextBoxLeft),
  39725. textBoxWidth (80),
  39726. textBoxHeight (20),
  39727. incDecButtonMode (incDecButtonsNotDraggable),
  39728. editableText (true),
  39729. doubleClickToValue (false),
  39730. isVelocityBased (false),
  39731. userKeyOverridesVelocity (true),
  39732. rotaryStop (true),
  39733. incDecButtonsSideBySide (false),
  39734. sendChangeOnlyOnRelease (false),
  39735. popupDisplayEnabled (false),
  39736. menuEnabled (false),
  39737. menuShown (false),
  39738. scrollWheelEnabled (true),
  39739. snapsToMousePos (true),
  39740. popupDisplay (0),
  39741. parentForPopupDisplay (0)
  39742. {
  39743. setWantsKeyboardFocus (false);
  39744. setRepaintsOnMouseActivity (true);
  39745. lookAndFeelChanged();
  39746. updateText();
  39747. currentValue.addListener (this);
  39748. valueMin.addListener (this);
  39749. valueMax.addListener (this);
  39750. }
  39751. Slider::~Slider()
  39752. {
  39753. currentValue.removeListener (this);
  39754. valueMin.removeListener (this);
  39755. valueMax.removeListener (this);
  39756. popupDisplay = 0;
  39757. }
  39758. void Slider::handleAsyncUpdate()
  39759. {
  39760. cancelPendingUpdate();
  39761. Component::BailOutChecker checker (this);
  39762. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39763. }
  39764. void Slider::sendDragStart()
  39765. {
  39766. startedDragging();
  39767. Component::BailOutChecker checker (this);
  39768. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39769. }
  39770. void Slider::sendDragEnd()
  39771. {
  39772. stoppedDragging();
  39773. sliderBeingDragged = -1;
  39774. Component::BailOutChecker checker (this);
  39775. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39776. }
  39777. void Slider::addListener (SliderListener* const listener)
  39778. {
  39779. listeners.add (listener);
  39780. }
  39781. void Slider::removeListener (SliderListener* const listener)
  39782. {
  39783. listeners.remove (listener);
  39784. }
  39785. void Slider::setSliderStyle (const SliderStyle newStyle)
  39786. {
  39787. if (style != newStyle)
  39788. {
  39789. style = newStyle;
  39790. repaint();
  39791. lookAndFeelChanged();
  39792. }
  39793. }
  39794. void Slider::setRotaryParameters (const float startAngleRadians,
  39795. const float endAngleRadians,
  39796. const bool stopAtEnd)
  39797. {
  39798. // make sure the values are sensible..
  39799. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39800. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39801. jassert (rotaryStart < rotaryEnd);
  39802. rotaryStart = startAngleRadians;
  39803. rotaryEnd = endAngleRadians;
  39804. rotaryStop = stopAtEnd;
  39805. }
  39806. void Slider::setVelocityBasedMode (const bool velBased)
  39807. {
  39808. isVelocityBased = velBased;
  39809. }
  39810. void Slider::setVelocityModeParameters (const double sensitivity,
  39811. const int threshold,
  39812. const double offset,
  39813. const bool userCanPressKeyToSwapMode)
  39814. {
  39815. jassert (threshold >= 0);
  39816. jassert (sensitivity > 0);
  39817. jassert (offset >= 0);
  39818. velocityModeSensitivity = sensitivity;
  39819. velocityModeOffset = offset;
  39820. velocityModeThreshold = threshold;
  39821. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39822. }
  39823. void Slider::setSkewFactor (const double factor)
  39824. {
  39825. skewFactor = factor;
  39826. }
  39827. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39828. {
  39829. if (maximum > minimum)
  39830. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39831. / (maximum - minimum));
  39832. }
  39833. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39834. {
  39835. jassert (distanceForFullScaleDrag > 0);
  39836. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39837. }
  39838. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39839. {
  39840. if (incDecButtonMode != mode)
  39841. {
  39842. incDecButtonMode = mode;
  39843. lookAndFeelChanged();
  39844. }
  39845. }
  39846. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39847. const bool isReadOnly,
  39848. const int textEntryBoxWidth,
  39849. const int textEntryBoxHeight)
  39850. {
  39851. if (textBoxPos != newPosition
  39852. || editableText != (! isReadOnly)
  39853. || textBoxWidth != textEntryBoxWidth
  39854. || textBoxHeight != textEntryBoxHeight)
  39855. {
  39856. textBoxPos = newPosition;
  39857. editableText = ! isReadOnly;
  39858. textBoxWidth = textEntryBoxWidth;
  39859. textBoxHeight = textEntryBoxHeight;
  39860. repaint();
  39861. lookAndFeelChanged();
  39862. }
  39863. }
  39864. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39865. {
  39866. editableText = shouldBeEditable;
  39867. if (valueBox != 0)
  39868. valueBox->setEditable (shouldBeEditable && isEnabled());
  39869. }
  39870. void Slider::showTextBox()
  39871. {
  39872. jassert (editableText); // this should probably be avoided in read-only sliders.
  39873. if (valueBox != 0)
  39874. valueBox->showEditor();
  39875. }
  39876. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39877. {
  39878. if (valueBox != 0)
  39879. {
  39880. valueBox->hideEditor (discardCurrentEditorContents);
  39881. if (discardCurrentEditorContents)
  39882. updateText();
  39883. }
  39884. }
  39885. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39886. {
  39887. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39888. }
  39889. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39890. {
  39891. snapsToMousePos = shouldSnapToMouse;
  39892. }
  39893. void Slider::setPopupDisplayEnabled (const bool enabled,
  39894. Component* const parentComponentToUse)
  39895. {
  39896. popupDisplayEnabled = enabled;
  39897. parentForPopupDisplay = parentComponentToUse;
  39898. }
  39899. void Slider::colourChanged()
  39900. {
  39901. lookAndFeelChanged();
  39902. }
  39903. void Slider::lookAndFeelChanged()
  39904. {
  39905. LookAndFeel& lf = getLookAndFeel();
  39906. if (textBoxPos != NoTextBox)
  39907. {
  39908. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39909. : getTextFromValue (currentValue.getValue()));
  39910. valueBox = 0;
  39911. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39912. valueBox->setWantsKeyboardFocus (false);
  39913. valueBox->setText (previousTextBoxContent, false);
  39914. valueBox->setEditable (editableText && isEnabled());
  39915. valueBox->addListener (this);
  39916. if (style == LinearBar)
  39917. valueBox->addMouseListener (this, false);
  39918. valueBox->setTooltip (getTooltip());
  39919. }
  39920. else
  39921. {
  39922. valueBox = 0;
  39923. }
  39924. if (style == IncDecButtons)
  39925. {
  39926. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39927. incButton->addListener (this);
  39928. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39929. decButton->addListener (this);
  39930. if (incDecButtonMode != incDecButtonsNotDraggable)
  39931. {
  39932. incButton->addMouseListener (this, false);
  39933. decButton->addMouseListener (this, false);
  39934. }
  39935. else
  39936. {
  39937. incButton->setRepeatSpeed (300, 100, 20);
  39938. incButton->addMouseListener (decButton, false);
  39939. decButton->setRepeatSpeed (300, 100, 20);
  39940. decButton->addMouseListener (incButton, false);
  39941. }
  39942. incButton->setTooltip (getTooltip());
  39943. decButton->setTooltip (getTooltip());
  39944. }
  39945. else
  39946. {
  39947. incButton = 0;
  39948. decButton = 0;
  39949. }
  39950. setComponentEffect (lf.getSliderEffect());
  39951. resized();
  39952. repaint();
  39953. }
  39954. void Slider::setRange (const double newMin,
  39955. const double newMax,
  39956. const double newInt)
  39957. {
  39958. if (minimum != newMin
  39959. || maximum != newMax
  39960. || interval != newInt)
  39961. {
  39962. minimum = newMin;
  39963. maximum = newMax;
  39964. interval = newInt;
  39965. // figure out the number of DPs needed to display all values at this
  39966. // interval setting.
  39967. numDecimalPlaces = 7;
  39968. if (newInt != 0)
  39969. {
  39970. int v = abs ((int) (newInt * 10000000));
  39971. while ((v % 10) == 0)
  39972. {
  39973. --numDecimalPlaces;
  39974. v /= 10;
  39975. }
  39976. }
  39977. // keep the current values inside the new range..
  39978. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39979. {
  39980. setValue (getValue(), false, false);
  39981. }
  39982. else
  39983. {
  39984. setMinValue (getMinValue(), false, false);
  39985. setMaxValue (getMaxValue(), false, false);
  39986. }
  39987. updateText();
  39988. }
  39989. }
  39990. void Slider::triggerChangeMessage (const bool synchronous)
  39991. {
  39992. if (synchronous)
  39993. handleAsyncUpdate();
  39994. else
  39995. triggerAsyncUpdate();
  39996. valueChanged();
  39997. }
  39998. void Slider::valueChanged (Value& value)
  39999. {
  40000. if (value.refersToSameSourceAs (currentValue))
  40001. {
  40002. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40003. setValue (currentValue.getValue(), false, false);
  40004. }
  40005. else if (value.refersToSameSourceAs (valueMin))
  40006. setMinValue (valueMin.getValue(), false, false, true);
  40007. else if (value.refersToSameSourceAs (valueMax))
  40008. setMaxValue (valueMax.getValue(), false, false, true);
  40009. }
  40010. double Slider::getValue() const
  40011. {
  40012. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40013. // methods to get the two values.
  40014. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40015. return currentValue.getValue();
  40016. }
  40017. void Slider::setValue (double newValue,
  40018. const bool sendUpdateMessage,
  40019. const bool sendMessageSynchronously)
  40020. {
  40021. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40022. // methods to set the two values.
  40023. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40024. newValue = constrainedValue (newValue);
  40025. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40026. {
  40027. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40028. newValue = jlimit ((double) valueMin.getValue(),
  40029. (double) valueMax.getValue(),
  40030. newValue);
  40031. }
  40032. if (newValue != lastCurrentValue)
  40033. {
  40034. if (valueBox != 0)
  40035. valueBox->hideEditor (true);
  40036. lastCurrentValue = newValue;
  40037. currentValue = newValue;
  40038. updateText();
  40039. repaint();
  40040. if (popupDisplay != 0)
  40041. {
  40042. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40043. ->updatePosition (getTextFromValue (newValue));
  40044. popupDisplay->repaint();
  40045. }
  40046. if (sendUpdateMessage)
  40047. triggerChangeMessage (sendMessageSynchronously);
  40048. }
  40049. }
  40050. double Slider::getMinValue() const
  40051. {
  40052. // The minimum value only applies to sliders that are in two- or three-value mode.
  40053. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40054. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40055. return valueMin.getValue();
  40056. }
  40057. double Slider::getMaxValue() const
  40058. {
  40059. // The maximum value only applies to sliders that are in two- or three-value mode.
  40060. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40061. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40062. return valueMax.getValue();
  40063. }
  40064. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40065. {
  40066. // The minimum value only applies to sliders that are in two- or three-value mode.
  40067. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40068. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40069. newValue = constrainedValue (newValue);
  40070. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40071. {
  40072. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40073. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40074. newValue = jmin ((double) valueMax.getValue(), newValue);
  40075. }
  40076. else
  40077. {
  40078. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40079. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40080. newValue = jmin (lastCurrentValue, newValue);
  40081. }
  40082. if (lastValueMin != newValue)
  40083. {
  40084. lastValueMin = newValue;
  40085. valueMin = newValue;
  40086. repaint();
  40087. if (popupDisplay != 0)
  40088. {
  40089. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40090. ->updatePosition (getTextFromValue (newValue));
  40091. popupDisplay->repaint();
  40092. }
  40093. if (sendUpdateMessage)
  40094. triggerChangeMessage (sendMessageSynchronously);
  40095. }
  40096. }
  40097. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40098. {
  40099. // The maximum value only applies to sliders that are in two- or three-value mode.
  40100. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40101. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40102. newValue = constrainedValue (newValue);
  40103. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40104. {
  40105. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40106. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40107. newValue = jmax ((double) valueMin.getValue(), newValue);
  40108. }
  40109. else
  40110. {
  40111. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40112. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40113. newValue = jmax (lastCurrentValue, newValue);
  40114. }
  40115. if (lastValueMax != newValue)
  40116. {
  40117. lastValueMax = newValue;
  40118. valueMax = newValue;
  40119. repaint();
  40120. if (popupDisplay != 0)
  40121. {
  40122. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40123. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40124. popupDisplay->repaint();
  40125. }
  40126. if (sendUpdateMessage)
  40127. triggerChangeMessage (sendMessageSynchronously);
  40128. }
  40129. }
  40130. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40131. const double valueToSetOnDoubleClick)
  40132. {
  40133. doubleClickToValue = isDoubleClickEnabled;
  40134. doubleClickReturnValue = valueToSetOnDoubleClick;
  40135. }
  40136. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40137. {
  40138. isEnabled_ = doubleClickToValue;
  40139. return doubleClickReturnValue;
  40140. }
  40141. void Slider::updateText()
  40142. {
  40143. if (valueBox != 0)
  40144. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40145. }
  40146. void Slider::setTextValueSuffix (const String& suffix)
  40147. {
  40148. if (textSuffix != suffix)
  40149. {
  40150. textSuffix = suffix;
  40151. updateText();
  40152. }
  40153. }
  40154. const String Slider::getTextValueSuffix() const
  40155. {
  40156. return textSuffix;
  40157. }
  40158. const String Slider::getTextFromValue (double v)
  40159. {
  40160. if (getNumDecimalPlacesToDisplay() > 0)
  40161. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40162. else
  40163. return String (roundToInt (v)) + getTextValueSuffix();
  40164. }
  40165. double Slider::getValueFromText (const String& text)
  40166. {
  40167. String t (text.trimStart());
  40168. if (t.endsWith (textSuffix))
  40169. t = t.substring (0, t.length() - textSuffix.length());
  40170. while (t.startsWithChar ('+'))
  40171. t = t.substring (1).trimStart();
  40172. return t.initialSectionContainingOnly ("0123456789.,-")
  40173. .getDoubleValue();
  40174. }
  40175. double Slider::proportionOfLengthToValue (double proportion)
  40176. {
  40177. if (skewFactor != 1.0 && proportion > 0.0)
  40178. proportion = exp (log (proportion) / skewFactor);
  40179. return minimum + (maximum - minimum) * proportion;
  40180. }
  40181. double Slider::valueToProportionOfLength (double value)
  40182. {
  40183. const double n = (value - minimum) / (maximum - minimum);
  40184. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40185. }
  40186. double Slider::snapValue (double attemptedValue, const bool)
  40187. {
  40188. return attemptedValue;
  40189. }
  40190. void Slider::startedDragging()
  40191. {
  40192. }
  40193. void Slider::stoppedDragging()
  40194. {
  40195. }
  40196. void Slider::valueChanged()
  40197. {
  40198. }
  40199. void Slider::enablementChanged()
  40200. {
  40201. repaint();
  40202. }
  40203. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40204. {
  40205. menuEnabled = menuEnabled_;
  40206. }
  40207. void Slider::setScrollWheelEnabled (const bool enabled)
  40208. {
  40209. scrollWheelEnabled = enabled;
  40210. }
  40211. void Slider::labelTextChanged (Label* label)
  40212. {
  40213. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40214. if (newValue != (double) currentValue.getValue())
  40215. {
  40216. sendDragStart();
  40217. setValue (newValue, true, true);
  40218. sendDragEnd();
  40219. }
  40220. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40221. }
  40222. void Slider::buttonClicked (Button* button)
  40223. {
  40224. if (style == IncDecButtons)
  40225. {
  40226. sendDragStart();
  40227. if (button == incButton)
  40228. setValue (snapValue (getValue() + interval, false), true, true);
  40229. else if (button == decButton)
  40230. setValue (snapValue (getValue() - interval, false), true, true);
  40231. sendDragEnd();
  40232. }
  40233. }
  40234. double Slider::constrainedValue (double value) const
  40235. {
  40236. if (interval > 0)
  40237. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40238. if (value <= minimum || maximum <= minimum)
  40239. value = minimum;
  40240. else if (value >= maximum)
  40241. value = maximum;
  40242. return value;
  40243. }
  40244. float Slider::getLinearSliderPos (const double value)
  40245. {
  40246. double sliderPosProportional;
  40247. if (maximum > minimum)
  40248. {
  40249. if (value < minimum)
  40250. {
  40251. sliderPosProportional = 0.0;
  40252. }
  40253. else if (value > maximum)
  40254. {
  40255. sliderPosProportional = 1.0;
  40256. }
  40257. else
  40258. {
  40259. sliderPosProportional = valueToProportionOfLength (value);
  40260. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40261. }
  40262. }
  40263. else
  40264. {
  40265. sliderPosProportional = 0.5;
  40266. }
  40267. if (isVertical() || style == IncDecButtons)
  40268. sliderPosProportional = 1.0 - sliderPosProportional;
  40269. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40270. }
  40271. bool Slider::isHorizontal() const
  40272. {
  40273. return style == LinearHorizontal
  40274. || style == LinearBar
  40275. || style == TwoValueHorizontal
  40276. || style == ThreeValueHorizontal;
  40277. }
  40278. bool Slider::isVertical() const
  40279. {
  40280. return style == LinearVertical
  40281. || style == TwoValueVertical
  40282. || style == ThreeValueVertical;
  40283. }
  40284. bool Slider::incDecDragDirectionIsHorizontal() const
  40285. {
  40286. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40287. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40288. }
  40289. float Slider::getPositionOfValue (const double value)
  40290. {
  40291. if (isHorizontal() || isVertical())
  40292. {
  40293. return getLinearSliderPos (value);
  40294. }
  40295. else
  40296. {
  40297. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40298. return 0.0f;
  40299. }
  40300. }
  40301. void Slider::paint (Graphics& g)
  40302. {
  40303. if (style != IncDecButtons)
  40304. {
  40305. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40306. {
  40307. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40308. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40309. getLookAndFeel().drawRotarySlider (g,
  40310. sliderRect.getX(),
  40311. sliderRect.getY(),
  40312. sliderRect.getWidth(),
  40313. sliderRect.getHeight(),
  40314. sliderPos,
  40315. rotaryStart, rotaryEnd,
  40316. *this);
  40317. }
  40318. else
  40319. {
  40320. getLookAndFeel().drawLinearSlider (g,
  40321. sliderRect.getX(),
  40322. sliderRect.getY(),
  40323. sliderRect.getWidth(),
  40324. sliderRect.getHeight(),
  40325. getLinearSliderPos (lastCurrentValue),
  40326. getLinearSliderPos (lastValueMin),
  40327. getLinearSliderPos (lastValueMax),
  40328. style,
  40329. *this);
  40330. }
  40331. if (style == LinearBar && valueBox == 0)
  40332. {
  40333. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40334. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40335. }
  40336. }
  40337. }
  40338. void Slider::resized()
  40339. {
  40340. int minXSpace = 0;
  40341. int minYSpace = 0;
  40342. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40343. minXSpace = 30;
  40344. else
  40345. minYSpace = 15;
  40346. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40347. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40348. if (style == LinearBar)
  40349. {
  40350. if (valueBox != 0)
  40351. valueBox->setBounds (getLocalBounds());
  40352. }
  40353. else
  40354. {
  40355. if (textBoxPos == NoTextBox)
  40356. {
  40357. sliderRect = getLocalBounds();
  40358. }
  40359. else if (textBoxPos == TextBoxLeft)
  40360. {
  40361. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40362. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40363. }
  40364. else if (textBoxPos == TextBoxRight)
  40365. {
  40366. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40367. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40368. }
  40369. else if (textBoxPos == TextBoxAbove)
  40370. {
  40371. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40372. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40373. }
  40374. else if (textBoxPos == TextBoxBelow)
  40375. {
  40376. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40377. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40378. }
  40379. }
  40380. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40381. if (style == LinearBar)
  40382. {
  40383. const int barIndent = 1;
  40384. sliderRegionStart = barIndent;
  40385. sliderRegionSize = getWidth() - barIndent * 2;
  40386. sliderRect.setBounds (sliderRegionStart, barIndent,
  40387. sliderRegionSize, getHeight() - barIndent * 2);
  40388. }
  40389. else if (isHorizontal())
  40390. {
  40391. sliderRegionStart = sliderRect.getX() + indent;
  40392. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40393. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40394. sliderRegionSize, sliderRect.getHeight());
  40395. }
  40396. else if (isVertical())
  40397. {
  40398. sliderRegionStart = sliderRect.getY() + indent;
  40399. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40400. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40401. sliderRect.getWidth(), sliderRegionSize);
  40402. }
  40403. else
  40404. {
  40405. sliderRegionStart = 0;
  40406. sliderRegionSize = 100;
  40407. }
  40408. if (style == IncDecButtons)
  40409. {
  40410. Rectangle<int> buttonRect (sliderRect);
  40411. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40412. buttonRect.expand (-2, 0);
  40413. else
  40414. buttonRect.expand (0, -2);
  40415. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40416. if (incDecButtonsSideBySide)
  40417. {
  40418. decButton->setBounds (buttonRect.getX(),
  40419. buttonRect.getY(),
  40420. buttonRect.getWidth() / 2,
  40421. buttonRect.getHeight());
  40422. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40423. incButton->setBounds (buttonRect.getCentreX(),
  40424. buttonRect.getY(),
  40425. buttonRect.getWidth() / 2,
  40426. buttonRect.getHeight());
  40427. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40428. }
  40429. else
  40430. {
  40431. incButton->setBounds (buttonRect.getX(),
  40432. buttonRect.getY(),
  40433. buttonRect.getWidth(),
  40434. buttonRect.getHeight() / 2);
  40435. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40436. decButton->setBounds (buttonRect.getX(),
  40437. buttonRect.getCentreY(),
  40438. buttonRect.getWidth(),
  40439. buttonRect.getHeight() / 2);
  40440. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40441. }
  40442. }
  40443. }
  40444. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40445. {
  40446. repaint();
  40447. }
  40448. void Slider::mouseDown (const MouseEvent& e)
  40449. {
  40450. mouseWasHidden = false;
  40451. incDecDragged = false;
  40452. mouseXWhenLastDragged = e.x;
  40453. mouseYWhenLastDragged = e.y;
  40454. mouseDragStartX = e.getMouseDownX();
  40455. mouseDragStartY = e.getMouseDownY();
  40456. if (isEnabled())
  40457. {
  40458. if (e.mods.isPopupMenu() && menuEnabled)
  40459. {
  40460. menuShown = true;
  40461. PopupMenu m;
  40462. m.setLookAndFeel (&getLookAndFeel());
  40463. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40464. m.addSeparator();
  40465. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40466. {
  40467. PopupMenu rotaryMenu;
  40468. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40469. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40470. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40471. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40472. }
  40473. const int r = m.show();
  40474. if (r == 1)
  40475. {
  40476. setVelocityBasedMode (! isVelocityBased);
  40477. }
  40478. else if (r == 2)
  40479. {
  40480. setSliderStyle (Rotary);
  40481. }
  40482. else if (r == 3)
  40483. {
  40484. setSliderStyle (RotaryHorizontalDrag);
  40485. }
  40486. else if (r == 4)
  40487. {
  40488. setSliderStyle (RotaryVerticalDrag);
  40489. }
  40490. }
  40491. else if (maximum > minimum)
  40492. {
  40493. menuShown = false;
  40494. if (valueBox != 0)
  40495. valueBox->hideEditor (true);
  40496. sliderBeingDragged = 0;
  40497. if (style == TwoValueHorizontal
  40498. || style == TwoValueVertical
  40499. || style == ThreeValueHorizontal
  40500. || style == ThreeValueVertical)
  40501. {
  40502. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40503. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40504. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40505. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40506. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40507. {
  40508. if (maxPosDistance <= minPosDistance)
  40509. sliderBeingDragged = 2;
  40510. else
  40511. sliderBeingDragged = 1;
  40512. }
  40513. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40514. {
  40515. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40516. sliderBeingDragged = 1;
  40517. else if (normalPosDistance >= maxPosDistance)
  40518. sliderBeingDragged = 2;
  40519. }
  40520. }
  40521. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40522. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40523. * valueToProportionOfLength (currentValue.getValue());
  40524. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40525. : ((sliderBeingDragged == 1) ? valueMin
  40526. : currentValue)).getValue();
  40527. valueOnMouseDown = valueWhenLastDragged;
  40528. if (popupDisplayEnabled)
  40529. {
  40530. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40531. popupDisplay = popup;
  40532. if (parentForPopupDisplay != 0)
  40533. {
  40534. parentForPopupDisplay->addChildComponent (popup);
  40535. }
  40536. else
  40537. {
  40538. popup->addToDesktop (0);
  40539. }
  40540. popup->setVisible (true);
  40541. }
  40542. sendDragStart();
  40543. mouseDrag (e);
  40544. }
  40545. }
  40546. }
  40547. void Slider::mouseUp (const MouseEvent&)
  40548. {
  40549. if (isEnabled()
  40550. && (! menuShown)
  40551. && (maximum > minimum)
  40552. && (style != IncDecButtons || incDecDragged))
  40553. {
  40554. restoreMouseIfHidden();
  40555. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40556. triggerChangeMessage (false);
  40557. sendDragEnd();
  40558. popupDisplay = 0;
  40559. if (style == IncDecButtons)
  40560. {
  40561. incButton->setState (Button::buttonNormal);
  40562. decButton->setState (Button::buttonNormal);
  40563. }
  40564. }
  40565. }
  40566. void Slider::restoreMouseIfHidden()
  40567. {
  40568. if (mouseWasHidden)
  40569. {
  40570. mouseWasHidden = false;
  40571. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40572. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40573. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40574. : ((sliderBeingDragged == 1) ? getMinValue()
  40575. : (double) currentValue.getValue());
  40576. Point<int> mousePos;
  40577. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40578. {
  40579. mousePos = Desktop::getLastMouseDownPosition();
  40580. if (style == RotaryHorizontalDrag)
  40581. {
  40582. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40583. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40584. }
  40585. else
  40586. {
  40587. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40588. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40589. }
  40590. }
  40591. else
  40592. {
  40593. const int pixelPos = (int) getLinearSliderPos (pos);
  40594. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40595. isVertical() ? pixelPos : (getHeight() / 2)));
  40596. }
  40597. Desktop::setMousePosition (mousePos);
  40598. }
  40599. }
  40600. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40601. {
  40602. if (isEnabled()
  40603. && style != IncDecButtons
  40604. && style != Rotary
  40605. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40606. {
  40607. restoreMouseIfHidden();
  40608. }
  40609. }
  40610. namespace SliderHelpers
  40611. {
  40612. double smallestAngleBetween (double a1, double a2) throw()
  40613. {
  40614. return jmin (std::abs (a1 - a2),
  40615. std::abs (a1 + double_Pi * 2.0 - a2),
  40616. std::abs (a2 + double_Pi * 2.0 - a1));
  40617. }
  40618. }
  40619. void Slider::mouseDrag (const MouseEvent& e)
  40620. {
  40621. if (isEnabled()
  40622. && (! menuShown)
  40623. && (maximum > minimum))
  40624. {
  40625. if (style == Rotary)
  40626. {
  40627. int dx = e.x - sliderRect.getCentreX();
  40628. int dy = e.y - sliderRect.getCentreY();
  40629. if (dx * dx + dy * dy > 25)
  40630. {
  40631. double angle = std::atan2 ((double) dx, (double) -dy);
  40632. while (angle < 0.0)
  40633. angle += double_Pi * 2.0;
  40634. if (rotaryStop && ! e.mouseWasClicked())
  40635. {
  40636. if (std::abs (angle - lastAngle) > double_Pi)
  40637. {
  40638. if (angle >= lastAngle)
  40639. angle -= double_Pi * 2.0;
  40640. else
  40641. angle += double_Pi * 2.0;
  40642. }
  40643. if (angle >= lastAngle)
  40644. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40645. else
  40646. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40647. }
  40648. else
  40649. {
  40650. while (angle < rotaryStart)
  40651. angle += double_Pi * 2.0;
  40652. if (angle > rotaryEnd)
  40653. {
  40654. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40655. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40656. angle = rotaryStart;
  40657. else
  40658. angle = rotaryEnd;
  40659. }
  40660. }
  40661. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40662. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40663. lastAngle = angle;
  40664. }
  40665. }
  40666. else
  40667. {
  40668. if (style == LinearBar && e.mouseWasClicked()
  40669. && valueBox != 0 && valueBox->isEditable())
  40670. return;
  40671. if (style == IncDecButtons && ! incDecDragged)
  40672. {
  40673. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40674. return;
  40675. incDecDragged = true;
  40676. mouseDragStartX = e.x;
  40677. mouseDragStartY = e.y;
  40678. }
  40679. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40680. : false))
  40681. || ((maximum - minimum) / sliderRegionSize < interval))
  40682. {
  40683. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40684. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40685. if (style == RotaryHorizontalDrag
  40686. || style == RotaryVerticalDrag
  40687. || style == IncDecButtons
  40688. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40689. && ! snapsToMousePos))
  40690. {
  40691. const int mouseDiff = (style == RotaryHorizontalDrag
  40692. || style == LinearHorizontal
  40693. || style == LinearBar
  40694. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40695. ? e.x - mouseDragStartX
  40696. : mouseDragStartY - e.y;
  40697. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40698. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40699. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40700. if (style == IncDecButtons)
  40701. {
  40702. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40703. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40704. }
  40705. }
  40706. else
  40707. {
  40708. if (isVertical())
  40709. scaledMousePos = 1.0 - scaledMousePos;
  40710. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40711. }
  40712. }
  40713. else
  40714. {
  40715. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40716. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40717. ? e.x - mouseXWhenLastDragged
  40718. : e.y - mouseYWhenLastDragged;
  40719. const double maxSpeed = jmax (200, sliderRegionSize);
  40720. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40721. if (speed != 0)
  40722. {
  40723. speed = 0.2 * velocityModeSensitivity
  40724. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40725. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40726. / maxSpeed))));
  40727. if (mouseDiff < 0)
  40728. speed = -speed;
  40729. if (isVertical() || style == RotaryVerticalDrag
  40730. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40731. speed = -speed;
  40732. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40733. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40734. e.source.enableUnboundedMouseMovement (true, false);
  40735. mouseWasHidden = true;
  40736. }
  40737. }
  40738. }
  40739. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40740. if (sliderBeingDragged == 0)
  40741. {
  40742. setValue (snapValue (valueWhenLastDragged, true),
  40743. ! sendChangeOnlyOnRelease, true);
  40744. }
  40745. else if (sliderBeingDragged == 1)
  40746. {
  40747. setMinValue (snapValue (valueWhenLastDragged, true),
  40748. ! sendChangeOnlyOnRelease, false, true);
  40749. if (e.mods.isShiftDown())
  40750. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40751. else
  40752. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40753. }
  40754. else
  40755. {
  40756. jassert (sliderBeingDragged == 2);
  40757. setMaxValue (snapValue (valueWhenLastDragged, true),
  40758. ! sendChangeOnlyOnRelease, false, true);
  40759. if (e.mods.isShiftDown())
  40760. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40761. else
  40762. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40763. }
  40764. mouseXWhenLastDragged = e.x;
  40765. mouseYWhenLastDragged = e.y;
  40766. }
  40767. }
  40768. void Slider::mouseDoubleClick (const MouseEvent&)
  40769. {
  40770. if (doubleClickToValue
  40771. && isEnabled()
  40772. && style != IncDecButtons
  40773. && minimum <= doubleClickReturnValue
  40774. && maximum >= doubleClickReturnValue)
  40775. {
  40776. sendDragStart();
  40777. setValue (doubleClickReturnValue, true, true);
  40778. sendDragEnd();
  40779. }
  40780. }
  40781. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40782. {
  40783. if (scrollWheelEnabled && isEnabled()
  40784. && style != TwoValueHorizontal
  40785. && style != TwoValueVertical)
  40786. {
  40787. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40788. {
  40789. if (valueBox != 0)
  40790. valueBox->hideEditor (false);
  40791. const double value = (double) currentValue.getValue();
  40792. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40793. const double currentPos = valueToProportionOfLength (value);
  40794. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40795. double delta = (newValue != value)
  40796. ? jmax (std::abs (newValue - value), interval) : 0;
  40797. if (value > newValue)
  40798. delta = -delta;
  40799. sendDragStart();
  40800. setValue (snapValue (value + delta, false), true, true);
  40801. sendDragEnd();
  40802. }
  40803. }
  40804. else
  40805. {
  40806. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40807. }
  40808. }
  40809. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40810. {
  40811. }
  40812. void SliderListener::sliderDragEnded (Slider*)
  40813. {
  40814. }
  40815. END_JUCE_NAMESPACE
  40816. /*** End of inlined file: juce_Slider.cpp ***/
  40817. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40818. BEGIN_JUCE_NAMESPACE
  40819. class DragOverlayComp : public Component
  40820. {
  40821. public:
  40822. DragOverlayComp (const Image& image_)
  40823. : image (image_)
  40824. {
  40825. image.duplicateIfShared();
  40826. image.multiplyAllAlphas (0.8f);
  40827. setAlwaysOnTop (true);
  40828. }
  40829. void paint (Graphics& g)
  40830. {
  40831. g.drawImageAt (image, 0, 0);
  40832. }
  40833. private:
  40834. Image image;
  40835. JUCE_DECLARE_NON_COPYABLE (DragOverlayComp);
  40836. };
  40837. TableHeaderComponent::TableHeaderComponent()
  40838. : columnsChanged (false),
  40839. columnsResized (false),
  40840. sortChanged (false),
  40841. menuActive (true),
  40842. stretchToFit (false),
  40843. columnIdBeingResized (0),
  40844. columnIdBeingDragged (0),
  40845. columnIdUnderMouse (0),
  40846. lastDeliberateWidth (0)
  40847. {
  40848. }
  40849. TableHeaderComponent::~TableHeaderComponent()
  40850. {
  40851. dragOverlayComp = 0;
  40852. }
  40853. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40854. {
  40855. menuActive = hasMenu;
  40856. }
  40857. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40858. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40859. {
  40860. if (onlyCountVisibleColumns)
  40861. {
  40862. int num = 0;
  40863. for (int i = columns.size(); --i >= 0;)
  40864. if (columns.getUnchecked(i)->isVisible())
  40865. ++num;
  40866. return num;
  40867. }
  40868. else
  40869. {
  40870. return columns.size();
  40871. }
  40872. }
  40873. const String TableHeaderComponent::getColumnName (const int columnId) const
  40874. {
  40875. const ColumnInfo* const ci = getInfoForId (columnId);
  40876. return ci != 0 ? ci->name : String::empty;
  40877. }
  40878. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40879. {
  40880. ColumnInfo* const ci = getInfoForId (columnId);
  40881. if (ci != 0 && ci->name != newName)
  40882. {
  40883. ci->name = newName;
  40884. sendColumnsChanged();
  40885. }
  40886. }
  40887. void TableHeaderComponent::addColumn (const String& columnName,
  40888. const int columnId,
  40889. const int width,
  40890. const int minimumWidth,
  40891. const int maximumWidth,
  40892. const int propertyFlags,
  40893. const int insertIndex)
  40894. {
  40895. // can't have a duplicate or null ID!
  40896. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40897. jassert (width > 0);
  40898. ColumnInfo* const ci = new ColumnInfo();
  40899. ci->name = columnName;
  40900. ci->id = columnId;
  40901. ci->width = width;
  40902. ci->lastDeliberateWidth = width;
  40903. ci->minimumWidth = minimumWidth;
  40904. ci->maximumWidth = maximumWidth;
  40905. if (ci->maximumWidth < 0)
  40906. ci->maximumWidth = std::numeric_limits<int>::max();
  40907. jassert (ci->maximumWidth >= ci->minimumWidth);
  40908. ci->propertyFlags = propertyFlags;
  40909. columns.insert (insertIndex, ci);
  40910. sendColumnsChanged();
  40911. }
  40912. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40913. {
  40914. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40915. if (index >= 0)
  40916. {
  40917. columns.remove (index);
  40918. sortChanged = true;
  40919. sendColumnsChanged();
  40920. }
  40921. }
  40922. void TableHeaderComponent::removeAllColumns()
  40923. {
  40924. if (columns.size() > 0)
  40925. {
  40926. columns.clear();
  40927. sendColumnsChanged();
  40928. }
  40929. }
  40930. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40931. {
  40932. const int currentIndex = getIndexOfColumnId (columnId, false);
  40933. newIndex = visibleIndexToTotalIndex (newIndex);
  40934. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40935. {
  40936. columns.move (currentIndex, newIndex);
  40937. sendColumnsChanged();
  40938. }
  40939. }
  40940. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40941. {
  40942. const ColumnInfo* const ci = getInfoForId (columnId);
  40943. return ci != 0 ? ci->width : 0;
  40944. }
  40945. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40946. {
  40947. ColumnInfo* const ci = getInfoForId (columnId);
  40948. if (ci != 0 && ci->width != newWidth)
  40949. {
  40950. const int numColumns = getNumColumns (true);
  40951. ci->lastDeliberateWidth = ci->width
  40952. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40953. if (stretchToFit)
  40954. {
  40955. const int index = getIndexOfColumnId (columnId, true) + 1;
  40956. if (isPositiveAndBelow (index, numColumns))
  40957. {
  40958. const int x = getColumnPosition (index).getX();
  40959. if (lastDeliberateWidth == 0)
  40960. lastDeliberateWidth = getTotalWidth();
  40961. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40962. }
  40963. }
  40964. repaint();
  40965. columnsResized = true;
  40966. triggerAsyncUpdate();
  40967. }
  40968. }
  40969. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40970. {
  40971. int n = 0;
  40972. for (int i = 0; i < columns.size(); ++i)
  40973. {
  40974. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40975. {
  40976. if (columns.getUnchecked(i)->id == columnId)
  40977. return n;
  40978. ++n;
  40979. }
  40980. }
  40981. return -1;
  40982. }
  40983. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40984. {
  40985. if (onlyCountVisibleColumns)
  40986. index = visibleIndexToTotalIndex (index);
  40987. const ColumnInfo* const ci = columns [index];
  40988. return (ci != 0) ? ci->id : 0;
  40989. }
  40990. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40991. {
  40992. int x = 0, width = 0, n = 0;
  40993. for (int i = 0; i < columns.size(); ++i)
  40994. {
  40995. x += width;
  40996. if (columns.getUnchecked(i)->isVisible())
  40997. {
  40998. width = columns.getUnchecked(i)->width;
  40999. if (n++ == index)
  41000. break;
  41001. }
  41002. else
  41003. {
  41004. width = 0;
  41005. }
  41006. }
  41007. return Rectangle<int> (x, 0, width, getHeight());
  41008. }
  41009. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41010. {
  41011. if (xToFind >= 0)
  41012. {
  41013. int x = 0;
  41014. for (int i = 0; i < columns.size(); ++i)
  41015. {
  41016. const ColumnInfo* const ci = columns.getUnchecked(i);
  41017. if (ci->isVisible())
  41018. {
  41019. x += ci->width;
  41020. if (xToFind < x)
  41021. return ci->id;
  41022. }
  41023. }
  41024. }
  41025. return 0;
  41026. }
  41027. int TableHeaderComponent::getTotalWidth() const
  41028. {
  41029. int w = 0;
  41030. for (int i = columns.size(); --i >= 0;)
  41031. if (columns.getUnchecked(i)->isVisible())
  41032. w += columns.getUnchecked(i)->width;
  41033. return w;
  41034. }
  41035. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41036. {
  41037. stretchToFit = shouldStretchToFit;
  41038. lastDeliberateWidth = getTotalWidth();
  41039. resized();
  41040. }
  41041. bool TableHeaderComponent::isStretchToFitActive() const
  41042. {
  41043. return stretchToFit;
  41044. }
  41045. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41046. {
  41047. if (stretchToFit && getWidth() > 0
  41048. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41049. {
  41050. lastDeliberateWidth = targetTotalWidth;
  41051. resizeColumnsToFit (0, targetTotalWidth);
  41052. }
  41053. }
  41054. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41055. {
  41056. targetTotalWidth = jmax (targetTotalWidth, 0);
  41057. StretchableObjectResizer sor;
  41058. int i;
  41059. for (i = firstColumnIndex; i < columns.size(); ++i)
  41060. {
  41061. ColumnInfo* const ci = columns.getUnchecked(i);
  41062. if (ci->isVisible())
  41063. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41064. }
  41065. sor.resizeToFit (targetTotalWidth);
  41066. int visIndex = 0;
  41067. for (i = firstColumnIndex; i < columns.size(); ++i)
  41068. {
  41069. ColumnInfo* const ci = columns.getUnchecked(i);
  41070. if (ci->isVisible())
  41071. {
  41072. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41073. (int) std::floor (sor.getItemSize (visIndex++)));
  41074. if (newWidth != ci->width)
  41075. {
  41076. ci->width = newWidth;
  41077. repaint();
  41078. columnsResized = true;
  41079. triggerAsyncUpdate();
  41080. }
  41081. }
  41082. }
  41083. }
  41084. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41085. {
  41086. ColumnInfo* const ci = getInfoForId (columnId);
  41087. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41088. {
  41089. if (shouldBeVisible)
  41090. ci->propertyFlags |= visible;
  41091. else
  41092. ci->propertyFlags &= ~visible;
  41093. sendColumnsChanged();
  41094. resized();
  41095. }
  41096. }
  41097. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41098. {
  41099. const ColumnInfo* const ci = getInfoForId (columnId);
  41100. return ci != 0 && ci->isVisible();
  41101. }
  41102. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41103. {
  41104. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41105. {
  41106. for (int i = columns.size(); --i >= 0;)
  41107. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41108. ColumnInfo* const ci = getInfoForId (columnId);
  41109. if (ci != 0)
  41110. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41111. reSortTable();
  41112. }
  41113. }
  41114. int TableHeaderComponent::getSortColumnId() const
  41115. {
  41116. for (int i = columns.size(); --i >= 0;)
  41117. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41118. return columns.getUnchecked(i)->id;
  41119. return 0;
  41120. }
  41121. bool TableHeaderComponent::isSortedForwards() const
  41122. {
  41123. for (int i = columns.size(); --i >= 0;)
  41124. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41125. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41126. return true;
  41127. }
  41128. void TableHeaderComponent::reSortTable()
  41129. {
  41130. sortChanged = true;
  41131. repaint();
  41132. triggerAsyncUpdate();
  41133. }
  41134. const String TableHeaderComponent::toString() const
  41135. {
  41136. String s;
  41137. XmlElement doc ("TABLELAYOUT");
  41138. doc.setAttribute ("sortedCol", getSortColumnId());
  41139. doc.setAttribute ("sortForwards", isSortedForwards());
  41140. for (int i = 0; i < columns.size(); ++i)
  41141. {
  41142. const ColumnInfo* const ci = columns.getUnchecked (i);
  41143. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41144. e->setAttribute ("id", ci->id);
  41145. e->setAttribute ("visible", ci->isVisible());
  41146. e->setAttribute ("width", ci->width);
  41147. }
  41148. return doc.createDocument (String::empty, true, false);
  41149. }
  41150. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41151. {
  41152. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  41153. int index = 0;
  41154. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41155. {
  41156. forEachXmlChildElement (*storedXml, col)
  41157. {
  41158. const int tabId = col->getIntAttribute ("id");
  41159. ColumnInfo* const ci = getInfoForId (tabId);
  41160. if (ci != 0)
  41161. {
  41162. columns.move (columns.indexOf (ci), index);
  41163. ci->width = col->getIntAttribute ("width");
  41164. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41165. }
  41166. ++index;
  41167. }
  41168. columnsResized = true;
  41169. sendColumnsChanged();
  41170. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41171. storedXml->getBoolAttribute ("sortForwards", true));
  41172. }
  41173. }
  41174. void TableHeaderComponent::addListener (Listener* const newListener)
  41175. {
  41176. listeners.addIfNotAlreadyThere (newListener);
  41177. }
  41178. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41179. {
  41180. listeners.removeValue (listenerToRemove);
  41181. }
  41182. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41183. {
  41184. const ColumnInfo* const ci = getInfoForId (columnId);
  41185. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41186. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41187. }
  41188. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41189. {
  41190. for (int i = 0; i < columns.size(); ++i)
  41191. {
  41192. const ColumnInfo* const ci = columns.getUnchecked(i);
  41193. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41194. menu.addItem (ci->id, ci->name,
  41195. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41196. isColumnVisible (ci->id));
  41197. }
  41198. }
  41199. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41200. {
  41201. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41202. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41203. }
  41204. void TableHeaderComponent::paint (Graphics& g)
  41205. {
  41206. LookAndFeel& lf = getLookAndFeel();
  41207. lf.drawTableHeaderBackground (g, *this);
  41208. const Rectangle<int> clip (g.getClipBounds());
  41209. int x = 0;
  41210. for (int i = 0; i < columns.size(); ++i)
  41211. {
  41212. const ColumnInfo* const ci = columns.getUnchecked(i);
  41213. if (ci->isVisible())
  41214. {
  41215. if (x + ci->width > clip.getX()
  41216. && (ci->id != columnIdBeingDragged
  41217. || dragOverlayComp == 0
  41218. || ! dragOverlayComp->isVisible()))
  41219. {
  41220. Graphics::ScopedSaveState ss (g);
  41221. g.setOrigin (x, 0);
  41222. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41223. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41224. ci->id == columnIdUnderMouse,
  41225. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41226. ci->propertyFlags);
  41227. }
  41228. x += ci->width;
  41229. if (x >= clip.getRight())
  41230. break;
  41231. }
  41232. }
  41233. }
  41234. void TableHeaderComponent::resized()
  41235. {
  41236. }
  41237. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41238. {
  41239. updateColumnUnderMouse (e.x, e.y);
  41240. }
  41241. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41242. {
  41243. updateColumnUnderMouse (e.x, e.y);
  41244. }
  41245. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41246. {
  41247. updateColumnUnderMouse (e.x, e.y);
  41248. }
  41249. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41250. {
  41251. repaint();
  41252. columnIdBeingResized = 0;
  41253. columnIdBeingDragged = 0;
  41254. if (columnIdUnderMouse != 0)
  41255. {
  41256. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41257. if (e.mods.isPopupMenu())
  41258. columnClicked (columnIdUnderMouse, e.mods);
  41259. }
  41260. if (menuActive && e.mods.isPopupMenu())
  41261. showColumnChooserMenu (columnIdUnderMouse);
  41262. }
  41263. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41264. {
  41265. if (columnIdBeingResized == 0
  41266. && columnIdBeingDragged == 0
  41267. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41268. {
  41269. dragOverlayComp = 0;
  41270. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41271. if (columnIdBeingResized != 0)
  41272. {
  41273. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41274. initialColumnWidth = ci->width;
  41275. }
  41276. else
  41277. {
  41278. beginDrag (e);
  41279. }
  41280. }
  41281. if (columnIdBeingResized != 0)
  41282. {
  41283. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41284. if (ci != 0)
  41285. {
  41286. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41287. initialColumnWidth + e.getDistanceFromDragStartX());
  41288. if (stretchToFit)
  41289. {
  41290. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41291. int minWidthOnRight = 0;
  41292. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41293. if (columns.getUnchecked (i)->isVisible())
  41294. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41295. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41296. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41297. }
  41298. setColumnWidth (columnIdBeingResized, w);
  41299. }
  41300. }
  41301. else if (columnIdBeingDragged != 0)
  41302. {
  41303. if (e.y >= -50 && e.y < getHeight() + 50)
  41304. {
  41305. if (dragOverlayComp != 0)
  41306. {
  41307. dragOverlayComp->setVisible (true);
  41308. dragOverlayComp->setBounds (jlimit (0,
  41309. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41310. e.x - draggingColumnOffset),
  41311. 0,
  41312. dragOverlayComp->getWidth(),
  41313. getHeight());
  41314. for (int i = columns.size(); --i >= 0;)
  41315. {
  41316. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41317. int newIndex = currentIndex;
  41318. if (newIndex > 0)
  41319. {
  41320. // if the previous column isn't draggable, we can't move our column
  41321. // past it, because that'd change the undraggable column's position..
  41322. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41323. if ((previous->propertyFlags & draggable) != 0)
  41324. {
  41325. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41326. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41327. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41328. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41329. {
  41330. --newIndex;
  41331. }
  41332. }
  41333. }
  41334. if (newIndex < columns.size() - 1)
  41335. {
  41336. // if the next column isn't draggable, we can't move our column
  41337. // past it, because that'd change the undraggable column's position..
  41338. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41339. if ((nextCol->propertyFlags & draggable) != 0)
  41340. {
  41341. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41342. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41343. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41344. > abs (dragOverlayComp->getRight() - rightOfNext))
  41345. {
  41346. ++newIndex;
  41347. }
  41348. }
  41349. }
  41350. if (newIndex != currentIndex)
  41351. moveColumn (columnIdBeingDragged, newIndex);
  41352. else
  41353. break;
  41354. }
  41355. }
  41356. }
  41357. else
  41358. {
  41359. endDrag (draggingColumnOriginalIndex);
  41360. }
  41361. }
  41362. }
  41363. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41364. {
  41365. if (columnIdBeingDragged == 0)
  41366. {
  41367. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41368. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41369. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41370. {
  41371. columnIdBeingDragged = 0;
  41372. }
  41373. else
  41374. {
  41375. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41376. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41377. const int temp = columnIdBeingDragged;
  41378. columnIdBeingDragged = 0;
  41379. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41380. columnIdBeingDragged = temp;
  41381. dragOverlayComp->setBounds (columnRect);
  41382. for (int i = listeners.size(); --i >= 0;)
  41383. {
  41384. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41385. i = jmin (i, listeners.size() - 1);
  41386. }
  41387. }
  41388. }
  41389. }
  41390. void TableHeaderComponent::endDrag (const int finalIndex)
  41391. {
  41392. if (columnIdBeingDragged != 0)
  41393. {
  41394. moveColumn (columnIdBeingDragged, finalIndex);
  41395. columnIdBeingDragged = 0;
  41396. repaint();
  41397. for (int i = listeners.size(); --i >= 0;)
  41398. {
  41399. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41400. i = jmin (i, listeners.size() - 1);
  41401. }
  41402. }
  41403. }
  41404. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41405. {
  41406. mouseDrag (e);
  41407. for (int i = columns.size(); --i >= 0;)
  41408. if (columns.getUnchecked (i)->isVisible())
  41409. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41410. columnIdBeingResized = 0;
  41411. repaint();
  41412. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41413. updateColumnUnderMouse (e.x, e.y);
  41414. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41415. columnClicked (columnIdUnderMouse, e.mods);
  41416. dragOverlayComp = 0;
  41417. }
  41418. const MouseCursor TableHeaderComponent::getMouseCursor()
  41419. {
  41420. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41421. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41422. return Component::getMouseCursor();
  41423. }
  41424. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41425. {
  41426. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41427. }
  41428. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41429. {
  41430. for (int i = columns.size(); --i >= 0;)
  41431. if (columns.getUnchecked(i)->id == id)
  41432. return columns.getUnchecked(i);
  41433. return 0;
  41434. }
  41435. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41436. {
  41437. int n = 0;
  41438. for (int i = 0; i < columns.size(); ++i)
  41439. {
  41440. if (columns.getUnchecked(i)->isVisible())
  41441. {
  41442. if (n == visibleIndex)
  41443. return i;
  41444. ++n;
  41445. }
  41446. }
  41447. return -1;
  41448. }
  41449. void TableHeaderComponent::sendColumnsChanged()
  41450. {
  41451. if (stretchToFit && lastDeliberateWidth > 0)
  41452. resizeAllColumnsToFit (lastDeliberateWidth);
  41453. repaint();
  41454. columnsChanged = true;
  41455. triggerAsyncUpdate();
  41456. }
  41457. void TableHeaderComponent::handleAsyncUpdate()
  41458. {
  41459. const bool changed = columnsChanged || sortChanged;
  41460. const bool sized = columnsResized || changed;
  41461. const bool sorted = sortChanged;
  41462. columnsChanged = false;
  41463. columnsResized = false;
  41464. sortChanged = false;
  41465. if (sorted)
  41466. {
  41467. for (int i = listeners.size(); --i >= 0;)
  41468. {
  41469. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41470. i = jmin (i, listeners.size() - 1);
  41471. }
  41472. }
  41473. if (changed)
  41474. {
  41475. for (int i = listeners.size(); --i >= 0;)
  41476. {
  41477. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41478. i = jmin (i, listeners.size() - 1);
  41479. }
  41480. }
  41481. if (sized)
  41482. {
  41483. for (int i = listeners.size(); --i >= 0;)
  41484. {
  41485. listeners.getUnchecked(i)->tableColumnsResized (this);
  41486. i = jmin (i, listeners.size() - 1);
  41487. }
  41488. }
  41489. }
  41490. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41491. {
  41492. if (isPositiveAndBelow (mouseX, getWidth()))
  41493. {
  41494. const int draggableDistance = 3;
  41495. int x = 0;
  41496. for (int i = 0; i < columns.size(); ++i)
  41497. {
  41498. const ColumnInfo* const ci = columns.getUnchecked(i);
  41499. if (ci->isVisible())
  41500. {
  41501. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41502. && (ci->propertyFlags & resizable) != 0)
  41503. return ci->id;
  41504. x += ci->width;
  41505. }
  41506. }
  41507. }
  41508. return 0;
  41509. }
  41510. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41511. {
  41512. const int newCol = (reallyContains (Point<int> (x, y), true) && getResizeDraggerAt (x) == 0)
  41513. ? getColumnIdAtX (x) : 0;
  41514. if (newCol != columnIdUnderMouse)
  41515. {
  41516. columnIdUnderMouse = newCol;
  41517. repaint();
  41518. }
  41519. }
  41520. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41521. {
  41522. PopupMenu m;
  41523. addMenuItems (m, columnIdClicked);
  41524. if (m.getNumItems() > 0)
  41525. {
  41526. m.setLookAndFeel (&getLookAndFeel());
  41527. const int result = m.show();
  41528. if (result != 0)
  41529. reactToMenuItem (result, columnIdClicked);
  41530. }
  41531. }
  41532. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41533. {
  41534. }
  41535. END_JUCE_NAMESPACE
  41536. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41537. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41538. BEGIN_JUCE_NAMESPACE
  41539. class TableListRowComp : public Component,
  41540. public TooltipClient
  41541. {
  41542. public:
  41543. TableListRowComp (TableListBox& owner_)
  41544. : owner (owner_), row (-1), isSelected (false)
  41545. {
  41546. }
  41547. void paint (Graphics& g)
  41548. {
  41549. TableListBoxModel* const model = owner.getModel();
  41550. if (model != 0)
  41551. {
  41552. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41553. const TableHeaderComponent& header = owner.getHeader();
  41554. const int numColumns = header.getNumColumns (true);
  41555. for (int i = 0; i < numColumns; ++i)
  41556. {
  41557. if (columnComponents[i] == 0)
  41558. {
  41559. const int columnId = header.getColumnIdOfIndex (i, true);
  41560. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41561. Graphics::ScopedSaveState ss (g);
  41562. g.reduceClipRegion (columnRect);
  41563. g.setOrigin (columnRect.getX(), 0);
  41564. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41565. }
  41566. }
  41567. }
  41568. }
  41569. void update (const int newRow, const bool isNowSelected)
  41570. {
  41571. jassert (newRow >= 0);
  41572. if (newRow != row || isNowSelected != isSelected)
  41573. {
  41574. row = newRow;
  41575. isSelected = isNowSelected;
  41576. repaint();
  41577. }
  41578. TableListBoxModel* const model = owner.getModel();
  41579. if (model != 0 && row < owner.getNumRows())
  41580. {
  41581. const Identifier columnProperty ("_tableColumnId");
  41582. const int numColumns = owner.getHeader().getNumColumns (true);
  41583. for (int i = 0; i < numColumns; ++i)
  41584. {
  41585. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41586. Component* comp = columnComponents[i];
  41587. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41588. {
  41589. columnComponents.set (i, 0);
  41590. comp = 0;
  41591. }
  41592. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41593. columnComponents.set (i, comp, false);
  41594. if (comp != 0)
  41595. {
  41596. comp->getProperties().set (columnProperty, columnId);
  41597. addAndMakeVisible (comp);
  41598. resizeCustomComp (i);
  41599. }
  41600. }
  41601. columnComponents.removeRange (numColumns, columnComponents.size());
  41602. }
  41603. else
  41604. {
  41605. columnComponents.clear();
  41606. }
  41607. }
  41608. void resized()
  41609. {
  41610. for (int i = columnComponents.size(); --i >= 0;)
  41611. resizeCustomComp (i);
  41612. }
  41613. void resizeCustomComp (const int index)
  41614. {
  41615. Component* const c = columnComponents.getUnchecked (index);
  41616. if (c != 0)
  41617. c->setBounds (owner.getHeader().getColumnPosition (index)
  41618. .withY (0).withHeight (getHeight()));
  41619. }
  41620. void mouseDown (const MouseEvent& e)
  41621. {
  41622. isDragging = false;
  41623. selectRowOnMouseUp = false;
  41624. if (isEnabled())
  41625. {
  41626. if (! isSelected)
  41627. {
  41628. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  41629. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41630. if (columnId != 0 && owner.getModel() != 0)
  41631. owner.getModel()->cellClicked (row, columnId, e);
  41632. }
  41633. else
  41634. {
  41635. selectRowOnMouseUp = true;
  41636. }
  41637. }
  41638. }
  41639. void mouseDrag (const MouseEvent& e)
  41640. {
  41641. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41642. {
  41643. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41644. if (selectedRows.size() > 0)
  41645. {
  41646. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41647. if (dragDescription.isNotEmpty())
  41648. {
  41649. isDragging = true;
  41650. owner.startDragAndDrop (e, dragDescription);
  41651. }
  41652. }
  41653. }
  41654. }
  41655. void mouseUp (const MouseEvent& e)
  41656. {
  41657. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41658. {
  41659. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  41660. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41661. if (columnId != 0 && owner.getModel() != 0)
  41662. owner.getModel()->cellClicked (row, columnId, e);
  41663. }
  41664. }
  41665. void mouseDoubleClick (const MouseEvent& e)
  41666. {
  41667. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41668. if (columnId != 0 && owner.getModel() != 0)
  41669. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41670. }
  41671. const String getTooltip()
  41672. {
  41673. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41674. if (columnId != 0 && owner.getModel() != 0)
  41675. return owner.getModel()->getCellTooltip (row, columnId);
  41676. return String::empty;
  41677. }
  41678. Component* findChildComponentForColumn (const int columnId) const
  41679. {
  41680. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41681. }
  41682. private:
  41683. TableListBox& owner;
  41684. OwnedArray<Component> columnComponents;
  41685. int row;
  41686. bool isSelected, isDragging, selectRowOnMouseUp;
  41687. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
  41688. };
  41689. class TableListBoxHeader : public TableHeaderComponent
  41690. {
  41691. public:
  41692. TableListBoxHeader (TableListBox& owner_)
  41693. : owner (owner_)
  41694. {
  41695. }
  41696. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41697. {
  41698. if (owner.isAutoSizeMenuOptionShown())
  41699. {
  41700. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41701. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41702. menu.addSeparator();
  41703. }
  41704. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41705. }
  41706. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41707. {
  41708. switch (menuReturnId)
  41709. {
  41710. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41711. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41712. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41713. }
  41714. }
  41715. private:
  41716. TableListBox& owner;
  41717. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41718. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
  41719. };
  41720. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41721. : ListBox (name, 0),
  41722. model (model_),
  41723. autoSizeOptionsShown (true)
  41724. {
  41725. ListBox::model = this;
  41726. header = new TableListBoxHeader (*this);
  41727. header->setSize (100, 28);
  41728. header->addListener (this);
  41729. setHeaderComponent (header);
  41730. }
  41731. TableListBox::~TableListBox()
  41732. {
  41733. header = 0;
  41734. }
  41735. void TableListBox::setModel (TableListBoxModel* const newModel)
  41736. {
  41737. if (model != newModel)
  41738. {
  41739. model = newModel;
  41740. updateContent();
  41741. }
  41742. }
  41743. int TableListBox::getHeaderHeight() const
  41744. {
  41745. return header->getHeight();
  41746. }
  41747. void TableListBox::setHeaderHeight (const int newHeight)
  41748. {
  41749. header->setSize (header->getWidth(), newHeight);
  41750. resized();
  41751. }
  41752. void TableListBox::autoSizeColumn (const int columnId)
  41753. {
  41754. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41755. if (width > 0)
  41756. header->setColumnWidth (columnId, width);
  41757. }
  41758. void TableListBox::autoSizeAllColumns()
  41759. {
  41760. for (int i = 0; i < header->getNumColumns (true); ++i)
  41761. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41762. }
  41763. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41764. {
  41765. autoSizeOptionsShown = shouldBeShown;
  41766. }
  41767. bool TableListBox::isAutoSizeMenuOptionShown() const
  41768. {
  41769. return autoSizeOptionsShown;
  41770. }
  41771. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41772. const bool relativeToComponentTopLeft) const
  41773. {
  41774. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41775. if (relativeToComponentTopLeft)
  41776. headerCell.translate (header->getX(), 0);
  41777. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41778. .withX (headerCell.getX())
  41779. .withWidth (headerCell.getWidth());
  41780. }
  41781. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41782. {
  41783. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41784. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41785. }
  41786. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41787. {
  41788. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41789. if (scrollbar != 0)
  41790. {
  41791. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41792. double x = scrollbar->getCurrentRangeStart();
  41793. const double w = scrollbar->getCurrentRangeSize();
  41794. if (pos.getX() < x)
  41795. x = pos.getX();
  41796. else if (pos.getRight() > x + w)
  41797. x += jmax (0.0, pos.getRight() - (x + w));
  41798. scrollbar->setCurrentRangeStart (x);
  41799. }
  41800. }
  41801. int TableListBox::getNumRows()
  41802. {
  41803. return model != 0 ? model->getNumRows() : 0;
  41804. }
  41805. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41806. {
  41807. }
  41808. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41809. {
  41810. if (existingComponentToUpdate == 0)
  41811. existingComponentToUpdate = new TableListRowComp (*this);
  41812. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41813. return existingComponentToUpdate;
  41814. }
  41815. void TableListBox::selectedRowsChanged (int row)
  41816. {
  41817. if (model != 0)
  41818. model->selectedRowsChanged (row);
  41819. }
  41820. void TableListBox::deleteKeyPressed (int row)
  41821. {
  41822. if (model != 0)
  41823. model->deleteKeyPressed (row);
  41824. }
  41825. void TableListBox::returnKeyPressed (int row)
  41826. {
  41827. if (model != 0)
  41828. model->returnKeyPressed (row);
  41829. }
  41830. void TableListBox::backgroundClicked()
  41831. {
  41832. if (model != 0)
  41833. model->backgroundClicked();
  41834. }
  41835. void TableListBox::listWasScrolled()
  41836. {
  41837. if (model != 0)
  41838. model->listWasScrolled();
  41839. }
  41840. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41841. {
  41842. setMinimumContentWidth (header->getTotalWidth());
  41843. repaint();
  41844. updateColumnComponents();
  41845. }
  41846. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41847. {
  41848. setMinimumContentWidth (header->getTotalWidth());
  41849. repaint();
  41850. updateColumnComponents();
  41851. }
  41852. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41853. {
  41854. if (model != 0)
  41855. model->sortOrderChanged (header->getSortColumnId(),
  41856. header->isSortedForwards());
  41857. }
  41858. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41859. {
  41860. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41861. repaint();
  41862. }
  41863. void TableListBox::resized()
  41864. {
  41865. ListBox::resized();
  41866. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41867. setMinimumContentWidth (header->getTotalWidth());
  41868. }
  41869. void TableListBox::updateColumnComponents() const
  41870. {
  41871. const int firstRow = getRowContainingPosition (0, 0);
  41872. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41873. {
  41874. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41875. if (rowComp != 0)
  41876. rowComp->resized();
  41877. }
  41878. }
  41879. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  41880. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  41881. void TableListBoxModel::backgroundClicked() {}
  41882. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  41883. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  41884. void TableListBoxModel::selectedRowsChanged (int) {}
  41885. void TableListBoxModel::deleteKeyPressed (int) {}
  41886. void TableListBoxModel::returnKeyPressed (int) {}
  41887. void TableListBoxModel::listWasScrolled() {}
  41888. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  41889. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  41890. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41891. {
  41892. (void) existingComponentToUpdate;
  41893. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41894. return 0;
  41895. }
  41896. END_JUCE_NAMESPACE
  41897. /*** End of inlined file: juce_TableListBox.cpp ***/
  41898. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41899. BEGIN_JUCE_NAMESPACE
  41900. // a word or space that can't be broken down any further
  41901. struct TextAtom
  41902. {
  41903. String atomText;
  41904. float width;
  41905. int numChars;
  41906. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41907. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41908. const String getText (const juce_wchar passwordCharacter) const
  41909. {
  41910. if (passwordCharacter == 0)
  41911. return atomText;
  41912. else
  41913. return String::repeatedString (String::charToString (passwordCharacter),
  41914. atomText.length());
  41915. }
  41916. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41917. {
  41918. if (passwordCharacter == 0)
  41919. return atomText.substring (0, numChars);
  41920. else if (isNewLine())
  41921. return String::empty;
  41922. else
  41923. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41924. }
  41925. };
  41926. // a run of text with a single font and colour
  41927. class TextEditor::UniformTextSection
  41928. {
  41929. public:
  41930. UniformTextSection (const String& text,
  41931. const Font& font_,
  41932. const Colour& colour_,
  41933. const juce_wchar passwordCharacter)
  41934. : font (font_),
  41935. colour (colour_)
  41936. {
  41937. initialiseAtoms (text, passwordCharacter);
  41938. }
  41939. UniformTextSection (const UniformTextSection& other)
  41940. : font (other.font),
  41941. colour (other.colour)
  41942. {
  41943. atoms.ensureStorageAllocated (other.atoms.size());
  41944. for (int i = 0; i < other.atoms.size(); ++i)
  41945. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41946. }
  41947. ~UniformTextSection()
  41948. {
  41949. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41950. }
  41951. void clear()
  41952. {
  41953. for (int i = atoms.size(); --i >= 0;)
  41954. delete getAtom(i);
  41955. atoms.clear();
  41956. }
  41957. int getNumAtoms() const
  41958. {
  41959. return atoms.size();
  41960. }
  41961. TextAtom* getAtom (const int index) const throw()
  41962. {
  41963. return atoms.getUnchecked (index);
  41964. }
  41965. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41966. {
  41967. if (other.atoms.size() > 0)
  41968. {
  41969. TextAtom* const lastAtom = atoms.getLast();
  41970. int i = 0;
  41971. if (lastAtom != 0)
  41972. {
  41973. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41974. {
  41975. TextAtom* const first = other.getAtom(0);
  41976. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41977. {
  41978. lastAtom->atomText += first->atomText;
  41979. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41980. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41981. delete first;
  41982. ++i;
  41983. }
  41984. }
  41985. }
  41986. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41987. while (i < other.atoms.size())
  41988. {
  41989. atoms.add (other.getAtom(i));
  41990. ++i;
  41991. }
  41992. }
  41993. }
  41994. UniformTextSection* split (const int indexToBreakAt,
  41995. const juce_wchar passwordCharacter)
  41996. {
  41997. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41998. font, colour,
  41999. passwordCharacter);
  42000. int index = 0;
  42001. for (int i = 0; i < atoms.size(); ++i)
  42002. {
  42003. TextAtom* const atom = getAtom(i);
  42004. const int nextIndex = index + atom->numChars;
  42005. if (index == indexToBreakAt)
  42006. {
  42007. int j;
  42008. for (j = i; j < atoms.size(); ++j)
  42009. section2->atoms.add (getAtom (j));
  42010. for (j = atoms.size(); --j >= i;)
  42011. atoms.remove (j);
  42012. break;
  42013. }
  42014. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42015. {
  42016. TextAtom* const secondAtom = new TextAtom();
  42017. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42018. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42019. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42020. section2->atoms.add (secondAtom);
  42021. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42022. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42023. atom->numChars = (uint16) (indexToBreakAt - index);
  42024. int j;
  42025. for (j = i + 1; j < atoms.size(); ++j)
  42026. section2->atoms.add (getAtom (j));
  42027. for (j = atoms.size(); --j > i;)
  42028. atoms.remove (j);
  42029. break;
  42030. }
  42031. index = nextIndex;
  42032. }
  42033. return section2;
  42034. }
  42035. void appendAllText (String::Concatenator& concatenator) const
  42036. {
  42037. for (int i = 0; i < atoms.size(); ++i)
  42038. concatenator.append (getAtom(i)->atomText);
  42039. }
  42040. void appendSubstring (String::Concatenator& concatenator,
  42041. const Range<int>& range) const
  42042. {
  42043. int index = 0;
  42044. for (int i = 0; i < atoms.size(); ++i)
  42045. {
  42046. const TextAtom* const atom = getAtom (i);
  42047. const int nextIndex = index + atom->numChars;
  42048. if (range.getStart() < nextIndex)
  42049. {
  42050. if (range.getEnd() <= index)
  42051. break;
  42052. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42053. if (! r.isEmpty())
  42054. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42055. }
  42056. index = nextIndex;
  42057. }
  42058. }
  42059. int getTotalLength() const
  42060. {
  42061. int total = 0;
  42062. for (int i = atoms.size(); --i >= 0;)
  42063. total += getAtom(i)->numChars;
  42064. return total;
  42065. }
  42066. void setFont (const Font& newFont,
  42067. const juce_wchar passwordCharacter)
  42068. {
  42069. if (font != newFont)
  42070. {
  42071. font = newFont;
  42072. for (int i = atoms.size(); --i >= 0;)
  42073. {
  42074. TextAtom* const atom = atoms.getUnchecked(i);
  42075. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42076. }
  42077. }
  42078. }
  42079. Font font;
  42080. Colour colour;
  42081. private:
  42082. Array <TextAtom*> atoms;
  42083. void initialiseAtoms (const String& textToParse,
  42084. const juce_wchar passwordCharacter)
  42085. {
  42086. int i = 0;
  42087. const int len = textToParse.length();
  42088. const juce_wchar* const text = textToParse;
  42089. while (i < len)
  42090. {
  42091. int start = i;
  42092. // create a whitespace atom unless it starts with non-ws
  42093. if (CharacterFunctions::isWhitespace (text[i])
  42094. && text[i] != '\r'
  42095. && text[i] != '\n')
  42096. {
  42097. while (i < len
  42098. && CharacterFunctions::isWhitespace (text[i])
  42099. && text[i] != '\r'
  42100. && text[i] != '\n')
  42101. {
  42102. ++i;
  42103. }
  42104. }
  42105. else
  42106. {
  42107. if (text[i] == '\r')
  42108. {
  42109. ++i;
  42110. if ((i < len) && (text[i] == '\n'))
  42111. {
  42112. ++start;
  42113. ++i;
  42114. }
  42115. }
  42116. else if (text[i] == '\n')
  42117. {
  42118. ++i;
  42119. }
  42120. else
  42121. {
  42122. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42123. ++i;
  42124. }
  42125. }
  42126. TextAtom* const atom = new TextAtom();
  42127. atom->atomText = String (text + start, i - start);
  42128. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42129. atom->numChars = (uint16) (i - start);
  42130. atoms.add (atom);
  42131. }
  42132. }
  42133. UniformTextSection& operator= (const UniformTextSection& other);
  42134. JUCE_LEAK_DETECTOR (UniformTextSection);
  42135. };
  42136. class TextEditor::Iterator
  42137. {
  42138. public:
  42139. Iterator (const Array <UniformTextSection*>& sections_,
  42140. const float wordWrapWidth_,
  42141. const juce_wchar passwordCharacter_)
  42142. : indexInText (0),
  42143. lineY (0),
  42144. lineHeight (0),
  42145. maxDescent (0),
  42146. atomX (0),
  42147. atomRight (0),
  42148. atom (0),
  42149. currentSection (0),
  42150. sections (sections_),
  42151. sectionIndex (0),
  42152. atomIndex (0),
  42153. wordWrapWidth (wordWrapWidth_),
  42154. passwordCharacter (passwordCharacter_)
  42155. {
  42156. jassert (wordWrapWidth_ > 0);
  42157. if (sections.size() > 0)
  42158. {
  42159. currentSection = sections.getUnchecked (sectionIndex);
  42160. if (currentSection != 0)
  42161. beginNewLine();
  42162. }
  42163. }
  42164. Iterator (const Iterator& other)
  42165. : indexInText (other.indexInText),
  42166. lineY (other.lineY),
  42167. lineHeight (other.lineHeight),
  42168. maxDescent (other.maxDescent),
  42169. atomX (other.atomX),
  42170. atomRight (other.atomRight),
  42171. atom (other.atom),
  42172. currentSection (other.currentSection),
  42173. sections (other.sections),
  42174. sectionIndex (other.sectionIndex),
  42175. atomIndex (other.atomIndex),
  42176. wordWrapWidth (other.wordWrapWidth),
  42177. passwordCharacter (other.passwordCharacter),
  42178. tempAtom (other.tempAtom)
  42179. {
  42180. }
  42181. bool next()
  42182. {
  42183. if (atom == &tempAtom)
  42184. {
  42185. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42186. if (numRemaining > 0)
  42187. {
  42188. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42189. atomX = 0;
  42190. if (tempAtom.numChars > 0)
  42191. lineY += lineHeight;
  42192. indexInText += tempAtom.numChars;
  42193. GlyphArrangement g;
  42194. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42195. int split;
  42196. for (split = 0; split < g.getNumGlyphs(); ++split)
  42197. if (shouldWrap (g.getGlyph (split).getRight()))
  42198. break;
  42199. if (split > 0 && split <= numRemaining)
  42200. {
  42201. tempAtom.numChars = (uint16) split;
  42202. tempAtom.width = g.getGlyph (split - 1).getRight();
  42203. atomRight = atomX + tempAtom.width;
  42204. return true;
  42205. }
  42206. }
  42207. }
  42208. bool forceNewLine = false;
  42209. if (sectionIndex >= sections.size())
  42210. {
  42211. moveToEndOfLastAtom();
  42212. return false;
  42213. }
  42214. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42215. {
  42216. if (atomIndex >= currentSection->getNumAtoms())
  42217. {
  42218. if (++sectionIndex >= sections.size())
  42219. {
  42220. moveToEndOfLastAtom();
  42221. return false;
  42222. }
  42223. atomIndex = 0;
  42224. currentSection = sections.getUnchecked (sectionIndex);
  42225. }
  42226. else
  42227. {
  42228. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42229. if (! lastAtom->isWhitespace())
  42230. {
  42231. // handle the case where the last atom in a section is actually part of the same
  42232. // word as the first atom of the next section...
  42233. float right = atomRight + lastAtom->width;
  42234. float lineHeight2 = lineHeight;
  42235. float maxDescent2 = maxDescent;
  42236. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42237. {
  42238. const UniformTextSection* const s = sections.getUnchecked (section);
  42239. if (s->getNumAtoms() == 0)
  42240. break;
  42241. const TextAtom* const nextAtom = s->getAtom (0);
  42242. if (nextAtom->isWhitespace())
  42243. break;
  42244. right += nextAtom->width;
  42245. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42246. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42247. if (shouldWrap (right))
  42248. {
  42249. lineHeight = lineHeight2;
  42250. maxDescent = maxDescent2;
  42251. forceNewLine = true;
  42252. break;
  42253. }
  42254. if (s->getNumAtoms() > 1)
  42255. break;
  42256. }
  42257. }
  42258. }
  42259. }
  42260. if (atom != 0)
  42261. {
  42262. atomX = atomRight;
  42263. indexInText += atom->numChars;
  42264. if (atom->isNewLine())
  42265. beginNewLine();
  42266. }
  42267. atom = currentSection->getAtom (atomIndex);
  42268. atomRight = atomX + atom->width;
  42269. ++atomIndex;
  42270. if (shouldWrap (atomRight) || forceNewLine)
  42271. {
  42272. if (atom->isWhitespace())
  42273. {
  42274. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42275. atomRight = jmin (atomRight, wordWrapWidth);
  42276. }
  42277. else
  42278. {
  42279. atomRight = atom->width;
  42280. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42281. {
  42282. tempAtom = *atom;
  42283. tempAtom.width = 0;
  42284. tempAtom.numChars = 0;
  42285. atom = &tempAtom;
  42286. if (atomX > 0)
  42287. beginNewLine();
  42288. return next();
  42289. }
  42290. beginNewLine();
  42291. return true;
  42292. }
  42293. }
  42294. return true;
  42295. }
  42296. void beginNewLine()
  42297. {
  42298. atomX = 0;
  42299. lineY += lineHeight;
  42300. int tempSectionIndex = sectionIndex;
  42301. int tempAtomIndex = atomIndex;
  42302. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42303. lineHeight = section->font.getHeight();
  42304. maxDescent = section->font.getDescent();
  42305. float x = (atom != 0) ? atom->width : 0;
  42306. while (! shouldWrap (x))
  42307. {
  42308. if (tempSectionIndex >= sections.size())
  42309. break;
  42310. bool checkSize = false;
  42311. if (tempAtomIndex >= section->getNumAtoms())
  42312. {
  42313. if (++tempSectionIndex >= sections.size())
  42314. break;
  42315. tempAtomIndex = 0;
  42316. section = sections.getUnchecked (tempSectionIndex);
  42317. checkSize = true;
  42318. }
  42319. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42320. if (nextAtom == 0)
  42321. break;
  42322. x += nextAtom->width;
  42323. if (shouldWrap (x) || nextAtom->isNewLine())
  42324. break;
  42325. if (checkSize)
  42326. {
  42327. lineHeight = jmax (lineHeight, section->font.getHeight());
  42328. maxDescent = jmax (maxDescent, section->font.getDescent());
  42329. }
  42330. ++tempAtomIndex;
  42331. }
  42332. }
  42333. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42334. {
  42335. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42336. {
  42337. if (lastSection != currentSection)
  42338. {
  42339. lastSection = currentSection;
  42340. g.setColour (currentSection->colour);
  42341. g.setFont (currentSection->font);
  42342. }
  42343. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42344. GlyphArrangement ga;
  42345. ga.addLineOfText (currentSection->font,
  42346. atom->getTrimmedText (passwordCharacter),
  42347. atomX,
  42348. (float) roundToInt (lineY + lineHeight - maxDescent));
  42349. ga.draw (g);
  42350. }
  42351. }
  42352. void drawSelection (Graphics& g,
  42353. const Range<int>& selection) const
  42354. {
  42355. const int startX = roundToInt (indexToX (selection.getStart()));
  42356. const int endX = roundToInt (indexToX (selection.getEnd()));
  42357. const int y = roundToInt (lineY);
  42358. const int nextY = roundToInt (lineY + lineHeight);
  42359. g.fillRect (startX, y, endX - startX, nextY - y);
  42360. }
  42361. void drawSelectedText (Graphics& g,
  42362. const Range<int>& selection,
  42363. const Colour& selectedTextColour) const
  42364. {
  42365. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42366. {
  42367. GlyphArrangement ga;
  42368. ga.addLineOfText (currentSection->font,
  42369. atom->getTrimmedText (passwordCharacter),
  42370. atomX,
  42371. (float) roundToInt (lineY + lineHeight - maxDescent));
  42372. if (selection.getEnd() < indexInText + atom->numChars)
  42373. {
  42374. GlyphArrangement ga2 (ga);
  42375. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42376. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42377. g.setColour (currentSection->colour);
  42378. ga2.draw (g);
  42379. }
  42380. if (selection.getStart() > indexInText)
  42381. {
  42382. GlyphArrangement ga2 (ga);
  42383. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42384. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42385. g.setColour (currentSection->colour);
  42386. ga2.draw (g);
  42387. }
  42388. g.setColour (selectedTextColour);
  42389. ga.draw (g);
  42390. }
  42391. }
  42392. float indexToX (const int indexToFind) const
  42393. {
  42394. if (indexToFind <= indexInText)
  42395. return atomX;
  42396. if (indexToFind >= indexInText + atom->numChars)
  42397. return atomRight;
  42398. GlyphArrangement g;
  42399. g.addLineOfText (currentSection->font,
  42400. atom->getText (passwordCharacter),
  42401. atomX, 0.0f);
  42402. if (indexToFind - indexInText >= g.getNumGlyphs())
  42403. return atomRight;
  42404. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42405. }
  42406. int xToIndex (const float xToFind) const
  42407. {
  42408. if (xToFind <= atomX || atom->isNewLine())
  42409. return indexInText;
  42410. if (xToFind >= atomRight)
  42411. return indexInText + atom->numChars;
  42412. GlyphArrangement g;
  42413. g.addLineOfText (currentSection->font,
  42414. atom->getText (passwordCharacter),
  42415. atomX, 0.0f);
  42416. int j;
  42417. for (j = 0; j < g.getNumGlyphs(); ++j)
  42418. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42419. break;
  42420. return indexInText + j;
  42421. }
  42422. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42423. {
  42424. while (next())
  42425. {
  42426. if (indexInText + atom->numChars > index)
  42427. {
  42428. cx = indexToX (index);
  42429. cy = lineY;
  42430. lineHeight_ = lineHeight;
  42431. return true;
  42432. }
  42433. }
  42434. cx = atomX;
  42435. cy = lineY;
  42436. lineHeight_ = lineHeight;
  42437. return false;
  42438. }
  42439. int indexInText;
  42440. float lineY, lineHeight, maxDescent;
  42441. float atomX, atomRight;
  42442. const TextAtom* atom;
  42443. const UniformTextSection* currentSection;
  42444. private:
  42445. const Array <UniformTextSection*>& sections;
  42446. int sectionIndex, atomIndex;
  42447. const float wordWrapWidth;
  42448. const juce_wchar passwordCharacter;
  42449. TextAtom tempAtom;
  42450. Iterator& operator= (const Iterator&);
  42451. void moveToEndOfLastAtom()
  42452. {
  42453. if (atom != 0)
  42454. {
  42455. atomX = atomRight;
  42456. if (atom->isNewLine())
  42457. {
  42458. atomX = 0.0f;
  42459. lineY += lineHeight;
  42460. }
  42461. }
  42462. }
  42463. bool shouldWrap (const float x) const
  42464. {
  42465. return (x - 0.0001f) >= wordWrapWidth;
  42466. }
  42467. JUCE_LEAK_DETECTOR (Iterator);
  42468. };
  42469. class TextEditor::InsertAction : public UndoableAction
  42470. {
  42471. public:
  42472. InsertAction (TextEditor& owner_,
  42473. const String& text_,
  42474. const int insertIndex_,
  42475. const Font& font_,
  42476. const Colour& colour_,
  42477. const int oldCaretPos_,
  42478. const int newCaretPos_)
  42479. : owner (owner_),
  42480. text (text_),
  42481. insertIndex (insertIndex_),
  42482. oldCaretPos (oldCaretPos_),
  42483. newCaretPos (newCaretPos_),
  42484. font (font_),
  42485. colour (colour_)
  42486. {
  42487. }
  42488. bool perform()
  42489. {
  42490. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42491. return true;
  42492. }
  42493. bool undo()
  42494. {
  42495. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42496. return true;
  42497. }
  42498. int getSizeInUnits()
  42499. {
  42500. return text.length() + 16;
  42501. }
  42502. private:
  42503. TextEditor& owner;
  42504. const String text;
  42505. const int insertIndex, oldCaretPos, newCaretPos;
  42506. const Font font;
  42507. const Colour colour;
  42508. JUCE_DECLARE_NON_COPYABLE (InsertAction);
  42509. };
  42510. class TextEditor::RemoveAction : public UndoableAction
  42511. {
  42512. public:
  42513. RemoveAction (TextEditor& owner_,
  42514. const Range<int> range_,
  42515. const int oldCaretPos_,
  42516. const int newCaretPos_,
  42517. const Array <UniformTextSection*>& removedSections_)
  42518. : owner (owner_),
  42519. range (range_),
  42520. oldCaretPos (oldCaretPos_),
  42521. newCaretPos (newCaretPos_),
  42522. removedSections (removedSections_)
  42523. {
  42524. }
  42525. ~RemoveAction()
  42526. {
  42527. for (int i = removedSections.size(); --i >= 0;)
  42528. {
  42529. UniformTextSection* const section = removedSections.getUnchecked (i);
  42530. section->clear();
  42531. delete section;
  42532. }
  42533. }
  42534. bool perform()
  42535. {
  42536. owner.remove (range, 0, newCaretPos);
  42537. return true;
  42538. }
  42539. bool undo()
  42540. {
  42541. owner.reinsert (range.getStart(), removedSections);
  42542. owner.moveCursorTo (oldCaretPos, false);
  42543. return true;
  42544. }
  42545. int getSizeInUnits()
  42546. {
  42547. int n = 0;
  42548. for (int i = removedSections.size(); --i >= 0;)
  42549. n += removedSections.getUnchecked (i)->getTotalLength();
  42550. return n + 16;
  42551. }
  42552. private:
  42553. TextEditor& owner;
  42554. const Range<int> range;
  42555. const int oldCaretPos, newCaretPos;
  42556. Array <UniformTextSection*> removedSections;
  42557. JUCE_DECLARE_NON_COPYABLE (RemoveAction);
  42558. };
  42559. class TextEditor::TextHolderComponent : public Component,
  42560. public Timer,
  42561. public ValueListener
  42562. {
  42563. public:
  42564. TextHolderComponent (TextEditor& owner_)
  42565. : owner (owner_)
  42566. {
  42567. setWantsKeyboardFocus (false);
  42568. setInterceptsMouseClicks (false, true);
  42569. owner.getTextValue().addListener (this);
  42570. }
  42571. ~TextHolderComponent()
  42572. {
  42573. owner.getTextValue().removeListener (this);
  42574. }
  42575. void paint (Graphics& g)
  42576. {
  42577. owner.drawContent (g);
  42578. }
  42579. void timerCallback()
  42580. {
  42581. owner.timerCallbackInt();
  42582. }
  42583. const MouseCursor getMouseCursor()
  42584. {
  42585. return owner.getMouseCursor();
  42586. }
  42587. void valueChanged (Value&)
  42588. {
  42589. owner.textWasChangedByValue();
  42590. }
  42591. private:
  42592. TextEditor& owner;
  42593. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent);
  42594. };
  42595. class TextEditorViewport : public Viewport
  42596. {
  42597. public:
  42598. TextEditorViewport (TextEditor& owner_)
  42599. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42600. {
  42601. }
  42602. void visibleAreaChanged (const Rectangle<int>&)
  42603. {
  42604. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42605. // appear and disappear, causing the wrap width to change.
  42606. {
  42607. const float wordWrapWidth = owner.getWordWrapWidth();
  42608. if (wordWrapWidth != lastWordWrapWidth)
  42609. {
  42610. lastWordWrapWidth = wordWrapWidth;
  42611. rentrant = true;
  42612. owner.updateTextHolderSize();
  42613. rentrant = false;
  42614. }
  42615. }
  42616. }
  42617. private:
  42618. TextEditor& owner;
  42619. float lastWordWrapWidth;
  42620. bool rentrant;
  42621. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport);
  42622. };
  42623. namespace TextEditorDefs
  42624. {
  42625. const int flashSpeedIntervalMs = 380;
  42626. const int textChangeMessageId = 0x10003001;
  42627. const int returnKeyMessageId = 0x10003002;
  42628. const int escapeKeyMessageId = 0x10003003;
  42629. const int focusLossMessageId = 0x10003004;
  42630. const int maxActionsPerTransaction = 100;
  42631. int getCharacterCategory (const juce_wchar character)
  42632. {
  42633. return CharacterFunctions::isLetterOrDigit (character)
  42634. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42635. }
  42636. }
  42637. TextEditor::TextEditor (const String& name,
  42638. const juce_wchar passwordCharacter_)
  42639. : Component (name),
  42640. borderSize (1, 1, 1, 3),
  42641. readOnly (false),
  42642. multiline (false),
  42643. wordWrap (false),
  42644. returnKeyStartsNewLine (false),
  42645. caretVisible (true),
  42646. popupMenuEnabled (true),
  42647. selectAllTextWhenFocused (false),
  42648. scrollbarVisible (true),
  42649. wasFocused (false),
  42650. caretFlashState (true),
  42651. keepCursorOnScreen (true),
  42652. tabKeyUsed (false),
  42653. menuActive (false),
  42654. valueTextNeedsUpdating (false),
  42655. cursorX (0),
  42656. cursorY (0),
  42657. cursorHeight (0),
  42658. maxTextLength (0),
  42659. leftIndent (4),
  42660. topIndent (4),
  42661. lastTransactionTime (0),
  42662. currentFont (14.0f),
  42663. totalNumChars (0),
  42664. caretPosition (0),
  42665. passwordCharacter (passwordCharacter_),
  42666. dragType (notDragging)
  42667. {
  42668. setOpaque (true);
  42669. addAndMakeVisible (viewport = new TextEditorViewport (*this));
  42670. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42671. viewport->setWantsKeyboardFocus (false);
  42672. viewport->setScrollBarsShown (false, false);
  42673. setMouseCursor (MouseCursor::IBeamCursor);
  42674. setWantsKeyboardFocus (true);
  42675. }
  42676. TextEditor::~TextEditor()
  42677. {
  42678. textValue.referTo (Value());
  42679. clearInternal (0);
  42680. viewport = 0;
  42681. textHolder = 0;
  42682. }
  42683. void TextEditor::newTransaction()
  42684. {
  42685. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42686. undoManager.beginNewTransaction();
  42687. }
  42688. void TextEditor::doUndoRedo (const bool isRedo)
  42689. {
  42690. if (! isReadOnly())
  42691. {
  42692. if (isRedo ? undoManager.redo()
  42693. : undoManager.undo())
  42694. {
  42695. scrollToMakeSureCursorIsVisible();
  42696. repaint();
  42697. textChanged();
  42698. }
  42699. }
  42700. }
  42701. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42702. const bool shouldWordWrap)
  42703. {
  42704. if (multiline != shouldBeMultiLine
  42705. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42706. {
  42707. multiline = shouldBeMultiLine;
  42708. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42709. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42710. scrollbarVisible && multiline);
  42711. viewport->setViewPosition (0, 0);
  42712. resized();
  42713. scrollToMakeSureCursorIsVisible();
  42714. }
  42715. }
  42716. bool TextEditor::isMultiLine() const
  42717. {
  42718. return multiline;
  42719. }
  42720. void TextEditor::setScrollbarsShown (bool shown)
  42721. {
  42722. if (scrollbarVisible != shown)
  42723. {
  42724. scrollbarVisible = shown;
  42725. shown = shown && isMultiLine();
  42726. viewport->setScrollBarsShown (shown, shown);
  42727. }
  42728. }
  42729. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42730. {
  42731. if (readOnly != shouldBeReadOnly)
  42732. {
  42733. readOnly = shouldBeReadOnly;
  42734. enablementChanged();
  42735. }
  42736. }
  42737. bool TextEditor::isReadOnly() const
  42738. {
  42739. return readOnly || ! isEnabled();
  42740. }
  42741. bool TextEditor::isTextInputActive() const
  42742. {
  42743. return ! isReadOnly();
  42744. }
  42745. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42746. {
  42747. returnKeyStartsNewLine = shouldStartNewLine;
  42748. }
  42749. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42750. {
  42751. tabKeyUsed = shouldTabKeyBeUsed;
  42752. }
  42753. void TextEditor::setPopupMenuEnabled (const bool b)
  42754. {
  42755. popupMenuEnabled = b;
  42756. }
  42757. void TextEditor::setSelectAllWhenFocused (const bool b)
  42758. {
  42759. selectAllTextWhenFocused = b;
  42760. }
  42761. const Font TextEditor::getFont() const
  42762. {
  42763. return currentFont;
  42764. }
  42765. void TextEditor::setFont (const Font& newFont)
  42766. {
  42767. currentFont = newFont;
  42768. scrollToMakeSureCursorIsVisible();
  42769. }
  42770. void TextEditor::applyFontToAllText (const Font& newFont)
  42771. {
  42772. currentFont = newFont;
  42773. const Colour overallColour (findColour (textColourId));
  42774. for (int i = sections.size(); --i >= 0;)
  42775. {
  42776. UniformTextSection* const uts = sections.getUnchecked (i);
  42777. uts->setFont (newFont, passwordCharacter);
  42778. uts->colour = overallColour;
  42779. }
  42780. coalesceSimilarSections();
  42781. updateTextHolderSize();
  42782. scrollToMakeSureCursorIsVisible();
  42783. repaint();
  42784. }
  42785. void TextEditor::colourChanged()
  42786. {
  42787. setOpaque (findColour (backgroundColourId).isOpaque());
  42788. repaint();
  42789. }
  42790. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42791. {
  42792. caretVisible = shouldCaretBeVisible;
  42793. if (shouldCaretBeVisible)
  42794. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42795. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42796. : MouseCursor::NormalCursor);
  42797. }
  42798. void TextEditor::setInputRestrictions (const int maxLen,
  42799. const String& chars)
  42800. {
  42801. maxTextLength = jmax (0, maxLen);
  42802. allowedCharacters = chars;
  42803. }
  42804. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42805. {
  42806. textToShowWhenEmpty = text;
  42807. colourForTextWhenEmpty = colourToUse;
  42808. }
  42809. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42810. {
  42811. if (passwordCharacter != newPasswordCharacter)
  42812. {
  42813. passwordCharacter = newPasswordCharacter;
  42814. resized();
  42815. repaint();
  42816. }
  42817. }
  42818. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42819. {
  42820. viewport->setScrollBarThickness (newThicknessPixels);
  42821. }
  42822. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42823. {
  42824. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42825. }
  42826. void TextEditor::clear()
  42827. {
  42828. clearInternal (0);
  42829. updateTextHolderSize();
  42830. undoManager.clearUndoHistory();
  42831. }
  42832. void TextEditor::setText (const String& newText,
  42833. const bool sendTextChangeMessage)
  42834. {
  42835. const int newLength = newText.length();
  42836. if (newLength != getTotalNumChars() || getText() != newText)
  42837. {
  42838. const int oldCursorPos = caretPosition;
  42839. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42840. clearInternal (0);
  42841. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42842. // if you're adding text with line-feeds to a single-line text editor, it
  42843. // ain't gonna look right!
  42844. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42845. if (cursorWasAtEnd && ! isMultiLine())
  42846. moveCursorTo (getTotalNumChars(), false);
  42847. else
  42848. moveCursorTo (oldCursorPos, false);
  42849. if (sendTextChangeMessage)
  42850. textChanged();
  42851. updateTextHolderSize();
  42852. scrollToMakeSureCursorIsVisible();
  42853. undoManager.clearUndoHistory();
  42854. repaint();
  42855. }
  42856. }
  42857. Value& TextEditor::getTextValue()
  42858. {
  42859. if (valueTextNeedsUpdating)
  42860. {
  42861. valueTextNeedsUpdating = false;
  42862. textValue = getText();
  42863. }
  42864. return textValue;
  42865. }
  42866. void TextEditor::textWasChangedByValue()
  42867. {
  42868. if (textValue.getValueSource().getReferenceCount() > 1)
  42869. setText (textValue.getValue());
  42870. }
  42871. void TextEditor::textChanged()
  42872. {
  42873. updateTextHolderSize();
  42874. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42875. if (textValue.getValueSource().getReferenceCount() > 1)
  42876. {
  42877. valueTextNeedsUpdating = false;
  42878. textValue = getText();
  42879. }
  42880. }
  42881. void TextEditor::returnPressed()
  42882. {
  42883. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42884. }
  42885. void TextEditor::escapePressed()
  42886. {
  42887. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42888. }
  42889. void TextEditor::addListener (TextEditorListener* const newListener)
  42890. {
  42891. listeners.add (newListener);
  42892. }
  42893. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42894. {
  42895. listeners.remove (listenerToRemove);
  42896. }
  42897. void TextEditor::timerCallbackInt()
  42898. {
  42899. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42900. if (caretFlashState != newState)
  42901. {
  42902. caretFlashState = newState;
  42903. if (caretFlashState)
  42904. wasFocused = true;
  42905. if (caretVisible
  42906. && hasKeyboardFocus (false)
  42907. && ! isReadOnly())
  42908. {
  42909. repaintCaret();
  42910. }
  42911. }
  42912. const unsigned int now = Time::getApproximateMillisecondCounter();
  42913. if (now > lastTransactionTime + 200)
  42914. newTransaction();
  42915. }
  42916. void TextEditor::repaintCaret()
  42917. {
  42918. if (! findColour (caretColourId).isTransparent())
  42919. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42920. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42921. 4,
  42922. roundToInt (cursorHeight) + 2);
  42923. }
  42924. void TextEditor::repaintText (const Range<int>& range)
  42925. {
  42926. if (! range.isEmpty())
  42927. {
  42928. float x = 0, y = 0, lh = currentFont.getHeight();
  42929. const float wordWrapWidth = getWordWrapWidth();
  42930. if (wordWrapWidth > 0)
  42931. {
  42932. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42933. i.getCharPosition (range.getStart(), x, y, lh);
  42934. const int y1 = (int) y;
  42935. int y2;
  42936. if (range.getEnd() >= getTotalNumChars())
  42937. {
  42938. y2 = textHolder->getHeight();
  42939. }
  42940. else
  42941. {
  42942. i.getCharPosition (range.getEnd(), x, y, lh);
  42943. y2 = (int) (y + lh * 2.0f);
  42944. }
  42945. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42946. }
  42947. }
  42948. }
  42949. void TextEditor::moveCaret (int newCaretPos)
  42950. {
  42951. if (newCaretPos < 0)
  42952. newCaretPos = 0;
  42953. else if (newCaretPos > getTotalNumChars())
  42954. newCaretPos = getTotalNumChars();
  42955. if (newCaretPos != getCaretPosition())
  42956. {
  42957. repaintCaret();
  42958. caretFlashState = true;
  42959. caretPosition = newCaretPos;
  42960. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42961. scrollToMakeSureCursorIsVisible();
  42962. repaintCaret();
  42963. }
  42964. }
  42965. void TextEditor::setCaretPosition (const int newIndex)
  42966. {
  42967. moveCursorTo (newIndex, false);
  42968. }
  42969. int TextEditor::getCaretPosition() const
  42970. {
  42971. return caretPosition;
  42972. }
  42973. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42974. const int desiredCaretY)
  42975. {
  42976. updateCaretPosition();
  42977. int vx = roundToInt (cursorX) - desiredCaretX;
  42978. int vy = roundToInt (cursorY) - desiredCaretY;
  42979. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42980. {
  42981. vx += desiredCaretX - proportionOfWidth (0.2f);
  42982. }
  42983. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42984. {
  42985. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42986. }
  42987. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42988. if (! isMultiLine())
  42989. {
  42990. vy = viewport->getViewPositionY();
  42991. }
  42992. else
  42993. {
  42994. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42995. const int curH = roundToInt (cursorHeight);
  42996. if (desiredCaretY < 0)
  42997. {
  42998. vy = jmax (0, desiredCaretY + vy);
  42999. }
  43000. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43001. {
  43002. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43003. }
  43004. }
  43005. viewport->setViewPosition (vx, vy);
  43006. }
  43007. const Rectangle<int> TextEditor::getCaretRectangle()
  43008. {
  43009. updateCaretPosition();
  43010. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43011. roundToInt (cursorY) - viewport->getY(),
  43012. 1, roundToInt (cursorHeight));
  43013. }
  43014. float TextEditor::getWordWrapWidth() const
  43015. {
  43016. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43017. : 1.0e10f;
  43018. }
  43019. void TextEditor::updateTextHolderSize()
  43020. {
  43021. const float wordWrapWidth = getWordWrapWidth();
  43022. if (wordWrapWidth > 0)
  43023. {
  43024. float maxWidth = 0.0f;
  43025. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43026. while (i.next())
  43027. maxWidth = jmax (maxWidth, i.atomRight);
  43028. const int w = leftIndent + roundToInt (maxWidth);
  43029. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43030. currentFont.getHeight()));
  43031. textHolder->setSize (w + 1, h + 1);
  43032. }
  43033. }
  43034. int TextEditor::getTextWidth() const
  43035. {
  43036. return textHolder->getWidth();
  43037. }
  43038. int TextEditor::getTextHeight() const
  43039. {
  43040. return textHolder->getHeight();
  43041. }
  43042. void TextEditor::setIndents (const int newLeftIndent,
  43043. const int newTopIndent)
  43044. {
  43045. leftIndent = newLeftIndent;
  43046. topIndent = newTopIndent;
  43047. }
  43048. void TextEditor::setBorder (const BorderSize& border)
  43049. {
  43050. borderSize = border;
  43051. resized();
  43052. }
  43053. const BorderSize TextEditor::getBorder() const
  43054. {
  43055. return borderSize;
  43056. }
  43057. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43058. {
  43059. keepCursorOnScreen = shouldScrollToShowCursor;
  43060. }
  43061. void TextEditor::updateCaretPosition()
  43062. {
  43063. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43064. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43065. }
  43066. void TextEditor::scrollToMakeSureCursorIsVisible()
  43067. {
  43068. updateCaretPosition();
  43069. if (keepCursorOnScreen)
  43070. {
  43071. int x = viewport->getViewPositionX();
  43072. int y = viewport->getViewPositionY();
  43073. const int relativeCursorX = roundToInt (cursorX) - x;
  43074. const int relativeCursorY = roundToInt (cursorY) - y;
  43075. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43076. {
  43077. x += relativeCursorX - proportionOfWidth (0.2f);
  43078. }
  43079. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43080. {
  43081. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43082. }
  43083. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43084. if (! isMultiLine())
  43085. {
  43086. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43087. }
  43088. else
  43089. {
  43090. const int curH = roundToInt (cursorHeight);
  43091. if (relativeCursorY < 0)
  43092. {
  43093. y = jmax (0, relativeCursorY + y);
  43094. }
  43095. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43096. {
  43097. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43098. }
  43099. }
  43100. viewport->setViewPosition (x, y);
  43101. }
  43102. }
  43103. void TextEditor::moveCursorTo (const int newPosition,
  43104. const bool isSelecting)
  43105. {
  43106. if (isSelecting)
  43107. {
  43108. moveCaret (newPosition);
  43109. const Range<int> oldSelection (selection);
  43110. if (dragType == notDragging)
  43111. {
  43112. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43113. dragType = draggingSelectionStart;
  43114. else
  43115. dragType = draggingSelectionEnd;
  43116. }
  43117. if (dragType == draggingSelectionStart)
  43118. {
  43119. if (getCaretPosition() >= selection.getEnd())
  43120. dragType = draggingSelectionEnd;
  43121. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43122. }
  43123. else
  43124. {
  43125. if (getCaretPosition() < selection.getStart())
  43126. dragType = draggingSelectionStart;
  43127. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43128. }
  43129. repaintText (selection.getUnionWith (oldSelection));
  43130. }
  43131. else
  43132. {
  43133. dragType = notDragging;
  43134. repaintText (selection);
  43135. moveCaret (newPosition);
  43136. selection = Range<int>::emptyRange (getCaretPosition());
  43137. }
  43138. }
  43139. int TextEditor::getTextIndexAt (const int x,
  43140. const int y)
  43141. {
  43142. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43143. (float) (y + viewport->getViewPositionY() - topIndent));
  43144. }
  43145. void TextEditor::insertTextAtCaret (const String& newText_)
  43146. {
  43147. String newText (newText_);
  43148. if (allowedCharacters.isNotEmpty())
  43149. newText = newText.retainCharacters (allowedCharacters);
  43150. if (! isMultiLine())
  43151. newText = newText.replaceCharacters ("\r\n", " ");
  43152. else
  43153. newText = newText.replace ("\r\n", "\n");
  43154. const int newCaretPos = selection.getStart() + newText.length();
  43155. const int insertIndex = selection.getStart();
  43156. remove (selection, getUndoManager(),
  43157. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43158. if (maxTextLength > 0)
  43159. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43160. if (newText.isNotEmpty())
  43161. insert (newText,
  43162. insertIndex,
  43163. currentFont,
  43164. findColour (textColourId),
  43165. getUndoManager(),
  43166. newCaretPos);
  43167. textChanged();
  43168. }
  43169. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43170. {
  43171. moveCursorTo (newSelection.getStart(), false);
  43172. moveCursorTo (newSelection.getEnd(), true);
  43173. }
  43174. void TextEditor::copy()
  43175. {
  43176. if (passwordCharacter == 0)
  43177. {
  43178. const String selectedText (getHighlightedText());
  43179. if (selectedText.isNotEmpty())
  43180. SystemClipboard::copyTextToClipboard (selectedText);
  43181. }
  43182. }
  43183. void TextEditor::paste()
  43184. {
  43185. if (! isReadOnly())
  43186. {
  43187. const String clip (SystemClipboard::getTextFromClipboard());
  43188. if (clip.isNotEmpty())
  43189. insertTextAtCaret (clip);
  43190. }
  43191. }
  43192. void TextEditor::cut()
  43193. {
  43194. if (! isReadOnly())
  43195. {
  43196. moveCaret (selection.getEnd());
  43197. insertTextAtCaret (String::empty);
  43198. }
  43199. }
  43200. void TextEditor::drawContent (Graphics& g)
  43201. {
  43202. const float wordWrapWidth = getWordWrapWidth();
  43203. if (wordWrapWidth > 0)
  43204. {
  43205. g.setOrigin (leftIndent, topIndent);
  43206. const Rectangle<int> clip (g.getClipBounds());
  43207. Colour selectedTextColour;
  43208. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43209. while (i.lineY + 200.0 < clip.getY() && i.next())
  43210. {}
  43211. if (! selection.isEmpty())
  43212. {
  43213. g.setColour (findColour (highlightColourId)
  43214. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43215. selectedTextColour = findColour (highlightedTextColourId);
  43216. Iterator i2 (i);
  43217. while (i2.next() && i2.lineY < clip.getBottom())
  43218. {
  43219. if (i2.lineY + i2.lineHeight >= clip.getY()
  43220. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43221. {
  43222. i2.drawSelection (g, selection);
  43223. }
  43224. }
  43225. }
  43226. const UniformTextSection* lastSection = 0;
  43227. while (i.next() && i.lineY < clip.getBottom())
  43228. {
  43229. if (i.lineY + i.lineHeight >= clip.getY())
  43230. {
  43231. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43232. {
  43233. i.drawSelectedText (g, selection, selectedTextColour);
  43234. lastSection = 0;
  43235. }
  43236. else
  43237. {
  43238. i.draw (g, lastSection);
  43239. }
  43240. }
  43241. }
  43242. }
  43243. }
  43244. void TextEditor::paint (Graphics& g)
  43245. {
  43246. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43247. }
  43248. void TextEditor::paintOverChildren (Graphics& g)
  43249. {
  43250. if (caretFlashState
  43251. && hasKeyboardFocus (false)
  43252. && caretVisible
  43253. && ! isReadOnly())
  43254. {
  43255. g.setColour (findColour (caretColourId));
  43256. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43257. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43258. 2.0f, cursorHeight);
  43259. }
  43260. if (textToShowWhenEmpty.isNotEmpty()
  43261. && (! hasKeyboardFocus (false))
  43262. && getTotalNumChars() == 0)
  43263. {
  43264. g.setColour (colourForTextWhenEmpty);
  43265. g.setFont (getFont());
  43266. if (isMultiLine())
  43267. {
  43268. g.drawText (textToShowWhenEmpty,
  43269. 0, 0, getWidth(), getHeight(),
  43270. Justification::centred, true);
  43271. }
  43272. else
  43273. {
  43274. g.drawText (textToShowWhenEmpty,
  43275. leftIndent, topIndent,
  43276. viewport->getWidth() - leftIndent,
  43277. viewport->getHeight() - topIndent,
  43278. Justification::centredLeft, true);
  43279. }
  43280. }
  43281. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43282. }
  43283. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43284. {
  43285. public:
  43286. TextEditorMenuPerformer (TextEditor* const editor_)
  43287. : editor (editor_)
  43288. {
  43289. }
  43290. void modalStateFinished (int returnValue)
  43291. {
  43292. if (editor != 0 && returnValue != 0)
  43293. editor->performPopupMenuAction (returnValue);
  43294. }
  43295. private:
  43296. Component::SafePointer<TextEditor> editor;
  43297. JUCE_DECLARE_NON_COPYABLE (TextEditorMenuPerformer);
  43298. };
  43299. void TextEditor::mouseDown (const MouseEvent& e)
  43300. {
  43301. beginDragAutoRepeat (100);
  43302. newTransaction();
  43303. if (wasFocused || ! selectAllTextWhenFocused)
  43304. {
  43305. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43306. {
  43307. moveCursorTo (getTextIndexAt (e.x, e.y),
  43308. e.mods.isShiftDown());
  43309. }
  43310. else
  43311. {
  43312. PopupMenu m;
  43313. m.setLookAndFeel (&getLookAndFeel());
  43314. addPopupMenuItems (m, &e);
  43315. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43316. }
  43317. }
  43318. }
  43319. void TextEditor::mouseDrag (const MouseEvent& e)
  43320. {
  43321. if (wasFocused || ! selectAllTextWhenFocused)
  43322. {
  43323. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43324. {
  43325. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43326. }
  43327. }
  43328. }
  43329. void TextEditor::mouseUp (const MouseEvent& e)
  43330. {
  43331. newTransaction();
  43332. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43333. if (wasFocused || ! selectAllTextWhenFocused)
  43334. {
  43335. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43336. {
  43337. moveCaret (getTextIndexAt (e.x, e.y));
  43338. }
  43339. }
  43340. wasFocused = true;
  43341. }
  43342. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43343. {
  43344. int tokenEnd = getTextIndexAt (e.x, e.y);
  43345. int tokenStart = tokenEnd;
  43346. if (e.getNumberOfClicks() > 3)
  43347. {
  43348. tokenStart = 0;
  43349. tokenEnd = getTotalNumChars();
  43350. }
  43351. else
  43352. {
  43353. const String t (getText());
  43354. const int totalLength = getTotalNumChars();
  43355. while (tokenEnd < totalLength)
  43356. {
  43357. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43358. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43359. ++tokenEnd;
  43360. else
  43361. break;
  43362. }
  43363. tokenStart = tokenEnd;
  43364. while (tokenStart > 0)
  43365. {
  43366. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43367. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43368. --tokenStart;
  43369. else
  43370. break;
  43371. }
  43372. if (e.getNumberOfClicks() > 2)
  43373. {
  43374. while (tokenEnd < totalLength)
  43375. {
  43376. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43377. ++tokenEnd;
  43378. else
  43379. break;
  43380. }
  43381. while (tokenStart > 0)
  43382. {
  43383. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43384. --tokenStart;
  43385. else
  43386. break;
  43387. }
  43388. }
  43389. }
  43390. moveCursorTo (tokenEnd, false);
  43391. moveCursorTo (tokenStart, true);
  43392. }
  43393. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43394. {
  43395. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43396. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43397. }
  43398. bool TextEditor::keyPressed (const KeyPress& key)
  43399. {
  43400. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43401. return false;
  43402. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43403. if (key.isKeyCode (KeyPress::leftKey)
  43404. || key.isKeyCode (KeyPress::upKey))
  43405. {
  43406. newTransaction();
  43407. int newPos;
  43408. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43409. newPos = indexAtPosition (cursorX, cursorY - 1);
  43410. else if (moveInWholeWordSteps)
  43411. newPos = findWordBreakBefore (getCaretPosition());
  43412. else
  43413. newPos = getCaretPosition() - 1;
  43414. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43415. }
  43416. else if (key.isKeyCode (KeyPress::rightKey)
  43417. || key.isKeyCode (KeyPress::downKey))
  43418. {
  43419. newTransaction();
  43420. int newPos;
  43421. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43422. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43423. else if (moveInWholeWordSteps)
  43424. newPos = findWordBreakAfter (getCaretPosition());
  43425. else
  43426. newPos = getCaretPosition() + 1;
  43427. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43428. }
  43429. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43430. {
  43431. newTransaction();
  43432. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43433. key.getModifiers().isShiftDown());
  43434. }
  43435. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43436. {
  43437. newTransaction();
  43438. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43439. key.getModifiers().isShiftDown());
  43440. }
  43441. else if (key.isKeyCode (KeyPress::homeKey))
  43442. {
  43443. newTransaction();
  43444. if (isMultiLine() && ! moveInWholeWordSteps)
  43445. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43446. key.getModifiers().isShiftDown());
  43447. else
  43448. moveCursorTo (0, key.getModifiers().isShiftDown());
  43449. }
  43450. else if (key.isKeyCode (KeyPress::endKey))
  43451. {
  43452. newTransaction();
  43453. if (isMultiLine() && ! moveInWholeWordSteps)
  43454. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43455. key.getModifiers().isShiftDown());
  43456. else
  43457. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43458. }
  43459. else if (key.isKeyCode (KeyPress::backspaceKey))
  43460. {
  43461. if (moveInWholeWordSteps)
  43462. {
  43463. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43464. }
  43465. else
  43466. {
  43467. if (selection.isEmpty() && selection.getStart() > 0)
  43468. selection.setStart (selection.getEnd() - 1);
  43469. }
  43470. cut();
  43471. }
  43472. else if (key.isKeyCode (KeyPress::deleteKey))
  43473. {
  43474. if (key.getModifiers().isShiftDown())
  43475. copy();
  43476. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43477. selection.setEnd (selection.getStart() + 1);
  43478. cut();
  43479. }
  43480. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43481. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43482. {
  43483. newTransaction();
  43484. copy();
  43485. }
  43486. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43487. {
  43488. newTransaction();
  43489. copy();
  43490. cut();
  43491. }
  43492. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43493. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43494. {
  43495. newTransaction();
  43496. paste();
  43497. }
  43498. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43499. {
  43500. newTransaction();
  43501. doUndoRedo (false);
  43502. }
  43503. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43504. {
  43505. newTransaction();
  43506. doUndoRedo (true);
  43507. }
  43508. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43509. {
  43510. newTransaction();
  43511. moveCursorTo (getTotalNumChars(), false);
  43512. moveCursorTo (0, true);
  43513. }
  43514. else if (key == KeyPress::returnKey)
  43515. {
  43516. newTransaction();
  43517. if (returnKeyStartsNewLine)
  43518. insertTextAtCaret ("\n");
  43519. else
  43520. returnPressed();
  43521. }
  43522. else if (key.isKeyCode (KeyPress::escapeKey))
  43523. {
  43524. newTransaction();
  43525. moveCursorTo (getCaretPosition(), false);
  43526. escapePressed();
  43527. }
  43528. else if (key.getTextCharacter() >= ' '
  43529. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43530. {
  43531. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43532. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43533. }
  43534. else
  43535. {
  43536. return false;
  43537. }
  43538. return true;
  43539. }
  43540. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43541. {
  43542. if (! isKeyDown)
  43543. return false;
  43544. #if JUCE_WINDOWS
  43545. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43546. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43547. #endif
  43548. // (overridden to avoid forwarding key events to the parent)
  43549. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43550. }
  43551. const int baseMenuItemID = 0x7fff0000;
  43552. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43553. {
  43554. const bool writable = ! isReadOnly();
  43555. if (passwordCharacter == 0)
  43556. {
  43557. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43558. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43559. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43560. }
  43561. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43562. m.addSeparator();
  43563. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43564. m.addSeparator();
  43565. if (getUndoManager() != 0)
  43566. {
  43567. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43568. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43569. }
  43570. }
  43571. void TextEditor::performPopupMenuAction (const int menuItemID)
  43572. {
  43573. switch (menuItemID)
  43574. {
  43575. case baseMenuItemID + 1:
  43576. copy();
  43577. cut();
  43578. break;
  43579. case baseMenuItemID + 2:
  43580. copy();
  43581. break;
  43582. case baseMenuItemID + 3:
  43583. paste();
  43584. break;
  43585. case baseMenuItemID + 4:
  43586. cut();
  43587. break;
  43588. case baseMenuItemID + 5:
  43589. moveCursorTo (getTotalNumChars(), false);
  43590. moveCursorTo (0, true);
  43591. break;
  43592. case baseMenuItemID + 6:
  43593. doUndoRedo (false);
  43594. break;
  43595. case baseMenuItemID + 7:
  43596. doUndoRedo (true);
  43597. break;
  43598. default:
  43599. break;
  43600. }
  43601. }
  43602. void TextEditor::focusGained (FocusChangeType)
  43603. {
  43604. newTransaction();
  43605. caretFlashState = true;
  43606. if (selectAllTextWhenFocused)
  43607. {
  43608. moveCursorTo (0, false);
  43609. moveCursorTo (getTotalNumChars(), true);
  43610. }
  43611. repaint();
  43612. if (caretVisible)
  43613. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43614. ComponentPeer* const peer = getPeer();
  43615. if (peer != 0 && ! isReadOnly())
  43616. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43617. }
  43618. void TextEditor::focusLost (FocusChangeType)
  43619. {
  43620. newTransaction();
  43621. wasFocused = false;
  43622. textHolder->stopTimer();
  43623. caretFlashState = false;
  43624. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43625. repaint();
  43626. }
  43627. void TextEditor::resized()
  43628. {
  43629. viewport->setBoundsInset (borderSize);
  43630. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43631. updateTextHolderSize();
  43632. if (! isMultiLine())
  43633. {
  43634. scrollToMakeSureCursorIsVisible();
  43635. }
  43636. else
  43637. {
  43638. updateCaretPosition();
  43639. }
  43640. }
  43641. void TextEditor::handleCommandMessage (const int commandId)
  43642. {
  43643. Component::BailOutChecker checker (this);
  43644. switch (commandId)
  43645. {
  43646. case TextEditorDefs::textChangeMessageId:
  43647. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43648. break;
  43649. case TextEditorDefs::returnKeyMessageId:
  43650. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43651. break;
  43652. case TextEditorDefs::escapeKeyMessageId:
  43653. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43654. break;
  43655. case TextEditorDefs::focusLossMessageId:
  43656. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43657. break;
  43658. default:
  43659. jassertfalse;
  43660. break;
  43661. }
  43662. }
  43663. void TextEditor::enablementChanged()
  43664. {
  43665. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43666. : MouseCursor::IBeamCursor);
  43667. repaint();
  43668. }
  43669. UndoManager* TextEditor::getUndoManager() throw()
  43670. {
  43671. return isReadOnly() ? 0 : &undoManager;
  43672. }
  43673. void TextEditor::clearInternal (UndoManager* const um)
  43674. {
  43675. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43676. }
  43677. void TextEditor::insert (const String& text,
  43678. const int insertIndex,
  43679. const Font& font,
  43680. const Colour& colour,
  43681. UndoManager* const um,
  43682. const int caretPositionToMoveTo)
  43683. {
  43684. if (text.isNotEmpty())
  43685. {
  43686. if (um != 0)
  43687. {
  43688. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43689. newTransaction();
  43690. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43691. caretPosition, caretPositionToMoveTo));
  43692. }
  43693. else
  43694. {
  43695. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43696. // a line gets moved due to word wrap
  43697. int index = 0;
  43698. int nextIndex = 0;
  43699. for (int i = 0; i < sections.size(); ++i)
  43700. {
  43701. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43702. if (insertIndex == index)
  43703. {
  43704. sections.insert (i, new UniformTextSection (text,
  43705. font, colour,
  43706. passwordCharacter));
  43707. break;
  43708. }
  43709. else if (insertIndex > index && insertIndex < nextIndex)
  43710. {
  43711. splitSection (i, insertIndex - index);
  43712. sections.insert (i + 1, new UniformTextSection (text,
  43713. font, colour,
  43714. passwordCharacter));
  43715. break;
  43716. }
  43717. index = nextIndex;
  43718. }
  43719. if (nextIndex == insertIndex)
  43720. sections.add (new UniformTextSection (text,
  43721. font, colour,
  43722. passwordCharacter));
  43723. coalesceSimilarSections();
  43724. totalNumChars = -1;
  43725. valueTextNeedsUpdating = true;
  43726. moveCursorTo (caretPositionToMoveTo, false);
  43727. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43728. }
  43729. }
  43730. }
  43731. void TextEditor::reinsert (const int insertIndex,
  43732. const Array <UniformTextSection*>& sectionsToInsert)
  43733. {
  43734. int index = 0;
  43735. int nextIndex = 0;
  43736. for (int i = 0; i < sections.size(); ++i)
  43737. {
  43738. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43739. if (insertIndex == index)
  43740. {
  43741. for (int j = sectionsToInsert.size(); --j >= 0;)
  43742. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43743. break;
  43744. }
  43745. else if (insertIndex > index && insertIndex < nextIndex)
  43746. {
  43747. splitSection (i, insertIndex - index);
  43748. for (int j = sectionsToInsert.size(); --j >= 0;)
  43749. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43750. break;
  43751. }
  43752. index = nextIndex;
  43753. }
  43754. if (nextIndex == insertIndex)
  43755. {
  43756. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43757. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43758. }
  43759. coalesceSimilarSections();
  43760. totalNumChars = -1;
  43761. valueTextNeedsUpdating = true;
  43762. }
  43763. void TextEditor::remove (const Range<int>& range,
  43764. UndoManager* const um,
  43765. const int caretPositionToMoveTo)
  43766. {
  43767. if (! range.isEmpty())
  43768. {
  43769. int index = 0;
  43770. for (int i = 0; i < sections.size(); ++i)
  43771. {
  43772. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43773. if (range.getStart() > index && range.getStart() < nextIndex)
  43774. {
  43775. splitSection (i, range.getStart() - index);
  43776. --i;
  43777. }
  43778. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43779. {
  43780. splitSection (i, range.getEnd() - index);
  43781. --i;
  43782. }
  43783. else
  43784. {
  43785. index = nextIndex;
  43786. if (index > range.getEnd())
  43787. break;
  43788. }
  43789. }
  43790. index = 0;
  43791. if (um != 0)
  43792. {
  43793. Array <UniformTextSection*> removedSections;
  43794. for (int i = 0; i < sections.size(); ++i)
  43795. {
  43796. if (range.getEnd() <= range.getStart())
  43797. break;
  43798. UniformTextSection* const section = sections.getUnchecked (i);
  43799. const int nextIndex = index + section->getTotalLength();
  43800. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43801. removedSections.add (new UniformTextSection (*section));
  43802. index = nextIndex;
  43803. }
  43804. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43805. newTransaction();
  43806. um->perform (new RemoveAction (*this, range, caretPosition,
  43807. caretPositionToMoveTo, removedSections));
  43808. }
  43809. else
  43810. {
  43811. Range<int> remainingRange (range);
  43812. for (int i = 0; i < sections.size(); ++i)
  43813. {
  43814. UniformTextSection* const section = sections.getUnchecked (i);
  43815. const int nextIndex = index + section->getTotalLength();
  43816. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43817. {
  43818. sections.remove(i);
  43819. section->clear();
  43820. delete section;
  43821. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43822. if (remainingRange.isEmpty())
  43823. break;
  43824. --i;
  43825. }
  43826. else
  43827. {
  43828. index = nextIndex;
  43829. }
  43830. }
  43831. coalesceSimilarSections();
  43832. totalNumChars = -1;
  43833. valueTextNeedsUpdating = true;
  43834. moveCursorTo (caretPositionToMoveTo, false);
  43835. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43836. }
  43837. }
  43838. }
  43839. const String TextEditor::getText() const
  43840. {
  43841. String t;
  43842. t.preallocateStorage (getTotalNumChars());
  43843. String::Concatenator concatenator (t);
  43844. for (int i = 0; i < sections.size(); ++i)
  43845. sections.getUnchecked (i)->appendAllText (concatenator);
  43846. return t;
  43847. }
  43848. const String TextEditor::getTextInRange (const Range<int>& range) const
  43849. {
  43850. String t;
  43851. if (! range.isEmpty())
  43852. {
  43853. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43854. String::Concatenator concatenator (t);
  43855. int index = 0;
  43856. for (int i = 0; i < sections.size(); ++i)
  43857. {
  43858. const UniformTextSection* const s = sections.getUnchecked (i);
  43859. const int nextIndex = index + s->getTotalLength();
  43860. if (range.getStart() < nextIndex)
  43861. {
  43862. if (range.getEnd() <= index)
  43863. break;
  43864. s->appendSubstring (concatenator, range - index);
  43865. }
  43866. index = nextIndex;
  43867. }
  43868. }
  43869. return t;
  43870. }
  43871. const String TextEditor::getHighlightedText() const
  43872. {
  43873. return getTextInRange (selection);
  43874. }
  43875. int TextEditor::getTotalNumChars() const
  43876. {
  43877. if (totalNumChars < 0)
  43878. {
  43879. totalNumChars = 0;
  43880. for (int i = sections.size(); --i >= 0;)
  43881. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43882. }
  43883. return totalNumChars;
  43884. }
  43885. bool TextEditor::isEmpty() const
  43886. {
  43887. return getTotalNumChars() == 0;
  43888. }
  43889. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43890. {
  43891. const float wordWrapWidth = getWordWrapWidth();
  43892. if (wordWrapWidth > 0 && sections.size() > 0)
  43893. {
  43894. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43895. i.getCharPosition (index, cx, cy, lineHeight);
  43896. }
  43897. else
  43898. {
  43899. cx = cy = 0;
  43900. lineHeight = currentFont.getHeight();
  43901. }
  43902. }
  43903. int TextEditor::indexAtPosition (const float x, const float y)
  43904. {
  43905. const float wordWrapWidth = getWordWrapWidth();
  43906. if (wordWrapWidth > 0)
  43907. {
  43908. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43909. while (i.next())
  43910. {
  43911. if (i.lineY + i.lineHeight > y)
  43912. {
  43913. if (i.lineY > y)
  43914. return jmax (0, i.indexInText - 1);
  43915. if (i.atomX >= x)
  43916. return i.indexInText;
  43917. if (x < i.atomRight)
  43918. return i.xToIndex (x);
  43919. }
  43920. }
  43921. }
  43922. return getTotalNumChars();
  43923. }
  43924. int TextEditor::findWordBreakAfter (const int position) const
  43925. {
  43926. const String t (getTextInRange (Range<int> (position, position + 512)));
  43927. const int totalLength = t.length();
  43928. int i = 0;
  43929. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43930. ++i;
  43931. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  43932. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  43933. ++i;
  43934. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43935. ++i;
  43936. return position + i;
  43937. }
  43938. int TextEditor::findWordBreakBefore (const int position) const
  43939. {
  43940. if (position <= 0)
  43941. return 0;
  43942. const int startOfBuffer = jmax (0, position - 512);
  43943. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43944. int i = position - startOfBuffer;
  43945. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43946. --i;
  43947. if (i > 0)
  43948. {
  43949. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  43950. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  43951. --i;
  43952. }
  43953. jassert (startOfBuffer + i >= 0);
  43954. return startOfBuffer + i;
  43955. }
  43956. void TextEditor::splitSection (const int sectionIndex,
  43957. const int charToSplitAt)
  43958. {
  43959. jassert (sections[sectionIndex] != 0);
  43960. sections.insert (sectionIndex + 1,
  43961. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43962. }
  43963. void TextEditor::coalesceSimilarSections()
  43964. {
  43965. for (int i = 0; i < sections.size() - 1; ++i)
  43966. {
  43967. UniformTextSection* const s1 = sections.getUnchecked (i);
  43968. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43969. if (s1->font == s2->font
  43970. && s1->colour == s2->colour)
  43971. {
  43972. s1->append (*s2, passwordCharacter);
  43973. sections.remove (i + 1);
  43974. delete s2;
  43975. --i;
  43976. }
  43977. }
  43978. }
  43979. END_JUCE_NAMESPACE
  43980. /*** End of inlined file: juce_TextEditor.cpp ***/
  43981. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43982. BEGIN_JUCE_NAMESPACE
  43983. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43984. class ToolbarSpacerComp : public ToolbarItemComponent
  43985. {
  43986. public:
  43987. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43988. : ToolbarItemComponent (itemId_, String::empty, false),
  43989. fixedSize (fixedSize_),
  43990. drawBar (drawBar_)
  43991. {
  43992. }
  43993. ~ToolbarSpacerComp()
  43994. {
  43995. }
  43996. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43997. int& preferredSize, int& minSize, int& maxSize)
  43998. {
  43999. if (fixedSize <= 0)
  44000. {
  44001. preferredSize = toolbarThickness * 2;
  44002. minSize = 4;
  44003. maxSize = 32768;
  44004. }
  44005. else
  44006. {
  44007. maxSize = roundToInt (toolbarThickness * fixedSize);
  44008. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44009. preferredSize = maxSize;
  44010. if (getEditingMode() == editableOnPalette)
  44011. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44012. }
  44013. return true;
  44014. }
  44015. void paintButtonArea (Graphics&, int, int, bool, bool)
  44016. {
  44017. }
  44018. void contentAreaChanged (const Rectangle<int>&)
  44019. {
  44020. }
  44021. int getResizeOrder() const throw()
  44022. {
  44023. return fixedSize <= 0 ? 0 : 1;
  44024. }
  44025. void paint (Graphics& g)
  44026. {
  44027. const int w = getWidth();
  44028. const int h = getHeight();
  44029. if (drawBar)
  44030. {
  44031. g.setColour (findColour (Toolbar::separatorColourId, true));
  44032. const float thickness = 0.2f;
  44033. if (isToolbarVertical())
  44034. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44035. else
  44036. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44037. }
  44038. if (getEditingMode() != normalMode && ! drawBar)
  44039. {
  44040. g.setColour (findColour (Toolbar::separatorColourId, true));
  44041. const int indentX = jmin (2, (w - 3) / 2);
  44042. const int indentY = jmin (2, (h - 3) / 2);
  44043. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44044. if (fixedSize <= 0)
  44045. {
  44046. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44047. if (isToolbarVertical())
  44048. {
  44049. x1 = w * 0.5f;
  44050. y1 = h * 0.4f;
  44051. x2 = x1;
  44052. y2 = indentX * 2.0f;
  44053. x3 = x1;
  44054. y3 = h * 0.6f;
  44055. x4 = x1;
  44056. y4 = h - y2;
  44057. hw = w * 0.15f;
  44058. hl = w * 0.2f;
  44059. }
  44060. else
  44061. {
  44062. x1 = w * 0.4f;
  44063. y1 = h * 0.5f;
  44064. x2 = indentX * 2.0f;
  44065. y2 = y1;
  44066. x3 = w * 0.6f;
  44067. y3 = y1;
  44068. x4 = w - x2;
  44069. y4 = y1;
  44070. hw = h * 0.15f;
  44071. hl = h * 0.2f;
  44072. }
  44073. Path p;
  44074. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44075. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44076. g.fillPath (p);
  44077. }
  44078. }
  44079. }
  44080. private:
  44081. const float fixedSize;
  44082. const bool drawBar;
  44083. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarSpacerComp);
  44084. };
  44085. class Toolbar::MissingItemsComponent : public PopupMenu::CustomComponent
  44086. {
  44087. public:
  44088. MissingItemsComponent (Toolbar& owner_, const int height_)
  44089. : PopupMenu::CustomComponent (true),
  44090. owner (&owner_),
  44091. height (height_)
  44092. {
  44093. for (int i = owner_.items.size(); --i >= 0;)
  44094. {
  44095. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44096. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44097. {
  44098. oldIndexes.insert (0, i);
  44099. addAndMakeVisible (tc, 0);
  44100. }
  44101. }
  44102. layout (400);
  44103. }
  44104. ~MissingItemsComponent()
  44105. {
  44106. if (owner != 0)
  44107. {
  44108. for (int i = 0; i < getNumChildComponents(); ++i)
  44109. {
  44110. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44111. if (tc != 0)
  44112. {
  44113. tc->setVisible (false);
  44114. const int index = oldIndexes.remove (i);
  44115. owner->addChildComponent (tc, index);
  44116. --i;
  44117. }
  44118. }
  44119. owner->resized();
  44120. }
  44121. }
  44122. void layout (const int preferredWidth)
  44123. {
  44124. const int indent = 8;
  44125. int x = indent;
  44126. int y = indent;
  44127. int maxX = 0;
  44128. for (int i = 0; i < getNumChildComponents(); ++i)
  44129. {
  44130. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44131. if (tc != 0)
  44132. {
  44133. int preferredSize = 1, minSize = 1, maxSize = 1;
  44134. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44135. {
  44136. if (x + preferredSize > preferredWidth && x > indent)
  44137. {
  44138. x = indent;
  44139. y += height;
  44140. }
  44141. tc->setBounds (x, y, preferredSize, height);
  44142. x += preferredSize;
  44143. maxX = jmax (maxX, x);
  44144. }
  44145. }
  44146. }
  44147. setSize (maxX + 8, y + height + 8);
  44148. }
  44149. void getIdealSize (int& idealWidth, int& idealHeight)
  44150. {
  44151. idealWidth = getWidth();
  44152. idealHeight = getHeight();
  44153. }
  44154. private:
  44155. Component::SafePointer<Toolbar> owner;
  44156. const int height;
  44157. Array <int> oldIndexes;
  44158. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingItemsComponent);
  44159. };
  44160. Toolbar::Toolbar()
  44161. : vertical (false),
  44162. isEditingActive (false),
  44163. toolbarStyle (Toolbar::iconsOnly)
  44164. {
  44165. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44166. missingItemsButton->setAlwaysOnTop (true);
  44167. missingItemsButton->addListener (this);
  44168. }
  44169. Toolbar::~Toolbar()
  44170. {
  44171. items.clear();
  44172. }
  44173. void Toolbar::setVertical (const bool shouldBeVertical)
  44174. {
  44175. if (vertical != shouldBeVertical)
  44176. {
  44177. vertical = shouldBeVertical;
  44178. resized();
  44179. }
  44180. }
  44181. void Toolbar::clear()
  44182. {
  44183. items.clear();
  44184. resized();
  44185. }
  44186. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44187. {
  44188. if (itemId == ToolbarItemFactory::separatorBarId)
  44189. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44190. else if (itemId == ToolbarItemFactory::spacerId)
  44191. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44192. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44193. return new ToolbarSpacerComp (itemId, 0, false);
  44194. return factory.createItem (itemId);
  44195. }
  44196. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44197. const int itemId,
  44198. const int insertIndex)
  44199. {
  44200. // An ID can't be zero - this might indicate a mistake somewhere?
  44201. jassert (itemId != 0);
  44202. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44203. if (tc != 0)
  44204. {
  44205. #if JUCE_DEBUG
  44206. Array <int> allowedIds;
  44207. factory.getAllToolbarItemIds (allowedIds);
  44208. // If your factory can create an item for a given ID, it must also return
  44209. // that ID from its getAllToolbarItemIds() method!
  44210. jassert (allowedIds.contains (itemId));
  44211. #endif
  44212. items.insert (insertIndex, tc);
  44213. addAndMakeVisible (tc, insertIndex);
  44214. }
  44215. }
  44216. void Toolbar::addItem (ToolbarItemFactory& factory,
  44217. const int itemId,
  44218. const int insertIndex)
  44219. {
  44220. addItemInternal (factory, itemId, insertIndex);
  44221. resized();
  44222. }
  44223. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44224. {
  44225. Array <int> ids;
  44226. factoryToUse.getDefaultItemSet (ids);
  44227. clear();
  44228. for (int i = 0; i < ids.size(); ++i)
  44229. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44230. resized();
  44231. }
  44232. void Toolbar::removeToolbarItem (const int itemIndex)
  44233. {
  44234. items.remove (itemIndex);
  44235. resized();
  44236. }
  44237. int Toolbar::getNumItems() const throw()
  44238. {
  44239. return items.size();
  44240. }
  44241. int Toolbar::getItemId (const int itemIndex) const throw()
  44242. {
  44243. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44244. return tc != 0 ? tc->getItemId() : 0;
  44245. }
  44246. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44247. {
  44248. return items [itemIndex];
  44249. }
  44250. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44251. {
  44252. for (;;)
  44253. {
  44254. index += delta;
  44255. ToolbarItemComponent* const tc = getItemComponent (index);
  44256. if (tc == 0)
  44257. break;
  44258. if (tc->isActive)
  44259. return tc;
  44260. }
  44261. return 0;
  44262. }
  44263. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44264. {
  44265. if (toolbarStyle != newStyle)
  44266. {
  44267. toolbarStyle = newStyle;
  44268. updateAllItemPositions (false);
  44269. }
  44270. }
  44271. const String Toolbar::toString() const
  44272. {
  44273. String s ("TB:");
  44274. for (int i = 0; i < getNumItems(); ++i)
  44275. s << getItemId(i) << ' ';
  44276. return s.trimEnd();
  44277. }
  44278. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44279. const String& savedVersion)
  44280. {
  44281. if (! savedVersion.startsWith ("TB:"))
  44282. return false;
  44283. StringArray tokens;
  44284. tokens.addTokens (savedVersion.substring (3), false);
  44285. clear();
  44286. for (int i = 0; i < tokens.size(); ++i)
  44287. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44288. resized();
  44289. return true;
  44290. }
  44291. void Toolbar::paint (Graphics& g)
  44292. {
  44293. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44294. }
  44295. int Toolbar::getThickness() const throw()
  44296. {
  44297. return vertical ? getWidth() : getHeight();
  44298. }
  44299. int Toolbar::getLength() const throw()
  44300. {
  44301. return vertical ? getHeight() : getWidth();
  44302. }
  44303. void Toolbar::setEditingActive (const bool active)
  44304. {
  44305. if (isEditingActive != active)
  44306. {
  44307. isEditingActive = active;
  44308. updateAllItemPositions (false);
  44309. }
  44310. }
  44311. void Toolbar::resized()
  44312. {
  44313. updateAllItemPositions (false);
  44314. }
  44315. void Toolbar::updateAllItemPositions (const bool animate)
  44316. {
  44317. if (getWidth() > 0 && getHeight() > 0)
  44318. {
  44319. StretchableObjectResizer resizer;
  44320. int i;
  44321. for (i = 0; i < items.size(); ++i)
  44322. {
  44323. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44324. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44325. : ToolbarItemComponent::normalMode);
  44326. tc->setStyle (toolbarStyle);
  44327. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44328. int preferredSize = 1, minSize = 1, maxSize = 1;
  44329. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44330. preferredSize, minSize, maxSize))
  44331. {
  44332. tc->isActive = true;
  44333. resizer.addItem (preferredSize, minSize, maxSize,
  44334. spacer != 0 ? spacer->getResizeOrder() : 2);
  44335. }
  44336. else
  44337. {
  44338. tc->isActive = false;
  44339. tc->setVisible (false);
  44340. }
  44341. }
  44342. resizer.resizeToFit (getLength());
  44343. int totalLength = 0;
  44344. for (i = 0; i < resizer.getNumItems(); ++i)
  44345. totalLength += (int) resizer.getItemSize (i);
  44346. const bool itemsOffTheEnd = totalLength > getLength();
  44347. const int extrasButtonSize = getThickness() / 2;
  44348. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44349. missingItemsButton->setVisible (itemsOffTheEnd);
  44350. missingItemsButton->setEnabled (! isEditingActive);
  44351. if (vertical)
  44352. missingItemsButton->setCentrePosition (getWidth() / 2,
  44353. getHeight() - 4 - extrasButtonSize / 2);
  44354. else
  44355. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44356. getHeight() / 2);
  44357. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44358. : missingItemsButton->getX()) - 4
  44359. : getLength();
  44360. int pos = 0, activeIndex = 0;
  44361. for (i = 0; i < items.size(); ++i)
  44362. {
  44363. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44364. if (tc->isActive)
  44365. {
  44366. const int size = (int) resizer.getItemSize (activeIndex++);
  44367. Rectangle<int> newBounds;
  44368. if (vertical)
  44369. newBounds.setBounds (0, pos, getWidth(), size);
  44370. else
  44371. newBounds.setBounds (pos, 0, size, getHeight());
  44372. if (animate)
  44373. {
  44374. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44375. }
  44376. else
  44377. {
  44378. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44379. tc->setBounds (newBounds);
  44380. }
  44381. pos += size;
  44382. tc->setVisible (pos <= maxLength
  44383. && ((! tc->isBeingDragged)
  44384. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44385. }
  44386. }
  44387. }
  44388. }
  44389. void Toolbar::buttonClicked (Button*)
  44390. {
  44391. jassert (missingItemsButton->isShowing());
  44392. if (missingItemsButton->isShowing())
  44393. {
  44394. PopupMenu m;
  44395. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44396. m.showAt (missingItemsButton);
  44397. }
  44398. }
  44399. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44400. Component* /*sourceComponent*/)
  44401. {
  44402. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44403. }
  44404. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44405. {
  44406. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44407. if (tc != 0)
  44408. {
  44409. if (! items.contains (tc))
  44410. {
  44411. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44412. {
  44413. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44414. if (palette != 0)
  44415. palette->replaceComponent (tc);
  44416. }
  44417. else
  44418. {
  44419. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44420. }
  44421. items.add (tc);
  44422. addChildComponent (tc);
  44423. updateAllItemPositions (true);
  44424. }
  44425. for (int i = getNumItems(); --i >= 0;)
  44426. {
  44427. const int currentIndex = items.indexOf (tc);
  44428. int newIndex = currentIndex;
  44429. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44430. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44431. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44432. .getComponentDestination (getChildComponent (newIndex)));
  44433. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44434. if (prev != 0)
  44435. {
  44436. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44437. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44438. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44439. {
  44440. newIndex = getIndexOfChildComponent (prev);
  44441. }
  44442. }
  44443. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44444. if (next != 0)
  44445. {
  44446. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44447. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44448. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44449. {
  44450. newIndex = getIndexOfChildComponent (next) + 1;
  44451. }
  44452. }
  44453. if (newIndex == currentIndex)
  44454. break;
  44455. items.removeObject (tc, false);
  44456. removeChildComponent (tc);
  44457. addChildComponent (tc, newIndex);
  44458. items.insert (newIndex, tc);
  44459. updateAllItemPositions (true);
  44460. }
  44461. }
  44462. }
  44463. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44464. {
  44465. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44466. if (tc != 0 && isParentOf (tc))
  44467. {
  44468. items.removeObject (tc, false);
  44469. removeChildComponent (tc);
  44470. updateAllItemPositions (true);
  44471. }
  44472. }
  44473. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44474. {
  44475. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44476. if (tc != 0)
  44477. tc->setState (Button::buttonNormal);
  44478. }
  44479. void Toolbar::mouseDown (const MouseEvent&)
  44480. {
  44481. }
  44482. class ToolbarCustomisationDialog : public DialogWindow
  44483. {
  44484. public:
  44485. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44486. Toolbar* const toolbar_,
  44487. const int optionFlags)
  44488. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44489. toolbar (toolbar_)
  44490. {
  44491. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44492. setResizable (true, true);
  44493. setResizeLimits (400, 300, 1500, 1000);
  44494. positionNearBar();
  44495. }
  44496. ~ToolbarCustomisationDialog()
  44497. {
  44498. setContentComponent (0, true);
  44499. }
  44500. void closeButtonPressed()
  44501. {
  44502. setVisible (false);
  44503. }
  44504. bool canModalEventBeSentToComponent (const Component* comp)
  44505. {
  44506. return toolbar->isParentOf (comp);
  44507. }
  44508. void positionNearBar()
  44509. {
  44510. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44511. const int tbx = toolbar->getScreenX();
  44512. const int tby = toolbar->getScreenY();
  44513. const int gap = 8;
  44514. int x, y;
  44515. if (toolbar->isVertical())
  44516. {
  44517. y = tby;
  44518. if (tbx > screenSize.getCentreX())
  44519. x = tbx - getWidth() - gap;
  44520. else
  44521. x = tbx + toolbar->getWidth() + gap;
  44522. }
  44523. else
  44524. {
  44525. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44526. if (tby > screenSize.getCentreY())
  44527. y = tby - getHeight() - gap;
  44528. else
  44529. y = tby + toolbar->getHeight() + gap;
  44530. }
  44531. setTopLeftPosition (x, y);
  44532. }
  44533. private:
  44534. Toolbar* const toolbar;
  44535. class CustomiserPanel : public Component,
  44536. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44537. private ButtonListener
  44538. {
  44539. public:
  44540. CustomiserPanel (ToolbarItemFactory& factory_,
  44541. Toolbar* const toolbar_,
  44542. const int optionFlags)
  44543. : factory (factory_),
  44544. toolbar (toolbar_),
  44545. palette (factory_, toolbar_),
  44546. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44547. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44548. defaultButton (TRANS ("Restore to default set of items"))
  44549. {
  44550. addAndMakeVisible (&palette);
  44551. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44552. | Toolbar::allowIconsWithTextChoice
  44553. | Toolbar::allowTextOnlyChoice)) != 0)
  44554. {
  44555. addAndMakeVisible (&styleBox);
  44556. styleBox.setEditableText (false);
  44557. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44558. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44559. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44560. int selectedStyle = 0;
  44561. switch (toolbar_->getStyle())
  44562. {
  44563. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44564. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44565. case Toolbar::textOnly: selectedStyle = 3; break;
  44566. }
  44567. styleBox.setSelectedId (selectedStyle);
  44568. styleBox.addListener (this);
  44569. }
  44570. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44571. {
  44572. addAndMakeVisible (&defaultButton);
  44573. defaultButton.addListener (this);
  44574. }
  44575. addAndMakeVisible (&instructions);
  44576. instructions.setFont (Font (13.0f));
  44577. setSize (500, 300);
  44578. }
  44579. void comboBoxChanged (ComboBox*)
  44580. {
  44581. switch (styleBox.getSelectedId())
  44582. {
  44583. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44584. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44585. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44586. }
  44587. palette.resized(); // to make it update the styles
  44588. }
  44589. void buttonClicked (Button*)
  44590. {
  44591. toolbar->addDefaultItems (factory);
  44592. }
  44593. void paint (Graphics& g)
  44594. {
  44595. Colour background;
  44596. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44597. if (dw != 0)
  44598. background = dw->getBackgroundColour();
  44599. g.setColour (background.contrasting().withAlpha (0.3f));
  44600. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44601. }
  44602. void resized()
  44603. {
  44604. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44605. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44606. defaultButton.changeWidthToFitText (22);
  44607. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44608. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44609. }
  44610. private:
  44611. ToolbarItemFactory& factory;
  44612. Toolbar* const toolbar;
  44613. ToolbarItemPalette palette;
  44614. Label instructions;
  44615. ComboBox styleBox;
  44616. TextButton defaultButton;
  44617. };
  44618. };
  44619. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44620. {
  44621. setEditingActive (true);
  44622. #if JUCE_DEBUG
  44623. WeakReference<Component> checker (this);
  44624. #endif
  44625. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44626. dw.runModalLoop();
  44627. #if JUCE_DEBUG
  44628. jassert (checker != 0); // Don't delete the toolbar while it's being customised!
  44629. #endif
  44630. setEditingActive (false);
  44631. }
  44632. END_JUCE_NAMESPACE
  44633. /*** End of inlined file: juce_Toolbar.cpp ***/
  44634. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44635. BEGIN_JUCE_NAMESPACE
  44636. ToolbarItemFactory::ToolbarItemFactory()
  44637. {
  44638. }
  44639. ToolbarItemFactory::~ToolbarItemFactory()
  44640. {
  44641. }
  44642. class ItemDragAndDropOverlayComponent : public Component
  44643. {
  44644. public:
  44645. ItemDragAndDropOverlayComponent()
  44646. : isDragging (false)
  44647. {
  44648. setAlwaysOnTop (true);
  44649. setRepaintsOnMouseActivity (true);
  44650. setMouseCursor (MouseCursor::DraggingHandCursor);
  44651. }
  44652. void paint (Graphics& g)
  44653. {
  44654. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44655. if (isMouseOverOrDragging()
  44656. && tc != 0
  44657. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44658. {
  44659. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44660. g.drawRect (0, 0, getWidth(), getHeight(),
  44661. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44662. }
  44663. }
  44664. void mouseDown (const MouseEvent& e)
  44665. {
  44666. isDragging = false;
  44667. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44668. if (tc != 0)
  44669. {
  44670. tc->dragOffsetX = e.x;
  44671. tc->dragOffsetY = e.y;
  44672. }
  44673. }
  44674. void mouseDrag (const MouseEvent& e)
  44675. {
  44676. if (! (isDragging || e.mouseWasClicked()))
  44677. {
  44678. isDragging = true;
  44679. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44680. if (dnd != 0)
  44681. {
  44682. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44683. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44684. if (tc != 0)
  44685. {
  44686. tc->isBeingDragged = true;
  44687. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44688. tc->setVisible (false);
  44689. }
  44690. }
  44691. }
  44692. }
  44693. void mouseUp (const MouseEvent&)
  44694. {
  44695. isDragging = false;
  44696. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44697. if (tc != 0)
  44698. {
  44699. tc->isBeingDragged = false;
  44700. Toolbar* const tb = tc->getToolbar();
  44701. if (tb != 0)
  44702. tb->updateAllItemPositions (true);
  44703. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44704. delete tc;
  44705. }
  44706. }
  44707. void parentSizeChanged()
  44708. {
  44709. setBounds (0, 0, getParentWidth(), getParentHeight());
  44710. }
  44711. private:
  44712. bool isDragging;
  44713. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
  44714. };
  44715. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44716. const String& labelText,
  44717. const bool isBeingUsedAsAButton_)
  44718. : Button (labelText),
  44719. itemId (itemId_),
  44720. mode (normalMode),
  44721. toolbarStyle (Toolbar::iconsOnly),
  44722. dragOffsetX (0),
  44723. dragOffsetY (0),
  44724. isActive (true),
  44725. isBeingDragged (false),
  44726. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44727. {
  44728. // Your item ID can't be 0!
  44729. jassert (itemId_ != 0);
  44730. }
  44731. ToolbarItemComponent::~ToolbarItemComponent()
  44732. {
  44733. overlayComp = 0;
  44734. }
  44735. Toolbar* ToolbarItemComponent::getToolbar() const
  44736. {
  44737. return dynamic_cast <Toolbar*> (getParentComponent());
  44738. }
  44739. bool ToolbarItemComponent::isToolbarVertical() const
  44740. {
  44741. const Toolbar* const t = getToolbar();
  44742. return t != 0 && t->isVertical();
  44743. }
  44744. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44745. {
  44746. if (toolbarStyle != newStyle)
  44747. {
  44748. toolbarStyle = newStyle;
  44749. repaint();
  44750. resized();
  44751. }
  44752. }
  44753. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44754. {
  44755. if (isBeingUsedAsAButton)
  44756. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44757. over, down, *this);
  44758. if (toolbarStyle != Toolbar::iconsOnly)
  44759. {
  44760. const int indent = contentArea.getX();
  44761. int y = indent;
  44762. int h = getHeight() - indent * 2;
  44763. if (toolbarStyle == Toolbar::iconsWithText)
  44764. {
  44765. y = contentArea.getBottom() + indent / 2;
  44766. h -= contentArea.getHeight();
  44767. }
  44768. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44769. getButtonText(), *this);
  44770. }
  44771. if (! contentArea.isEmpty())
  44772. {
  44773. Graphics::ScopedSaveState ss (g);
  44774. g.reduceClipRegion (contentArea);
  44775. g.setOrigin (contentArea.getX(), contentArea.getY());
  44776. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44777. }
  44778. }
  44779. void ToolbarItemComponent::resized()
  44780. {
  44781. if (toolbarStyle != Toolbar::textOnly)
  44782. {
  44783. const int indent = jmin (proportionOfWidth (0.08f),
  44784. proportionOfHeight (0.08f));
  44785. contentArea = Rectangle<int> (indent, indent,
  44786. getWidth() - indent * 2,
  44787. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44788. : (getHeight() - indent * 2));
  44789. }
  44790. else
  44791. {
  44792. contentArea = Rectangle<int>();
  44793. }
  44794. contentAreaChanged (contentArea);
  44795. }
  44796. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44797. {
  44798. if (mode != newMode)
  44799. {
  44800. mode = newMode;
  44801. repaint();
  44802. if (mode == normalMode)
  44803. {
  44804. overlayComp = 0;
  44805. }
  44806. else if (overlayComp == 0)
  44807. {
  44808. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44809. overlayComp->parentSizeChanged();
  44810. }
  44811. resized();
  44812. }
  44813. }
  44814. END_JUCE_NAMESPACE
  44815. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44816. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44817. BEGIN_JUCE_NAMESPACE
  44818. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44819. Toolbar* const toolbar_)
  44820. : factory (factory_),
  44821. toolbar (toolbar_)
  44822. {
  44823. Component* const itemHolder = new Component();
  44824. viewport.setViewedComponent (itemHolder);
  44825. Array <int> allIds;
  44826. factory.getAllToolbarItemIds (allIds);
  44827. for (int i = 0; i < allIds.size(); ++i)
  44828. addComponent (allIds.getUnchecked (i), -1);
  44829. addAndMakeVisible (&viewport);
  44830. }
  44831. ToolbarItemPalette::~ToolbarItemPalette()
  44832. {
  44833. }
  44834. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  44835. {
  44836. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  44837. jassert (tc != 0);
  44838. if (tc != 0)
  44839. {
  44840. items.insert (index, tc);
  44841. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  44842. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44843. }
  44844. }
  44845. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44846. {
  44847. const int index = items.indexOf (comp);
  44848. jassert (index >= 0);
  44849. items.removeObject (comp, false);
  44850. addComponent (comp->getItemId(), index);
  44851. resized();
  44852. }
  44853. void ToolbarItemPalette::resized()
  44854. {
  44855. viewport.setBoundsInset (BorderSize (1));
  44856. Component* const itemHolder = viewport.getViewedComponent();
  44857. const int indent = 8;
  44858. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  44859. const int height = toolbar->getThickness();
  44860. int x = indent;
  44861. int y = indent;
  44862. int maxX = 0;
  44863. for (int i = 0; i < items.size(); ++i)
  44864. {
  44865. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44866. tc->setStyle (toolbar->getStyle());
  44867. int preferredSize = 1, minSize = 1, maxSize = 1;
  44868. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44869. {
  44870. if (x + preferredSize > preferredWidth && x > indent)
  44871. {
  44872. x = indent;
  44873. y += height;
  44874. }
  44875. tc->setBounds (x, y, preferredSize, height);
  44876. x += preferredSize + 8;
  44877. maxX = jmax (maxX, x);
  44878. }
  44879. }
  44880. itemHolder->setSize (maxX, y + height + 8);
  44881. }
  44882. END_JUCE_NAMESPACE
  44883. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44884. /*** Start of inlined file: juce_TreeView.cpp ***/
  44885. BEGIN_JUCE_NAMESPACE
  44886. class TreeViewContentComponent : public Component,
  44887. public TooltipClient
  44888. {
  44889. public:
  44890. TreeViewContentComponent (TreeView& owner_)
  44891. : owner (owner_),
  44892. buttonUnderMouse (0),
  44893. isDragging (false)
  44894. {
  44895. }
  44896. void mouseDown (const MouseEvent& e)
  44897. {
  44898. updateButtonUnderMouse (e);
  44899. isDragging = false;
  44900. needSelectionOnMouseUp = false;
  44901. Rectangle<int> pos;
  44902. TreeViewItem* const item = findItemAt (e.y, pos);
  44903. if (item == 0)
  44904. return;
  44905. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44906. // as selection clicks)
  44907. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44908. {
  44909. if (e.x >= pos.getX() - owner.getIndentSize())
  44910. item->setOpen (! item->isOpen());
  44911. // (clicks to the left of an open/close button are ignored)
  44912. }
  44913. else
  44914. {
  44915. // mouse-down inside the body of the item..
  44916. if (! owner.isMultiSelectEnabled())
  44917. item->setSelected (true, true);
  44918. else if (item->isSelected())
  44919. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44920. else
  44921. selectBasedOnModifiers (item, e.mods);
  44922. if (e.x >= pos.getX())
  44923. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44924. }
  44925. }
  44926. void mouseUp (const MouseEvent& e)
  44927. {
  44928. updateButtonUnderMouse (e);
  44929. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44930. {
  44931. Rectangle<int> pos;
  44932. TreeViewItem* const item = findItemAt (e.y, pos);
  44933. if (item != 0)
  44934. selectBasedOnModifiers (item, e.mods);
  44935. }
  44936. }
  44937. void mouseDoubleClick (const MouseEvent& e)
  44938. {
  44939. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44940. {
  44941. Rectangle<int> pos;
  44942. TreeViewItem* const item = findItemAt (e.y, pos);
  44943. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44944. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44945. }
  44946. }
  44947. void mouseDrag (const MouseEvent& e)
  44948. {
  44949. if (isEnabled()
  44950. && ! (isDragging || e.mouseWasClicked()
  44951. || e.getDistanceFromDragStart() < 5
  44952. || e.mods.isPopupMenu()))
  44953. {
  44954. isDragging = true;
  44955. Rectangle<int> pos;
  44956. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44957. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44958. {
  44959. const String dragDescription (item->getDragSourceDescription());
  44960. if (dragDescription.isNotEmpty())
  44961. {
  44962. DragAndDropContainer* const dragContainer
  44963. = DragAndDropContainer::findParentDragContainerFor (this);
  44964. if (dragContainer != 0)
  44965. {
  44966. pos.setSize (pos.getWidth(), item->itemHeight);
  44967. Image dragImage (Component::createComponentSnapshot (pos, true));
  44968. dragImage.multiplyAllAlphas (0.6f);
  44969. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44970. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44971. }
  44972. else
  44973. {
  44974. // to be able to do a drag-and-drop operation, the treeview needs to
  44975. // be inside a component which is also a DragAndDropContainer.
  44976. jassertfalse;
  44977. }
  44978. }
  44979. }
  44980. }
  44981. }
  44982. void mouseMove (const MouseEvent& e)
  44983. {
  44984. updateButtonUnderMouse (e);
  44985. }
  44986. void mouseExit (const MouseEvent& e)
  44987. {
  44988. updateButtonUnderMouse (e);
  44989. }
  44990. void paint (Graphics& g)
  44991. {
  44992. if (owner.rootItem != 0)
  44993. {
  44994. owner.handleAsyncUpdate();
  44995. if (! owner.rootItemVisible)
  44996. g.setOrigin (0, -owner.rootItem->itemHeight);
  44997. owner.rootItem->paintRecursively (g, getWidth());
  44998. }
  44999. }
  45000. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45001. {
  45002. if (owner.rootItem != 0)
  45003. {
  45004. owner.handleAsyncUpdate();
  45005. if (! owner.rootItemVisible)
  45006. y += owner.rootItem->itemHeight;
  45007. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45008. if (ti != 0)
  45009. itemPosition = ti->getItemPosition (false);
  45010. return ti;
  45011. }
  45012. return 0;
  45013. }
  45014. void updateComponents()
  45015. {
  45016. const int visibleTop = -getY();
  45017. const int visibleBottom = visibleTop + getParentHeight();
  45018. {
  45019. for (int i = items.size(); --i >= 0;)
  45020. items.getUnchecked(i)->shouldKeep = false;
  45021. }
  45022. {
  45023. TreeViewItem* item = owner.rootItem;
  45024. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45025. while (item != 0 && y < visibleBottom)
  45026. {
  45027. y += item->itemHeight;
  45028. if (y >= visibleTop)
  45029. {
  45030. RowItem* const ri = findItem (item->uid);
  45031. if (ri != 0)
  45032. {
  45033. ri->shouldKeep = true;
  45034. }
  45035. else
  45036. {
  45037. Component* const comp = item->createItemComponent();
  45038. if (comp != 0)
  45039. {
  45040. items.add (new RowItem (item, comp, item->uid));
  45041. addAndMakeVisible (comp);
  45042. }
  45043. }
  45044. }
  45045. item = item->getNextVisibleItem (true);
  45046. }
  45047. }
  45048. for (int i = items.size(); --i >= 0;)
  45049. {
  45050. RowItem* const ri = items.getUnchecked(i);
  45051. bool keep = false;
  45052. if (isParentOf (ri->component))
  45053. {
  45054. if (ri->shouldKeep)
  45055. {
  45056. Rectangle<int> pos (ri->item->getItemPosition (false));
  45057. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  45058. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45059. {
  45060. keep = true;
  45061. ri->component->setBounds (pos);
  45062. }
  45063. }
  45064. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  45065. {
  45066. keep = true;
  45067. ri->component->setSize (0, 0);
  45068. }
  45069. }
  45070. if (! keep)
  45071. items.remove (i);
  45072. }
  45073. }
  45074. void updateButtonUnderMouse (const MouseEvent& e)
  45075. {
  45076. TreeViewItem* newItem = 0;
  45077. if (owner.openCloseButtonsVisible)
  45078. {
  45079. Rectangle<int> pos;
  45080. TreeViewItem* item = findItemAt (e.y, pos);
  45081. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45082. {
  45083. newItem = item;
  45084. if (! newItem->mightContainSubItems())
  45085. newItem = 0;
  45086. }
  45087. }
  45088. if (buttonUnderMouse != newItem)
  45089. {
  45090. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45091. {
  45092. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45093. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45094. }
  45095. buttonUnderMouse = newItem;
  45096. if (buttonUnderMouse != 0)
  45097. {
  45098. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45099. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45100. }
  45101. }
  45102. }
  45103. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45104. {
  45105. return item == buttonUnderMouse;
  45106. }
  45107. void resized()
  45108. {
  45109. owner.itemsChanged();
  45110. }
  45111. const String getTooltip()
  45112. {
  45113. Rectangle<int> pos;
  45114. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45115. if (item != 0)
  45116. return item->getTooltip();
  45117. return owner.getTooltip();
  45118. }
  45119. private:
  45120. TreeView& owner;
  45121. struct RowItem
  45122. {
  45123. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  45124. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45125. {
  45126. }
  45127. ~RowItem()
  45128. {
  45129. delete component.get();
  45130. }
  45131. WeakReference<Component> component;
  45132. TreeViewItem* item;
  45133. int uid;
  45134. bool shouldKeep;
  45135. };
  45136. OwnedArray <RowItem> items;
  45137. TreeViewItem* buttonUnderMouse;
  45138. bool isDragging, needSelectionOnMouseUp;
  45139. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45140. {
  45141. TreeViewItem* firstSelected = 0;
  45142. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45143. {
  45144. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45145. jassert (lastSelected != 0);
  45146. int rowStart = firstSelected->getRowNumberInTree();
  45147. int rowEnd = lastSelected->getRowNumberInTree();
  45148. if (rowStart > rowEnd)
  45149. swapVariables (rowStart, rowEnd);
  45150. int ourRow = item->getRowNumberInTree();
  45151. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45152. if (ourRow > otherEnd)
  45153. swapVariables (ourRow, otherEnd);
  45154. for (int i = ourRow; i <= otherEnd; ++i)
  45155. owner.getItemOnRow (i)->setSelected (true, false);
  45156. }
  45157. else
  45158. {
  45159. const bool cmd = modifiers.isCommandDown();
  45160. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45161. }
  45162. }
  45163. bool containsItem (TreeViewItem* const item) const throw()
  45164. {
  45165. for (int i = items.size(); --i >= 0;)
  45166. if (items.getUnchecked(i)->item == item)
  45167. return true;
  45168. return false;
  45169. }
  45170. RowItem* findItem (const int uid) const throw()
  45171. {
  45172. for (int i = items.size(); --i >= 0;)
  45173. {
  45174. RowItem* const ri = items.getUnchecked(i);
  45175. if (ri->uid == uid)
  45176. return ri;
  45177. }
  45178. return 0;
  45179. }
  45180. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45181. {
  45182. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45183. {
  45184. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45185. if (source->isDragging())
  45186. {
  45187. Component* const underMouse = source->getComponentUnderMouse();
  45188. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45189. return true;
  45190. }
  45191. }
  45192. return false;
  45193. }
  45194. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewContentComponent);
  45195. };
  45196. class TreeView::TreeViewport : public Viewport
  45197. {
  45198. public:
  45199. TreeViewport() throw() : lastX (-1) {}
  45200. void updateComponents (const bool triggerResize = false)
  45201. {
  45202. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45203. if (tvc != 0)
  45204. {
  45205. if (triggerResize)
  45206. tvc->resized();
  45207. else
  45208. tvc->updateComponents();
  45209. }
  45210. repaint();
  45211. }
  45212. void visibleAreaChanged (const Rectangle<int>& newVisibleArea)
  45213. {
  45214. const bool hasScrolledSideways = (newVisibleArea.getX() != lastX);
  45215. lastX = newVisibleArea.getX();
  45216. updateComponents (hasScrolledSideways);
  45217. }
  45218. private:
  45219. int lastX;
  45220. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport);
  45221. };
  45222. TreeView::TreeView (const String& componentName)
  45223. : Component (componentName),
  45224. rootItem (0),
  45225. indentSize (24),
  45226. defaultOpenness (false),
  45227. needsRecalculating (true),
  45228. rootItemVisible (true),
  45229. multiSelectEnabled (false),
  45230. openCloseButtonsVisible (true)
  45231. {
  45232. addAndMakeVisible (viewport = new TreeViewport());
  45233. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45234. viewport->setWantsKeyboardFocus (false);
  45235. setWantsKeyboardFocus (true);
  45236. }
  45237. TreeView::~TreeView()
  45238. {
  45239. if (rootItem != 0)
  45240. rootItem->setOwnerView (0);
  45241. }
  45242. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45243. {
  45244. if (rootItem != newRootItem)
  45245. {
  45246. if (newRootItem != 0)
  45247. {
  45248. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45249. if (newRootItem->ownerView != 0)
  45250. newRootItem->ownerView->setRootItem (0);
  45251. }
  45252. if (rootItem != 0)
  45253. rootItem->setOwnerView (0);
  45254. rootItem = newRootItem;
  45255. if (newRootItem != 0)
  45256. newRootItem->setOwnerView (this);
  45257. needsRecalculating = true;
  45258. handleAsyncUpdate();
  45259. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45260. {
  45261. rootItem->setOpen (false); // force a re-open
  45262. rootItem->setOpen (true);
  45263. }
  45264. }
  45265. }
  45266. void TreeView::deleteRootItem()
  45267. {
  45268. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45269. setRootItem (0);
  45270. }
  45271. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45272. {
  45273. rootItemVisible = shouldBeVisible;
  45274. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45275. {
  45276. rootItem->setOpen (false); // force a re-open
  45277. rootItem->setOpen (true);
  45278. }
  45279. itemsChanged();
  45280. }
  45281. void TreeView::colourChanged()
  45282. {
  45283. setOpaque (findColour (backgroundColourId).isOpaque());
  45284. repaint();
  45285. }
  45286. void TreeView::setIndentSize (const int newIndentSize)
  45287. {
  45288. if (indentSize != newIndentSize)
  45289. {
  45290. indentSize = newIndentSize;
  45291. resized();
  45292. }
  45293. }
  45294. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45295. {
  45296. if (defaultOpenness != isOpenByDefault)
  45297. {
  45298. defaultOpenness = isOpenByDefault;
  45299. itemsChanged();
  45300. }
  45301. }
  45302. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45303. {
  45304. multiSelectEnabled = canMultiSelect;
  45305. }
  45306. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45307. {
  45308. if (openCloseButtonsVisible != shouldBeVisible)
  45309. {
  45310. openCloseButtonsVisible = shouldBeVisible;
  45311. itemsChanged();
  45312. }
  45313. }
  45314. Viewport* TreeView::getViewport() const throw()
  45315. {
  45316. return viewport;
  45317. }
  45318. void TreeView::clearSelectedItems()
  45319. {
  45320. if (rootItem != 0)
  45321. rootItem->deselectAllRecursively();
  45322. }
  45323. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const throw()
  45324. {
  45325. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  45326. }
  45327. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45328. {
  45329. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45330. }
  45331. int TreeView::getNumRowsInTree() const
  45332. {
  45333. if (rootItem != 0)
  45334. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45335. return 0;
  45336. }
  45337. TreeViewItem* TreeView::getItemOnRow (int index) const
  45338. {
  45339. if (! rootItemVisible)
  45340. ++index;
  45341. if (rootItem != 0 && index >= 0)
  45342. return rootItem->getItemOnRow (index);
  45343. return 0;
  45344. }
  45345. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45346. {
  45347. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45348. Rectangle<int> pos;
  45349. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45350. }
  45351. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45352. {
  45353. if (rootItem == 0)
  45354. return 0;
  45355. return rootItem->findItemFromIdentifierString (identifierString);
  45356. }
  45357. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45358. {
  45359. XmlElement* e = 0;
  45360. if (rootItem != 0)
  45361. {
  45362. e = rootItem->getOpennessState();
  45363. if (e != 0 && alsoIncludeScrollPosition)
  45364. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45365. }
  45366. return e;
  45367. }
  45368. void TreeView::restoreOpennessState (const XmlElement& newState)
  45369. {
  45370. if (rootItem != 0)
  45371. {
  45372. rootItem->restoreOpennessState (newState);
  45373. if (newState.hasAttribute ("scrollPos"))
  45374. viewport->setViewPosition (viewport->getViewPositionX(),
  45375. newState.getIntAttribute ("scrollPos"));
  45376. }
  45377. }
  45378. void TreeView::paint (Graphics& g)
  45379. {
  45380. g.fillAll (findColour (backgroundColourId));
  45381. }
  45382. void TreeView::resized()
  45383. {
  45384. viewport->setBounds (getLocalBounds());
  45385. itemsChanged();
  45386. handleAsyncUpdate();
  45387. }
  45388. void TreeView::enablementChanged()
  45389. {
  45390. repaint();
  45391. }
  45392. void TreeView::moveSelectedRow (int delta)
  45393. {
  45394. if (delta == 0)
  45395. return;
  45396. int rowSelected = 0;
  45397. TreeViewItem* const firstSelected = getSelectedItem (0);
  45398. if (firstSelected != 0)
  45399. rowSelected = firstSelected->getRowNumberInTree();
  45400. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45401. for (;;)
  45402. {
  45403. TreeViewItem* item = getItemOnRow (rowSelected);
  45404. if (item != 0)
  45405. {
  45406. if (! item->canBeSelected())
  45407. {
  45408. // if the row we want to highlight doesn't allow it, try skipping
  45409. // to the next item..
  45410. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45411. rowSelected + (delta < 0 ? -1 : 1));
  45412. if (rowSelected != nextRowToTry)
  45413. {
  45414. rowSelected = nextRowToTry;
  45415. continue;
  45416. }
  45417. else
  45418. {
  45419. break;
  45420. }
  45421. }
  45422. item->setSelected (true, true);
  45423. scrollToKeepItemVisible (item);
  45424. }
  45425. break;
  45426. }
  45427. }
  45428. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45429. {
  45430. if (item != 0 && item->ownerView == this)
  45431. {
  45432. handleAsyncUpdate();
  45433. item = item->getDeepestOpenParentItem();
  45434. int y = item->y;
  45435. int viewTop = viewport->getViewPositionY();
  45436. if (y < viewTop)
  45437. {
  45438. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45439. }
  45440. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45441. {
  45442. viewport->setViewPosition (viewport->getViewPositionX(),
  45443. (y + item->itemHeight) - viewport->getViewHeight());
  45444. }
  45445. }
  45446. }
  45447. bool TreeView::keyPressed (const KeyPress& key)
  45448. {
  45449. if (key.isKeyCode (KeyPress::upKey))
  45450. {
  45451. moveSelectedRow (-1);
  45452. }
  45453. else if (key.isKeyCode (KeyPress::downKey))
  45454. {
  45455. moveSelectedRow (1);
  45456. }
  45457. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45458. {
  45459. if (rootItem != 0)
  45460. {
  45461. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45462. if (key.isKeyCode (KeyPress::pageUpKey))
  45463. rowsOnScreen = -rowsOnScreen;
  45464. moveSelectedRow (rowsOnScreen);
  45465. }
  45466. }
  45467. else if (key.isKeyCode (KeyPress::homeKey))
  45468. {
  45469. moveSelectedRow (-0x3fffffff);
  45470. }
  45471. else if (key.isKeyCode (KeyPress::endKey))
  45472. {
  45473. moveSelectedRow (0x3fffffff);
  45474. }
  45475. else if (key.isKeyCode (KeyPress::returnKey))
  45476. {
  45477. TreeViewItem* const firstSelected = getSelectedItem (0);
  45478. if (firstSelected != 0)
  45479. firstSelected->setOpen (! firstSelected->isOpen());
  45480. }
  45481. else if (key.isKeyCode (KeyPress::leftKey))
  45482. {
  45483. TreeViewItem* const firstSelected = getSelectedItem (0);
  45484. if (firstSelected != 0)
  45485. {
  45486. if (firstSelected->isOpen())
  45487. {
  45488. firstSelected->setOpen (false);
  45489. }
  45490. else
  45491. {
  45492. TreeViewItem* parent = firstSelected->parentItem;
  45493. if ((! rootItemVisible) && parent == rootItem)
  45494. parent = 0;
  45495. if (parent != 0)
  45496. {
  45497. parent->setSelected (true, true);
  45498. scrollToKeepItemVisible (parent);
  45499. }
  45500. }
  45501. }
  45502. }
  45503. else if (key.isKeyCode (KeyPress::rightKey))
  45504. {
  45505. TreeViewItem* const firstSelected = getSelectedItem (0);
  45506. if (firstSelected != 0)
  45507. {
  45508. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45509. moveSelectedRow (1);
  45510. else
  45511. firstSelected->setOpen (true);
  45512. }
  45513. }
  45514. else
  45515. {
  45516. return false;
  45517. }
  45518. return true;
  45519. }
  45520. void TreeView::itemsChanged() throw()
  45521. {
  45522. needsRecalculating = true;
  45523. repaint();
  45524. triggerAsyncUpdate();
  45525. }
  45526. void TreeView::handleAsyncUpdate()
  45527. {
  45528. if (needsRecalculating)
  45529. {
  45530. needsRecalculating = false;
  45531. const ScopedLock sl (nodeAlterationLock);
  45532. if (rootItem != 0)
  45533. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45534. viewport->updateComponents();
  45535. if (rootItem != 0)
  45536. {
  45537. viewport->getViewedComponent()
  45538. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45539. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45540. }
  45541. else
  45542. {
  45543. viewport->getViewedComponent()->setSize (0, 0);
  45544. }
  45545. }
  45546. }
  45547. class TreeView::InsertPointHighlight : public Component
  45548. {
  45549. public:
  45550. InsertPointHighlight()
  45551. : lastItem (0)
  45552. {
  45553. setSize (100, 12);
  45554. setAlwaysOnTop (true);
  45555. setInterceptsMouseClicks (false, false);
  45556. }
  45557. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45558. {
  45559. lastItem = item;
  45560. lastIndex = insertIndex;
  45561. const int offset = getHeight() / 2;
  45562. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45563. }
  45564. void paint (Graphics& g)
  45565. {
  45566. Path p;
  45567. const float h = (float) getHeight();
  45568. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45569. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45570. p.lineTo ((float) getWidth(), h / 2.0f);
  45571. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45572. g.strokePath (p, PathStrokeType (2.0f));
  45573. }
  45574. TreeViewItem* lastItem;
  45575. int lastIndex;
  45576. private:
  45577. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight);
  45578. };
  45579. class TreeView::TargetGroupHighlight : public Component
  45580. {
  45581. public:
  45582. TargetGroupHighlight()
  45583. {
  45584. setAlwaysOnTop (true);
  45585. setInterceptsMouseClicks (false, false);
  45586. }
  45587. void setTargetPosition (TreeViewItem* const item) throw()
  45588. {
  45589. Rectangle<int> r (item->getItemPosition (true));
  45590. r.setHeight (item->getItemHeight());
  45591. setBounds (r);
  45592. }
  45593. void paint (Graphics& g)
  45594. {
  45595. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45596. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45597. }
  45598. private:
  45599. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight);
  45600. };
  45601. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45602. {
  45603. beginDragAutoRepeat (100);
  45604. if (dragInsertPointHighlight == 0)
  45605. {
  45606. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45607. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45608. }
  45609. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45610. dragTargetGroupHighlight->setTargetPosition (item);
  45611. }
  45612. void TreeView::hideDragHighlight() throw()
  45613. {
  45614. dragInsertPointHighlight = 0;
  45615. dragTargetGroupHighlight = 0;
  45616. }
  45617. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45618. const StringArray& files, const String& sourceDescription,
  45619. Component* sourceComponent) const throw()
  45620. {
  45621. insertIndex = 0;
  45622. TreeViewItem* item = getItemAt (y);
  45623. if (item == 0)
  45624. return 0;
  45625. Rectangle<int> itemPos (item->getItemPosition (true));
  45626. insertIndex = item->getIndexInParent();
  45627. const int oldY = y;
  45628. y = itemPos.getY();
  45629. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45630. {
  45631. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45632. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45633. {
  45634. // Check if we're trying to drag into an empty group item..
  45635. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45636. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45637. {
  45638. insertIndex = 0;
  45639. x = itemPos.getX() + getIndentSize();
  45640. y = itemPos.getBottom();
  45641. return item;
  45642. }
  45643. }
  45644. }
  45645. if (oldY > itemPos.getCentreY())
  45646. {
  45647. y += item->getItemHeight();
  45648. while (item->isLastOfSiblings() && item->parentItem != 0
  45649. && item->parentItem->parentItem != 0)
  45650. {
  45651. if (x > itemPos.getX())
  45652. break;
  45653. item = item->parentItem;
  45654. itemPos = item->getItemPosition (true);
  45655. insertIndex = item->getIndexInParent();
  45656. }
  45657. ++insertIndex;
  45658. }
  45659. x = itemPos.getX();
  45660. return item->parentItem;
  45661. }
  45662. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45663. {
  45664. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45665. int insertIndex;
  45666. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45667. if (item != 0)
  45668. {
  45669. if (scrolled || dragInsertPointHighlight == 0
  45670. || dragInsertPointHighlight->lastItem != item
  45671. || dragInsertPointHighlight->lastIndex != insertIndex)
  45672. {
  45673. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45674. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45675. showDragHighlight (item, insertIndex, x, y);
  45676. else
  45677. hideDragHighlight();
  45678. }
  45679. }
  45680. else
  45681. {
  45682. hideDragHighlight();
  45683. }
  45684. }
  45685. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45686. {
  45687. hideDragHighlight();
  45688. int insertIndex;
  45689. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45690. if (item != 0)
  45691. {
  45692. if (files.size() > 0)
  45693. {
  45694. if (item->isInterestedInFileDrag (files))
  45695. item->filesDropped (files, insertIndex);
  45696. }
  45697. else
  45698. {
  45699. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45700. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45701. }
  45702. }
  45703. }
  45704. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45705. {
  45706. return true;
  45707. }
  45708. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45709. {
  45710. fileDragMove (files, x, y);
  45711. }
  45712. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45713. {
  45714. handleDrag (files, String::empty, 0, x, y);
  45715. }
  45716. void TreeView::fileDragExit (const StringArray&)
  45717. {
  45718. hideDragHighlight();
  45719. }
  45720. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45721. {
  45722. handleDrop (files, String::empty, 0, x, y);
  45723. }
  45724. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45725. {
  45726. return true;
  45727. }
  45728. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45729. {
  45730. itemDragMove (sourceDescription, sourceComponent, x, y);
  45731. }
  45732. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45733. {
  45734. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45735. }
  45736. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45737. {
  45738. hideDragHighlight();
  45739. }
  45740. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45741. {
  45742. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45743. }
  45744. enum TreeViewOpenness
  45745. {
  45746. opennessDefault = 0,
  45747. opennessClosed = 1,
  45748. opennessOpen = 2
  45749. };
  45750. TreeViewItem::TreeViewItem()
  45751. : ownerView (0),
  45752. parentItem (0),
  45753. y (0),
  45754. itemHeight (0),
  45755. totalHeight (0),
  45756. selected (false),
  45757. redrawNeeded (true),
  45758. drawLinesInside (true),
  45759. drawsInLeftMargin (false),
  45760. openness (opennessDefault)
  45761. {
  45762. static int nextUID = 0;
  45763. uid = nextUID++;
  45764. }
  45765. TreeViewItem::~TreeViewItem()
  45766. {
  45767. }
  45768. const String TreeViewItem::getUniqueName() const
  45769. {
  45770. return String::empty;
  45771. }
  45772. void TreeViewItem::itemOpennessChanged (bool)
  45773. {
  45774. }
  45775. int TreeViewItem::getNumSubItems() const throw()
  45776. {
  45777. return subItems.size();
  45778. }
  45779. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45780. {
  45781. return subItems [index];
  45782. }
  45783. void TreeViewItem::clearSubItems()
  45784. {
  45785. if (subItems.size() > 0)
  45786. {
  45787. if (ownerView != 0)
  45788. {
  45789. const ScopedLock sl (ownerView->nodeAlterationLock);
  45790. subItems.clear();
  45791. treeHasChanged();
  45792. }
  45793. else
  45794. {
  45795. subItems.clear();
  45796. }
  45797. }
  45798. }
  45799. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45800. {
  45801. if (newItem != 0)
  45802. {
  45803. newItem->parentItem = this;
  45804. newItem->setOwnerView (ownerView);
  45805. newItem->y = 0;
  45806. newItem->itemHeight = newItem->getItemHeight();
  45807. newItem->totalHeight = 0;
  45808. newItem->itemWidth = newItem->getItemWidth();
  45809. newItem->totalWidth = 0;
  45810. if (ownerView != 0)
  45811. {
  45812. const ScopedLock sl (ownerView->nodeAlterationLock);
  45813. subItems.insert (insertPosition, newItem);
  45814. treeHasChanged();
  45815. if (newItem->isOpen())
  45816. newItem->itemOpennessChanged (true);
  45817. }
  45818. else
  45819. {
  45820. subItems.insert (insertPosition, newItem);
  45821. if (newItem->isOpen())
  45822. newItem->itemOpennessChanged (true);
  45823. }
  45824. }
  45825. }
  45826. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45827. {
  45828. if (ownerView != 0)
  45829. {
  45830. const ScopedLock sl (ownerView->nodeAlterationLock);
  45831. if (isPositiveAndBelow (index, subItems.size()))
  45832. {
  45833. subItems.remove (index, deleteItem);
  45834. treeHasChanged();
  45835. }
  45836. }
  45837. else
  45838. {
  45839. subItems.remove (index, deleteItem);
  45840. }
  45841. }
  45842. bool TreeViewItem::isOpen() const throw()
  45843. {
  45844. if (openness == opennessDefault)
  45845. return ownerView != 0 && ownerView->defaultOpenness;
  45846. else
  45847. return openness == opennessOpen;
  45848. }
  45849. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45850. {
  45851. if (isOpen() != shouldBeOpen)
  45852. {
  45853. openness = shouldBeOpen ? opennessOpen
  45854. : opennessClosed;
  45855. treeHasChanged();
  45856. itemOpennessChanged (isOpen());
  45857. }
  45858. }
  45859. bool TreeViewItem::isSelected() const throw()
  45860. {
  45861. return selected;
  45862. }
  45863. void TreeViewItem::deselectAllRecursively()
  45864. {
  45865. setSelected (false, false);
  45866. for (int i = 0; i < subItems.size(); ++i)
  45867. subItems.getUnchecked(i)->deselectAllRecursively();
  45868. }
  45869. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45870. const bool deselectOtherItemsFirst)
  45871. {
  45872. if (shouldBeSelected && ! canBeSelected())
  45873. return;
  45874. if (deselectOtherItemsFirst)
  45875. getTopLevelItem()->deselectAllRecursively();
  45876. if (shouldBeSelected != selected)
  45877. {
  45878. selected = shouldBeSelected;
  45879. if (ownerView != 0)
  45880. ownerView->repaint();
  45881. itemSelectionChanged (shouldBeSelected);
  45882. }
  45883. }
  45884. void TreeViewItem::paintItem (Graphics&, int, int)
  45885. {
  45886. }
  45887. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45888. {
  45889. ownerView->getLookAndFeel()
  45890. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45891. }
  45892. void TreeViewItem::itemClicked (const MouseEvent&)
  45893. {
  45894. }
  45895. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45896. {
  45897. if (mightContainSubItems())
  45898. setOpen (! isOpen());
  45899. }
  45900. void TreeViewItem::itemSelectionChanged (bool)
  45901. {
  45902. }
  45903. const String TreeViewItem::getTooltip()
  45904. {
  45905. return String::empty;
  45906. }
  45907. const String TreeViewItem::getDragSourceDescription()
  45908. {
  45909. return String::empty;
  45910. }
  45911. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45912. {
  45913. return false;
  45914. }
  45915. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45916. {
  45917. }
  45918. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45919. {
  45920. return false;
  45921. }
  45922. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45923. {
  45924. }
  45925. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45926. {
  45927. const int indentX = getIndentX();
  45928. int width = itemWidth;
  45929. if (ownerView != 0 && width < 0)
  45930. width = ownerView->viewport->getViewWidth() - indentX;
  45931. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45932. if (relativeToTreeViewTopLeft)
  45933. r -= ownerView->viewport->getViewPosition();
  45934. return r;
  45935. }
  45936. void TreeViewItem::treeHasChanged() const throw()
  45937. {
  45938. if (ownerView != 0)
  45939. ownerView->itemsChanged();
  45940. }
  45941. void TreeViewItem::repaintItem() const
  45942. {
  45943. if (ownerView != 0 && areAllParentsOpen())
  45944. {
  45945. Rectangle<int> r (getItemPosition (true));
  45946. r.setLeft (0);
  45947. ownerView->viewport->repaint (r);
  45948. }
  45949. }
  45950. bool TreeViewItem::areAllParentsOpen() const throw()
  45951. {
  45952. return parentItem == 0
  45953. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45954. }
  45955. void TreeViewItem::updatePositions (int newY)
  45956. {
  45957. y = newY;
  45958. itemHeight = getItemHeight();
  45959. totalHeight = itemHeight;
  45960. itemWidth = getItemWidth();
  45961. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45962. if (isOpen())
  45963. {
  45964. newY += totalHeight;
  45965. for (int i = 0; i < subItems.size(); ++i)
  45966. {
  45967. TreeViewItem* const ti = subItems.getUnchecked(i);
  45968. ti->updatePositions (newY);
  45969. newY += ti->totalHeight;
  45970. totalHeight += ti->totalHeight;
  45971. totalWidth = jmax (totalWidth, ti->totalWidth);
  45972. }
  45973. }
  45974. }
  45975. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45976. {
  45977. TreeViewItem* result = this;
  45978. TreeViewItem* item = this;
  45979. while (item->parentItem != 0)
  45980. {
  45981. item = item->parentItem;
  45982. if (! item->isOpen())
  45983. result = item;
  45984. }
  45985. return result;
  45986. }
  45987. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45988. {
  45989. ownerView = newOwner;
  45990. for (int i = subItems.size(); --i >= 0;)
  45991. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45992. }
  45993. int TreeViewItem::getIndentX() const throw()
  45994. {
  45995. const int indentWidth = ownerView->getIndentSize();
  45996. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45997. if (! ownerView->openCloseButtonsVisible)
  45998. x -= indentWidth;
  45999. TreeViewItem* p = parentItem;
  46000. while (p != 0)
  46001. {
  46002. x += indentWidth;
  46003. p = p->parentItem;
  46004. }
  46005. return x;
  46006. }
  46007. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46008. {
  46009. drawsInLeftMargin = canDrawInLeftMargin;
  46010. }
  46011. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46012. {
  46013. jassert (ownerView != 0);
  46014. if (ownerView == 0)
  46015. return;
  46016. const int indent = getIndentX();
  46017. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46018. {
  46019. Graphics::ScopedSaveState ss (g);
  46020. g.setOrigin (indent, 0);
  46021. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46022. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46023. paintItem (g, itemW, itemHeight);
  46024. }
  46025. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46026. const float halfH = itemHeight * 0.5f;
  46027. int depth = 0;
  46028. TreeViewItem* p = parentItem;
  46029. while (p != 0)
  46030. {
  46031. ++depth;
  46032. p = p->parentItem;
  46033. }
  46034. if (! ownerView->rootItemVisible)
  46035. --depth;
  46036. const int indentWidth = ownerView->getIndentSize();
  46037. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46038. {
  46039. float x = (depth + 0.5f) * indentWidth;
  46040. if (depth >= 0)
  46041. {
  46042. if (parentItem != 0 && parentItem->drawLinesInside)
  46043. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46044. if ((parentItem != 0 && parentItem->drawLinesInside)
  46045. || (parentItem == 0 && drawLinesInside))
  46046. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46047. }
  46048. p = parentItem;
  46049. int d = depth;
  46050. while (p != 0 && --d >= 0)
  46051. {
  46052. x -= (float) indentWidth;
  46053. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46054. && ! p->isLastOfSiblings())
  46055. {
  46056. g.drawLine (x, 0, x, (float) itemHeight);
  46057. }
  46058. p = p->parentItem;
  46059. }
  46060. if (mightContainSubItems())
  46061. {
  46062. Graphics::ScopedSaveState ss (g);
  46063. g.setOrigin (depth * indentWidth, 0);
  46064. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46065. paintOpenCloseButton (g, indentWidth, itemHeight,
  46066. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46067. ->isMouseOverButton (this));
  46068. }
  46069. }
  46070. if (isOpen())
  46071. {
  46072. const Rectangle<int> clip (g.getClipBounds());
  46073. for (int i = 0; i < subItems.size(); ++i)
  46074. {
  46075. TreeViewItem* const ti = subItems.getUnchecked(i);
  46076. const int relY = ti->y - y;
  46077. if (relY >= clip.getBottom())
  46078. break;
  46079. if (relY + ti->totalHeight >= clip.getY())
  46080. {
  46081. Graphics::ScopedSaveState ss (g);
  46082. g.setOrigin (0, relY);
  46083. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46084. ti->paintRecursively (g, width);
  46085. }
  46086. }
  46087. }
  46088. }
  46089. bool TreeViewItem::isLastOfSiblings() const throw()
  46090. {
  46091. return parentItem == 0
  46092. || parentItem->subItems.getLast() == this;
  46093. }
  46094. int TreeViewItem::getIndexInParent() const throw()
  46095. {
  46096. return parentItem == 0 ? 0
  46097. : parentItem->subItems.indexOf (this);
  46098. }
  46099. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46100. {
  46101. return parentItem == 0 ? this
  46102. : parentItem->getTopLevelItem();
  46103. }
  46104. int TreeViewItem::getNumRows() const throw()
  46105. {
  46106. int num = 1;
  46107. if (isOpen())
  46108. {
  46109. for (int i = subItems.size(); --i >= 0;)
  46110. num += subItems.getUnchecked(i)->getNumRows();
  46111. }
  46112. return num;
  46113. }
  46114. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46115. {
  46116. if (index == 0)
  46117. return this;
  46118. if (index > 0 && isOpen())
  46119. {
  46120. --index;
  46121. for (int i = 0; i < subItems.size(); ++i)
  46122. {
  46123. TreeViewItem* const item = subItems.getUnchecked(i);
  46124. if (index == 0)
  46125. return item;
  46126. const int numRows = item->getNumRows();
  46127. if (numRows > index)
  46128. return item->getItemOnRow (index);
  46129. index -= numRows;
  46130. }
  46131. }
  46132. return 0;
  46133. }
  46134. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46135. {
  46136. if (isPositiveAndBelow (targetY, totalHeight))
  46137. {
  46138. const int h = itemHeight;
  46139. if (targetY < h)
  46140. return this;
  46141. if (isOpen())
  46142. {
  46143. targetY -= h;
  46144. for (int i = 0; i < subItems.size(); ++i)
  46145. {
  46146. TreeViewItem* const ti = subItems.getUnchecked(i);
  46147. if (targetY < ti->totalHeight)
  46148. return ti->findItemRecursively (targetY);
  46149. targetY -= ti->totalHeight;
  46150. }
  46151. }
  46152. }
  46153. return 0;
  46154. }
  46155. int TreeViewItem::countSelectedItemsRecursively (int depth) const throw()
  46156. {
  46157. int total = isSelected() ? 1 : 0;
  46158. if (depth != 0)
  46159. for (int i = subItems.size(); --i >= 0;)
  46160. total += subItems.getUnchecked(i)->countSelectedItemsRecursively (depth - 1);
  46161. return total;
  46162. }
  46163. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46164. {
  46165. if (isSelected())
  46166. {
  46167. if (index == 0)
  46168. return this;
  46169. --index;
  46170. }
  46171. if (index >= 0)
  46172. {
  46173. for (int i = 0; i < subItems.size(); ++i)
  46174. {
  46175. TreeViewItem* const item = subItems.getUnchecked(i);
  46176. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46177. if (found != 0)
  46178. return found;
  46179. index -= item->countSelectedItemsRecursively (-1);
  46180. }
  46181. }
  46182. return 0;
  46183. }
  46184. int TreeViewItem::getRowNumberInTree() const throw()
  46185. {
  46186. if (parentItem != 0 && ownerView != 0)
  46187. {
  46188. int n = 1 + parentItem->getRowNumberInTree();
  46189. int ourIndex = parentItem->subItems.indexOf (this);
  46190. jassert (ourIndex >= 0);
  46191. while (--ourIndex >= 0)
  46192. n += parentItem->subItems [ourIndex]->getNumRows();
  46193. if (parentItem->parentItem == 0
  46194. && ! ownerView->rootItemVisible)
  46195. --n;
  46196. return n;
  46197. }
  46198. else
  46199. {
  46200. return 0;
  46201. }
  46202. }
  46203. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46204. {
  46205. drawLinesInside = drawLines;
  46206. }
  46207. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46208. {
  46209. if (recurse && isOpen() && subItems.size() > 0)
  46210. return subItems [0];
  46211. if (parentItem != 0)
  46212. {
  46213. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46214. if (nextIndex >= parentItem->subItems.size())
  46215. return parentItem->getNextVisibleItem (false);
  46216. return parentItem->subItems [nextIndex];
  46217. }
  46218. return 0;
  46219. }
  46220. const String TreeViewItem::getItemIdentifierString() const
  46221. {
  46222. String s;
  46223. if (parentItem != 0)
  46224. s = parentItem->getItemIdentifierString();
  46225. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46226. }
  46227. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46228. {
  46229. const String thisId (getUniqueName());
  46230. if (thisId == identifierString)
  46231. return this;
  46232. if (identifierString.startsWith (thisId + "/"))
  46233. {
  46234. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46235. bool wasOpen = isOpen();
  46236. setOpen (true);
  46237. for (int i = subItems.size(); --i >= 0;)
  46238. {
  46239. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46240. if (item != 0)
  46241. return item;
  46242. }
  46243. setOpen (wasOpen);
  46244. }
  46245. return 0;
  46246. }
  46247. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46248. {
  46249. if (e.hasTagName ("CLOSED"))
  46250. {
  46251. setOpen (false);
  46252. }
  46253. else if (e.hasTagName ("OPEN"))
  46254. {
  46255. setOpen (true);
  46256. forEachXmlChildElement (e, n)
  46257. {
  46258. const String id (n->getStringAttribute ("id"));
  46259. for (int i = 0; i < subItems.size(); ++i)
  46260. {
  46261. TreeViewItem* const ti = subItems.getUnchecked(i);
  46262. if (ti->getUniqueName() == id)
  46263. {
  46264. ti->restoreOpennessState (*n);
  46265. break;
  46266. }
  46267. }
  46268. }
  46269. }
  46270. }
  46271. XmlElement* TreeViewItem::getOpennessState() const throw()
  46272. {
  46273. const String name (getUniqueName());
  46274. if (name.isNotEmpty())
  46275. {
  46276. XmlElement* e;
  46277. if (isOpen())
  46278. {
  46279. e = new XmlElement ("OPEN");
  46280. for (int i = 0; i < subItems.size(); ++i)
  46281. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46282. }
  46283. else
  46284. {
  46285. e = new XmlElement ("CLOSED");
  46286. }
  46287. e->setAttribute ("id", name);
  46288. return e;
  46289. }
  46290. else
  46291. {
  46292. // trying to save the openness for an element that has no name - this won't
  46293. // work because it needs the names to identify what to open.
  46294. jassertfalse;
  46295. }
  46296. return 0;
  46297. }
  46298. END_JUCE_NAMESPACE
  46299. /*** End of inlined file: juce_TreeView.cpp ***/
  46300. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46301. BEGIN_JUCE_NAMESPACE
  46302. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46303. : fileList (listToShow)
  46304. {
  46305. }
  46306. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46307. {
  46308. }
  46309. FileBrowserListener::~FileBrowserListener()
  46310. {
  46311. }
  46312. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46313. {
  46314. listeners.add (listener);
  46315. }
  46316. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46317. {
  46318. listeners.remove (listener);
  46319. }
  46320. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46321. {
  46322. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46323. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46324. }
  46325. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46326. {
  46327. if (fileList.getDirectory().exists())
  46328. {
  46329. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46330. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46331. }
  46332. }
  46333. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46334. {
  46335. if (fileList.getDirectory().exists())
  46336. {
  46337. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46338. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46339. }
  46340. }
  46341. END_JUCE_NAMESPACE
  46342. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46343. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46344. BEGIN_JUCE_NAMESPACE
  46345. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46346. TimeSliceThread& thread_)
  46347. : fileFilter (fileFilter_),
  46348. thread (thread_),
  46349. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46350. fileFindHandle (0),
  46351. shouldStop (true)
  46352. {
  46353. }
  46354. DirectoryContentsList::~DirectoryContentsList()
  46355. {
  46356. clear();
  46357. }
  46358. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46359. {
  46360. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46361. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46362. }
  46363. bool DirectoryContentsList::ignoresHiddenFiles() const
  46364. {
  46365. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46366. }
  46367. const File& DirectoryContentsList::getDirectory() const
  46368. {
  46369. return root;
  46370. }
  46371. void DirectoryContentsList::setDirectory (const File& directory,
  46372. const bool includeDirectories,
  46373. const bool includeFiles)
  46374. {
  46375. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46376. if (directory != root)
  46377. {
  46378. clear();
  46379. root = directory;
  46380. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46381. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46382. }
  46383. int newFlags = fileTypeFlags;
  46384. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46385. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46386. setTypeFlags (newFlags);
  46387. }
  46388. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46389. {
  46390. if (fileTypeFlags != newFlags)
  46391. {
  46392. fileTypeFlags = newFlags;
  46393. refresh();
  46394. }
  46395. }
  46396. void DirectoryContentsList::clear()
  46397. {
  46398. shouldStop = true;
  46399. thread.removeTimeSliceClient (this);
  46400. fileFindHandle = 0;
  46401. if (files.size() > 0)
  46402. {
  46403. files.clear();
  46404. changed();
  46405. }
  46406. }
  46407. void DirectoryContentsList::refresh()
  46408. {
  46409. clear();
  46410. if (root.isDirectory())
  46411. {
  46412. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46413. shouldStop = false;
  46414. thread.addTimeSliceClient (this);
  46415. }
  46416. }
  46417. int DirectoryContentsList::getNumFiles() const
  46418. {
  46419. return files.size();
  46420. }
  46421. bool DirectoryContentsList::getFileInfo (const int index,
  46422. FileInfo& result) const
  46423. {
  46424. const ScopedLock sl (fileListLock);
  46425. const FileInfo* const info = files [index];
  46426. if (info != 0)
  46427. {
  46428. result = *info;
  46429. return true;
  46430. }
  46431. return false;
  46432. }
  46433. const File DirectoryContentsList::getFile (const int index) const
  46434. {
  46435. const ScopedLock sl (fileListLock);
  46436. const FileInfo* const info = files [index];
  46437. if (info != 0)
  46438. return root.getChildFile (info->filename);
  46439. return File::nonexistent;
  46440. }
  46441. bool DirectoryContentsList::isStillLoading() const
  46442. {
  46443. return fileFindHandle != 0;
  46444. }
  46445. void DirectoryContentsList::changed()
  46446. {
  46447. sendChangeMessage();
  46448. }
  46449. bool DirectoryContentsList::useTimeSlice()
  46450. {
  46451. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46452. bool hasChanged = false;
  46453. for (int i = 100; --i >= 0;)
  46454. {
  46455. if (! checkNextFile (hasChanged))
  46456. {
  46457. if (hasChanged)
  46458. changed();
  46459. return false;
  46460. }
  46461. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46462. break;
  46463. }
  46464. if (hasChanged)
  46465. changed();
  46466. return true;
  46467. }
  46468. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46469. {
  46470. if (fileFindHandle != 0)
  46471. {
  46472. bool fileFoundIsDir, isHidden, isReadOnly;
  46473. int64 fileSize;
  46474. Time modTime, creationTime;
  46475. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46476. &modTime, &creationTime, &isReadOnly))
  46477. {
  46478. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46479. fileSize, modTime, creationTime, isReadOnly))
  46480. {
  46481. hasChanged = true;
  46482. }
  46483. return true;
  46484. }
  46485. else
  46486. {
  46487. fileFindHandle = 0;
  46488. }
  46489. }
  46490. return false;
  46491. }
  46492. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46493. const DirectoryContentsList::FileInfo* const second)
  46494. {
  46495. #if JUCE_WINDOWS
  46496. if (first->isDirectory != second->isDirectory)
  46497. return first->isDirectory ? -1 : 1;
  46498. #endif
  46499. return first->filename.compareIgnoreCase (second->filename);
  46500. }
  46501. bool DirectoryContentsList::addFile (const File& file,
  46502. const bool isDir,
  46503. const int64 fileSize,
  46504. const Time& modTime,
  46505. const Time& creationTime,
  46506. const bool isReadOnly)
  46507. {
  46508. if (fileFilter == 0
  46509. || ((! isDir) && fileFilter->isFileSuitable (file))
  46510. || (isDir && fileFilter->isDirectorySuitable (file)))
  46511. {
  46512. ScopedPointer <FileInfo> info (new FileInfo());
  46513. info->filename = file.getFileName();
  46514. info->fileSize = fileSize;
  46515. info->modificationTime = modTime;
  46516. info->creationTime = creationTime;
  46517. info->isDirectory = isDir;
  46518. info->isReadOnly = isReadOnly;
  46519. const ScopedLock sl (fileListLock);
  46520. for (int i = files.size(); --i >= 0;)
  46521. if (files.getUnchecked(i)->filename == info->filename)
  46522. return false;
  46523. files.addSorted (*this, info.release());
  46524. return true;
  46525. }
  46526. return false;
  46527. }
  46528. END_JUCE_NAMESPACE
  46529. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46530. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46531. BEGIN_JUCE_NAMESPACE
  46532. FileBrowserComponent::FileBrowserComponent (int flags_,
  46533. const File& initialFileOrDirectory,
  46534. const FileFilter* fileFilter_,
  46535. FilePreviewComponent* previewComp_)
  46536. : FileFilter (String::empty),
  46537. fileFilter (fileFilter_),
  46538. flags (flags_),
  46539. previewComp (previewComp_),
  46540. currentPathBox ("path"),
  46541. fileLabel ("f", TRANS ("file:")),
  46542. thread ("Juce FileBrowser")
  46543. {
  46544. // You need to specify one or other of the open/save flags..
  46545. jassert ((flags & (saveMode | openMode)) != 0);
  46546. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46547. // You need to specify at least one of these flags..
  46548. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46549. String filename;
  46550. if (initialFileOrDirectory == File::nonexistent)
  46551. {
  46552. currentRoot = File::getCurrentWorkingDirectory();
  46553. }
  46554. else if (initialFileOrDirectory.isDirectory())
  46555. {
  46556. currentRoot = initialFileOrDirectory;
  46557. }
  46558. else
  46559. {
  46560. chosenFiles.add (initialFileOrDirectory);
  46561. currentRoot = initialFileOrDirectory.getParentDirectory();
  46562. filename = initialFileOrDirectory.getFileName();
  46563. }
  46564. fileList = new DirectoryContentsList (this, thread);
  46565. if ((flags & useTreeView) != 0)
  46566. {
  46567. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46568. fileListComponent = tree;
  46569. if ((flags & canSelectMultipleItems) != 0)
  46570. tree->setMultiSelectEnabled (true);
  46571. addAndMakeVisible (tree);
  46572. }
  46573. else
  46574. {
  46575. FileListComponent* const list = new FileListComponent (*fileList);
  46576. fileListComponent = list;
  46577. list->setOutlineThickness (1);
  46578. if ((flags & canSelectMultipleItems) != 0)
  46579. list->setMultipleSelectionEnabled (true);
  46580. addAndMakeVisible (list);
  46581. }
  46582. fileListComponent->addListener (this);
  46583. addAndMakeVisible (&currentPathBox);
  46584. currentPathBox.setEditableText (true);
  46585. StringArray rootNames, rootPaths;
  46586. getRoots (rootNames, rootPaths);
  46587. for (int i = 0; i < rootNames.size(); ++i)
  46588. {
  46589. if (rootNames[i].isEmpty())
  46590. currentPathBox.addSeparator();
  46591. else
  46592. currentPathBox.addItem (rootNames[i], i + 1);
  46593. }
  46594. currentPathBox.addSeparator();
  46595. currentPathBox.addListener (this);
  46596. addAndMakeVisible (&filenameBox);
  46597. filenameBox.setMultiLine (false);
  46598. filenameBox.setSelectAllWhenFocused (true);
  46599. filenameBox.setText (filename, false);
  46600. filenameBox.addListener (this);
  46601. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46602. addAndMakeVisible (&fileLabel);
  46603. fileLabel.attachToComponent (&filenameBox, true);
  46604. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46605. goUpButton->addListener (this);
  46606. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46607. if (previewComp != 0)
  46608. addAndMakeVisible (previewComp);
  46609. setRoot (currentRoot);
  46610. thread.startThread (4);
  46611. }
  46612. FileBrowserComponent::~FileBrowserComponent()
  46613. {
  46614. fileListComponent = 0;
  46615. fileList = 0;
  46616. thread.stopThread (10000);
  46617. }
  46618. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46619. {
  46620. listeners.add (newListener);
  46621. }
  46622. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46623. {
  46624. listeners.remove (listener);
  46625. }
  46626. bool FileBrowserComponent::isSaveMode() const throw()
  46627. {
  46628. return (flags & saveMode) != 0;
  46629. }
  46630. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46631. {
  46632. if (chosenFiles.size() == 0 && currentFileIsValid())
  46633. return 1;
  46634. return chosenFiles.size();
  46635. }
  46636. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46637. {
  46638. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46639. return currentRoot;
  46640. if (! filenameBox.isReadOnly())
  46641. return currentRoot.getChildFile (filenameBox.getText());
  46642. return chosenFiles[index];
  46643. }
  46644. bool FileBrowserComponent::currentFileIsValid() const
  46645. {
  46646. if (isSaveMode())
  46647. return ! getSelectedFile (0).isDirectory();
  46648. else
  46649. return getSelectedFile (0).exists();
  46650. }
  46651. const File FileBrowserComponent::getHighlightedFile() const throw()
  46652. {
  46653. return fileListComponent->getSelectedFile (0);
  46654. }
  46655. void FileBrowserComponent::deselectAllFiles()
  46656. {
  46657. fileListComponent->deselectAllFiles();
  46658. }
  46659. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46660. {
  46661. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46662. }
  46663. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46664. {
  46665. return true;
  46666. }
  46667. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46668. {
  46669. if (f.isDirectory())
  46670. return (flags & canSelectDirectories) != 0
  46671. && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46672. return (flags & canSelectFiles) != 0 && f.exists()
  46673. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46674. }
  46675. const File FileBrowserComponent::getRoot() const
  46676. {
  46677. return currentRoot;
  46678. }
  46679. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46680. {
  46681. if (currentRoot != newRootDirectory)
  46682. {
  46683. fileListComponent->scrollToTop();
  46684. String path (newRootDirectory.getFullPathName());
  46685. if (path.isEmpty())
  46686. path = File::separatorString;
  46687. StringArray rootNames, rootPaths;
  46688. getRoots (rootNames, rootPaths);
  46689. if (! rootPaths.contains (path, true))
  46690. {
  46691. bool alreadyListed = false;
  46692. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46693. {
  46694. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46695. {
  46696. alreadyListed = true;
  46697. break;
  46698. }
  46699. }
  46700. if (! alreadyListed)
  46701. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46702. }
  46703. }
  46704. currentRoot = newRootDirectory;
  46705. fileList->setDirectory (currentRoot, true, true);
  46706. String currentRootName (currentRoot.getFullPathName());
  46707. if (currentRootName.isEmpty())
  46708. currentRootName = File::separatorString;
  46709. currentPathBox.setText (currentRootName, true);
  46710. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46711. && currentRoot.getParentDirectory() != currentRoot);
  46712. }
  46713. void FileBrowserComponent::goUp()
  46714. {
  46715. setRoot (getRoot().getParentDirectory());
  46716. }
  46717. void FileBrowserComponent::refresh()
  46718. {
  46719. fileList->refresh();
  46720. }
  46721. void FileBrowserComponent::setFileFilter (const FileFilter* const newFileFilter)
  46722. {
  46723. if (fileFilter != newFileFilter)
  46724. {
  46725. fileFilter = newFileFilter;
  46726. refresh();
  46727. }
  46728. }
  46729. const String FileBrowserComponent::getActionVerb() const
  46730. {
  46731. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46732. }
  46733. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46734. {
  46735. return previewComp;
  46736. }
  46737. void FileBrowserComponent::resized()
  46738. {
  46739. getLookAndFeel()
  46740. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46741. &currentPathBox, &filenameBox, goUpButton);
  46742. }
  46743. void FileBrowserComponent::sendListenerChangeMessage()
  46744. {
  46745. Component::BailOutChecker checker (this);
  46746. if (previewComp != 0)
  46747. previewComp->selectedFileChanged (getSelectedFile (0));
  46748. // You shouldn't delete the browser when the file gets changed!
  46749. jassert (! checker.shouldBailOut());
  46750. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46751. }
  46752. void FileBrowserComponent::selectionChanged()
  46753. {
  46754. StringArray newFilenames;
  46755. bool resetChosenFiles = true;
  46756. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46757. {
  46758. const File f (fileListComponent->getSelectedFile (i));
  46759. if (isFileOrDirSuitable (f))
  46760. {
  46761. if (resetChosenFiles)
  46762. {
  46763. chosenFiles.clear();
  46764. resetChosenFiles = false;
  46765. }
  46766. chosenFiles.add (f);
  46767. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46768. }
  46769. }
  46770. if (newFilenames.size() > 0)
  46771. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46772. sendListenerChangeMessage();
  46773. }
  46774. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46775. {
  46776. Component::BailOutChecker checker (this);
  46777. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46778. }
  46779. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46780. {
  46781. if (f.isDirectory())
  46782. {
  46783. setRoot (f);
  46784. if ((flags & canSelectDirectories) != 0)
  46785. filenameBox.setText (String::empty);
  46786. }
  46787. else
  46788. {
  46789. Component::BailOutChecker checker (this);
  46790. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46791. }
  46792. }
  46793. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46794. {
  46795. (void) key;
  46796. #if JUCE_LINUX || JUCE_WINDOWS
  46797. if (key.getModifiers().isCommandDown()
  46798. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46799. {
  46800. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46801. fileList->refresh();
  46802. return true;
  46803. }
  46804. #endif
  46805. return false;
  46806. }
  46807. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46808. {
  46809. sendListenerChangeMessage();
  46810. }
  46811. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46812. {
  46813. if (filenameBox.getText().containsChar (File::separator))
  46814. {
  46815. const File f (currentRoot.getChildFile (filenameBox.getText()));
  46816. if (f.isDirectory())
  46817. {
  46818. setRoot (f);
  46819. chosenFiles.clear();
  46820. filenameBox.setText (String::empty);
  46821. }
  46822. else
  46823. {
  46824. setRoot (f.getParentDirectory());
  46825. chosenFiles.clear();
  46826. chosenFiles.add (f);
  46827. filenameBox.setText (f.getFileName());
  46828. }
  46829. }
  46830. else
  46831. {
  46832. fileDoubleClicked (getSelectedFile (0));
  46833. }
  46834. }
  46835. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46836. {
  46837. }
  46838. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46839. {
  46840. if (! isSaveMode())
  46841. selectionChanged();
  46842. }
  46843. void FileBrowserComponent::buttonClicked (Button*)
  46844. {
  46845. goUp();
  46846. }
  46847. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46848. {
  46849. const String newText (currentPathBox.getText().trim().unquoted());
  46850. if (newText.isNotEmpty())
  46851. {
  46852. const int index = currentPathBox.getSelectedId() - 1;
  46853. StringArray rootNames, rootPaths;
  46854. getRoots (rootNames, rootPaths);
  46855. if (rootPaths [index].isNotEmpty())
  46856. {
  46857. setRoot (File (rootPaths [index]));
  46858. }
  46859. else
  46860. {
  46861. File f (newText);
  46862. for (;;)
  46863. {
  46864. if (f.isDirectory())
  46865. {
  46866. setRoot (f);
  46867. break;
  46868. }
  46869. if (f.getParentDirectory() == f)
  46870. break;
  46871. f = f.getParentDirectory();
  46872. }
  46873. }
  46874. }
  46875. }
  46876. void FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46877. {
  46878. #if JUCE_WINDOWS
  46879. Array<File> roots;
  46880. File::findFileSystemRoots (roots);
  46881. rootPaths.clear();
  46882. for (int i = 0; i < roots.size(); ++i)
  46883. {
  46884. const File& drive = roots.getReference(i);
  46885. String name (drive.getFullPathName());
  46886. rootPaths.add (name);
  46887. if (drive.isOnHardDisk())
  46888. {
  46889. String volume (drive.getVolumeLabel());
  46890. if (volume.isEmpty())
  46891. volume = TRANS("Hard Drive");
  46892. name << " [" << volume << ']';
  46893. }
  46894. else if (drive.isOnCDRomDrive())
  46895. {
  46896. name << TRANS(" [CD/DVD drive]");
  46897. }
  46898. rootNames.add (name);
  46899. }
  46900. rootPaths.add (String::empty);
  46901. rootNames.add (String::empty);
  46902. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46903. rootNames.add ("Documents");
  46904. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46905. rootNames.add ("Desktop");
  46906. #endif
  46907. #if JUCE_MAC
  46908. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46909. rootNames.add ("Home folder");
  46910. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46911. rootNames.add ("Documents");
  46912. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46913. rootNames.add ("Desktop");
  46914. rootPaths.add (String::empty);
  46915. rootNames.add (String::empty);
  46916. Array <File> volumes;
  46917. File vol ("/Volumes");
  46918. vol.findChildFiles (volumes, File::findDirectories, false);
  46919. for (int i = 0; i < volumes.size(); ++i)
  46920. {
  46921. const File& volume = volumes.getReference(i);
  46922. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46923. {
  46924. rootPaths.add (volume.getFullPathName());
  46925. rootNames.add (volume.getFileName());
  46926. }
  46927. }
  46928. #endif
  46929. #if JUCE_LINUX
  46930. rootPaths.add ("/");
  46931. rootNames.add ("/");
  46932. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46933. rootNames.add ("Home folder");
  46934. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46935. rootNames.add ("Desktop");
  46936. #endif
  46937. }
  46938. END_JUCE_NAMESPACE
  46939. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46940. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46941. BEGIN_JUCE_NAMESPACE
  46942. FileChooser::FileChooser (const String& chooserBoxTitle,
  46943. const File& currentFileOrDirectory,
  46944. const String& fileFilters,
  46945. const bool useNativeDialogBox_)
  46946. : title (chooserBoxTitle),
  46947. filters (fileFilters),
  46948. startingFile (currentFileOrDirectory),
  46949. useNativeDialogBox (useNativeDialogBox_)
  46950. {
  46951. #if JUCE_LINUX
  46952. useNativeDialogBox = false;
  46953. #endif
  46954. if (! fileFilters.containsNonWhitespaceChars())
  46955. filters = "*";
  46956. }
  46957. FileChooser::~FileChooser()
  46958. {
  46959. }
  46960. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46961. {
  46962. return showDialog (false, true, false, false, false, previewComponent);
  46963. }
  46964. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46965. {
  46966. return showDialog (false, true, false, false, true, previewComponent);
  46967. }
  46968. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46969. {
  46970. return showDialog (true, true, false, false, true, previewComponent);
  46971. }
  46972. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46973. {
  46974. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46975. }
  46976. bool FileChooser::browseForDirectory()
  46977. {
  46978. return showDialog (true, false, false, false, false, 0);
  46979. }
  46980. const File FileChooser::getResult() const
  46981. {
  46982. // if you've used a multiple-file select, you should use the getResults() method
  46983. // to retrieve all the files that were chosen.
  46984. jassert (results.size() <= 1);
  46985. return results.getFirst();
  46986. }
  46987. const Array<File>& FileChooser::getResults() const
  46988. {
  46989. return results;
  46990. }
  46991. bool FileChooser::showDialog (const bool selectsDirectories,
  46992. const bool selectsFiles,
  46993. const bool isSave,
  46994. const bool warnAboutOverwritingExistingFiles,
  46995. const bool selectMultipleFiles,
  46996. FilePreviewComponent* const previewComponent)
  46997. {
  46998. WeakReference<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46999. results.clear();
  47000. // the preview component needs to be the right size before you pass it in here..
  47001. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47002. && previewComponent->getHeight() > 10));
  47003. #if JUCE_WINDOWS
  47004. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47005. #elif JUCE_MAC
  47006. if (useNativeDialogBox && (previewComponent == 0))
  47007. #else
  47008. if (false)
  47009. #endif
  47010. {
  47011. showPlatformDialog (results, title, startingFile, filters,
  47012. selectsDirectories, selectsFiles, isSave,
  47013. warnAboutOverwritingExistingFiles,
  47014. selectMultipleFiles,
  47015. previewComponent);
  47016. }
  47017. else
  47018. {
  47019. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47020. selectsDirectories ? "*" : String::empty,
  47021. String::empty);
  47022. int flags = isSave ? FileBrowserComponent::saveMode
  47023. : FileBrowserComponent::openMode;
  47024. if (selectsFiles)
  47025. flags |= FileBrowserComponent::canSelectFiles;
  47026. if (selectsDirectories)
  47027. {
  47028. flags |= FileBrowserComponent::canSelectDirectories;
  47029. if (! isSave)
  47030. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47031. }
  47032. if (selectMultipleFiles)
  47033. flags |= FileBrowserComponent::canSelectMultipleItems;
  47034. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47035. FileChooserDialogBox box (title, String::empty,
  47036. browserComponent,
  47037. warnAboutOverwritingExistingFiles,
  47038. browserComponent.findColour (AlertWindow::backgroundColourId));
  47039. if (box.show())
  47040. {
  47041. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47042. results.add (browserComponent.getSelectedFile (i));
  47043. }
  47044. }
  47045. if (previouslyFocused != 0)
  47046. previouslyFocused->grabKeyboardFocus();
  47047. return results.size() > 0;
  47048. }
  47049. FilePreviewComponent::FilePreviewComponent()
  47050. {
  47051. }
  47052. FilePreviewComponent::~FilePreviewComponent()
  47053. {
  47054. }
  47055. END_JUCE_NAMESPACE
  47056. /*** End of inlined file: juce_FileChooser.cpp ***/
  47057. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47058. BEGIN_JUCE_NAMESPACE
  47059. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47060. const String& instructions,
  47061. FileBrowserComponent& chooserComponent,
  47062. const bool warnAboutOverwritingExistingFiles_,
  47063. const Colour& backgroundColour)
  47064. : ResizableWindow (name, backgroundColour, true),
  47065. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47066. {
  47067. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47068. setResizable (true, true);
  47069. setResizeLimits (300, 300, 1200, 1000);
  47070. content->okButton.addListener (this);
  47071. content->cancelButton.addListener (this);
  47072. content->newFolderButton.addListener (this);
  47073. content->chooserComponent.addListener (this);
  47074. selectionChanged();
  47075. }
  47076. FileChooserDialogBox::~FileChooserDialogBox()
  47077. {
  47078. content->chooserComponent.removeListener (this);
  47079. }
  47080. bool FileChooserDialogBox::show (int w, int h)
  47081. {
  47082. return showAt (-1, -1, w, h);
  47083. }
  47084. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47085. {
  47086. if (w <= 0)
  47087. {
  47088. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47089. if (previewComp != 0)
  47090. w = 400 + previewComp->getWidth();
  47091. else
  47092. w = 600;
  47093. }
  47094. if (h <= 0)
  47095. h = 500;
  47096. if (x < 0 || y < 0)
  47097. centreWithSize (w, h);
  47098. else
  47099. setBounds (x, y, w, h);
  47100. const bool ok = (runModalLoop() != 0);
  47101. setVisible (false);
  47102. return ok;
  47103. }
  47104. void FileChooserDialogBox::buttonClicked (Button* button)
  47105. {
  47106. if (button == &(content->okButton))
  47107. {
  47108. okButtonPressed();
  47109. }
  47110. else if (button == &(content->cancelButton))
  47111. {
  47112. closeButtonPressed();
  47113. }
  47114. else if (button == &(content->newFolderButton))
  47115. {
  47116. createNewFolder();
  47117. }
  47118. }
  47119. void FileChooserDialogBox::closeButtonPressed()
  47120. {
  47121. setVisible (false);
  47122. }
  47123. void FileChooserDialogBox::selectionChanged()
  47124. {
  47125. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47126. content->newFolderButton.setVisible (content->chooserComponent.isSaveMode()
  47127. && content->chooserComponent.getRoot().isDirectory());
  47128. }
  47129. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47130. {
  47131. }
  47132. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47133. {
  47134. selectionChanged();
  47135. content->okButton.triggerClick();
  47136. }
  47137. void FileChooserDialogBox::okButtonPressed()
  47138. {
  47139. if ((! (warnAboutOverwritingExistingFiles
  47140. && content->chooserComponent.isSaveMode()
  47141. && content->chooserComponent.getSelectedFile(0).exists()))
  47142. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47143. TRANS("File already exists"),
  47144. TRANS("There's already a file called:")
  47145. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47146. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47147. TRANS("overwrite"),
  47148. TRANS("cancel")))
  47149. {
  47150. exitModalState (1);
  47151. }
  47152. }
  47153. void FileChooserDialogBox::createNewFolder()
  47154. {
  47155. File parent (content->chooserComponent.getRoot());
  47156. if (parent.isDirectory())
  47157. {
  47158. AlertWindow aw (TRANS("New Folder"),
  47159. TRANS("Please enter the name for the folder"),
  47160. AlertWindow::NoIcon, this);
  47161. aw.addTextEditor ("name", String::empty, String::empty, false);
  47162. aw.addButton (TRANS("ok"), 1, KeyPress::returnKey);
  47163. aw.addButton (TRANS("cancel"), KeyPress::escapeKey);
  47164. if (aw.runModalLoop() != 0)
  47165. {
  47166. aw.setVisible (false);
  47167. const String name (File::createLegalFileName (aw.getTextEditorContents ("name")));
  47168. if (! name.isEmpty())
  47169. {
  47170. if (! parent.getChildFile (name).createDirectory())
  47171. {
  47172. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  47173. TRANS ("New Folder"),
  47174. TRANS ("Couldn't create the folder!"));
  47175. }
  47176. content->chooserComponent.refresh();
  47177. }
  47178. }
  47179. }
  47180. }
  47181. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47182. : Component (name), instructions (instructions_),
  47183. chooserComponent (chooserComponent_),
  47184. okButton (chooserComponent_.getActionVerb()),
  47185. cancelButton (TRANS ("Cancel")),
  47186. newFolderButton (TRANS ("New Folder"))
  47187. {
  47188. addAndMakeVisible (&chooserComponent);
  47189. addAndMakeVisible (&okButton);
  47190. okButton.addShortcut (KeyPress::returnKey);
  47191. addAndMakeVisible (&cancelButton);
  47192. cancelButton.addShortcut (KeyPress::escapeKey);
  47193. addChildComponent (&newFolderButton);
  47194. setInterceptsMouseClicks (false, true);
  47195. }
  47196. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47197. {
  47198. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47199. text.draw (g);
  47200. }
  47201. void FileChooserDialogBox::ContentComponent::resized()
  47202. {
  47203. const int buttonHeight = 26;
  47204. Rectangle<int> area (getLocalBounds());
  47205. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47206. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47207. area.removeFromTop (roundToInt (bb.getBottom()) + 10);
  47208. chooserComponent.setBounds (area.removeFromTop (area.getHeight() - buttonHeight - 20));
  47209. Rectangle<int> buttonArea (area.reduced (16, 10));
  47210. okButton.changeWidthToFitText (buttonHeight);
  47211. okButton.setBounds (buttonArea.removeFromRight (okButton.getWidth() + 16));
  47212. buttonArea.removeFromRight (16);
  47213. cancelButton.changeWidthToFitText (buttonHeight);
  47214. cancelButton.setBounds (buttonArea.removeFromRight (cancelButton.getWidth()));
  47215. newFolderButton.changeWidthToFitText (buttonHeight);
  47216. newFolderButton.setBounds (buttonArea.removeFromLeft (newFolderButton.getWidth()));
  47217. }
  47218. END_JUCE_NAMESPACE
  47219. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47220. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47221. BEGIN_JUCE_NAMESPACE
  47222. FileFilter::FileFilter (const String& filterDescription)
  47223. : description (filterDescription)
  47224. {
  47225. }
  47226. FileFilter::~FileFilter()
  47227. {
  47228. }
  47229. const String& FileFilter::getDescription() const throw()
  47230. {
  47231. return description;
  47232. }
  47233. END_JUCE_NAMESPACE
  47234. /*** End of inlined file: juce_FileFilter.cpp ***/
  47235. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47236. BEGIN_JUCE_NAMESPACE
  47237. const Image juce_createIconForFile (const File& file);
  47238. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47239. : ListBox (String::empty, 0),
  47240. DirectoryContentsDisplayComponent (listToShow)
  47241. {
  47242. setModel (this);
  47243. fileList.addChangeListener (this);
  47244. }
  47245. FileListComponent::~FileListComponent()
  47246. {
  47247. fileList.removeChangeListener (this);
  47248. }
  47249. int FileListComponent::getNumSelectedFiles() const
  47250. {
  47251. return getNumSelectedRows();
  47252. }
  47253. const File FileListComponent::getSelectedFile (int index) const
  47254. {
  47255. return fileList.getFile (getSelectedRow (index));
  47256. }
  47257. void FileListComponent::deselectAllFiles()
  47258. {
  47259. deselectAllRows();
  47260. }
  47261. void FileListComponent::scrollToTop()
  47262. {
  47263. getVerticalScrollBar()->setCurrentRangeStart (0);
  47264. }
  47265. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47266. {
  47267. updateContent();
  47268. if (lastDirectory != fileList.getDirectory())
  47269. {
  47270. lastDirectory = fileList.getDirectory();
  47271. deselectAllRows();
  47272. }
  47273. }
  47274. class FileListItemComponent : public Component,
  47275. public TimeSliceClient,
  47276. public AsyncUpdater
  47277. {
  47278. public:
  47279. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47280. : owner (owner_), thread (thread_), index (0), highlighted (false)
  47281. {
  47282. }
  47283. ~FileListItemComponent()
  47284. {
  47285. thread.removeTimeSliceClient (this);
  47286. }
  47287. void paint (Graphics& g)
  47288. {
  47289. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47290. file.getFileName(),
  47291. &icon, fileSize, modTime,
  47292. isDirectory, highlighted,
  47293. index, owner);
  47294. }
  47295. void mouseDown (const MouseEvent& e)
  47296. {
  47297. owner.selectRowsBasedOnModifierKeys (index, e.mods, false);
  47298. owner.sendMouseClickMessage (file, e);
  47299. }
  47300. void mouseDoubleClick (const MouseEvent&)
  47301. {
  47302. owner.sendDoubleClickMessage (file);
  47303. }
  47304. void update (const File& root,
  47305. const DirectoryContentsList::FileInfo* const fileInfo,
  47306. const int index_,
  47307. const bool highlighted_)
  47308. {
  47309. thread.removeTimeSliceClient (this);
  47310. if (highlighted_ != highlighted || index_ != index)
  47311. {
  47312. index = index_;
  47313. highlighted = highlighted_;
  47314. repaint();
  47315. }
  47316. File newFile;
  47317. String newFileSize, newModTime;
  47318. if (fileInfo != 0)
  47319. {
  47320. newFile = root.getChildFile (fileInfo->filename);
  47321. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47322. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47323. }
  47324. if (newFile != file
  47325. || fileSize != newFileSize
  47326. || modTime != newModTime)
  47327. {
  47328. file = newFile;
  47329. fileSize = newFileSize;
  47330. modTime = newModTime;
  47331. icon = Image::null;
  47332. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47333. repaint();
  47334. }
  47335. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47336. {
  47337. updateIcon (true);
  47338. if (! icon.isValid())
  47339. thread.addTimeSliceClient (this);
  47340. }
  47341. }
  47342. bool useTimeSlice()
  47343. {
  47344. updateIcon (false);
  47345. return false;
  47346. }
  47347. void handleAsyncUpdate()
  47348. {
  47349. repaint();
  47350. }
  47351. private:
  47352. FileListComponent& owner;
  47353. TimeSliceThread& thread;
  47354. File file;
  47355. String fileSize, modTime;
  47356. Image icon;
  47357. int index;
  47358. bool highlighted, isDirectory;
  47359. void updateIcon (const bool onlyUpdateIfCached)
  47360. {
  47361. if (icon.isNull())
  47362. {
  47363. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47364. Image im (ImageCache::getFromHashCode (hashCode));
  47365. if (im.isNull() && ! onlyUpdateIfCached)
  47366. {
  47367. im = juce_createIconForFile (file);
  47368. if (im.isValid())
  47369. ImageCache::addImageToCache (im, hashCode);
  47370. }
  47371. if (im.isValid())
  47372. {
  47373. icon = im;
  47374. triggerAsyncUpdate();
  47375. }
  47376. }
  47377. }
  47378. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListItemComponent);
  47379. };
  47380. int FileListComponent::getNumRows()
  47381. {
  47382. return fileList.getNumFiles();
  47383. }
  47384. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47385. {
  47386. }
  47387. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47388. {
  47389. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47390. if (comp == 0)
  47391. {
  47392. delete existingComponentToUpdate;
  47393. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47394. }
  47395. DirectoryContentsList::FileInfo fileInfo;
  47396. if (fileList.getFileInfo (row, fileInfo))
  47397. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47398. else
  47399. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47400. return comp;
  47401. }
  47402. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47403. {
  47404. sendSelectionChangeMessage();
  47405. }
  47406. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47407. {
  47408. }
  47409. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47410. {
  47411. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47412. }
  47413. END_JUCE_NAMESPACE
  47414. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47415. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47416. BEGIN_JUCE_NAMESPACE
  47417. FilenameComponent::FilenameComponent (const String& name,
  47418. const File& currentFile,
  47419. const bool canEditFilename,
  47420. const bool isDirectory,
  47421. const bool isForSaving,
  47422. const String& fileBrowserWildcard,
  47423. const String& enforcedSuffix_,
  47424. const String& textWhenNothingSelected)
  47425. : Component (name),
  47426. maxRecentFiles (30),
  47427. isDir (isDirectory),
  47428. isSaving (isForSaving),
  47429. isFileDragOver (false),
  47430. wildcard (fileBrowserWildcard),
  47431. enforcedSuffix (enforcedSuffix_)
  47432. {
  47433. addAndMakeVisible (&filenameBox);
  47434. filenameBox.setEditableText (canEditFilename);
  47435. filenameBox.addListener (this);
  47436. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47437. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47438. setBrowseButtonText ("...");
  47439. setCurrentFile (currentFile, true);
  47440. }
  47441. FilenameComponent::~FilenameComponent()
  47442. {
  47443. }
  47444. void FilenameComponent::paintOverChildren (Graphics& g)
  47445. {
  47446. if (isFileDragOver)
  47447. {
  47448. g.setColour (Colours::red.withAlpha (0.2f));
  47449. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47450. }
  47451. }
  47452. void FilenameComponent::resized()
  47453. {
  47454. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47455. }
  47456. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47457. {
  47458. browseButtonText = newBrowseButtonText;
  47459. lookAndFeelChanged();
  47460. }
  47461. void FilenameComponent::lookAndFeelChanged()
  47462. {
  47463. browseButton = 0;
  47464. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47465. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47466. resized();
  47467. browseButton->addListener (this);
  47468. }
  47469. void FilenameComponent::setTooltip (const String& newTooltip)
  47470. {
  47471. SettableTooltipClient::setTooltip (newTooltip);
  47472. filenameBox.setTooltip (newTooltip);
  47473. }
  47474. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47475. {
  47476. defaultBrowseFile = newDefaultDirectory;
  47477. }
  47478. void FilenameComponent::buttonClicked (Button*)
  47479. {
  47480. FileChooser fc (TRANS("Choose a new file"),
  47481. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47482. : getCurrentFile(),
  47483. wildcard);
  47484. if (isDir ? fc.browseForDirectory()
  47485. : (isSaving ? fc.browseForFileToSave (false)
  47486. : fc.browseForFileToOpen()))
  47487. {
  47488. setCurrentFile (fc.getResult(), true);
  47489. }
  47490. }
  47491. void FilenameComponent::comboBoxChanged (ComboBox*)
  47492. {
  47493. setCurrentFile (getCurrentFile(), true);
  47494. }
  47495. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47496. {
  47497. return true;
  47498. }
  47499. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47500. {
  47501. isFileDragOver = false;
  47502. repaint();
  47503. const File f (filenames[0]);
  47504. if (f.exists() && (f.isDirectory() == isDir))
  47505. setCurrentFile (f, true);
  47506. }
  47507. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47508. {
  47509. isFileDragOver = true;
  47510. repaint();
  47511. }
  47512. void FilenameComponent::fileDragExit (const StringArray&)
  47513. {
  47514. isFileDragOver = false;
  47515. repaint();
  47516. }
  47517. const File FilenameComponent::getCurrentFile() const
  47518. {
  47519. File f (filenameBox.getText());
  47520. if (enforcedSuffix.isNotEmpty())
  47521. f = f.withFileExtension (enforcedSuffix);
  47522. return f;
  47523. }
  47524. void FilenameComponent::setCurrentFile (File newFile,
  47525. const bool addToRecentlyUsedList,
  47526. const bool sendChangeNotification)
  47527. {
  47528. if (enforcedSuffix.isNotEmpty())
  47529. newFile = newFile.withFileExtension (enforcedSuffix);
  47530. if (newFile.getFullPathName() != lastFilename)
  47531. {
  47532. lastFilename = newFile.getFullPathName();
  47533. if (addToRecentlyUsedList)
  47534. addRecentlyUsedFile (newFile);
  47535. filenameBox.setText (lastFilename, true);
  47536. if (sendChangeNotification)
  47537. triggerAsyncUpdate();
  47538. }
  47539. }
  47540. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47541. {
  47542. filenameBox.setEditableText (shouldBeEditable);
  47543. }
  47544. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47545. {
  47546. StringArray names;
  47547. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47548. names.add (filenameBox.getItemText (i));
  47549. return names;
  47550. }
  47551. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47552. {
  47553. if (filenames != getRecentlyUsedFilenames())
  47554. {
  47555. filenameBox.clear();
  47556. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47557. filenameBox.addItem (filenames[i], i + 1);
  47558. }
  47559. }
  47560. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47561. {
  47562. maxRecentFiles = jmax (1, newMaximum);
  47563. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47564. }
  47565. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47566. {
  47567. StringArray files (getRecentlyUsedFilenames());
  47568. if (file.getFullPathName().isNotEmpty())
  47569. {
  47570. files.removeString (file.getFullPathName(), true);
  47571. files.insert (0, file.getFullPathName());
  47572. setRecentlyUsedFilenames (files);
  47573. }
  47574. }
  47575. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47576. {
  47577. listeners.add (listener);
  47578. }
  47579. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47580. {
  47581. listeners.remove (listener);
  47582. }
  47583. void FilenameComponent::handleAsyncUpdate()
  47584. {
  47585. Component::BailOutChecker checker (this);
  47586. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47587. }
  47588. END_JUCE_NAMESPACE
  47589. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47590. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47591. BEGIN_JUCE_NAMESPACE
  47592. FileSearchPathListComponent::FileSearchPathListComponent()
  47593. : addButton ("+"),
  47594. removeButton ("-"),
  47595. changeButton (TRANS ("change...")),
  47596. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47597. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47598. {
  47599. listBox.setModel (this);
  47600. addAndMakeVisible (&listBox);
  47601. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47602. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47603. listBox.setOutlineThickness (1);
  47604. addAndMakeVisible (&addButton);
  47605. addButton.addListener (this);
  47606. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47607. addAndMakeVisible (&removeButton);
  47608. removeButton.addListener (this);
  47609. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47610. addAndMakeVisible (&changeButton);
  47611. changeButton.addListener (this);
  47612. addAndMakeVisible (&upButton);
  47613. upButton.addListener (this);
  47614. {
  47615. Path arrowPath;
  47616. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47617. DrawablePath arrowImage;
  47618. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47619. arrowImage.setPath (arrowPath);
  47620. upButton.setImages (&arrowImage);
  47621. }
  47622. addAndMakeVisible (&downButton);
  47623. downButton.addListener (this);
  47624. {
  47625. Path arrowPath;
  47626. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47627. DrawablePath arrowImage;
  47628. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47629. arrowImage.setPath (arrowPath);
  47630. downButton.setImages (&arrowImage);
  47631. }
  47632. updateButtons();
  47633. }
  47634. FileSearchPathListComponent::~FileSearchPathListComponent()
  47635. {
  47636. }
  47637. void FileSearchPathListComponent::updateButtons()
  47638. {
  47639. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47640. removeButton.setEnabled (anythingSelected);
  47641. changeButton.setEnabled (anythingSelected);
  47642. upButton.setEnabled (anythingSelected);
  47643. downButton.setEnabled (anythingSelected);
  47644. }
  47645. void FileSearchPathListComponent::changed()
  47646. {
  47647. listBox.updateContent();
  47648. listBox.repaint();
  47649. updateButtons();
  47650. }
  47651. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47652. {
  47653. if (newPath.toString() != path.toString())
  47654. {
  47655. path = newPath;
  47656. changed();
  47657. }
  47658. }
  47659. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47660. {
  47661. defaultBrowseTarget = newDefaultDirectory;
  47662. }
  47663. int FileSearchPathListComponent::getNumRows()
  47664. {
  47665. return path.getNumPaths();
  47666. }
  47667. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47668. {
  47669. if (rowIsSelected)
  47670. g.fillAll (findColour (TextEditor::highlightColourId));
  47671. g.setColour (findColour (ListBox::textColourId));
  47672. Font f (height * 0.7f);
  47673. f.setHorizontalScale (0.9f);
  47674. g.setFont (f);
  47675. g.drawText (path [rowNumber].getFullPathName(),
  47676. 4, 0, width - 6, height,
  47677. Justification::centredLeft, true);
  47678. }
  47679. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47680. {
  47681. if (isPositiveAndBelow (row, path.getNumPaths()))
  47682. {
  47683. path.remove (row);
  47684. changed();
  47685. }
  47686. }
  47687. void FileSearchPathListComponent::returnKeyPressed (int row)
  47688. {
  47689. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47690. if (chooser.browseForDirectory())
  47691. {
  47692. path.remove (row);
  47693. path.add (chooser.getResult(), row);
  47694. changed();
  47695. }
  47696. }
  47697. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47698. {
  47699. returnKeyPressed (row);
  47700. }
  47701. void FileSearchPathListComponent::selectedRowsChanged (int)
  47702. {
  47703. updateButtons();
  47704. }
  47705. void FileSearchPathListComponent::paint (Graphics& g)
  47706. {
  47707. g.fillAll (findColour (backgroundColourId));
  47708. }
  47709. void FileSearchPathListComponent::resized()
  47710. {
  47711. const int buttonH = 22;
  47712. const int buttonY = getHeight() - buttonH - 4;
  47713. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47714. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47715. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47716. changeButton.changeWidthToFitText (buttonH);
  47717. downButton.setSize (buttonH * 2, buttonH);
  47718. upButton.setSize (buttonH * 2, buttonH);
  47719. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47720. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47721. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47722. }
  47723. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47724. {
  47725. return true;
  47726. }
  47727. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47728. {
  47729. for (int i = filenames.size(); --i >= 0;)
  47730. {
  47731. const File f (filenames[i]);
  47732. if (f.isDirectory())
  47733. {
  47734. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47735. path.add (f, row);
  47736. changed();
  47737. }
  47738. }
  47739. }
  47740. void FileSearchPathListComponent::buttonClicked (Button* button)
  47741. {
  47742. const int currentRow = listBox.getSelectedRow();
  47743. if (button == &removeButton)
  47744. {
  47745. deleteKeyPressed (currentRow);
  47746. }
  47747. else if (button == &addButton)
  47748. {
  47749. File start (defaultBrowseTarget);
  47750. if (start == File::nonexistent)
  47751. start = path [0];
  47752. if (start == File::nonexistent)
  47753. start = File::getCurrentWorkingDirectory();
  47754. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47755. if (chooser.browseForDirectory())
  47756. {
  47757. path.add (chooser.getResult(), currentRow);
  47758. }
  47759. }
  47760. else if (button == &changeButton)
  47761. {
  47762. returnKeyPressed (currentRow);
  47763. }
  47764. else if (button == &upButton)
  47765. {
  47766. if (currentRow > 0 && currentRow < path.getNumPaths())
  47767. {
  47768. const File f (path[currentRow]);
  47769. path.remove (currentRow);
  47770. path.add (f, currentRow - 1);
  47771. listBox.selectRow (currentRow - 1);
  47772. }
  47773. }
  47774. else if (button == &downButton)
  47775. {
  47776. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47777. {
  47778. const File f (path[currentRow]);
  47779. path.remove (currentRow);
  47780. path.add (f, currentRow + 1);
  47781. listBox.selectRow (currentRow + 1);
  47782. }
  47783. }
  47784. changed();
  47785. }
  47786. END_JUCE_NAMESPACE
  47787. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47788. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47789. BEGIN_JUCE_NAMESPACE
  47790. const Image juce_createIconForFile (const File& file);
  47791. class FileListTreeItem : public TreeViewItem,
  47792. public TimeSliceClient,
  47793. public AsyncUpdater,
  47794. public ChangeListener
  47795. {
  47796. public:
  47797. FileListTreeItem (FileTreeComponent& owner_,
  47798. DirectoryContentsList* const parentContentsList_,
  47799. const int indexInContentsList_,
  47800. const File& file_,
  47801. TimeSliceThread& thread_)
  47802. : file (file_),
  47803. owner (owner_),
  47804. parentContentsList (parentContentsList_),
  47805. indexInContentsList (indexInContentsList_),
  47806. subContentsList (0),
  47807. canDeleteSubContentsList (false),
  47808. thread (thread_),
  47809. icon (0)
  47810. {
  47811. DirectoryContentsList::FileInfo fileInfo;
  47812. if (parentContentsList_ != 0
  47813. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47814. {
  47815. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47816. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47817. isDirectory = fileInfo.isDirectory;
  47818. }
  47819. else
  47820. {
  47821. isDirectory = true;
  47822. }
  47823. }
  47824. ~FileListTreeItem()
  47825. {
  47826. thread.removeTimeSliceClient (this);
  47827. clearSubItems();
  47828. if (canDeleteSubContentsList)
  47829. delete subContentsList;
  47830. }
  47831. bool mightContainSubItems() { return isDirectory; }
  47832. const String getUniqueName() const { return file.getFullPathName(); }
  47833. int getItemHeight() const { return 22; }
  47834. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47835. void itemOpennessChanged (bool isNowOpen)
  47836. {
  47837. if (isNowOpen)
  47838. {
  47839. clearSubItems();
  47840. isDirectory = file.isDirectory();
  47841. if (isDirectory)
  47842. {
  47843. if (subContentsList == 0)
  47844. {
  47845. jassert (parentContentsList != 0);
  47846. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47847. l->setDirectory (file, true, true);
  47848. setSubContentsList (l);
  47849. canDeleteSubContentsList = true;
  47850. }
  47851. changeListenerCallback (0);
  47852. }
  47853. }
  47854. }
  47855. void setSubContentsList (DirectoryContentsList* newList)
  47856. {
  47857. jassert (subContentsList == 0);
  47858. subContentsList = newList;
  47859. newList->addChangeListener (this);
  47860. }
  47861. void changeListenerCallback (ChangeBroadcaster*)
  47862. {
  47863. clearSubItems();
  47864. if (isOpen() && subContentsList != 0)
  47865. {
  47866. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47867. {
  47868. FileListTreeItem* const item
  47869. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47870. addSubItem (item);
  47871. }
  47872. }
  47873. }
  47874. void paintItem (Graphics& g, int width, int height)
  47875. {
  47876. if (file != File::nonexistent)
  47877. {
  47878. updateIcon (true);
  47879. if (icon.isNull())
  47880. thread.addTimeSliceClient (this);
  47881. }
  47882. owner.getLookAndFeel()
  47883. .drawFileBrowserRow (g, width, height,
  47884. file.getFileName(),
  47885. &icon, fileSize, modTime,
  47886. isDirectory, isSelected(),
  47887. indexInContentsList, owner);
  47888. }
  47889. void itemClicked (const MouseEvent& e)
  47890. {
  47891. owner.sendMouseClickMessage (file, e);
  47892. }
  47893. void itemDoubleClicked (const MouseEvent& e)
  47894. {
  47895. TreeViewItem::itemDoubleClicked (e);
  47896. owner.sendDoubleClickMessage (file);
  47897. }
  47898. void itemSelectionChanged (bool)
  47899. {
  47900. owner.sendSelectionChangeMessage();
  47901. }
  47902. bool useTimeSlice()
  47903. {
  47904. updateIcon (false);
  47905. thread.removeTimeSliceClient (this);
  47906. return false;
  47907. }
  47908. void handleAsyncUpdate()
  47909. {
  47910. owner.repaint();
  47911. }
  47912. const File file;
  47913. private:
  47914. FileTreeComponent& owner;
  47915. DirectoryContentsList* parentContentsList;
  47916. int indexInContentsList;
  47917. DirectoryContentsList* subContentsList;
  47918. bool isDirectory, canDeleteSubContentsList;
  47919. TimeSliceThread& thread;
  47920. Image icon;
  47921. String fileSize;
  47922. String modTime;
  47923. void updateIcon (const bool onlyUpdateIfCached)
  47924. {
  47925. if (icon.isNull())
  47926. {
  47927. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47928. Image im (ImageCache::getFromHashCode (hashCode));
  47929. if (im.isNull() && ! onlyUpdateIfCached)
  47930. {
  47931. im = juce_createIconForFile (file);
  47932. if (im.isValid())
  47933. ImageCache::addImageToCache (im, hashCode);
  47934. }
  47935. if (im.isValid())
  47936. {
  47937. icon = im;
  47938. triggerAsyncUpdate();
  47939. }
  47940. }
  47941. }
  47942. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem);
  47943. };
  47944. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47945. : DirectoryContentsDisplayComponent (listToShow)
  47946. {
  47947. FileListTreeItem* const root
  47948. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47949. listToShow.getTimeSliceThread());
  47950. root->setSubContentsList (&listToShow);
  47951. setRootItemVisible (false);
  47952. setRootItem (root);
  47953. }
  47954. FileTreeComponent::~FileTreeComponent()
  47955. {
  47956. deleteRootItem();
  47957. }
  47958. const File FileTreeComponent::getSelectedFile (const int index) const
  47959. {
  47960. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47961. return item != 0 ? item->file
  47962. : File::nonexistent;
  47963. }
  47964. void FileTreeComponent::deselectAllFiles()
  47965. {
  47966. clearSelectedItems();
  47967. }
  47968. void FileTreeComponent::scrollToTop()
  47969. {
  47970. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47971. }
  47972. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47973. {
  47974. dragAndDropDescription = description;
  47975. }
  47976. END_JUCE_NAMESPACE
  47977. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47978. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47979. BEGIN_JUCE_NAMESPACE
  47980. ImagePreviewComponent::ImagePreviewComponent()
  47981. {
  47982. }
  47983. ImagePreviewComponent::~ImagePreviewComponent()
  47984. {
  47985. }
  47986. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47987. {
  47988. const int availableW = proportionOfWidth (0.97f);
  47989. const int availableH = getHeight() - 13 * 4;
  47990. const double scale = jmin (1.0,
  47991. availableW / (double) w,
  47992. availableH / (double) h);
  47993. w = roundToInt (scale * w);
  47994. h = roundToInt (scale * h);
  47995. }
  47996. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47997. {
  47998. if (fileToLoad != file)
  47999. {
  48000. fileToLoad = file;
  48001. startTimer (100);
  48002. }
  48003. }
  48004. void ImagePreviewComponent::timerCallback()
  48005. {
  48006. stopTimer();
  48007. currentThumbnail = Image::null;
  48008. currentDetails = String::empty;
  48009. repaint();
  48010. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48011. if (in != 0)
  48012. {
  48013. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48014. if (format != 0)
  48015. {
  48016. currentThumbnail = format->decodeImage (*in);
  48017. if (currentThumbnail.isValid())
  48018. {
  48019. int w = currentThumbnail.getWidth();
  48020. int h = currentThumbnail.getHeight();
  48021. currentDetails
  48022. << fileToLoad.getFileName() << "\n"
  48023. << format->getFormatName() << "\n"
  48024. << w << " x " << h << " pixels\n"
  48025. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48026. getThumbSize (w, h);
  48027. currentThumbnail = currentThumbnail.rescaled (w, h);
  48028. }
  48029. }
  48030. }
  48031. }
  48032. void ImagePreviewComponent::paint (Graphics& g)
  48033. {
  48034. if (currentThumbnail.isValid())
  48035. {
  48036. g.setFont (13.0f);
  48037. int w = currentThumbnail.getWidth();
  48038. int h = currentThumbnail.getHeight();
  48039. getThumbSize (w, h);
  48040. const int numLines = 4;
  48041. const int totalH = 13 * numLines + h + 4;
  48042. const int y = (getHeight() - totalH) / 2;
  48043. g.drawImageWithin (currentThumbnail,
  48044. (getWidth() - w) / 2, y, w, h,
  48045. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48046. false);
  48047. g.drawFittedText (currentDetails,
  48048. 0, y + h + 4, getWidth(), 100,
  48049. Justification::centredTop, numLines);
  48050. }
  48051. }
  48052. END_JUCE_NAMESPACE
  48053. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48054. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48055. BEGIN_JUCE_NAMESPACE
  48056. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48057. const String& directoryWildcardPatterns,
  48058. const String& description_)
  48059. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48060. : (description_ + " (" + fileWildcardPatterns + ")"))
  48061. {
  48062. parse (fileWildcardPatterns, fileWildcards);
  48063. parse (directoryWildcardPatterns, directoryWildcards);
  48064. }
  48065. WildcardFileFilter::~WildcardFileFilter()
  48066. {
  48067. }
  48068. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48069. {
  48070. return match (file, fileWildcards);
  48071. }
  48072. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48073. {
  48074. return match (file, directoryWildcards);
  48075. }
  48076. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48077. {
  48078. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48079. result.trim();
  48080. result.removeEmptyStrings();
  48081. // special case for *.*, because people use it to mean "any file", but it
  48082. // would actually ignore files with no extension.
  48083. for (int i = result.size(); --i >= 0;)
  48084. if (result[i] == "*.*")
  48085. result.set (i, "*");
  48086. }
  48087. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48088. {
  48089. const String filename (file.getFileName());
  48090. for (int i = wildcards.size(); --i >= 0;)
  48091. if (filename.matchesWildcard (wildcards[i], true))
  48092. return true;
  48093. return false;
  48094. }
  48095. END_JUCE_NAMESPACE
  48096. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48097. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48098. BEGIN_JUCE_NAMESPACE
  48099. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48100. {
  48101. }
  48102. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48103. {
  48104. }
  48105. namespace KeyboardFocusHelpers
  48106. {
  48107. // This will sort a set of components, so that they are ordered in terms of
  48108. // left-to-right and then top-to-bottom.
  48109. class ScreenPositionComparator
  48110. {
  48111. public:
  48112. ScreenPositionComparator() {}
  48113. static int compareElements (const Component* const first, const Component* const second)
  48114. {
  48115. int explicitOrder1 = first->getExplicitFocusOrder();
  48116. if (explicitOrder1 <= 0)
  48117. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48118. int explicitOrder2 = second->getExplicitFocusOrder();
  48119. if (explicitOrder2 <= 0)
  48120. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48121. if (explicitOrder1 != explicitOrder2)
  48122. return explicitOrder1 - explicitOrder2;
  48123. const int diff = first->getY() - second->getY();
  48124. return (diff == 0) ? first->getX() - second->getX()
  48125. : diff;
  48126. }
  48127. };
  48128. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48129. {
  48130. if (parent->getNumChildComponents() > 0)
  48131. {
  48132. Array <Component*> localComps;
  48133. ScreenPositionComparator comparator;
  48134. int i;
  48135. for (i = parent->getNumChildComponents(); --i >= 0;)
  48136. {
  48137. Component* const c = parent->getChildComponent (i);
  48138. if (c->isVisible() && c->isEnabled())
  48139. localComps.addSorted (comparator, c);
  48140. }
  48141. for (i = 0; i < localComps.size(); ++i)
  48142. {
  48143. Component* const c = localComps.getUnchecked (i);
  48144. if (c->getWantsKeyboardFocus())
  48145. comps.add (c);
  48146. if (! c->isFocusContainer())
  48147. findAllFocusableComponents (c, comps);
  48148. }
  48149. }
  48150. }
  48151. }
  48152. namespace KeyboardFocusHelpers
  48153. {
  48154. Component* getIncrementedComponent (Component* const current, const int delta)
  48155. {
  48156. Component* focusContainer = current->getParentComponent();
  48157. if (focusContainer != 0)
  48158. {
  48159. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48160. focusContainer = focusContainer->getParentComponent();
  48161. if (focusContainer != 0)
  48162. {
  48163. Array <Component*> comps;
  48164. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48165. if (comps.size() > 0)
  48166. {
  48167. const int index = comps.indexOf (current);
  48168. return comps [(index + comps.size() + delta) % comps.size()];
  48169. }
  48170. }
  48171. }
  48172. return 0;
  48173. }
  48174. }
  48175. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48176. {
  48177. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48178. }
  48179. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48180. {
  48181. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48182. }
  48183. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48184. {
  48185. Array <Component*> comps;
  48186. if (parentComponent != 0)
  48187. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48188. return comps.getFirst();
  48189. }
  48190. END_JUCE_NAMESPACE
  48191. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48192. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48193. BEGIN_JUCE_NAMESPACE
  48194. bool KeyListener::keyStateChanged (const bool, Component*)
  48195. {
  48196. return false;
  48197. }
  48198. END_JUCE_NAMESPACE
  48199. /*** End of inlined file: juce_KeyListener.cpp ***/
  48200. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48201. BEGIN_JUCE_NAMESPACE
  48202. // N.B. these two includes are put here deliberately to avoid problems with
  48203. // old GCCs failing on long include paths
  48204. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48205. {
  48206. public:
  48207. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48208. const CommandID commandID_,
  48209. const String& keyName,
  48210. const int keyNum_)
  48211. : Button (keyName),
  48212. owner (owner_),
  48213. commandID (commandID_),
  48214. keyNum (keyNum_)
  48215. {
  48216. setWantsKeyboardFocus (false);
  48217. setTriggeredOnMouseDown (keyNum >= 0);
  48218. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48219. : TRANS("click to change this key-mapping"));
  48220. }
  48221. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48222. {
  48223. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48224. keyNum >= 0 ? getName() : String::empty);
  48225. }
  48226. void clicked()
  48227. {
  48228. if (keyNum >= 0)
  48229. {
  48230. // existing key clicked..
  48231. PopupMenu m;
  48232. m.addItem (1, TRANS("change this key-mapping"));
  48233. m.addSeparator();
  48234. m.addItem (2, TRANS("remove this key-mapping"));
  48235. switch (m.show())
  48236. {
  48237. case 1: assignNewKey(); break;
  48238. case 2: owner.getMappings().removeKeyPress (commandID, keyNum); break;
  48239. default: break;
  48240. }
  48241. }
  48242. else
  48243. {
  48244. assignNewKey(); // + button pressed..
  48245. }
  48246. }
  48247. void fitToContent (const int h) throw()
  48248. {
  48249. if (keyNum < 0)
  48250. {
  48251. setSize (h, h);
  48252. }
  48253. else
  48254. {
  48255. Font f (h * 0.6f);
  48256. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48257. }
  48258. }
  48259. class KeyEntryWindow : public AlertWindow
  48260. {
  48261. public:
  48262. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48263. : AlertWindow (TRANS("New key-mapping"),
  48264. TRANS("Please press a key combination now..."),
  48265. AlertWindow::NoIcon),
  48266. owner (owner_)
  48267. {
  48268. addButton (TRANS("Ok"), 1);
  48269. addButton (TRANS("Cancel"), 0);
  48270. // (avoid return + escape keys getting processed by the buttons..)
  48271. for (int i = getNumChildComponents(); --i >= 0;)
  48272. getChildComponent (i)->setWantsKeyboardFocus (false);
  48273. setWantsKeyboardFocus (true);
  48274. grabKeyboardFocus();
  48275. }
  48276. bool keyPressed (const KeyPress& key)
  48277. {
  48278. lastPress = key;
  48279. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48280. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48281. if (previousCommand != 0)
  48282. message << "\n\n" << TRANS("(Currently assigned to \"")
  48283. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48284. setMessage (message);
  48285. return true;
  48286. }
  48287. bool keyStateChanged (bool)
  48288. {
  48289. return true;
  48290. }
  48291. KeyPress lastPress;
  48292. private:
  48293. KeyMappingEditorComponent& owner;
  48294. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow);
  48295. };
  48296. void assignNewKey()
  48297. {
  48298. KeyEntryWindow entryWindow (owner);
  48299. if (entryWindow.runModalLoop() != 0)
  48300. {
  48301. entryWindow.setVisible (false);
  48302. if (entryWindow.lastPress.isValid())
  48303. {
  48304. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (entryWindow.lastPress);
  48305. if (previousCommand == 0
  48306. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48307. TRANS("Change key-mapping"),
  48308. TRANS("This key is already assigned to the command \"")
  48309. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48310. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48311. TRANS("Re-assign"),
  48312. TRANS("Cancel")))
  48313. {
  48314. owner.getMappings().removeKeyPress (entryWindow.lastPress);
  48315. if (keyNum >= 0)
  48316. owner.getMappings().removeKeyPress (commandID, keyNum);
  48317. owner.getMappings().addKeyPress (commandID, entryWindow.lastPress, keyNum);
  48318. }
  48319. }
  48320. }
  48321. }
  48322. private:
  48323. KeyMappingEditorComponent& owner;
  48324. const CommandID commandID;
  48325. const int keyNum;
  48326. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton);
  48327. };
  48328. class KeyMappingEditorComponent::ItemComponent : public Component
  48329. {
  48330. public:
  48331. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48332. : owner (owner_), commandID (commandID_)
  48333. {
  48334. setInterceptsMouseClicks (false, true);
  48335. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48336. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48337. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48338. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48339. addKeyPressButton (String::empty, -1, isReadOnly);
  48340. }
  48341. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48342. {
  48343. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48344. keyChangeButtons.add (b);
  48345. b->setEnabled (! isReadOnly);
  48346. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48347. addChildComponent (b);
  48348. }
  48349. void paint (Graphics& g)
  48350. {
  48351. g.setFont (getHeight() * 0.7f);
  48352. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48353. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48354. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48355. Justification::centredLeft, true);
  48356. }
  48357. void resized()
  48358. {
  48359. int x = getWidth() - 4;
  48360. for (int i = keyChangeButtons.size(); --i >= 0;)
  48361. {
  48362. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48363. b->fitToContent (getHeight() - 2);
  48364. b->setTopRightPosition (x, 1);
  48365. x = b->getX() - 5;
  48366. }
  48367. }
  48368. private:
  48369. KeyMappingEditorComponent& owner;
  48370. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48371. const CommandID commandID;
  48372. enum { maxNumAssignments = 3 };
  48373. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  48374. };
  48375. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48376. {
  48377. public:
  48378. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48379. : owner (owner_), commandID (commandID_)
  48380. {
  48381. }
  48382. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48383. bool mightContainSubItems() { return false; }
  48384. int getItemHeight() const { return 20; }
  48385. Component* createItemComponent()
  48386. {
  48387. return new ItemComponent (owner, commandID);
  48388. }
  48389. private:
  48390. KeyMappingEditorComponent& owner;
  48391. const CommandID commandID;
  48392. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem);
  48393. };
  48394. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48395. {
  48396. public:
  48397. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48398. : owner (owner_), categoryName (name)
  48399. {
  48400. }
  48401. const String getUniqueName() const { return categoryName + "_cat"; }
  48402. bool mightContainSubItems() { return true; }
  48403. int getItemHeight() const { return 28; }
  48404. void paintItem (Graphics& g, int width, int height)
  48405. {
  48406. g.setFont (height * 0.6f, Font::bold);
  48407. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48408. g.drawText (categoryName,
  48409. 2, 0, width - 2, height,
  48410. Justification::centredLeft, true);
  48411. }
  48412. void itemOpennessChanged (bool isNowOpen)
  48413. {
  48414. if (isNowOpen)
  48415. {
  48416. if (getNumSubItems() == 0)
  48417. {
  48418. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48419. for (int i = 0; i < commands.size(); ++i)
  48420. {
  48421. if (owner.shouldCommandBeIncluded (commands[i]))
  48422. addSubItem (new MappingItem (owner, commands[i]));
  48423. }
  48424. }
  48425. }
  48426. else
  48427. {
  48428. clearSubItems();
  48429. }
  48430. }
  48431. private:
  48432. KeyMappingEditorComponent& owner;
  48433. String categoryName;
  48434. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem);
  48435. };
  48436. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48437. public ChangeListener,
  48438. public ButtonListener
  48439. {
  48440. public:
  48441. TopLevelItem (KeyMappingEditorComponent& owner_)
  48442. : owner (owner_)
  48443. {
  48444. setLinesDrawnForSubItems (false);
  48445. owner.getMappings().addChangeListener (this);
  48446. }
  48447. ~TopLevelItem()
  48448. {
  48449. owner.getMappings().removeChangeListener (this);
  48450. }
  48451. bool mightContainSubItems() { return true; }
  48452. const String getUniqueName() const { return "keys"; }
  48453. void changeListenerCallback (ChangeBroadcaster*)
  48454. {
  48455. const ScopedPointer <XmlElement> oldOpenness (owner.tree.getOpennessState (true));
  48456. clearSubItems();
  48457. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48458. for (int i = 0; i < categories.size(); ++i)
  48459. {
  48460. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48461. int count = 0;
  48462. for (int j = 0; j < commands.size(); ++j)
  48463. if (owner.shouldCommandBeIncluded (commands[j]))
  48464. ++count;
  48465. if (count > 0)
  48466. addSubItem (new CategoryItem (owner, categories[i]));
  48467. }
  48468. if (oldOpenness != 0)
  48469. owner.tree.restoreOpennessState (*oldOpenness);
  48470. }
  48471. void buttonClicked (Button*)
  48472. {
  48473. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48474. TRANS("Reset to defaults"),
  48475. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48476. TRANS("Reset")))
  48477. {
  48478. owner.getMappings().resetToDefaultMappings();
  48479. }
  48480. }
  48481. private:
  48482. KeyMappingEditorComponent& owner;
  48483. };
  48484. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48485. const bool showResetToDefaultButton)
  48486. : mappings (mappingManager),
  48487. resetButton (TRANS ("reset to defaults"))
  48488. {
  48489. treeItem = new TopLevelItem (*this);
  48490. if (showResetToDefaultButton)
  48491. {
  48492. addAndMakeVisible (&resetButton);
  48493. resetButton.addListener (treeItem);
  48494. }
  48495. addAndMakeVisible (&tree);
  48496. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48497. tree.setRootItemVisible (false);
  48498. tree.setDefaultOpenness (true);
  48499. tree.setRootItem (treeItem);
  48500. }
  48501. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48502. {
  48503. tree.setRootItem (0);
  48504. }
  48505. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48506. const Colour& textColour)
  48507. {
  48508. setColour (backgroundColourId, mainBackground);
  48509. setColour (textColourId, textColour);
  48510. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48511. }
  48512. void KeyMappingEditorComponent::parentHierarchyChanged()
  48513. {
  48514. treeItem->changeListenerCallback (0);
  48515. }
  48516. void KeyMappingEditorComponent::resized()
  48517. {
  48518. int h = getHeight();
  48519. if (resetButton.isVisible())
  48520. {
  48521. const int buttonHeight = 20;
  48522. h -= buttonHeight + 8;
  48523. int x = getWidth() - 8;
  48524. resetButton.changeWidthToFitText (buttonHeight);
  48525. resetButton.setTopRightPosition (x, h + 6);
  48526. }
  48527. tree.setBounds (0, 0, getWidth(), h);
  48528. }
  48529. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48530. {
  48531. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48532. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48533. }
  48534. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48535. {
  48536. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48537. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48538. }
  48539. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48540. {
  48541. return key.getTextDescription();
  48542. }
  48543. END_JUCE_NAMESPACE
  48544. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48545. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48546. BEGIN_JUCE_NAMESPACE
  48547. KeyPress::KeyPress() throw()
  48548. : keyCode (0),
  48549. mods (0),
  48550. textCharacter (0)
  48551. {
  48552. }
  48553. KeyPress::KeyPress (const int keyCode_,
  48554. const ModifierKeys& mods_,
  48555. const juce_wchar textCharacter_) throw()
  48556. : keyCode (keyCode_),
  48557. mods (mods_),
  48558. textCharacter (textCharacter_)
  48559. {
  48560. }
  48561. KeyPress::KeyPress (const int keyCode_) throw()
  48562. : keyCode (keyCode_),
  48563. textCharacter (0)
  48564. {
  48565. }
  48566. KeyPress::KeyPress (const KeyPress& other) throw()
  48567. : keyCode (other.keyCode),
  48568. mods (other.mods),
  48569. textCharacter (other.textCharacter)
  48570. {
  48571. }
  48572. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48573. {
  48574. keyCode = other.keyCode;
  48575. mods = other.mods;
  48576. textCharacter = other.textCharacter;
  48577. return *this;
  48578. }
  48579. bool KeyPress::operator== (const KeyPress& other) const throw()
  48580. {
  48581. return mods.getRawFlags() == other.mods.getRawFlags()
  48582. && (textCharacter == other.textCharacter
  48583. || textCharacter == 0
  48584. || other.textCharacter == 0)
  48585. && (keyCode == other.keyCode
  48586. || (keyCode < 256
  48587. && other.keyCode < 256
  48588. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48589. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48590. }
  48591. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48592. {
  48593. return ! operator== (other);
  48594. }
  48595. bool KeyPress::isCurrentlyDown() const
  48596. {
  48597. return isKeyCurrentlyDown (keyCode)
  48598. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48599. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48600. }
  48601. namespace KeyPressHelpers
  48602. {
  48603. struct KeyNameAndCode
  48604. {
  48605. const char* name;
  48606. int code;
  48607. };
  48608. const KeyNameAndCode translations[] =
  48609. {
  48610. { "spacebar", KeyPress::spaceKey },
  48611. { "return", KeyPress::returnKey },
  48612. { "escape", KeyPress::escapeKey },
  48613. { "backspace", KeyPress::backspaceKey },
  48614. { "cursor left", KeyPress::leftKey },
  48615. { "cursor right", KeyPress::rightKey },
  48616. { "cursor up", KeyPress::upKey },
  48617. { "cursor down", KeyPress::downKey },
  48618. { "page up", KeyPress::pageUpKey },
  48619. { "page down", KeyPress::pageDownKey },
  48620. { "home", KeyPress::homeKey },
  48621. { "end", KeyPress::endKey },
  48622. { "delete", KeyPress::deleteKey },
  48623. { "insert", KeyPress::insertKey },
  48624. { "tab", KeyPress::tabKey },
  48625. { "play", KeyPress::playKey },
  48626. { "stop", KeyPress::stopKey },
  48627. { "fast forward", KeyPress::fastForwardKey },
  48628. { "rewind", KeyPress::rewindKey }
  48629. };
  48630. const String numberPadPrefix() { return "numpad "; }
  48631. }
  48632. const KeyPress KeyPress::createFromDescription (const String& desc)
  48633. {
  48634. int modifiers = 0;
  48635. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48636. || desc.containsWholeWordIgnoreCase ("control")
  48637. || desc.containsWholeWordIgnoreCase ("ctl"))
  48638. modifiers |= ModifierKeys::ctrlModifier;
  48639. if (desc.containsWholeWordIgnoreCase ("shift")
  48640. || desc.containsWholeWordIgnoreCase ("shft"))
  48641. modifiers |= ModifierKeys::shiftModifier;
  48642. if (desc.containsWholeWordIgnoreCase ("alt")
  48643. || desc.containsWholeWordIgnoreCase ("option"))
  48644. modifiers |= ModifierKeys::altModifier;
  48645. if (desc.containsWholeWordIgnoreCase ("command")
  48646. || desc.containsWholeWordIgnoreCase ("cmd"))
  48647. modifiers |= ModifierKeys::commandModifier;
  48648. int key = 0;
  48649. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48650. {
  48651. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48652. {
  48653. key = KeyPressHelpers::translations[i].code;
  48654. break;
  48655. }
  48656. }
  48657. if (key == 0)
  48658. {
  48659. // see if it's a numpad key..
  48660. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48661. {
  48662. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48663. if (lastChar >= '0' && lastChar <= '9')
  48664. key = numberPad0 + lastChar - '0';
  48665. else if (lastChar == '+')
  48666. key = numberPadAdd;
  48667. else if (lastChar == '-')
  48668. key = numberPadSubtract;
  48669. else if (lastChar == '*')
  48670. key = numberPadMultiply;
  48671. else if (lastChar == '/')
  48672. key = numberPadDivide;
  48673. else if (lastChar == '.')
  48674. key = numberPadDecimalPoint;
  48675. else if (lastChar == '=')
  48676. key = numberPadEquals;
  48677. else if (desc.endsWith ("separator"))
  48678. key = numberPadSeparator;
  48679. else if (desc.endsWith ("delete"))
  48680. key = numberPadDelete;
  48681. }
  48682. if (key == 0)
  48683. {
  48684. // see if it's a function key..
  48685. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48686. for (int i = 1; i <= 12; ++i)
  48687. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48688. key = F1Key + i - 1;
  48689. if (key == 0)
  48690. {
  48691. // give up and use the hex code..
  48692. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48693. .toLowerCase()
  48694. .retainCharacters ("0123456789abcdef")
  48695. .getHexValue32();
  48696. if (hexCode > 0)
  48697. key = hexCode;
  48698. else
  48699. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48700. }
  48701. }
  48702. }
  48703. return KeyPress (key, ModifierKeys (modifiers), 0);
  48704. }
  48705. const String KeyPress::getTextDescription() const
  48706. {
  48707. String desc;
  48708. if (keyCode > 0)
  48709. {
  48710. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48711. // want to store it as being a slash, not shift+whatever.
  48712. if (textCharacter == '/')
  48713. return "/";
  48714. if (mods.isCtrlDown())
  48715. desc << "ctrl + ";
  48716. if (mods.isShiftDown())
  48717. desc << "shift + ";
  48718. #if JUCE_MAC
  48719. // only do this on the mac, because on Windows ctrl and command are the same,
  48720. // and this would get confusing
  48721. if (mods.isCommandDown())
  48722. desc << "command + ";
  48723. if (mods.isAltDown())
  48724. desc << "option + ";
  48725. #else
  48726. if (mods.isAltDown())
  48727. desc << "alt + ";
  48728. #endif
  48729. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48730. if (keyCode == KeyPressHelpers::translations[i].code)
  48731. return desc + KeyPressHelpers::translations[i].name;
  48732. if (keyCode >= F1Key && keyCode <= F16Key)
  48733. desc << 'F' << (1 + keyCode - F1Key);
  48734. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48735. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48736. else if (keyCode >= 33 && keyCode < 176)
  48737. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48738. else if (keyCode == numberPadAdd)
  48739. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48740. else if (keyCode == numberPadSubtract)
  48741. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48742. else if (keyCode == numberPadMultiply)
  48743. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48744. else if (keyCode == numberPadDivide)
  48745. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48746. else if (keyCode == numberPadSeparator)
  48747. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48748. else if (keyCode == numberPadDecimalPoint)
  48749. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48750. else if (keyCode == numberPadDelete)
  48751. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48752. else
  48753. desc << '#' << String::toHexString (keyCode);
  48754. }
  48755. return desc;
  48756. }
  48757. END_JUCE_NAMESPACE
  48758. /*** End of inlined file: juce_KeyPress.cpp ***/
  48759. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48760. BEGIN_JUCE_NAMESPACE
  48761. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48762. : commandManager (commandManager_)
  48763. {
  48764. // A manager is needed to get the descriptions of commands, and will be called when
  48765. // a command is invoked. So you can't leave this null..
  48766. jassert (commandManager_ != 0);
  48767. Desktop::getInstance().addFocusChangeListener (this);
  48768. }
  48769. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48770. : commandManager (other.commandManager)
  48771. {
  48772. Desktop::getInstance().addFocusChangeListener (this);
  48773. }
  48774. KeyPressMappingSet::~KeyPressMappingSet()
  48775. {
  48776. Desktop::getInstance().removeFocusChangeListener (this);
  48777. }
  48778. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48779. {
  48780. for (int i = 0; i < mappings.size(); ++i)
  48781. if (mappings.getUnchecked(i)->commandID == commandID)
  48782. return mappings.getUnchecked (i)->keypresses;
  48783. return Array <KeyPress> ();
  48784. }
  48785. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48786. const KeyPress& newKeyPress,
  48787. int insertIndex)
  48788. {
  48789. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48790. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48791. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48792. && ! newKeyPress.getModifiers().isShiftDown()));
  48793. if (findCommandForKeyPress (newKeyPress) != commandID)
  48794. {
  48795. removeKeyPress (newKeyPress);
  48796. if (newKeyPress.isValid())
  48797. {
  48798. for (int i = mappings.size(); --i >= 0;)
  48799. {
  48800. if (mappings.getUnchecked(i)->commandID == commandID)
  48801. {
  48802. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48803. sendChangeMessage();
  48804. return;
  48805. }
  48806. }
  48807. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48808. if (ci != 0)
  48809. {
  48810. CommandMapping* const cm = new CommandMapping();
  48811. cm->commandID = commandID;
  48812. cm->keypresses.add (newKeyPress);
  48813. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48814. mappings.add (cm);
  48815. sendChangeMessage();
  48816. }
  48817. }
  48818. }
  48819. }
  48820. void KeyPressMappingSet::resetToDefaultMappings()
  48821. {
  48822. mappings.clear();
  48823. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48824. {
  48825. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48826. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48827. {
  48828. addKeyPress (ci->commandID,
  48829. ci->defaultKeypresses.getReference (j));
  48830. }
  48831. }
  48832. sendChangeMessage();
  48833. }
  48834. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48835. {
  48836. clearAllKeyPresses (commandID);
  48837. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48838. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48839. {
  48840. addKeyPress (ci->commandID,
  48841. ci->defaultKeypresses.getReference (j));
  48842. }
  48843. }
  48844. void KeyPressMappingSet::clearAllKeyPresses()
  48845. {
  48846. if (mappings.size() > 0)
  48847. {
  48848. sendChangeMessage();
  48849. mappings.clear();
  48850. }
  48851. }
  48852. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48853. {
  48854. for (int i = mappings.size(); --i >= 0;)
  48855. {
  48856. if (mappings.getUnchecked(i)->commandID == commandID)
  48857. {
  48858. mappings.remove (i);
  48859. sendChangeMessage();
  48860. }
  48861. }
  48862. }
  48863. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48864. {
  48865. if (keypress.isValid())
  48866. {
  48867. for (int i = mappings.size(); --i >= 0;)
  48868. {
  48869. CommandMapping* const cm = mappings.getUnchecked(i);
  48870. for (int j = cm->keypresses.size(); --j >= 0;)
  48871. {
  48872. if (keypress == cm->keypresses [j])
  48873. {
  48874. cm->keypresses.remove (j);
  48875. sendChangeMessage();
  48876. }
  48877. }
  48878. }
  48879. }
  48880. }
  48881. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48882. {
  48883. for (int i = mappings.size(); --i >= 0;)
  48884. {
  48885. if (mappings.getUnchecked(i)->commandID == commandID)
  48886. {
  48887. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48888. sendChangeMessage();
  48889. break;
  48890. }
  48891. }
  48892. }
  48893. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48894. {
  48895. for (int i = 0; i < mappings.size(); ++i)
  48896. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48897. return mappings.getUnchecked(i)->commandID;
  48898. return 0;
  48899. }
  48900. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48901. {
  48902. for (int i = mappings.size(); --i >= 0;)
  48903. if (mappings.getUnchecked(i)->commandID == commandID)
  48904. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48905. return false;
  48906. }
  48907. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48908. const KeyPress& key,
  48909. const bool isKeyDown,
  48910. const int millisecsSinceKeyPressed,
  48911. Component* const originatingComponent) const
  48912. {
  48913. ApplicationCommandTarget::InvocationInfo info (commandID);
  48914. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48915. info.isKeyDown = isKeyDown;
  48916. info.keyPress = key;
  48917. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48918. info.originatingComponent = originatingComponent;
  48919. commandManager->invoke (info, false);
  48920. }
  48921. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48922. {
  48923. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48924. {
  48925. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48926. {
  48927. // if the XML was created as a set of differences from the default mappings,
  48928. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48929. resetToDefaultMappings();
  48930. }
  48931. else
  48932. {
  48933. // if the XML was created calling createXml (false), then we need to clear all
  48934. // the keys and treat the xml as describing the entire set of mappings.
  48935. clearAllKeyPresses();
  48936. }
  48937. forEachXmlChildElement (xmlVersion, map)
  48938. {
  48939. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48940. if (commandId != 0)
  48941. {
  48942. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48943. if (map->hasTagName ("MAPPING"))
  48944. {
  48945. addKeyPress (commandId, key);
  48946. }
  48947. else if (map->hasTagName ("UNMAPPING"))
  48948. {
  48949. if (containsMapping (commandId, key))
  48950. removeKeyPress (key);
  48951. }
  48952. }
  48953. }
  48954. return true;
  48955. }
  48956. return false;
  48957. }
  48958. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48959. {
  48960. ScopedPointer <KeyPressMappingSet> defaultSet;
  48961. if (saveDifferencesFromDefaultSet)
  48962. {
  48963. defaultSet = new KeyPressMappingSet (commandManager);
  48964. defaultSet->resetToDefaultMappings();
  48965. }
  48966. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48967. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48968. int i;
  48969. for (i = 0; i < mappings.size(); ++i)
  48970. {
  48971. const CommandMapping* const cm = mappings.getUnchecked(i);
  48972. for (int j = 0; j < cm->keypresses.size(); ++j)
  48973. {
  48974. if (defaultSet == 0
  48975. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48976. {
  48977. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48978. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48979. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48980. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48981. }
  48982. }
  48983. }
  48984. if (defaultSet != 0)
  48985. {
  48986. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48987. {
  48988. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48989. for (int j = 0; j < cm->keypresses.size(); ++j)
  48990. {
  48991. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48992. {
  48993. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48994. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48995. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48996. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48997. }
  48998. }
  48999. }
  49000. }
  49001. return doc;
  49002. }
  49003. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49004. Component* originatingComponent)
  49005. {
  49006. bool used = false;
  49007. const CommandID commandID = findCommandForKeyPress (key);
  49008. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49009. if (ci != 0
  49010. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49011. {
  49012. ApplicationCommandInfo info (0);
  49013. if (commandManager->getTargetForCommand (commandID, info) != 0
  49014. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49015. {
  49016. invokeCommand (commandID, key, true, 0, originatingComponent);
  49017. used = true;
  49018. }
  49019. else
  49020. {
  49021. if (originatingComponent != 0)
  49022. originatingComponent->getLookAndFeel().playAlertSound();
  49023. }
  49024. }
  49025. return used;
  49026. }
  49027. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49028. {
  49029. bool used = false;
  49030. const uint32 now = Time::getMillisecondCounter();
  49031. for (int i = mappings.size(); --i >= 0;)
  49032. {
  49033. CommandMapping* const cm = mappings.getUnchecked(i);
  49034. if (cm->wantsKeyUpDownCallbacks)
  49035. {
  49036. for (int j = cm->keypresses.size(); --j >= 0;)
  49037. {
  49038. const KeyPress key (cm->keypresses.getReference (j));
  49039. const bool isDown = key.isCurrentlyDown();
  49040. int keyPressEntryIndex = 0;
  49041. bool wasDown = false;
  49042. for (int k = keysDown.size(); --k >= 0;)
  49043. {
  49044. if (key == keysDown.getUnchecked(k)->key)
  49045. {
  49046. keyPressEntryIndex = k;
  49047. wasDown = true;
  49048. used = true;
  49049. break;
  49050. }
  49051. }
  49052. if (isDown != wasDown)
  49053. {
  49054. int millisecs = 0;
  49055. if (isDown)
  49056. {
  49057. KeyPressTime* const k = new KeyPressTime();
  49058. k->key = key;
  49059. k->timeWhenPressed = now;
  49060. keysDown.add (k);
  49061. }
  49062. else
  49063. {
  49064. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49065. if (now > pressTime)
  49066. millisecs = now - pressTime;
  49067. keysDown.remove (keyPressEntryIndex);
  49068. }
  49069. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49070. used = true;
  49071. }
  49072. }
  49073. }
  49074. }
  49075. return used;
  49076. }
  49077. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49078. {
  49079. if (focusedComponent != 0)
  49080. focusedComponent->keyStateChanged (false);
  49081. }
  49082. END_JUCE_NAMESPACE
  49083. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49084. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49085. BEGIN_JUCE_NAMESPACE
  49086. ModifierKeys::ModifierKeys (const int flags_) throw()
  49087. : flags (flags_)
  49088. {
  49089. }
  49090. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49091. : flags (other.flags)
  49092. {
  49093. }
  49094. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49095. {
  49096. flags = other.flags;
  49097. return *this;
  49098. }
  49099. ModifierKeys ModifierKeys::currentModifiers;
  49100. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49101. {
  49102. return currentModifiers;
  49103. }
  49104. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49105. {
  49106. int num = 0;
  49107. if (isLeftButtonDown()) ++num;
  49108. if (isRightButtonDown()) ++num;
  49109. if (isMiddleButtonDown()) ++num;
  49110. return num;
  49111. }
  49112. END_JUCE_NAMESPACE
  49113. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49114. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49115. BEGIN_JUCE_NAMESPACE
  49116. class ComponentAnimator::AnimationTask
  49117. {
  49118. public:
  49119. AnimationTask (Component* const comp)
  49120. : component (comp)
  49121. {
  49122. }
  49123. void reset (const Rectangle<int>& finalBounds,
  49124. float finalAlpha,
  49125. int millisecondsToSpendMoving,
  49126. bool useProxyComponent,
  49127. double startSpeed_, double endSpeed_)
  49128. {
  49129. msElapsed = 0;
  49130. msTotal = jmax (1, millisecondsToSpendMoving);
  49131. lastProgress = 0;
  49132. destination = finalBounds;
  49133. destAlpha = finalAlpha;
  49134. isMoving = (finalBounds != component->getBounds());
  49135. isChangingAlpha = (finalAlpha != component->getAlpha());
  49136. left = component->getX();
  49137. top = component->getY();
  49138. right = component->getRight();
  49139. bottom = component->getBottom();
  49140. alpha = component->getAlpha();
  49141. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49142. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49143. midSpeed = invTotalDistance;
  49144. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49145. if (useProxyComponent)
  49146. proxy = new ProxyComponent (*component);
  49147. else
  49148. proxy = 0;
  49149. component->setVisible (! useProxyComponent);
  49150. }
  49151. bool useTimeslice (const int elapsed)
  49152. {
  49153. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49154. : static_cast <Component*> (component);
  49155. if (c != 0)
  49156. {
  49157. msElapsed += elapsed;
  49158. double newProgress = msElapsed / (double) msTotal;
  49159. if (newProgress >= 0 && newProgress < 1.0)
  49160. {
  49161. newProgress = timeToDistance (newProgress);
  49162. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49163. jassert (newProgress >= lastProgress);
  49164. lastProgress = newProgress;
  49165. if (delta < 1.0)
  49166. {
  49167. bool stillBusy = false;
  49168. if (isMoving)
  49169. {
  49170. left += (destination.getX() - left) * delta;
  49171. top += (destination.getY() - top) * delta;
  49172. right += (destination.getRight() - right) * delta;
  49173. bottom += (destination.getBottom() - bottom) * delta;
  49174. const Rectangle<int> newBounds (roundToInt (left),
  49175. roundToInt (top),
  49176. roundToInt (right - left),
  49177. roundToInt (bottom - top));
  49178. if (newBounds != destination)
  49179. {
  49180. c->setBounds (newBounds);
  49181. stillBusy = true;
  49182. }
  49183. }
  49184. if (isChangingAlpha)
  49185. {
  49186. alpha += (destAlpha - alpha) * delta;
  49187. c->setAlpha ((float) alpha);
  49188. stillBusy = true;
  49189. }
  49190. if (stillBusy)
  49191. return true;
  49192. }
  49193. }
  49194. }
  49195. moveToFinalDestination();
  49196. return false;
  49197. }
  49198. void moveToFinalDestination()
  49199. {
  49200. if (component != 0)
  49201. {
  49202. component->setAlpha ((float) destAlpha);
  49203. component->setBounds (destination);
  49204. }
  49205. }
  49206. class ProxyComponent : public Component
  49207. {
  49208. public:
  49209. ProxyComponent (Component& component)
  49210. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49211. {
  49212. setBounds (component.getBounds());
  49213. setAlpha (component.getAlpha());
  49214. setInterceptsMouseClicks (false, false);
  49215. Component* const parent = component.getParentComponent();
  49216. if (parent != 0)
  49217. parent->addAndMakeVisible (this);
  49218. else if (component.isOnDesktop() && component.getPeer() != 0)
  49219. addToDesktop (component.getPeer()->getStyleFlags());
  49220. else
  49221. jassertfalse; // seem to be trying to animate a component that's not visible..
  49222. setVisible (true);
  49223. toBehind (&component);
  49224. }
  49225. void paint (Graphics& g)
  49226. {
  49227. g.setOpacity (1.0f);
  49228. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49229. 0, 0, image.getWidth(), image.getHeight());
  49230. }
  49231. private:
  49232. Image image;
  49233. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent);
  49234. };
  49235. WeakReference<Component> component;
  49236. ScopedPointer<Component> proxy;
  49237. Rectangle<int> destination;
  49238. double destAlpha;
  49239. int msElapsed, msTotal;
  49240. double startSpeed, midSpeed, endSpeed, lastProgress;
  49241. double left, top, right, bottom, alpha;
  49242. bool isMoving, isChangingAlpha;
  49243. private:
  49244. double timeToDistance (const double time) const throw()
  49245. {
  49246. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49247. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49248. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49249. }
  49250. };
  49251. ComponentAnimator::ComponentAnimator()
  49252. : lastTime (0)
  49253. {
  49254. }
  49255. ComponentAnimator::~ComponentAnimator()
  49256. {
  49257. }
  49258. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49259. {
  49260. for (int i = tasks.size(); --i >= 0;)
  49261. if (component == tasks.getUnchecked(i)->component.get())
  49262. return tasks.getUnchecked(i);
  49263. return 0;
  49264. }
  49265. void ComponentAnimator::animateComponent (Component* const component,
  49266. const Rectangle<int>& finalBounds,
  49267. const float finalAlpha,
  49268. const int millisecondsToSpendMoving,
  49269. const bool useProxyComponent,
  49270. const double startSpeed,
  49271. const double endSpeed)
  49272. {
  49273. // the speeds must be 0 or greater!
  49274. jassert (startSpeed >= 0 && endSpeed >= 0)
  49275. if (component != 0)
  49276. {
  49277. AnimationTask* at = findTaskFor (component);
  49278. if (at == 0)
  49279. {
  49280. at = new AnimationTask (component);
  49281. tasks.add (at);
  49282. sendChangeMessage();
  49283. }
  49284. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49285. useProxyComponent, startSpeed, endSpeed);
  49286. if (! isTimerRunning())
  49287. {
  49288. lastTime = Time::getMillisecondCounter();
  49289. startTimer (1000 / 50);
  49290. }
  49291. }
  49292. }
  49293. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49294. {
  49295. if (component != 0)
  49296. {
  49297. if (component->isShowing() && millisecondsToTake > 0)
  49298. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49299. component->setVisible (false);
  49300. }
  49301. }
  49302. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49303. {
  49304. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49305. {
  49306. component->setAlpha (0.0f);
  49307. component->setVisible (true);
  49308. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49309. }
  49310. }
  49311. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49312. {
  49313. if (tasks.size() > 0)
  49314. {
  49315. if (moveComponentsToTheirFinalPositions)
  49316. for (int i = tasks.size(); --i >= 0;)
  49317. tasks.getUnchecked(i)->moveToFinalDestination();
  49318. tasks.clear();
  49319. sendChangeMessage();
  49320. }
  49321. }
  49322. void ComponentAnimator::cancelAnimation (Component* const component,
  49323. const bool moveComponentToItsFinalPosition)
  49324. {
  49325. AnimationTask* const at = findTaskFor (component);
  49326. if (at != 0)
  49327. {
  49328. if (moveComponentToItsFinalPosition)
  49329. at->moveToFinalDestination();
  49330. tasks.removeObject (at);
  49331. sendChangeMessage();
  49332. }
  49333. }
  49334. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49335. {
  49336. jassert (component != 0);
  49337. AnimationTask* const at = findTaskFor (component);
  49338. if (at != 0)
  49339. return at->destination;
  49340. return component->getBounds();
  49341. }
  49342. bool ComponentAnimator::isAnimating (Component* component) const
  49343. {
  49344. return findTaskFor (component) != 0;
  49345. }
  49346. void ComponentAnimator::timerCallback()
  49347. {
  49348. const uint32 timeNow = Time::getMillisecondCounter();
  49349. if (lastTime == 0 || lastTime == timeNow)
  49350. lastTime = timeNow;
  49351. const int elapsed = timeNow - lastTime;
  49352. for (int i = tasks.size(); --i >= 0;)
  49353. {
  49354. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49355. {
  49356. tasks.remove (i);
  49357. sendChangeMessage();
  49358. }
  49359. }
  49360. lastTime = timeNow;
  49361. if (tasks.size() == 0)
  49362. stopTimer();
  49363. }
  49364. END_JUCE_NAMESPACE
  49365. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49366. /*** Start of inlined file: juce_ComponentBuilder.cpp ***/
  49367. BEGIN_JUCE_NAMESPACE
  49368. namespace ComponentBuilderHelpers
  49369. {
  49370. const String getStateId (const ValueTree& state)
  49371. {
  49372. return state [ComponentBuilder::idProperty].toString();
  49373. }
  49374. Component* findComponentWithID (OwnedArray<Component>& components, const String& compId)
  49375. {
  49376. jassert (compId.isNotEmpty());
  49377. for (int i = components.size(); --i >= 0;)
  49378. {
  49379. Component* const c = components.getUnchecked (i);
  49380. if (c->getComponentID() == compId)
  49381. return components.removeAndReturn (i);
  49382. }
  49383. return 0;
  49384. }
  49385. Component* findComponentWithID (Component* const c, const String& compId)
  49386. {
  49387. jassert (compId.isNotEmpty());
  49388. if (c->getComponentID() == compId)
  49389. return c;
  49390. for (int i = c->getNumChildComponents(); --i >= 0;)
  49391. {
  49392. Component* const child = findComponentWithID (c->getChildComponent (i), compId);
  49393. if (child != 0)
  49394. return child;
  49395. }
  49396. return 0;
  49397. }
  49398. Component* createNewComponent (ComponentBuilder::TypeHandler& type,
  49399. const ValueTree& state, Component* parent)
  49400. {
  49401. Component* const c = type.addNewComponentFromState (state, parent);
  49402. jassert (c != 0);
  49403. c->setComponentID (getStateId (state));
  49404. return c;
  49405. }
  49406. void updateComponent (ComponentBuilder& builder, const ValueTree& state)
  49407. {
  49408. Component* topLevelComp = builder.getManagedComponent();
  49409. if (topLevelComp != 0)
  49410. {
  49411. ComponentBuilder::TypeHandler* const type = builder.getHandlerForState (state);
  49412. const String uid (getStateId (state));
  49413. if (type == 0 || uid.isEmpty())
  49414. {
  49415. // ..handle the case where a child of the actual state node has changed.
  49416. if (state.getParent().isValid())
  49417. updateComponent (builder, state.getParent());
  49418. }
  49419. else
  49420. {
  49421. Component* const changedComp = findComponentWithID (topLevelComp, uid);
  49422. if (changedComp != 0)
  49423. type->updateComponentFromState (changedComp, state);
  49424. }
  49425. }
  49426. }
  49427. }
  49428. const Identifier ComponentBuilder::idProperty ("id");
  49429. ComponentBuilder::ComponentBuilder (const ValueTree& state_)
  49430. : state (state_), imageProvider (0)
  49431. {
  49432. state.addListener (this);
  49433. }
  49434. ComponentBuilder::~ComponentBuilder()
  49435. {
  49436. state.removeListener (this);
  49437. #if JUCE_DEBUG
  49438. // Don't delete the managed component!! The builder owns that component, and will delete
  49439. // it automatically when it gets deleted.
  49440. jassert (componentRef.get() == static_cast <Component*> (component));
  49441. #endif
  49442. }
  49443. Component* ComponentBuilder::getManagedComponent()
  49444. {
  49445. if (component == 0)
  49446. {
  49447. component = createComponent();
  49448. #if JUCE_DEBUG
  49449. componentRef = component;
  49450. #endif
  49451. }
  49452. return component;
  49453. }
  49454. Component* ComponentBuilder::createComponent()
  49455. {
  49456. jassert (types.size() > 0); // You need to register all the necessary types before you can load a component!
  49457. TypeHandler* const type = getHandlerForState (state);
  49458. jassert (type != 0); // trying to create a component from an unknown type of ValueTree
  49459. return type != 0 ? ComponentBuilderHelpers::createNewComponent (*type, state, 0) : 0;
  49460. }
  49461. void ComponentBuilder::registerTypeHandler (ComponentBuilder::TypeHandler* const type)
  49462. {
  49463. jassert (type != 0);
  49464. // Don't try to move your types around! Once a type has been added to a builder, the
  49465. // builder owns it, and you should leave it alone!
  49466. jassert (type->builder == 0);
  49467. types.add (type);
  49468. type->builder = this;
  49469. }
  49470. ComponentBuilder::TypeHandler* ComponentBuilder::getHandlerForState (const ValueTree& s) const
  49471. {
  49472. const Identifier targetType (s.getType());
  49473. for (int i = 0; i < types.size(); ++i)
  49474. {
  49475. TypeHandler* const t = types.getUnchecked(i);
  49476. if (t->getType() == targetType)
  49477. return t;
  49478. }
  49479. return 0;
  49480. }
  49481. int ComponentBuilder::getNumHandlers() const throw()
  49482. {
  49483. return types.size();
  49484. }
  49485. ComponentBuilder::TypeHandler* ComponentBuilder::getHandler (const int index) const throw()
  49486. {
  49487. return types [index];
  49488. }
  49489. void ComponentBuilder::setImageProvider (ImageProvider* newImageProvider) throw()
  49490. {
  49491. imageProvider = newImageProvider;
  49492. }
  49493. ComponentBuilder::ImageProvider* ComponentBuilder::getImageProvider() const throw()
  49494. {
  49495. return imageProvider;
  49496. }
  49497. void ComponentBuilder::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
  49498. {
  49499. ComponentBuilderHelpers::updateComponent (*this, tree);
  49500. }
  49501. void ComponentBuilder::valueTreeChildrenChanged (ValueTree& tree)
  49502. {
  49503. ComponentBuilderHelpers::updateComponent (*this, tree);
  49504. }
  49505. void ComponentBuilder::valueTreeParentChanged (ValueTree& tree)
  49506. {
  49507. ComponentBuilderHelpers::updateComponent (*this, tree);
  49508. }
  49509. ComponentBuilder::TypeHandler::TypeHandler (const Identifier& valueTreeType_)
  49510. : builder (0), valueTreeType (valueTreeType_)
  49511. {
  49512. }
  49513. ComponentBuilder::TypeHandler::~TypeHandler()
  49514. {
  49515. }
  49516. ComponentBuilder* ComponentBuilder::TypeHandler::getBuilder() const throw()
  49517. {
  49518. // A type handler needs to be registered with a ComponentBuilder before using it!
  49519. jassert (builder != 0);
  49520. return builder;
  49521. }
  49522. void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children)
  49523. {
  49524. using namespace ComponentBuilderHelpers;
  49525. const int numExistingChildComps = parent.getNumChildComponents();
  49526. Array <Component*> componentsInOrder;
  49527. componentsInOrder.ensureStorageAllocated (numExistingChildComps);
  49528. {
  49529. OwnedArray<Component> existingComponents;
  49530. existingComponents.ensureStorageAllocated (numExistingChildComps);
  49531. int i;
  49532. for (i = 0; i < numExistingChildComps; ++i)
  49533. existingComponents.add (parent.getChildComponent (i));
  49534. const int newNumChildren = children.getNumChildren();
  49535. for (i = 0; i < newNumChildren; ++i)
  49536. {
  49537. const ValueTree childState (children.getChild (i));
  49538. ComponentBuilder::TypeHandler* const type = getHandlerForState (childState);
  49539. jassert (type != 0);
  49540. if (type != 0)
  49541. {
  49542. Component* c = findComponentWithID (existingComponents, getStateId (childState));
  49543. if (c == 0)
  49544. c = createNewComponent (*type, childState, &parent);
  49545. componentsInOrder.add (c);
  49546. }
  49547. }
  49548. // (remaining unused items in existingComponents get deleted here as it goes out of scope)
  49549. }
  49550. // Make sure the z-order is correct..
  49551. if (componentsInOrder.size() > 0)
  49552. {
  49553. componentsInOrder.getLast()->toFront (false);
  49554. for (int i = componentsInOrder.size() - 1; --i >= 0;)
  49555. componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1));
  49556. }
  49557. }
  49558. END_JUCE_NAMESPACE
  49559. /*** End of inlined file: juce_ComponentBuilder.cpp ***/
  49560. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49561. BEGIN_JUCE_NAMESPACE
  49562. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49563. : minW (0),
  49564. maxW (0x3fffffff),
  49565. minH (0),
  49566. maxH (0x3fffffff),
  49567. minOffTop (0),
  49568. minOffLeft (0),
  49569. minOffBottom (0),
  49570. minOffRight (0),
  49571. aspectRatio (0.0)
  49572. {
  49573. }
  49574. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49575. {
  49576. }
  49577. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49578. {
  49579. minW = minimumWidth;
  49580. }
  49581. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49582. {
  49583. maxW = maximumWidth;
  49584. }
  49585. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49586. {
  49587. minH = minimumHeight;
  49588. }
  49589. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49590. {
  49591. maxH = maximumHeight;
  49592. }
  49593. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49594. {
  49595. jassert (maxW >= minimumWidth);
  49596. jassert (maxH >= minimumHeight);
  49597. jassert (minimumWidth > 0 && minimumHeight > 0);
  49598. minW = minimumWidth;
  49599. minH = minimumHeight;
  49600. if (minW > maxW)
  49601. maxW = minW;
  49602. if (minH > maxH)
  49603. maxH = minH;
  49604. }
  49605. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49606. {
  49607. jassert (maximumWidth >= minW);
  49608. jassert (maximumHeight >= minH);
  49609. jassert (maximumWidth > 0 && maximumHeight > 0);
  49610. maxW = jmax (minW, maximumWidth);
  49611. maxH = jmax (minH, maximumHeight);
  49612. }
  49613. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49614. const int minimumHeight,
  49615. const int maximumWidth,
  49616. const int maximumHeight) throw()
  49617. {
  49618. jassert (maximumWidth >= minimumWidth);
  49619. jassert (maximumHeight >= minimumHeight);
  49620. jassert (maximumWidth > 0 && maximumHeight > 0);
  49621. jassert (minimumWidth > 0 && minimumHeight > 0);
  49622. minW = jmax (0, minimumWidth);
  49623. minH = jmax (0, minimumHeight);
  49624. maxW = jmax (minW, maximumWidth);
  49625. maxH = jmax (minH, maximumHeight);
  49626. }
  49627. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49628. const int minimumWhenOffTheLeft,
  49629. const int minimumWhenOffTheBottom,
  49630. const int minimumWhenOffTheRight) throw()
  49631. {
  49632. minOffTop = minimumWhenOffTheTop;
  49633. minOffLeft = minimumWhenOffTheLeft;
  49634. minOffBottom = minimumWhenOffTheBottom;
  49635. minOffRight = minimumWhenOffTheRight;
  49636. }
  49637. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49638. {
  49639. aspectRatio = jmax (0.0, widthOverHeight);
  49640. }
  49641. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49642. {
  49643. return aspectRatio;
  49644. }
  49645. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49646. const Rectangle<int>& targetBounds,
  49647. const bool isStretchingTop,
  49648. const bool isStretchingLeft,
  49649. const bool isStretchingBottom,
  49650. const bool isStretchingRight)
  49651. {
  49652. jassert (component != 0);
  49653. Rectangle<int> limits, bounds (targetBounds);
  49654. BorderSize border;
  49655. Component* const parent = component->getParentComponent();
  49656. if (parent == 0)
  49657. {
  49658. ComponentPeer* peer = component->getPeer();
  49659. if (peer != 0)
  49660. border = peer->getFrameSize();
  49661. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49662. }
  49663. else
  49664. {
  49665. limits.setSize (parent->getWidth(), parent->getHeight());
  49666. }
  49667. border.addTo (bounds);
  49668. checkBounds (bounds,
  49669. border.addedTo (component->getBounds()), limits,
  49670. isStretchingTop, isStretchingLeft,
  49671. isStretchingBottom, isStretchingRight);
  49672. border.subtractFrom (bounds);
  49673. applyBoundsToComponent (component, bounds);
  49674. }
  49675. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49676. {
  49677. setBoundsForComponent (component, component->getBounds(),
  49678. false, false, false, false);
  49679. }
  49680. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49681. const Rectangle<int>& bounds)
  49682. {
  49683. component->setBounds (bounds);
  49684. }
  49685. void ComponentBoundsConstrainer::resizeStart()
  49686. {
  49687. }
  49688. void ComponentBoundsConstrainer::resizeEnd()
  49689. {
  49690. }
  49691. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49692. const Rectangle<int>& old,
  49693. const Rectangle<int>& limits,
  49694. const bool isStretchingTop,
  49695. const bool isStretchingLeft,
  49696. const bool isStretchingBottom,
  49697. const bool isStretchingRight)
  49698. {
  49699. // constrain the size if it's being stretched..
  49700. if (isStretchingLeft)
  49701. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49702. if (isStretchingRight)
  49703. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49704. if (isStretchingTop)
  49705. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49706. if (isStretchingBottom)
  49707. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49708. if (bounds.isEmpty())
  49709. return;
  49710. if (minOffTop > 0)
  49711. {
  49712. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49713. if (bounds.getY() < limit)
  49714. {
  49715. if (isStretchingTop)
  49716. bounds.setTop (limits.getY());
  49717. else
  49718. bounds.setY (limit);
  49719. }
  49720. }
  49721. if (minOffLeft > 0)
  49722. {
  49723. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49724. if (bounds.getX() < limit)
  49725. {
  49726. if (isStretchingLeft)
  49727. bounds.setLeft (limits.getX());
  49728. else
  49729. bounds.setX (limit);
  49730. }
  49731. }
  49732. if (minOffBottom > 0)
  49733. {
  49734. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49735. if (bounds.getY() > limit)
  49736. {
  49737. if (isStretchingBottom)
  49738. bounds.setBottom (limits.getBottom());
  49739. else
  49740. bounds.setY (limit);
  49741. }
  49742. }
  49743. if (minOffRight > 0)
  49744. {
  49745. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49746. if (bounds.getX() > limit)
  49747. {
  49748. if (isStretchingRight)
  49749. bounds.setRight (limits.getRight());
  49750. else
  49751. bounds.setX (limit);
  49752. }
  49753. }
  49754. // constrain the aspect ratio if one has been specified..
  49755. if (aspectRatio > 0.0)
  49756. {
  49757. bool adjustWidth;
  49758. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49759. {
  49760. adjustWidth = true;
  49761. }
  49762. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49763. {
  49764. adjustWidth = false;
  49765. }
  49766. else
  49767. {
  49768. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49769. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49770. adjustWidth = (oldRatio > newRatio);
  49771. }
  49772. if (adjustWidth)
  49773. {
  49774. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49775. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49776. {
  49777. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49778. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49779. }
  49780. }
  49781. else
  49782. {
  49783. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49784. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49785. {
  49786. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49787. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49788. }
  49789. }
  49790. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49791. {
  49792. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49793. }
  49794. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49795. {
  49796. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49797. }
  49798. else
  49799. {
  49800. if (isStretchingLeft)
  49801. bounds.setX (old.getRight() - bounds.getWidth());
  49802. if (isStretchingTop)
  49803. bounds.setY (old.getBottom() - bounds.getHeight());
  49804. }
  49805. }
  49806. jassert (! bounds.isEmpty());
  49807. }
  49808. END_JUCE_NAMESPACE
  49809. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49810. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49811. BEGIN_JUCE_NAMESPACE
  49812. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49813. : component (component_),
  49814. lastPeer (0),
  49815. reentrant (false),
  49816. wasShowing (component_->isShowing())
  49817. {
  49818. jassert (component != 0); // can't use this with a null pointer..
  49819. component->addComponentListener (this);
  49820. registerWithParentComps();
  49821. }
  49822. ComponentMovementWatcher::~ComponentMovementWatcher()
  49823. {
  49824. if (component != 0)
  49825. component->removeComponentListener (this);
  49826. unregister();
  49827. }
  49828. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49829. {
  49830. if (component != 0 && ! reentrant)
  49831. {
  49832. reentrant = true;
  49833. ComponentPeer* const peer = component->getPeer();
  49834. if (peer != lastPeer)
  49835. {
  49836. componentPeerChanged();
  49837. if (component == 0)
  49838. return;
  49839. lastPeer = peer;
  49840. }
  49841. unregister();
  49842. registerWithParentComps();
  49843. componentMovedOrResized (*component, true, true);
  49844. if (component != 0)
  49845. componentVisibilityChanged (*component);
  49846. reentrant = false;
  49847. }
  49848. }
  49849. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49850. {
  49851. if (component != 0)
  49852. {
  49853. if (wasMoved)
  49854. {
  49855. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49856. wasMoved = lastBounds.getPosition() != pos;
  49857. lastBounds.setPosition (pos);
  49858. }
  49859. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49860. lastBounds.setSize (component->getWidth(), component->getHeight());
  49861. if (wasMoved || wasResized)
  49862. componentMovedOrResized (wasMoved, wasResized);
  49863. }
  49864. }
  49865. void ComponentMovementWatcher::componentBeingDeleted (Component& comp)
  49866. {
  49867. registeredParentComps.removeValue (&comp);
  49868. if (component == &comp)
  49869. unregister();
  49870. }
  49871. void ComponentMovementWatcher::componentVisibilityChanged (Component&)
  49872. {
  49873. if (component != 0)
  49874. {
  49875. const bool isShowingNow = component->isShowing();
  49876. if (wasShowing != isShowingNow)
  49877. {
  49878. wasShowing = isShowingNow;
  49879. componentVisibilityChanged();
  49880. }
  49881. }
  49882. }
  49883. void ComponentMovementWatcher::registerWithParentComps()
  49884. {
  49885. Component* p = component->getParentComponent();
  49886. while (p != 0)
  49887. {
  49888. p->addComponentListener (this);
  49889. registeredParentComps.add (p);
  49890. p = p->getParentComponent();
  49891. }
  49892. }
  49893. void ComponentMovementWatcher::unregister()
  49894. {
  49895. for (int i = registeredParentComps.size(); --i >= 0;)
  49896. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49897. registeredParentComps.clear();
  49898. }
  49899. END_JUCE_NAMESPACE
  49900. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49901. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49902. BEGIN_JUCE_NAMESPACE
  49903. GroupComponent::GroupComponent (const String& componentName,
  49904. const String& labelText)
  49905. : Component (componentName),
  49906. text (labelText),
  49907. justification (Justification::left)
  49908. {
  49909. setInterceptsMouseClicks (false, true);
  49910. }
  49911. GroupComponent::~GroupComponent()
  49912. {
  49913. }
  49914. void GroupComponent::setText (const String& newText)
  49915. {
  49916. if (text != newText)
  49917. {
  49918. text = newText;
  49919. repaint();
  49920. }
  49921. }
  49922. const String GroupComponent::getText() const
  49923. {
  49924. return text;
  49925. }
  49926. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49927. {
  49928. if (justification != newJustification)
  49929. {
  49930. justification = newJustification;
  49931. repaint();
  49932. }
  49933. }
  49934. void GroupComponent::paint (Graphics& g)
  49935. {
  49936. getLookAndFeel()
  49937. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49938. text, justification,
  49939. *this);
  49940. }
  49941. void GroupComponent::enablementChanged()
  49942. {
  49943. repaint();
  49944. }
  49945. void GroupComponent::colourChanged()
  49946. {
  49947. repaint();
  49948. }
  49949. END_JUCE_NAMESPACE
  49950. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49951. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49952. BEGIN_JUCE_NAMESPACE
  49953. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49954. : DocumentWindow (String::empty, backgroundColour,
  49955. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49956. {
  49957. }
  49958. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49959. {
  49960. }
  49961. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49962. {
  49963. MultiDocumentPanel* const owner = getOwner();
  49964. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49965. if (owner != 0)
  49966. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49967. }
  49968. void MultiDocumentPanelWindow::closeButtonPressed()
  49969. {
  49970. MultiDocumentPanel* const owner = getOwner();
  49971. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49972. if (owner != 0)
  49973. owner->closeDocument (getContentComponent(), true);
  49974. }
  49975. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49976. {
  49977. DocumentWindow::activeWindowStatusChanged();
  49978. updateOrder();
  49979. }
  49980. void MultiDocumentPanelWindow::broughtToFront()
  49981. {
  49982. DocumentWindow::broughtToFront();
  49983. updateOrder();
  49984. }
  49985. void MultiDocumentPanelWindow::updateOrder()
  49986. {
  49987. MultiDocumentPanel* const owner = getOwner();
  49988. if (owner != 0)
  49989. owner->updateOrder();
  49990. }
  49991. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49992. {
  49993. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49994. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49995. }
  49996. class MDITabbedComponentInternal : public TabbedComponent
  49997. {
  49998. public:
  49999. MDITabbedComponentInternal()
  50000. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50001. {
  50002. }
  50003. ~MDITabbedComponentInternal()
  50004. {
  50005. }
  50006. void currentTabChanged (int, const String&)
  50007. {
  50008. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50009. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50010. if (owner != 0)
  50011. owner->updateOrder();
  50012. }
  50013. };
  50014. MultiDocumentPanel::MultiDocumentPanel()
  50015. : mode (MaximisedWindowsWithTabs),
  50016. backgroundColour (Colours::lightblue),
  50017. maximumNumDocuments (0),
  50018. numDocsBeforeTabsUsed (0)
  50019. {
  50020. setOpaque (true);
  50021. }
  50022. MultiDocumentPanel::~MultiDocumentPanel()
  50023. {
  50024. closeAllDocuments (false);
  50025. }
  50026. namespace MultiDocHelpers
  50027. {
  50028. bool shouldDeleteComp (Component* const c)
  50029. {
  50030. return c->getProperties() ["mdiDocumentDelete_"];
  50031. }
  50032. }
  50033. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50034. {
  50035. while (components.size() > 0)
  50036. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50037. return false;
  50038. return true;
  50039. }
  50040. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50041. {
  50042. return new MultiDocumentPanelWindow (backgroundColour);
  50043. }
  50044. void MultiDocumentPanel::addWindow (Component* component)
  50045. {
  50046. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50047. dw->setResizable (true, false);
  50048. dw->setContentComponent (component, false, true);
  50049. dw->setName (component->getName());
  50050. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50051. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50052. int x = 4;
  50053. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50054. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50055. x += 16;
  50056. dw->setTopLeftPosition (x, x);
  50057. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50058. if (pos.toString().isNotEmpty())
  50059. dw->restoreWindowStateFromString (pos.toString());
  50060. addAndMakeVisible (dw);
  50061. dw->toFront (true);
  50062. }
  50063. bool MultiDocumentPanel::addDocument (Component* const component,
  50064. const Colour& docColour,
  50065. const bool deleteWhenRemoved)
  50066. {
  50067. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50068. // with a frame-within-a-frame! Just pass in the bare content component.
  50069. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50070. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50071. return false;
  50072. components.add (component);
  50073. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50074. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50075. component->addComponentListener (this);
  50076. if (mode == FloatingWindows)
  50077. {
  50078. if (isFullscreenWhenOneDocument())
  50079. {
  50080. if (components.size() == 1)
  50081. {
  50082. addAndMakeVisible (component);
  50083. }
  50084. else
  50085. {
  50086. if (components.size() == 2)
  50087. addWindow (components.getFirst());
  50088. addWindow (component);
  50089. }
  50090. }
  50091. else
  50092. {
  50093. addWindow (component);
  50094. }
  50095. }
  50096. else
  50097. {
  50098. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50099. {
  50100. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50101. Array <Component*> temp (components);
  50102. for (int i = 0; i < temp.size(); ++i)
  50103. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50104. resized();
  50105. }
  50106. else
  50107. {
  50108. if (tabComponent != 0)
  50109. tabComponent->addTab (component->getName(), docColour, component, false);
  50110. else
  50111. addAndMakeVisible (component);
  50112. }
  50113. setActiveDocument (component);
  50114. }
  50115. resized();
  50116. activeDocumentChanged();
  50117. return true;
  50118. }
  50119. bool MultiDocumentPanel::closeDocument (Component* component,
  50120. const bool checkItsOkToCloseFirst)
  50121. {
  50122. if (components.contains (component))
  50123. {
  50124. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50125. return false;
  50126. component->removeComponentListener (this);
  50127. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50128. component->getProperties().remove ("mdiDocumentDelete_");
  50129. component->getProperties().remove ("mdiDocumentBkg_");
  50130. if (mode == FloatingWindows)
  50131. {
  50132. for (int i = getNumChildComponents(); --i >= 0;)
  50133. {
  50134. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50135. if (dw != 0 && dw->getContentComponent() == component)
  50136. {
  50137. dw->setContentComponent (0, false);
  50138. delete dw;
  50139. break;
  50140. }
  50141. }
  50142. if (shouldDelete)
  50143. delete component;
  50144. components.removeValue (component);
  50145. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50146. {
  50147. for (int i = getNumChildComponents(); --i >= 0;)
  50148. {
  50149. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50150. if (dw != 0)
  50151. {
  50152. dw->setContentComponent (0, false);
  50153. delete dw;
  50154. }
  50155. }
  50156. addAndMakeVisible (components.getFirst());
  50157. }
  50158. }
  50159. else
  50160. {
  50161. jassert (components.indexOf (component) >= 0);
  50162. if (tabComponent != 0)
  50163. {
  50164. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50165. if (tabComponent->getTabContentComponent (i) == component)
  50166. tabComponent->removeTab (i);
  50167. }
  50168. else
  50169. {
  50170. removeChildComponent (component);
  50171. }
  50172. if (shouldDelete)
  50173. delete component;
  50174. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50175. tabComponent = 0;
  50176. components.removeValue (component);
  50177. if (components.size() > 0 && tabComponent == 0)
  50178. addAndMakeVisible (components.getFirst());
  50179. }
  50180. resized();
  50181. activeDocumentChanged();
  50182. }
  50183. else
  50184. {
  50185. jassertfalse;
  50186. }
  50187. return true;
  50188. }
  50189. int MultiDocumentPanel::getNumDocuments() const throw()
  50190. {
  50191. return components.size();
  50192. }
  50193. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50194. {
  50195. return components [index];
  50196. }
  50197. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50198. {
  50199. if (mode == FloatingWindows)
  50200. {
  50201. for (int i = getNumChildComponents(); --i >= 0;)
  50202. {
  50203. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50204. if (dw != 0 && dw->isActiveWindow())
  50205. return dw->getContentComponent();
  50206. }
  50207. }
  50208. return components.getLast();
  50209. }
  50210. void MultiDocumentPanel::setActiveDocument (Component* component)
  50211. {
  50212. if (mode == FloatingWindows)
  50213. {
  50214. component = getContainerComp (component);
  50215. if (component != 0)
  50216. component->toFront (true);
  50217. }
  50218. else if (tabComponent != 0)
  50219. {
  50220. jassert (components.indexOf (component) >= 0);
  50221. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50222. {
  50223. if (tabComponent->getTabContentComponent (i) == component)
  50224. {
  50225. tabComponent->setCurrentTabIndex (i);
  50226. break;
  50227. }
  50228. }
  50229. }
  50230. else
  50231. {
  50232. component->grabKeyboardFocus();
  50233. }
  50234. }
  50235. void MultiDocumentPanel::activeDocumentChanged()
  50236. {
  50237. }
  50238. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50239. {
  50240. maximumNumDocuments = newNumber;
  50241. }
  50242. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50243. {
  50244. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50245. }
  50246. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50247. {
  50248. return numDocsBeforeTabsUsed != 0;
  50249. }
  50250. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50251. {
  50252. if (mode != newLayoutMode)
  50253. {
  50254. mode = newLayoutMode;
  50255. if (mode == FloatingWindows)
  50256. {
  50257. tabComponent = 0;
  50258. }
  50259. else
  50260. {
  50261. for (int i = getNumChildComponents(); --i >= 0;)
  50262. {
  50263. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50264. if (dw != 0)
  50265. {
  50266. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50267. dw->setContentComponent (0, false);
  50268. delete dw;
  50269. }
  50270. }
  50271. }
  50272. resized();
  50273. const Array <Component*> tempComps (components);
  50274. components.clear();
  50275. for (int i = 0; i < tempComps.size(); ++i)
  50276. {
  50277. Component* const c = tempComps.getUnchecked(i);
  50278. addDocument (c,
  50279. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50280. MultiDocHelpers::shouldDeleteComp (c));
  50281. }
  50282. }
  50283. }
  50284. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50285. {
  50286. if (backgroundColour != newBackgroundColour)
  50287. {
  50288. backgroundColour = newBackgroundColour;
  50289. setOpaque (newBackgroundColour.isOpaque());
  50290. repaint();
  50291. }
  50292. }
  50293. void MultiDocumentPanel::paint (Graphics& g)
  50294. {
  50295. g.fillAll (backgroundColour);
  50296. }
  50297. void MultiDocumentPanel::resized()
  50298. {
  50299. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50300. {
  50301. for (int i = getNumChildComponents(); --i >= 0;)
  50302. getChildComponent (i)->setBounds (getLocalBounds());
  50303. }
  50304. setWantsKeyboardFocus (components.size() == 0);
  50305. }
  50306. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50307. {
  50308. if (mode == FloatingWindows)
  50309. {
  50310. for (int i = 0; i < getNumChildComponents(); ++i)
  50311. {
  50312. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50313. if (dw != 0 && dw->getContentComponent() == c)
  50314. {
  50315. c = dw;
  50316. break;
  50317. }
  50318. }
  50319. }
  50320. return c;
  50321. }
  50322. void MultiDocumentPanel::componentNameChanged (Component&)
  50323. {
  50324. if (mode == FloatingWindows)
  50325. {
  50326. for (int i = 0; i < getNumChildComponents(); ++i)
  50327. {
  50328. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50329. if (dw != 0)
  50330. dw->setName (dw->getContentComponent()->getName());
  50331. }
  50332. }
  50333. else if (tabComponent != 0)
  50334. {
  50335. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50336. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50337. }
  50338. }
  50339. void MultiDocumentPanel::updateOrder()
  50340. {
  50341. const Array <Component*> oldList (components);
  50342. if (mode == FloatingWindows)
  50343. {
  50344. components.clear();
  50345. for (int i = 0; i < getNumChildComponents(); ++i)
  50346. {
  50347. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50348. if (dw != 0)
  50349. components.add (dw->getContentComponent());
  50350. }
  50351. }
  50352. else
  50353. {
  50354. if (tabComponent != 0)
  50355. {
  50356. Component* const current = tabComponent->getCurrentContentComponent();
  50357. if (current != 0)
  50358. {
  50359. components.removeValue (current);
  50360. components.add (current);
  50361. }
  50362. }
  50363. }
  50364. if (components != oldList)
  50365. activeDocumentChanged();
  50366. }
  50367. END_JUCE_NAMESPACE
  50368. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50369. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50370. BEGIN_JUCE_NAMESPACE
  50371. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50372. : zone (zoneFlags)
  50373. {}
  50374. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50375. : zone (other.zone)
  50376. {}
  50377. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50378. {
  50379. zone = other.zone;
  50380. return *this;
  50381. }
  50382. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50383. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50384. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50385. const BorderSize& border,
  50386. const Point<int>& position)
  50387. {
  50388. int z = 0;
  50389. if (totalSize.contains (position)
  50390. && ! border.subtractedFrom (totalSize).contains (position))
  50391. {
  50392. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50393. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50394. z |= left;
  50395. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50396. z |= right;
  50397. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50398. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50399. z |= top;
  50400. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50401. z |= bottom;
  50402. }
  50403. return Zone (z);
  50404. }
  50405. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50406. {
  50407. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50408. switch (zone)
  50409. {
  50410. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50411. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50412. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50413. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50414. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50415. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50416. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50417. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50418. default: break;
  50419. }
  50420. return mc;
  50421. }
  50422. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50423. ComponentBoundsConstrainer* const constrainer_)
  50424. : component (componentToResize),
  50425. constrainer (constrainer_),
  50426. borderSize (5),
  50427. mouseZone (0)
  50428. {
  50429. }
  50430. ResizableBorderComponent::~ResizableBorderComponent()
  50431. {
  50432. }
  50433. void ResizableBorderComponent::paint (Graphics& g)
  50434. {
  50435. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50436. }
  50437. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50438. {
  50439. updateMouseZone (e);
  50440. }
  50441. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50442. {
  50443. updateMouseZone (e);
  50444. }
  50445. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50446. {
  50447. if (component == 0)
  50448. {
  50449. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50450. return;
  50451. }
  50452. updateMouseZone (e);
  50453. originalBounds = component->getBounds();
  50454. if (constrainer != 0)
  50455. constrainer->resizeStart();
  50456. }
  50457. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50458. {
  50459. if (component == 0)
  50460. {
  50461. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50462. return;
  50463. }
  50464. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50465. if (constrainer != 0)
  50466. constrainer->setBoundsForComponent (component, bounds,
  50467. mouseZone.isDraggingTopEdge(),
  50468. mouseZone.isDraggingLeftEdge(),
  50469. mouseZone.isDraggingBottomEdge(),
  50470. mouseZone.isDraggingRightEdge());
  50471. else
  50472. component->setBounds (bounds);
  50473. }
  50474. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50475. {
  50476. if (constrainer != 0)
  50477. constrainer->resizeEnd();
  50478. }
  50479. bool ResizableBorderComponent::hitTest (int x, int y)
  50480. {
  50481. return x < borderSize.getLeft()
  50482. || x >= getWidth() - borderSize.getRight()
  50483. || y < borderSize.getTop()
  50484. || y >= getHeight() - borderSize.getBottom();
  50485. }
  50486. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50487. {
  50488. if (borderSize != newBorderSize)
  50489. {
  50490. borderSize = newBorderSize;
  50491. repaint();
  50492. }
  50493. }
  50494. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50495. {
  50496. return borderSize;
  50497. }
  50498. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50499. {
  50500. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50501. if (mouseZone != newZone)
  50502. {
  50503. mouseZone = newZone;
  50504. setMouseCursor (newZone.getMouseCursor());
  50505. }
  50506. }
  50507. END_JUCE_NAMESPACE
  50508. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50509. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50510. BEGIN_JUCE_NAMESPACE
  50511. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50512. ComponentBoundsConstrainer* const constrainer_)
  50513. : component (componentToResize),
  50514. constrainer (constrainer_)
  50515. {
  50516. setRepaintsOnMouseActivity (true);
  50517. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50518. }
  50519. ResizableCornerComponent::~ResizableCornerComponent()
  50520. {
  50521. }
  50522. void ResizableCornerComponent::paint (Graphics& g)
  50523. {
  50524. getLookAndFeel()
  50525. .drawCornerResizer (g, getWidth(), getHeight(),
  50526. isMouseOverOrDragging(),
  50527. isMouseButtonDown());
  50528. }
  50529. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50530. {
  50531. if (component == 0)
  50532. {
  50533. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50534. return;
  50535. }
  50536. originalBounds = component->getBounds();
  50537. if (constrainer != 0)
  50538. constrainer->resizeStart();
  50539. }
  50540. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50541. {
  50542. if (component == 0)
  50543. {
  50544. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50545. return;
  50546. }
  50547. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50548. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50549. if (constrainer != 0)
  50550. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50551. else
  50552. component->setBounds (r);
  50553. }
  50554. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50555. {
  50556. if (constrainer != 0)
  50557. constrainer->resizeStart();
  50558. }
  50559. bool ResizableCornerComponent::hitTest (int x, int y)
  50560. {
  50561. if (getWidth() <= 0)
  50562. return false;
  50563. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50564. return y >= yAtX - getHeight() / 4;
  50565. }
  50566. END_JUCE_NAMESPACE
  50567. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50568. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50569. BEGIN_JUCE_NAMESPACE
  50570. class ScrollBar::ScrollbarButton : public Button
  50571. {
  50572. public:
  50573. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50574. : Button (String::empty),
  50575. direction (direction_),
  50576. owner (owner_)
  50577. {
  50578. setWantsKeyboardFocus (false);
  50579. }
  50580. void paintButton (Graphics& g, bool over, bool down)
  50581. {
  50582. getLookAndFeel()
  50583. .drawScrollbarButton (g, owner,
  50584. getWidth(), getHeight(),
  50585. direction,
  50586. owner.isVertical(),
  50587. over, down);
  50588. }
  50589. void clicked()
  50590. {
  50591. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50592. }
  50593. int direction;
  50594. private:
  50595. ScrollBar& owner;
  50596. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton);
  50597. };
  50598. ScrollBar::ScrollBar (const bool vertical_,
  50599. const bool buttonsAreVisible)
  50600. : totalRange (0.0, 1.0),
  50601. visibleRange (0.0, 0.1),
  50602. singleStepSize (0.1),
  50603. thumbAreaStart (0),
  50604. thumbAreaSize (0),
  50605. thumbStart (0),
  50606. thumbSize (0),
  50607. initialDelayInMillisecs (100),
  50608. repeatDelayInMillisecs (50),
  50609. minimumDelayInMillisecs (10),
  50610. vertical (vertical_),
  50611. isDraggingThumb (false),
  50612. autohides (true)
  50613. {
  50614. setButtonVisibility (buttonsAreVisible);
  50615. setRepaintsOnMouseActivity (true);
  50616. setFocusContainer (true);
  50617. }
  50618. ScrollBar::~ScrollBar()
  50619. {
  50620. upButton = 0;
  50621. downButton = 0;
  50622. }
  50623. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50624. {
  50625. if (totalRange != newRangeLimit)
  50626. {
  50627. totalRange = newRangeLimit;
  50628. setCurrentRange (visibleRange);
  50629. updateThumbPosition();
  50630. }
  50631. }
  50632. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50633. {
  50634. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50635. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50636. }
  50637. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50638. {
  50639. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50640. if (visibleRange != constrainedRange)
  50641. {
  50642. visibleRange = constrainedRange;
  50643. updateThumbPosition();
  50644. triggerAsyncUpdate();
  50645. }
  50646. }
  50647. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50648. {
  50649. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50650. }
  50651. void ScrollBar::setCurrentRangeStart (const double newStart)
  50652. {
  50653. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50654. }
  50655. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50656. {
  50657. singleStepSize = newSingleStepSize;
  50658. }
  50659. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50660. {
  50661. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50662. }
  50663. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50664. {
  50665. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50666. }
  50667. void ScrollBar::scrollToTop()
  50668. {
  50669. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50670. }
  50671. void ScrollBar::scrollToBottom()
  50672. {
  50673. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50674. }
  50675. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50676. const int repeatDelayInMillisecs_,
  50677. const int minimumDelayInMillisecs_)
  50678. {
  50679. initialDelayInMillisecs = initialDelayInMillisecs_;
  50680. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50681. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50682. if (upButton != 0)
  50683. {
  50684. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50685. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50686. }
  50687. }
  50688. void ScrollBar::addListener (Listener* const listener)
  50689. {
  50690. listeners.add (listener);
  50691. }
  50692. void ScrollBar::removeListener (Listener* const listener)
  50693. {
  50694. listeners.remove (listener);
  50695. }
  50696. void ScrollBar::handleAsyncUpdate()
  50697. {
  50698. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50699. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50700. }
  50701. void ScrollBar::updateThumbPosition()
  50702. {
  50703. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50704. : thumbAreaSize);
  50705. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50706. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50707. if (newThumbSize > thumbAreaSize)
  50708. newThumbSize = thumbAreaSize;
  50709. int newThumbStart = thumbAreaStart;
  50710. if (totalRange.getLength() > visibleRange.getLength())
  50711. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50712. / (totalRange.getLength() - visibleRange.getLength()));
  50713. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50714. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50715. {
  50716. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50717. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50718. if (vertical)
  50719. repaint (0, repaintStart, getWidth(), repaintSize);
  50720. else
  50721. repaint (repaintStart, 0, repaintSize, getHeight());
  50722. thumbStart = newThumbStart;
  50723. thumbSize = newThumbSize;
  50724. }
  50725. }
  50726. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50727. {
  50728. if (vertical != shouldBeVertical)
  50729. {
  50730. vertical = shouldBeVertical;
  50731. if (upButton != 0)
  50732. {
  50733. upButton->direction = vertical ? 0 : 3;
  50734. downButton->direction = vertical ? 2 : 1;
  50735. }
  50736. updateThumbPosition();
  50737. }
  50738. }
  50739. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50740. {
  50741. upButton = 0;
  50742. downButton = 0;
  50743. if (buttonsAreVisible)
  50744. {
  50745. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50746. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50747. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50748. }
  50749. updateThumbPosition();
  50750. }
  50751. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50752. {
  50753. autohides = shouldHideWhenFullRange;
  50754. updateThumbPosition();
  50755. }
  50756. bool ScrollBar::autoHides() const throw()
  50757. {
  50758. return autohides;
  50759. }
  50760. void ScrollBar::paint (Graphics& g)
  50761. {
  50762. if (thumbAreaSize > 0)
  50763. {
  50764. LookAndFeel& lf = getLookAndFeel();
  50765. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50766. ? thumbSize : 0;
  50767. if (vertical)
  50768. {
  50769. lf.drawScrollbar (g, *this,
  50770. 0, thumbAreaStart,
  50771. getWidth(), thumbAreaSize,
  50772. vertical,
  50773. thumbStart, thumb,
  50774. isMouseOver(), isMouseButtonDown());
  50775. }
  50776. else
  50777. {
  50778. lf.drawScrollbar (g, *this,
  50779. thumbAreaStart, 0,
  50780. thumbAreaSize, getHeight(),
  50781. vertical,
  50782. thumbStart, thumb,
  50783. isMouseOver(), isMouseButtonDown());
  50784. }
  50785. }
  50786. }
  50787. void ScrollBar::lookAndFeelChanged()
  50788. {
  50789. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50790. }
  50791. void ScrollBar::resized()
  50792. {
  50793. const int length = ((vertical) ? getHeight() : getWidth());
  50794. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50795. : 0;
  50796. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50797. {
  50798. thumbAreaStart = length >> 1;
  50799. thumbAreaSize = 0;
  50800. }
  50801. else
  50802. {
  50803. thumbAreaStart = buttonSize;
  50804. thumbAreaSize = length - (buttonSize << 1);
  50805. }
  50806. if (upButton != 0)
  50807. {
  50808. if (vertical)
  50809. {
  50810. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50811. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50812. }
  50813. else
  50814. {
  50815. upButton->setBounds (0, 0, buttonSize, getHeight());
  50816. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50817. }
  50818. }
  50819. updateThumbPosition();
  50820. }
  50821. void ScrollBar::mouseDown (const MouseEvent& e)
  50822. {
  50823. isDraggingThumb = false;
  50824. lastMousePos = vertical ? e.y : e.x;
  50825. dragStartMousePos = lastMousePos;
  50826. dragStartRange = visibleRange.getStart();
  50827. if (dragStartMousePos < thumbStart)
  50828. {
  50829. moveScrollbarInPages (-1);
  50830. startTimer (400);
  50831. }
  50832. else if (dragStartMousePos >= thumbStart + thumbSize)
  50833. {
  50834. moveScrollbarInPages (1);
  50835. startTimer (400);
  50836. }
  50837. else
  50838. {
  50839. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50840. && (thumbAreaSize > thumbSize);
  50841. }
  50842. }
  50843. void ScrollBar::mouseDrag (const MouseEvent& e)
  50844. {
  50845. const int mousePos = vertical ? e.y : e.x;
  50846. if (isDraggingThumb && lastMousePos != mousePos)
  50847. {
  50848. const int deltaPixels = mousePos - dragStartMousePos;
  50849. setCurrentRangeStart (dragStartRange
  50850. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50851. / (thumbAreaSize - thumbSize));
  50852. }
  50853. lastMousePos = mousePos;
  50854. }
  50855. void ScrollBar::mouseUp (const MouseEvent&)
  50856. {
  50857. isDraggingThumb = false;
  50858. stopTimer();
  50859. repaint();
  50860. }
  50861. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50862. float wheelIncrementX,
  50863. float wheelIncrementY)
  50864. {
  50865. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50866. if (increment < 0)
  50867. increment = jmin (increment * 10.0f, -1.0f);
  50868. else if (increment > 0)
  50869. increment = jmax (increment * 10.0f, 1.0f);
  50870. setCurrentRange (visibleRange - singleStepSize * increment);
  50871. }
  50872. void ScrollBar::timerCallback()
  50873. {
  50874. if (isMouseButtonDown())
  50875. {
  50876. startTimer (40);
  50877. if (lastMousePos < thumbStart)
  50878. setCurrentRange (visibleRange - visibleRange.getLength());
  50879. else if (lastMousePos > thumbStart + thumbSize)
  50880. setCurrentRangeStart (visibleRange.getEnd());
  50881. }
  50882. else
  50883. {
  50884. stopTimer();
  50885. }
  50886. }
  50887. bool ScrollBar::keyPressed (const KeyPress& key)
  50888. {
  50889. if (! isVisible())
  50890. return false;
  50891. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50892. moveScrollbarInSteps (-1);
  50893. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50894. moveScrollbarInSteps (1);
  50895. else if (key.isKeyCode (KeyPress::pageUpKey))
  50896. moveScrollbarInPages (-1);
  50897. else if (key.isKeyCode (KeyPress::pageDownKey))
  50898. moveScrollbarInPages (1);
  50899. else if (key.isKeyCode (KeyPress::homeKey))
  50900. scrollToTop();
  50901. else if (key.isKeyCode (KeyPress::endKey))
  50902. scrollToBottom();
  50903. else
  50904. return false;
  50905. return true;
  50906. }
  50907. END_JUCE_NAMESPACE
  50908. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50909. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50910. BEGIN_JUCE_NAMESPACE
  50911. StretchableLayoutManager::StretchableLayoutManager()
  50912. : totalSize (0)
  50913. {
  50914. }
  50915. StretchableLayoutManager::~StretchableLayoutManager()
  50916. {
  50917. }
  50918. void StretchableLayoutManager::clearAllItems()
  50919. {
  50920. items.clear();
  50921. totalSize = 0;
  50922. }
  50923. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50924. const double minimumSize,
  50925. const double maximumSize,
  50926. const double preferredSize)
  50927. {
  50928. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50929. if (layout == 0)
  50930. {
  50931. layout = new ItemLayoutProperties();
  50932. layout->itemIndex = itemIndex;
  50933. int i;
  50934. for (i = 0; i < items.size(); ++i)
  50935. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50936. break;
  50937. items.insert (i, layout);
  50938. }
  50939. layout->minSize = minimumSize;
  50940. layout->maxSize = maximumSize;
  50941. layout->preferredSize = preferredSize;
  50942. layout->currentSize = 0;
  50943. }
  50944. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50945. double& minimumSize,
  50946. double& maximumSize,
  50947. double& preferredSize) const
  50948. {
  50949. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50950. if (layout != 0)
  50951. {
  50952. minimumSize = layout->minSize;
  50953. maximumSize = layout->maxSize;
  50954. preferredSize = layout->preferredSize;
  50955. return true;
  50956. }
  50957. return false;
  50958. }
  50959. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50960. {
  50961. totalSize = newTotalSize;
  50962. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50963. }
  50964. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50965. {
  50966. int pos = 0;
  50967. for (int i = 0; i < itemIndex; ++i)
  50968. {
  50969. const ItemLayoutProperties* const layout = getInfoFor (i);
  50970. if (layout != 0)
  50971. pos += layout->currentSize;
  50972. }
  50973. return pos;
  50974. }
  50975. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50976. {
  50977. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50978. if (layout != 0)
  50979. return layout->currentSize;
  50980. return 0;
  50981. }
  50982. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50983. {
  50984. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50985. if (layout != 0)
  50986. return -layout->currentSize / (double) totalSize;
  50987. return 0;
  50988. }
  50989. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50990. int newPosition)
  50991. {
  50992. for (int i = items.size(); --i >= 0;)
  50993. {
  50994. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50995. if (layout->itemIndex == itemIndex)
  50996. {
  50997. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50998. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50999. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51000. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51001. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51002. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51003. endPos += layout->currentSize;
  51004. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51005. updatePrefSizesToMatchCurrentPositions();
  51006. break;
  51007. }
  51008. }
  51009. }
  51010. void StretchableLayoutManager::layOutComponents (Component** const components,
  51011. int numComponents,
  51012. int x, int y, int w, int h,
  51013. const bool vertically,
  51014. const bool resizeOtherDimension)
  51015. {
  51016. setTotalSize (vertically ? h : w);
  51017. int pos = vertically ? y : x;
  51018. for (int i = 0; i < numComponents; ++i)
  51019. {
  51020. const ItemLayoutProperties* const layout = getInfoFor (i);
  51021. if (layout != 0)
  51022. {
  51023. Component* const c = components[i];
  51024. if (c != 0)
  51025. {
  51026. if (i == numComponents - 1)
  51027. {
  51028. // if it's the last item, crop it to exactly fit the available space..
  51029. if (resizeOtherDimension)
  51030. {
  51031. if (vertically)
  51032. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51033. else
  51034. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51035. }
  51036. else
  51037. {
  51038. if (vertically)
  51039. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51040. else
  51041. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51042. }
  51043. }
  51044. else
  51045. {
  51046. if (resizeOtherDimension)
  51047. {
  51048. if (vertically)
  51049. c->setBounds (x, pos, w, layout->currentSize);
  51050. else
  51051. c->setBounds (pos, y, layout->currentSize, h);
  51052. }
  51053. else
  51054. {
  51055. if (vertically)
  51056. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51057. else
  51058. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51059. }
  51060. }
  51061. }
  51062. pos += layout->currentSize;
  51063. }
  51064. }
  51065. }
  51066. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51067. {
  51068. for (int i = items.size(); --i >= 0;)
  51069. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51070. return items.getUnchecked(i);
  51071. return 0;
  51072. }
  51073. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51074. const int endIndex,
  51075. const int availableSpace,
  51076. int startPos)
  51077. {
  51078. // calculate the total sizes
  51079. int i;
  51080. double totalIdealSize = 0.0;
  51081. int totalMinimums = 0;
  51082. for (i = startIndex; i < endIndex; ++i)
  51083. {
  51084. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51085. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51086. totalMinimums += layout->currentSize;
  51087. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51088. }
  51089. if (totalIdealSize <= 0)
  51090. totalIdealSize = 1.0;
  51091. // now calc the best sizes..
  51092. int extraSpace = availableSpace - totalMinimums;
  51093. while (extraSpace > 0)
  51094. {
  51095. int numWantingMoreSpace = 0;
  51096. int numHavingTakenExtraSpace = 0;
  51097. // first figure out how many comps want a slice of the extra space..
  51098. for (i = startIndex; i < endIndex; ++i)
  51099. {
  51100. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51101. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51102. const int bestSize = jlimit (layout->currentSize,
  51103. jmax (layout->currentSize,
  51104. sizeToRealSize (layout->maxSize, totalSize)),
  51105. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51106. if (bestSize > layout->currentSize)
  51107. ++numWantingMoreSpace;
  51108. }
  51109. // ..share out the extra space..
  51110. for (i = startIndex; i < endIndex; ++i)
  51111. {
  51112. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51113. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51114. int bestSize = jlimit (layout->currentSize,
  51115. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51116. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51117. const int extraWanted = bestSize - layout->currentSize;
  51118. if (extraWanted > 0)
  51119. {
  51120. const int extraAllowed = jmin (extraWanted,
  51121. extraSpace / jmax (1, numWantingMoreSpace));
  51122. if (extraAllowed > 0)
  51123. {
  51124. ++numHavingTakenExtraSpace;
  51125. --numWantingMoreSpace;
  51126. layout->currentSize += extraAllowed;
  51127. extraSpace -= extraAllowed;
  51128. }
  51129. }
  51130. }
  51131. if (numHavingTakenExtraSpace <= 0)
  51132. break;
  51133. }
  51134. // ..and calculate the end position
  51135. for (i = startIndex; i < endIndex; ++i)
  51136. {
  51137. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51138. startPos += layout->currentSize;
  51139. }
  51140. return startPos;
  51141. }
  51142. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51143. const int endIndex) const
  51144. {
  51145. int totalMinimums = 0;
  51146. for (int i = startIndex; i < endIndex; ++i)
  51147. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51148. return totalMinimums;
  51149. }
  51150. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51151. {
  51152. int totalMaximums = 0;
  51153. for (int i = startIndex; i < endIndex; ++i)
  51154. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51155. return totalMaximums;
  51156. }
  51157. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51158. {
  51159. for (int i = 0; i < items.size(); ++i)
  51160. {
  51161. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51162. layout->preferredSize
  51163. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51164. : getItemCurrentAbsoluteSize (i);
  51165. }
  51166. }
  51167. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51168. {
  51169. if (size < 0)
  51170. size *= -totalSpace;
  51171. return roundToInt (size);
  51172. }
  51173. END_JUCE_NAMESPACE
  51174. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51175. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51176. BEGIN_JUCE_NAMESPACE
  51177. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51178. const int itemIndex_,
  51179. const bool isVertical_)
  51180. : layout (layout_),
  51181. itemIndex (itemIndex_),
  51182. isVertical (isVertical_)
  51183. {
  51184. setRepaintsOnMouseActivity (true);
  51185. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51186. : MouseCursor::UpDownResizeCursor));
  51187. }
  51188. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51189. {
  51190. }
  51191. void StretchableLayoutResizerBar::paint (Graphics& g)
  51192. {
  51193. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51194. getWidth(), getHeight(),
  51195. isVertical,
  51196. isMouseOver(),
  51197. isMouseButtonDown());
  51198. }
  51199. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51200. {
  51201. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51202. }
  51203. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51204. {
  51205. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51206. : e.getDistanceFromDragStartY());
  51207. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51208. {
  51209. layout->setItemPosition (itemIndex, desiredPos);
  51210. hasBeenMoved();
  51211. }
  51212. }
  51213. void StretchableLayoutResizerBar::hasBeenMoved()
  51214. {
  51215. if (getParentComponent() != 0)
  51216. getParentComponent()->resized();
  51217. }
  51218. END_JUCE_NAMESPACE
  51219. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51220. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51221. BEGIN_JUCE_NAMESPACE
  51222. StretchableObjectResizer::StretchableObjectResizer()
  51223. {
  51224. }
  51225. StretchableObjectResizer::~StretchableObjectResizer()
  51226. {
  51227. }
  51228. void StretchableObjectResizer::addItem (const double size,
  51229. const double minSize, const double maxSize,
  51230. const int order)
  51231. {
  51232. // the order must be >= 0 but less than the maximum integer value.
  51233. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51234. Item* const item = new Item();
  51235. item->size = size;
  51236. item->minSize = minSize;
  51237. item->maxSize = maxSize;
  51238. item->order = order;
  51239. items.add (item);
  51240. }
  51241. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51242. {
  51243. const Item* const it = items [index];
  51244. return it != 0 ? it->size : 0;
  51245. }
  51246. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51247. {
  51248. int order = 0;
  51249. for (;;)
  51250. {
  51251. double currentSize = 0;
  51252. double minSize = 0;
  51253. double maxSize = 0;
  51254. int nextHighestOrder = std::numeric_limits<int>::max();
  51255. for (int i = 0; i < items.size(); ++i)
  51256. {
  51257. const Item* const it = items.getUnchecked(i);
  51258. currentSize += it->size;
  51259. if (it->order <= order)
  51260. {
  51261. minSize += it->minSize;
  51262. maxSize += it->maxSize;
  51263. }
  51264. else
  51265. {
  51266. minSize += it->size;
  51267. maxSize += it->size;
  51268. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51269. }
  51270. }
  51271. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51272. if (thisIterationTarget >= currentSize)
  51273. {
  51274. const double availableExtraSpace = maxSize - currentSize;
  51275. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51276. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51277. for (int i = 0; i < items.size(); ++i)
  51278. {
  51279. Item* const it = items.getUnchecked(i);
  51280. if (it->order <= order)
  51281. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51282. }
  51283. }
  51284. else
  51285. {
  51286. const double amountOfSlack = currentSize - minSize;
  51287. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51288. const double scale = targetAmountOfSlack / amountOfSlack;
  51289. for (int i = 0; i < items.size(); ++i)
  51290. {
  51291. Item* const it = items.getUnchecked(i);
  51292. if (it->order <= order)
  51293. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51294. }
  51295. }
  51296. if (nextHighestOrder < std::numeric_limits<int>::max())
  51297. order = nextHighestOrder;
  51298. else
  51299. break;
  51300. }
  51301. }
  51302. END_JUCE_NAMESPACE
  51303. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51304. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51305. BEGIN_JUCE_NAMESPACE
  51306. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51307. : Button (name),
  51308. owner (owner_),
  51309. overlapPixels (0)
  51310. {
  51311. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51312. setComponentEffect (&shadow);
  51313. setWantsKeyboardFocus (false);
  51314. }
  51315. TabBarButton::~TabBarButton()
  51316. {
  51317. }
  51318. int TabBarButton::getIndex() const
  51319. {
  51320. return owner.indexOfTabButton (this);
  51321. }
  51322. void TabBarButton::paintButton (Graphics& g,
  51323. bool isMouseOverButton,
  51324. bool isButtonDown)
  51325. {
  51326. const Rectangle<int> area (getActiveArea());
  51327. g.setOrigin (area.getX(), area.getY());
  51328. getLookAndFeel()
  51329. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51330. owner.getTabBackgroundColour (getIndex()),
  51331. getIndex(), getButtonText(), *this,
  51332. owner.getOrientation(),
  51333. isMouseOverButton, isButtonDown,
  51334. getToggleState());
  51335. }
  51336. void TabBarButton::clicked (const ModifierKeys& mods)
  51337. {
  51338. if (mods.isPopupMenu())
  51339. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51340. else
  51341. owner.setCurrentTabIndex (getIndex());
  51342. }
  51343. bool TabBarButton::hitTest (int mx, int my)
  51344. {
  51345. const Rectangle<int> area (getActiveArea());
  51346. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51347. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51348. {
  51349. if (isPositiveAndBelow (mx, getWidth())
  51350. && my >= area.getY() + overlapPixels
  51351. && my < area.getBottom() - overlapPixels)
  51352. return true;
  51353. }
  51354. else
  51355. {
  51356. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51357. && isPositiveAndBelow (my, getHeight()))
  51358. return true;
  51359. }
  51360. Path p;
  51361. getLookAndFeel()
  51362. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51363. owner.getOrientation(), false, false, getToggleState());
  51364. return p.contains ((float) (mx - area.getX()),
  51365. (float) (my - area.getY()));
  51366. }
  51367. int TabBarButton::getBestTabLength (const int depth)
  51368. {
  51369. return jlimit (depth * 2,
  51370. depth * 7,
  51371. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51372. }
  51373. const Rectangle<int> TabBarButton::getActiveArea()
  51374. {
  51375. Rectangle<int> r (getLocalBounds());
  51376. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51377. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51378. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51379. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51380. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51381. return r;
  51382. }
  51383. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51384. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51385. {
  51386. public:
  51387. BehindFrontTabComp (TabbedButtonBar& owner_)
  51388. : owner (owner_)
  51389. {
  51390. setInterceptsMouseClicks (false, false);
  51391. }
  51392. void paint (Graphics& g)
  51393. {
  51394. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51395. owner, owner.getOrientation());
  51396. }
  51397. void enablementChanged()
  51398. {
  51399. repaint();
  51400. }
  51401. void buttonClicked (Button*)
  51402. {
  51403. owner.showExtraItemsMenu();
  51404. }
  51405. private:
  51406. TabbedButtonBar& owner;
  51407. JUCE_DECLARE_NON_COPYABLE (BehindFrontTabComp);
  51408. };
  51409. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51410. : orientation (orientation_),
  51411. minimumScale (0.7),
  51412. currentTabIndex (-1)
  51413. {
  51414. setInterceptsMouseClicks (false, true);
  51415. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51416. setFocusContainer (true);
  51417. }
  51418. TabbedButtonBar::~TabbedButtonBar()
  51419. {
  51420. tabs.clear();
  51421. extraTabsButton = 0;
  51422. }
  51423. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51424. {
  51425. orientation = newOrientation;
  51426. for (int i = getNumChildComponents(); --i >= 0;)
  51427. getChildComponent (i)->resized();
  51428. resized();
  51429. }
  51430. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51431. {
  51432. return new TabBarButton (name, *this);
  51433. }
  51434. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51435. {
  51436. minimumScale = newMinimumScale;
  51437. resized();
  51438. }
  51439. void TabbedButtonBar::clearTabs()
  51440. {
  51441. tabs.clear();
  51442. extraTabsButton = 0;
  51443. setCurrentTabIndex (-1);
  51444. }
  51445. void TabbedButtonBar::addTab (const String& tabName,
  51446. const Colour& tabBackgroundColour,
  51447. int insertIndex)
  51448. {
  51449. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51450. if (tabName.isNotEmpty())
  51451. {
  51452. if (! isPositiveAndBelow (insertIndex, tabs.size()))
  51453. insertIndex = tabs.size();
  51454. TabInfo* newTab = new TabInfo();
  51455. newTab->name = tabName;
  51456. newTab->colour = tabBackgroundColour;
  51457. newTab->component = createTabButton (tabName, insertIndex);
  51458. jassert (newTab->component != 0);
  51459. tabs.insert (insertIndex, newTab);
  51460. addAndMakeVisible (newTab->component, insertIndex);
  51461. resized();
  51462. if (currentTabIndex < 0)
  51463. setCurrentTabIndex (0);
  51464. }
  51465. }
  51466. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51467. {
  51468. TabInfo* const tab = tabs [tabIndex];
  51469. if (tab != 0 && tab->name != newName)
  51470. {
  51471. tab->name = newName;
  51472. tab->component->setButtonText (newName);
  51473. resized();
  51474. }
  51475. }
  51476. void TabbedButtonBar::removeTab (const int tabIndex)
  51477. {
  51478. if (tabs [tabIndex] != 0)
  51479. {
  51480. const int oldTabIndex = currentTabIndex;
  51481. if (currentTabIndex == tabIndex)
  51482. currentTabIndex = -1;
  51483. tabs.remove (tabIndex);
  51484. resized();
  51485. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51486. }
  51487. }
  51488. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51489. {
  51490. tabs.move (currentIndex, newIndex);
  51491. resized();
  51492. }
  51493. int TabbedButtonBar::getNumTabs() const
  51494. {
  51495. return tabs.size();
  51496. }
  51497. const String TabbedButtonBar::getCurrentTabName() const
  51498. {
  51499. TabInfo* tab = tabs [currentTabIndex];
  51500. return tab == 0 ? String::empty : tab->name;
  51501. }
  51502. const StringArray TabbedButtonBar::getTabNames() const
  51503. {
  51504. StringArray names;
  51505. for (int i = 0; i < tabs.size(); ++i)
  51506. names.add (tabs.getUnchecked(i)->name);
  51507. return names;
  51508. }
  51509. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51510. {
  51511. if (currentTabIndex != newIndex)
  51512. {
  51513. if (! isPositiveAndBelow (newIndex, tabs.size()))
  51514. newIndex = -1;
  51515. currentTabIndex = newIndex;
  51516. for (int i = 0; i < tabs.size(); ++i)
  51517. {
  51518. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51519. tb->setToggleState (i == newIndex, false);
  51520. }
  51521. resized();
  51522. if (sendChangeMessage_)
  51523. sendChangeMessage();
  51524. currentTabChanged (newIndex, getCurrentTabName());
  51525. }
  51526. }
  51527. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51528. {
  51529. TabInfo* const tab = tabs[index];
  51530. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51531. }
  51532. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51533. {
  51534. for (int i = tabs.size(); --i >= 0;)
  51535. if (tabs.getUnchecked(i)->component == button)
  51536. return i;
  51537. return -1;
  51538. }
  51539. void TabbedButtonBar::lookAndFeelChanged()
  51540. {
  51541. extraTabsButton = 0;
  51542. resized();
  51543. }
  51544. void TabbedButtonBar::resized()
  51545. {
  51546. int depth = getWidth();
  51547. int length = getHeight();
  51548. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51549. swapVariables (depth, length);
  51550. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51551. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51552. int i, totalLength = overlap;
  51553. int numVisibleButtons = tabs.size();
  51554. for (i = 0; i < tabs.size(); ++i)
  51555. {
  51556. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51557. totalLength += tb->getBestTabLength (depth) - overlap;
  51558. tb->overlapPixels = overlap / 2;
  51559. }
  51560. double scale = 1.0;
  51561. if (totalLength > length)
  51562. scale = jmax (minimumScale, length / (double) totalLength);
  51563. const bool isTooBig = totalLength * scale > length;
  51564. int tabsButtonPos = 0;
  51565. if (isTooBig)
  51566. {
  51567. if (extraTabsButton == 0)
  51568. {
  51569. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51570. extraTabsButton->addListener (behindFrontTab);
  51571. extraTabsButton->setAlwaysOnTop (true);
  51572. extraTabsButton->setTriggeredOnMouseDown (true);
  51573. }
  51574. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51575. extraTabsButton->setSize (buttonSize, buttonSize);
  51576. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51577. {
  51578. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51579. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51580. }
  51581. else
  51582. {
  51583. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51584. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51585. }
  51586. totalLength = 0;
  51587. for (i = 0; i < tabs.size(); ++i)
  51588. {
  51589. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51590. const int newLength = totalLength + tb->getBestTabLength (depth);
  51591. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51592. {
  51593. totalLength += overlap;
  51594. break;
  51595. }
  51596. numVisibleButtons = i + 1;
  51597. totalLength = newLength - overlap;
  51598. }
  51599. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51600. }
  51601. else
  51602. {
  51603. extraTabsButton = 0;
  51604. }
  51605. int pos = 0;
  51606. TabBarButton* frontTab = 0;
  51607. for (i = 0; i < tabs.size(); ++i)
  51608. {
  51609. TabBarButton* const tb = getTabButton (i);
  51610. if (tb != 0)
  51611. {
  51612. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51613. if (i < numVisibleButtons)
  51614. {
  51615. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51616. tb->setBounds (pos, 0, bestLength, getHeight());
  51617. else
  51618. tb->setBounds (0, pos, getWidth(), bestLength);
  51619. tb->toBack();
  51620. if (i == currentTabIndex)
  51621. frontTab = tb;
  51622. tb->setVisible (true);
  51623. }
  51624. else
  51625. {
  51626. tb->setVisible (false);
  51627. }
  51628. pos += bestLength - overlap;
  51629. }
  51630. }
  51631. behindFrontTab->setBounds (getLocalBounds());
  51632. if (frontTab != 0)
  51633. {
  51634. frontTab->toFront (false);
  51635. behindFrontTab->toBehind (frontTab);
  51636. }
  51637. }
  51638. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51639. {
  51640. TabInfo* const tab = tabs [tabIndex];
  51641. return tab == 0 ? Colours::white : tab->colour;
  51642. }
  51643. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51644. {
  51645. TabInfo* const tab = tabs [tabIndex];
  51646. if (tab != 0 && tab->colour != newColour)
  51647. {
  51648. tab->colour = newColour;
  51649. repaint();
  51650. }
  51651. }
  51652. void TabbedButtonBar::showExtraItemsMenu()
  51653. {
  51654. PopupMenu m;
  51655. for (int i = 0; i < tabs.size(); ++i)
  51656. {
  51657. const TabInfo* const tab = tabs.getUnchecked(i);
  51658. if (! tab->component->isVisible())
  51659. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51660. }
  51661. const int res = m.showAt (extraTabsButton);
  51662. if (res != 0)
  51663. setCurrentTabIndex (res - 1);
  51664. }
  51665. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51666. {
  51667. }
  51668. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51669. {
  51670. }
  51671. END_JUCE_NAMESPACE
  51672. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51673. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51674. BEGIN_JUCE_NAMESPACE
  51675. namespace TabbedComponentHelpers
  51676. {
  51677. const Identifier deleteComponentId ("deleteByTabComp_");
  51678. void deleteIfNecessary (Component* const comp)
  51679. {
  51680. if (comp != 0 && (bool) comp->getProperties() [deleteComponentId])
  51681. delete comp;
  51682. }
  51683. const Rectangle<int> getTabArea (Rectangle<int>& content, BorderSize& outline,
  51684. const TabbedButtonBar::Orientation orientation, const int tabDepth)
  51685. {
  51686. switch (orientation)
  51687. {
  51688. case TabbedButtonBar::TabsAtTop: outline.setTop (0); return content.removeFromTop (tabDepth);
  51689. case TabbedButtonBar::TabsAtBottom: outline.setBottom (0); return content.removeFromBottom (tabDepth);
  51690. case TabbedButtonBar::TabsAtLeft: outline.setLeft (0); return content.removeFromLeft (tabDepth);
  51691. case TabbedButtonBar::TabsAtRight: outline.setRight (0); return content.removeFromRight (tabDepth);
  51692. default: jassertfalse; break;
  51693. }
  51694. return Rectangle<int>();
  51695. }
  51696. }
  51697. class TabbedComponent::ButtonBar : public TabbedButtonBar
  51698. {
  51699. public:
  51700. ButtonBar (TabbedComponent& owner_, const TabbedButtonBar::Orientation orientation_)
  51701. : TabbedButtonBar (orientation_),
  51702. owner (owner_)
  51703. {
  51704. }
  51705. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51706. {
  51707. owner.changeCallback (newCurrentTabIndex, newTabName);
  51708. }
  51709. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51710. {
  51711. owner.popupMenuClickOnTab (tabIndex, tabName);
  51712. }
  51713. const Colour getTabBackgroundColour (const int tabIndex)
  51714. {
  51715. return owner.tabs->getTabBackgroundColour (tabIndex);
  51716. }
  51717. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51718. {
  51719. return owner.createTabButton (tabName, tabIndex);
  51720. }
  51721. private:
  51722. TabbedComponent& owner;
  51723. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonBar);
  51724. };
  51725. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51726. : tabDepth (30),
  51727. outlineThickness (1),
  51728. edgeIndent (0)
  51729. {
  51730. addAndMakeVisible (tabs = new ButtonBar (*this, orientation));
  51731. }
  51732. TabbedComponent::~TabbedComponent()
  51733. {
  51734. clearTabs();
  51735. tabs = 0;
  51736. }
  51737. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51738. {
  51739. tabs->setOrientation (orientation);
  51740. resized();
  51741. }
  51742. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51743. {
  51744. return tabs->getOrientation();
  51745. }
  51746. void TabbedComponent::setTabBarDepth (const int newDepth)
  51747. {
  51748. if (tabDepth != newDepth)
  51749. {
  51750. tabDepth = newDepth;
  51751. resized();
  51752. }
  51753. }
  51754. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51755. {
  51756. return new TabBarButton (tabName, *tabs);
  51757. }
  51758. void TabbedComponent::clearTabs()
  51759. {
  51760. if (panelComponent != 0)
  51761. {
  51762. panelComponent->setVisible (false);
  51763. removeChildComponent (panelComponent);
  51764. panelComponent = 0;
  51765. }
  51766. tabs->clearTabs();
  51767. for (int i = contentComponents.size(); --i >= 0;)
  51768. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (i));
  51769. contentComponents.clear();
  51770. }
  51771. void TabbedComponent::addTab (const String& tabName,
  51772. const Colour& tabBackgroundColour,
  51773. Component* const contentComponent,
  51774. const bool deleteComponentWhenNotNeeded,
  51775. const int insertIndex)
  51776. {
  51777. contentComponents.insert (insertIndex, WeakReference<Component> (contentComponent));
  51778. if (deleteComponentWhenNotNeeded && contentComponent != 0)
  51779. contentComponent->getProperties().set (TabbedComponentHelpers::deleteComponentId, true);
  51780. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51781. }
  51782. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51783. {
  51784. tabs->setTabName (tabIndex, newName);
  51785. }
  51786. void TabbedComponent::removeTab (const int tabIndex)
  51787. {
  51788. if (isPositiveAndBelow (tabIndex, contentComponents.size()))
  51789. {
  51790. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (tabIndex));
  51791. contentComponents.remove (tabIndex);
  51792. tabs->removeTab (tabIndex);
  51793. }
  51794. }
  51795. int TabbedComponent::getNumTabs() const
  51796. {
  51797. return tabs->getNumTabs();
  51798. }
  51799. const StringArray TabbedComponent::getTabNames() const
  51800. {
  51801. return tabs->getTabNames();
  51802. }
  51803. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51804. {
  51805. return contentComponents [tabIndex];
  51806. }
  51807. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51808. {
  51809. return tabs->getTabBackgroundColour (tabIndex);
  51810. }
  51811. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51812. {
  51813. tabs->setTabBackgroundColour (tabIndex, newColour);
  51814. if (getCurrentTabIndex() == tabIndex)
  51815. repaint();
  51816. }
  51817. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51818. {
  51819. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51820. }
  51821. int TabbedComponent::getCurrentTabIndex() const
  51822. {
  51823. return tabs->getCurrentTabIndex();
  51824. }
  51825. const String TabbedComponent::getCurrentTabName() const
  51826. {
  51827. return tabs->getCurrentTabName();
  51828. }
  51829. void TabbedComponent::setOutline (const int thickness)
  51830. {
  51831. outlineThickness = thickness;
  51832. resized();
  51833. repaint();
  51834. }
  51835. void TabbedComponent::setIndent (const int indentThickness)
  51836. {
  51837. edgeIndent = indentThickness;
  51838. resized();
  51839. repaint();
  51840. }
  51841. void TabbedComponent::paint (Graphics& g)
  51842. {
  51843. g.fillAll (findColour (backgroundColourId));
  51844. Rectangle<int> content (getLocalBounds());
  51845. BorderSize outline (outlineThickness);
  51846. TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth);
  51847. g.reduceClipRegion (content);
  51848. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51849. if (outlineThickness > 0)
  51850. {
  51851. RectangleList rl (content);
  51852. rl.subtract (outline.subtractedFrom (content));
  51853. g.reduceClipRegion (rl);
  51854. g.fillAll (findColour (outlineColourId));
  51855. }
  51856. }
  51857. void TabbedComponent::resized()
  51858. {
  51859. Rectangle<int> content (getLocalBounds());
  51860. BorderSize outline (outlineThickness);
  51861. tabs->setBounds (TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth));
  51862. content = BorderSize (edgeIndent).subtractedFrom (outline.subtractedFrom (content));
  51863. for (int i = contentComponents.size(); --i >= 0;)
  51864. if (contentComponents.getReference (i) != 0)
  51865. contentComponents.getReference (i)->setBounds (content);
  51866. }
  51867. void TabbedComponent::lookAndFeelChanged()
  51868. {
  51869. for (int i = contentComponents.size(); --i >= 0;)
  51870. if (contentComponents.getReference (i) != 0)
  51871. contentComponents.getReference (i)->lookAndFeelChanged();
  51872. }
  51873. void TabbedComponent::changeCallback (const int newCurrentTabIndex, const String& newTabName)
  51874. {
  51875. if (panelComponent != 0)
  51876. {
  51877. panelComponent->setVisible (false);
  51878. removeChildComponent (panelComponent);
  51879. panelComponent = 0;
  51880. }
  51881. if (getCurrentTabIndex() >= 0)
  51882. {
  51883. panelComponent = getTabContentComponent (getCurrentTabIndex());
  51884. if (panelComponent != 0)
  51885. {
  51886. // do these ops as two stages instead of addAndMakeVisible() so that the
  51887. // component has always got a parent when it gets the visibilityChanged() callback
  51888. addChildComponent (panelComponent);
  51889. panelComponent->setVisible (true);
  51890. panelComponent->toFront (true);
  51891. }
  51892. repaint();
  51893. }
  51894. resized();
  51895. currentTabChanged (newCurrentTabIndex, newTabName);
  51896. }
  51897. void TabbedComponent::currentTabChanged (const int, const String&) {}
  51898. void TabbedComponent::popupMenuClickOnTab (const int, const String&) {}
  51899. END_JUCE_NAMESPACE
  51900. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51901. /*** Start of inlined file: juce_Viewport.cpp ***/
  51902. BEGIN_JUCE_NAMESPACE
  51903. Viewport::Viewport (const String& componentName)
  51904. : Component (componentName),
  51905. scrollBarThickness (0),
  51906. singleStepX (16),
  51907. singleStepY (16),
  51908. showHScrollbar (true),
  51909. showVScrollbar (true),
  51910. verticalScrollBar (true),
  51911. horizontalScrollBar (false)
  51912. {
  51913. // content holder is used to clip the contents so they don't overlap the scrollbars
  51914. addAndMakeVisible (&contentHolder);
  51915. contentHolder.setInterceptsMouseClicks (false, true);
  51916. addChildComponent (&verticalScrollBar);
  51917. addChildComponent (&horizontalScrollBar);
  51918. verticalScrollBar.addListener (this);
  51919. horizontalScrollBar.addListener (this);
  51920. setInterceptsMouseClicks (false, true);
  51921. setWantsKeyboardFocus (true);
  51922. }
  51923. Viewport::~Viewport()
  51924. {
  51925. deleteContentComp();
  51926. }
  51927. void Viewport::visibleAreaChanged (const Rectangle<int>&)
  51928. {
  51929. }
  51930. void Viewport::deleteContentComp()
  51931. {
  51932. // This sets the content comp to a null pointer before deleting the old one, in case
  51933. // anything tries to use the old one while it's in mid-deletion..
  51934. ScopedPointer<Component> oldCompDeleter (contentComp);
  51935. contentComp = 0;
  51936. }
  51937. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51938. {
  51939. if (contentComp.get() != newViewedComponent)
  51940. {
  51941. deleteContentComp();
  51942. contentComp = newViewedComponent;
  51943. if (contentComp != 0)
  51944. {
  51945. contentHolder.addAndMakeVisible (contentComp);
  51946. setViewPosition (0, 0);
  51947. contentComp->addComponentListener (this);
  51948. }
  51949. updateVisibleArea();
  51950. }
  51951. }
  51952. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  51953. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  51954. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51955. {
  51956. if (contentComp != 0)
  51957. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51958. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51959. }
  51960. void Viewport::setViewPosition (const Point<int>& newPosition)
  51961. {
  51962. setViewPosition (newPosition.getX(), newPosition.getY());
  51963. }
  51964. void Viewport::setViewPositionProportionately (const double x, const double y)
  51965. {
  51966. if (contentComp != 0)
  51967. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51968. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51969. }
  51970. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51971. {
  51972. if (contentComp != 0)
  51973. {
  51974. int dx = 0, dy = 0;
  51975. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51976. {
  51977. if (mouseX < activeBorderThickness)
  51978. dx = activeBorderThickness - mouseX;
  51979. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51980. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51981. if (dx < 0)
  51982. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51983. else
  51984. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51985. }
  51986. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51987. {
  51988. if (mouseY < activeBorderThickness)
  51989. dy = activeBorderThickness - mouseY;
  51990. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51991. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51992. if (dy < 0)
  51993. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51994. else
  51995. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51996. }
  51997. if (dx != 0 || dy != 0)
  51998. {
  51999. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52000. contentComp->getY() + dy);
  52001. return true;
  52002. }
  52003. }
  52004. return false;
  52005. }
  52006. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52007. {
  52008. updateVisibleArea();
  52009. }
  52010. void Viewport::resized()
  52011. {
  52012. updateVisibleArea();
  52013. }
  52014. void Viewport::updateVisibleArea()
  52015. {
  52016. const int scrollbarWidth = getScrollBarThickness();
  52017. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52018. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52019. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52020. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52021. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52022. Rectangle<int> contentArea (getLocalBounds());
  52023. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52024. {
  52025. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52026. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52027. if (vBarVisible)
  52028. contentArea.setWidth (getWidth() - scrollbarWidth);
  52029. if (hBarVisible)
  52030. contentArea.setHeight (getHeight() - scrollbarWidth);
  52031. if (! contentArea.contains (contentComp->getBounds()))
  52032. {
  52033. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52034. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52035. }
  52036. }
  52037. if (vBarVisible)
  52038. contentArea.setWidth (getWidth() - scrollbarWidth);
  52039. if (hBarVisible)
  52040. contentArea.setHeight (getHeight() - scrollbarWidth);
  52041. contentHolder.setBounds (contentArea);
  52042. Rectangle<int> contentBounds;
  52043. if (contentComp != 0)
  52044. contentBounds = contentHolder.getLocalArea (contentComp, contentComp->getLocalBounds());
  52045. Point<int> visibleOrigin (-contentBounds.getPosition());
  52046. if (hBarVisible)
  52047. {
  52048. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52049. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52050. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52051. horizontalScrollBar.setSingleStepSize (singleStepX);
  52052. horizontalScrollBar.cancelPendingUpdate();
  52053. }
  52054. else if (canShowHBar)
  52055. {
  52056. visibleOrigin.setX (0);
  52057. }
  52058. if (vBarVisible)
  52059. {
  52060. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52061. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52062. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52063. verticalScrollBar.setSingleStepSize (singleStepY);
  52064. verticalScrollBar.cancelPendingUpdate();
  52065. }
  52066. else if (canShowVBar)
  52067. {
  52068. visibleOrigin.setY (0);
  52069. }
  52070. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52071. horizontalScrollBar.setVisible (hBarVisible);
  52072. verticalScrollBar.setVisible (vBarVisible);
  52073. setViewPosition (visibleOrigin);
  52074. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52075. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52076. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52077. if (lastVisibleArea != visibleArea)
  52078. {
  52079. lastVisibleArea = visibleArea;
  52080. visibleAreaChanged (visibleArea);
  52081. }
  52082. horizontalScrollBar.handleUpdateNowIfNeeded();
  52083. verticalScrollBar.handleUpdateNowIfNeeded();
  52084. }
  52085. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52086. {
  52087. if (singleStepX != stepX || singleStepY != stepY)
  52088. {
  52089. singleStepX = stepX;
  52090. singleStepY = stepY;
  52091. updateVisibleArea();
  52092. }
  52093. }
  52094. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52095. const bool showHorizontalScrollbarIfNeeded)
  52096. {
  52097. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52098. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52099. {
  52100. showVScrollbar = showVerticalScrollbarIfNeeded;
  52101. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52102. updateVisibleArea();
  52103. }
  52104. }
  52105. void Viewport::setScrollBarThickness (const int thickness)
  52106. {
  52107. if (scrollBarThickness != thickness)
  52108. {
  52109. scrollBarThickness = thickness;
  52110. updateVisibleArea();
  52111. }
  52112. }
  52113. int Viewport::getScrollBarThickness() const
  52114. {
  52115. return scrollBarThickness > 0 ? scrollBarThickness
  52116. : getLookAndFeel().getDefaultScrollbarWidth();
  52117. }
  52118. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52119. {
  52120. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52121. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52122. }
  52123. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52124. {
  52125. const int newRangeStartInt = roundToInt (newRangeStart);
  52126. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52127. {
  52128. setViewPosition (newRangeStartInt, getViewPositionY());
  52129. }
  52130. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52131. {
  52132. setViewPosition (getViewPositionX(), newRangeStartInt);
  52133. }
  52134. }
  52135. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52136. {
  52137. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52138. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52139. }
  52140. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52141. {
  52142. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52143. {
  52144. const bool hasVertBar = verticalScrollBar.isVisible();
  52145. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52146. if (hasHorzBar || hasVertBar)
  52147. {
  52148. if (wheelIncrementX != 0)
  52149. {
  52150. wheelIncrementX *= 14.0f * singleStepX;
  52151. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52152. : jmax (wheelIncrementX, 1.0f);
  52153. }
  52154. if (wheelIncrementY != 0)
  52155. {
  52156. wheelIncrementY *= 14.0f * singleStepY;
  52157. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52158. : jmax (wheelIncrementY, 1.0f);
  52159. }
  52160. Point<int> pos (getViewPosition());
  52161. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52162. {
  52163. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52164. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52165. }
  52166. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52167. {
  52168. if (wheelIncrementX == 0 && ! hasVertBar)
  52169. wheelIncrementX = wheelIncrementY;
  52170. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52171. }
  52172. else if (hasVertBar && wheelIncrementY != 0)
  52173. {
  52174. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52175. }
  52176. if (pos != getViewPosition())
  52177. {
  52178. setViewPosition (pos);
  52179. return true;
  52180. }
  52181. }
  52182. }
  52183. return false;
  52184. }
  52185. bool Viewport::keyPressed (const KeyPress& key)
  52186. {
  52187. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52188. || key.isKeyCode (KeyPress::downKey)
  52189. || key.isKeyCode (KeyPress::pageUpKey)
  52190. || key.isKeyCode (KeyPress::pageDownKey)
  52191. || key.isKeyCode (KeyPress::homeKey)
  52192. || key.isKeyCode (KeyPress::endKey);
  52193. if (verticalScrollBar.isVisible() && isUpDownKey)
  52194. return verticalScrollBar.keyPressed (key);
  52195. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52196. || key.isKeyCode (KeyPress::rightKey);
  52197. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52198. return horizontalScrollBar.keyPressed (key);
  52199. return false;
  52200. }
  52201. END_JUCE_NAMESPACE
  52202. /*** End of inlined file: juce_Viewport.cpp ***/
  52203. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52204. BEGIN_JUCE_NAMESPACE
  52205. namespace LookAndFeelHelpers
  52206. {
  52207. void createRoundedPath (Path& p,
  52208. const float x, const float y,
  52209. const float w, const float h,
  52210. const float cs,
  52211. const bool curveTopLeft, const bool curveTopRight,
  52212. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52213. {
  52214. const float cs2 = 2.0f * cs;
  52215. if (curveTopLeft)
  52216. {
  52217. p.startNewSubPath (x, y + cs);
  52218. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52219. }
  52220. else
  52221. {
  52222. p.startNewSubPath (x, y);
  52223. }
  52224. if (curveTopRight)
  52225. {
  52226. p.lineTo (x + w - cs, y);
  52227. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52228. }
  52229. else
  52230. {
  52231. p.lineTo (x + w, y);
  52232. }
  52233. if (curveBottomRight)
  52234. {
  52235. p.lineTo (x + w, y + h - cs);
  52236. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52237. }
  52238. else
  52239. {
  52240. p.lineTo (x + w, y + h);
  52241. }
  52242. if (curveBottomLeft)
  52243. {
  52244. p.lineTo (x + cs, y + h);
  52245. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52246. }
  52247. else
  52248. {
  52249. p.lineTo (x, y + h);
  52250. }
  52251. p.closeSubPath();
  52252. }
  52253. const Colour createBaseColour (const Colour& buttonColour,
  52254. const bool hasKeyboardFocus,
  52255. const bool isMouseOverButton,
  52256. const bool isButtonDown) throw()
  52257. {
  52258. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52259. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52260. if (isButtonDown)
  52261. return baseColour.contrasting (0.2f);
  52262. else if (isMouseOverButton)
  52263. return baseColour.contrasting (0.1f);
  52264. return baseColour;
  52265. }
  52266. const TextLayout layoutTooltipText (const String& text) throw()
  52267. {
  52268. const float tooltipFontSize = 12.0f;
  52269. const int maxToolTipWidth = 400;
  52270. const Font f (tooltipFontSize, Font::bold);
  52271. TextLayout tl (text, f);
  52272. tl.layout (maxToolTipWidth, Justification::left, true);
  52273. return tl;
  52274. }
  52275. LookAndFeel* defaultLF = 0;
  52276. LookAndFeel* currentDefaultLF = 0;
  52277. }
  52278. LookAndFeel::LookAndFeel()
  52279. {
  52280. /* if this fails it means you're trying to create a LookAndFeel object before
  52281. the static Colours have been initialised. That ain't gonna work. It probably
  52282. means that you're using a static LookAndFeel object and that your compiler has
  52283. decided to intialise it before the Colours class.
  52284. */
  52285. jassert (Colours::white == Colour (0xffffffff));
  52286. // set up the standard set of colours..
  52287. const int textButtonColour = 0xffbbbbff;
  52288. const int textHighlightColour = 0x401111ee;
  52289. const int standardOutlineColour = 0xb2808080;
  52290. static const int standardColours[] =
  52291. {
  52292. TextButton::buttonColourId, textButtonColour,
  52293. TextButton::buttonOnColourId, 0xff4444ff,
  52294. TextButton::textColourOnId, 0xff000000,
  52295. TextButton::textColourOffId, 0xff000000,
  52296. ComboBox::buttonColourId, 0xffbbbbff,
  52297. ComboBox::outlineColourId, standardOutlineColour,
  52298. ToggleButton::textColourId, 0xff000000,
  52299. TextEditor::backgroundColourId, 0xffffffff,
  52300. TextEditor::textColourId, 0xff000000,
  52301. TextEditor::highlightColourId, textHighlightColour,
  52302. TextEditor::highlightedTextColourId, 0xff000000,
  52303. TextEditor::caretColourId, 0xff000000,
  52304. TextEditor::outlineColourId, 0x00000000,
  52305. TextEditor::focusedOutlineColourId, textButtonColour,
  52306. TextEditor::shadowColourId, 0x38000000,
  52307. Label::backgroundColourId, 0x00000000,
  52308. Label::textColourId, 0xff000000,
  52309. Label::outlineColourId, 0x00000000,
  52310. ScrollBar::backgroundColourId, 0x00000000,
  52311. ScrollBar::thumbColourId, 0xffffffff,
  52312. TreeView::linesColourId, 0x4c000000,
  52313. TreeView::backgroundColourId, 0x00000000,
  52314. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52315. PopupMenu::backgroundColourId, 0xffffffff,
  52316. PopupMenu::textColourId, 0xff000000,
  52317. PopupMenu::headerTextColourId, 0xff000000,
  52318. PopupMenu::highlightedTextColourId, 0xffffffff,
  52319. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52320. ComboBox::textColourId, 0xff000000,
  52321. ComboBox::backgroundColourId, 0xffffffff,
  52322. ComboBox::arrowColourId, 0x99000000,
  52323. ListBox::backgroundColourId, 0xffffffff,
  52324. ListBox::outlineColourId, standardOutlineColour,
  52325. ListBox::textColourId, 0xff000000,
  52326. Slider::backgroundColourId, 0x00000000,
  52327. Slider::thumbColourId, textButtonColour,
  52328. Slider::trackColourId, 0x7fffffff,
  52329. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52330. Slider::rotarySliderOutlineColourId, 0x66000000,
  52331. Slider::textBoxTextColourId, 0xff000000,
  52332. Slider::textBoxBackgroundColourId, 0xffffffff,
  52333. Slider::textBoxHighlightColourId, textHighlightColour,
  52334. Slider::textBoxOutlineColourId, standardOutlineColour,
  52335. ResizableWindow::backgroundColourId, 0xff777777,
  52336. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52337. AlertWindow::backgroundColourId, 0xffededed,
  52338. AlertWindow::textColourId, 0xff000000,
  52339. AlertWindow::outlineColourId, 0xff666666,
  52340. ProgressBar::backgroundColourId, 0xffeeeeee,
  52341. ProgressBar::foregroundColourId, 0xffaaaaee,
  52342. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52343. TooltipWindow::textColourId, 0xff000000,
  52344. TooltipWindow::outlineColourId, 0x4c000000,
  52345. TabbedComponent::backgroundColourId, 0x00000000,
  52346. TabbedComponent::outlineColourId, 0xff777777,
  52347. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52348. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52349. Toolbar::backgroundColourId, 0xfff6f8f9,
  52350. Toolbar::separatorColourId, 0x4c000000,
  52351. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52352. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52353. Toolbar::labelTextColourId, 0xff000000,
  52354. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52355. HyperlinkButton::textColourId, 0xcc1111ee,
  52356. GroupComponent::outlineColourId, 0x66000000,
  52357. GroupComponent::textColourId, 0xff000000,
  52358. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52359. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52360. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52361. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52362. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52363. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52364. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52365. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52366. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52367. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52368. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52369. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52370. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52371. CodeEditorComponent::caretColourId, 0xff000000,
  52372. CodeEditorComponent::highlightColourId, textHighlightColour,
  52373. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52374. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52375. ColourSelector::labelTextColourId, 0xff000000,
  52376. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52377. KeyMappingEditorComponent::textColourId, 0xff000000,
  52378. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52379. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52380. DrawableButton::textColourId, 0xff000000,
  52381. };
  52382. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52383. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52384. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52385. if (defaultSansName.isEmpty())
  52386. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52387. defaultSans = defaultSansName;
  52388. defaultSerif = defaultSerifName;
  52389. defaultFixed = defaultFixedName;
  52390. Font::setFallbackFontName (defaultFallback);
  52391. }
  52392. LookAndFeel::~LookAndFeel()
  52393. {
  52394. if (this == LookAndFeelHelpers::currentDefaultLF)
  52395. setDefaultLookAndFeel (0);
  52396. }
  52397. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52398. {
  52399. const int index = colourIds.indexOf (colourId);
  52400. if (index >= 0)
  52401. return colours [index];
  52402. jassertfalse;
  52403. return Colours::black;
  52404. }
  52405. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52406. {
  52407. const int index = colourIds.indexOf (colourId);
  52408. if (index >= 0)
  52409. {
  52410. colours.set (index, colour);
  52411. }
  52412. else
  52413. {
  52414. colourIds.add (colourId);
  52415. colours.add (colour);
  52416. }
  52417. }
  52418. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52419. {
  52420. return colourIds.contains (colourId);
  52421. }
  52422. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52423. {
  52424. // if this happens, your app hasn't initialised itself properly.. if you're
  52425. // trying to hack your own main() function, have a look at
  52426. // JUCEApplication::initialiseForGUI()
  52427. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52428. return *LookAndFeelHelpers::currentDefaultLF;
  52429. }
  52430. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52431. {
  52432. using namespace LookAndFeelHelpers;
  52433. if (newDefaultLookAndFeel == 0)
  52434. {
  52435. if (defaultLF == 0)
  52436. defaultLF = new LookAndFeel();
  52437. newDefaultLookAndFeel = defaultLF;
  52438. }
  52439. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52440. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52441. {
  52442. Component* const c = Desktop::getInstance().getComponent (i);
  52443. if (c != 0)
  52444. c->sendLookAndFeelChange();
  52445. }
  52446. }
  52447. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52448. {
  52449. using namespace LookAndFeelHelpers;
  52450. if (currentDefaultLF == defaultLF)
  52451. currentDefaultLF = 0;
  52452. deleteAndZero (defaultLF);
  52453. }
  52454. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52455. {
  52456. String faceName (font.getTypefaceName());
  52457. if (faceName == Font::getDefaultSansSerifFontName())
  52458. faceName = defaultSans;
  52459. else if (faceName == Font::getDefaultSerifFontName())
  52460. faceName = defaultSerif;
  52461. else if (faceName == Font::getDefaultMonospacedFontName())
  52462. faceName = defaultFixed;
  52463. Font f (font);
  52464. f.setTypefaceName (faceName);
  52465. return Typeface::createSystemTypefaceFor (f);
  52466. }
  52467. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52468. {
  52469. defaultSans = newName;
  52470. }
  52471. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52472. {
  52473. return component.getMouseCursor();
  52474. }
  52475. void LookAndFeel::drawButtonBackground (Graphics& g,
  52476. Button& button,
  52477. const Colour& backgroundColour,
  52478. bool isMouseOverButton,
  52479. bool isButtonDown)
  52480. {
  52481. const int width = button.getWidth();
  52482. const int height = button.getHeight();
  52483. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52484. const float halfThickness = outlineThickness * 0.5f;
  52485. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52486. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52487. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52488. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52489. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52490. button.hasKeyboardFocus (true),
  52491. isMouseOverButton, isButtonDown)
  52492. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52493. drawGlassLozenge (g,
  52494. indentL,
  52495. indentT,
  52496. width - indentL - indentR,
  52497. height - indentT - indentB,
  52498. baseColour, outlineThickness, -1.0f,
  52499. button.isConnectedOnLeft(),
  52500. button.isConnectedOnRight(),
  52501. button.isConnectedOnTop(),
  52502. button.isConnectedOnBottom());
  52503. }
  52504. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52505. {
  52506. return button.getFont();
  52507. }
  52508. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52509. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52510. {
  52511. Font font (getFontForTextButton (button));
  52512. g.setFont (font);
  52513. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52514. : TextButton::textColourOffId)
  52515. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52516. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52517. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52518. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52519. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52520. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52521. g.drawFittedText (button.getButtonText(),
  52522. leftIndent,
  52523. yIndent,
  52524. button.getWidth() - leftIndent - rightIndent,
  52525. button.getHeight() - yIndent * 2,
  52526. Justification::centred, 2);
  52527. }
  52528. void LookAndFeel::drawTickBox (Graphics& g,
  52529. Component& component,
  52530. float x, float y, float w, float h,
  52531. const bool ticked,
  52532. const bool isEnabled,
  52533. const bool isMouseOverButton,
  52534. const bool isButtonDown)
  52535. {
  52536. const float boxSize = w * 0.7f;
  52537. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52538. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52539. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52540. true, isMouseOverButton, isButtonDown),
  52541. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52542. if (ticked)
  52543. {
  52544. Path tick;
  52545. tick.startNewSubPath (1.5f, 3.0f);
  52546. tick.lineTo (3.0f, 6.0f);
  52547. tick.lineTo (6.0f, 0.0f);
  52548. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52549. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52550. .translated (x, y));
  52551. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52552. }
  52553. }
  52554. void LookAndFeel::drawToggleButton (Graphics& g,
  52555. ToggleButton& button,
  52556. bool isMouseOverButton,
  52557. bool isButtonDown)
  52558. {
  52559. if (button.hasKeyboardFocus (true))
  52560. {
  52561. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52562. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52563. }
  52564. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52565. const float tickWidth = fontSize * 1.1f;
  52566. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52567. tickWidth, tickWidth,
  52568. button.getToggleState(),
  52569. button.isEnabled(),
  52570. isMouseOverButton,
  52571. isButtonDown);
  52572. g.setColour (button.findColour (ToggleButton::textColourId));
  52573. g.setFont (fontSize);
  52574. if (! button.isEnabled())
  52575. g.setOpacity (0.5f);
  52576. const int textX = (int) tickWidth + 5;
  52577. g.drawFittedText (button.getButtonText(),
  52578. textX, 0,
  52579. button.getWidth() - textX - 2, button.getHeight(),
  52580. Justification::centredLeft, 10);
  52581. }
  52582. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52583. {
  52584. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52585. const int tickWidth = jmin (24, button.getHeight());
  52586. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52587. button.getHeight());
  52588. }
  52589. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52590. const String& message,
  52591. const String& button1,
  52592. const String& button2,
  52593. const String& button3,
  52594. AlertWindow::AlertIconType iconType,
  52595. int numButtons,
  52596. Component* associatedComponent)
  52597. {
  52598. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52599. if (numButtons == 1)
  52600. {
  52601. aw->addButton (button1, 0,
  52602. KeyPress (KeyPress::escapeKey, 0, 0),
  52603. KeyPress (KeyPress::returnKey, 0, 0));
  52604. }
  52605. else
  52606. {
  52607. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52608. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52609. if (button1ShortCut == button2ShortCut)
  52610. button2ShortCut = KeyPress();
  52611. if (numButtons == 2)
  52612. {
  52613. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52614. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52615. }
  52616. else if (numButtons == 3)
  52617. {
  52618. aw->addButton (button1, 1, button1ShortCut);
  52619. aw->addButton (button2, 2, button2ShortCut);
  52620. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52621. }
  52622. }
  52623. return aw;
  52624. }
  52625. void LookAndFeel::drawAlertBox (Graphics& g,
  52626. AlertWindow& alert,
  52627. const Rectangle<int>& textArea,
  52628. TextLayout& textLayout)
  52629. {
  52630. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52631. int iconSpaceUsed = 0;
  52632. Justification alignment (Justification::horizontallyCentred);
  52633. const int iconWidth = 80;
  52634. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52635. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52636. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52637. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52638. iconSize, iconSize);
  52639. if (alert.getAlertType() != AlertWindow::NoIcon)
  52640. {
  52641. Path icon;
  52642. uint32 colour;
  52643. char character;
  52644. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52645. {
  52646. colour = 0x55ff5555;
  52647. character = '!';
  52648. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52649. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52650. (float) iconRect.getX(), (float) iconRect.getBottom());
  52651. icon = icon.createPathWithRoundedCorners (5.0f);
  52652. }
  52653. else
  52654. {
  52655. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52656. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52657. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52658. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52659. }
  52660. GlyphArrangement ga;
  52661. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52662. String::charToString (character),
  52663. (float) iconRect.getX(), (float) iconRect.getY(),
  52664. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52665. Justification::centred, false);
  52666. ga.createPath (icon);
  52667. icon.setUsingNonZeroWinding (false);
  52668. g.setColour (Colour (colour));
  52669. g.fillPath (icon);
  52670. iconSpaceUsed = iconWidth;
  52671. alignment = Justification::left;
  52672. }
  52673. g.setColour (alert.findColour (AlertWindow::textColourId));
  52674. textLayout.drawWithin (g,
  52675. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52676. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52677. alignment.getFlags() | Justification::top);
  52678. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52679. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52680. }
  52681. int LookAndFeel::getAlertBoxWindowFlags()
  52682. {
  52683. return ComponentPeer::windowAppearsOnTaskbar
  52684. | ComponentPeer::windowHasDropShadow;
  52685. }
  52686. int LookAndFeel::getAlertWindowButtonHeight()
  52687. {
  52688. return 28;
  52689. }
  52690. const Font LookAndFeel::getAlertWindowMessageFont()
  52691. {
  52692. return Font (15.0f);
  52693. }
  52694. const Font LookAndFeel::getAlertWindowFont()
  52695. {
  52696. return Font (12.0f);
  52697. }
  52698. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52699. int width, int height,
  52700. double progress, const String& textToShow)
  52701. {
  52702. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52703. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52704. g.fillAll (background);
  52705. if (progress >= 0.0f && progress < 1.0f)
  52706. {
  52707. drawGlassLozenge (g, 1.0f, 1.0f,
  52708. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52709. (float) (height - 2),
  52710. foreground,
  52711. 0.5f, 0.0f,
  52712. true, true, true, true);
  52713. }
  52714. else
  52715. {
  52716. // spinning bar..
  52717. g.setColour (foreground);
  52718. const int stripeWidth = height * 2;
  52719. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52720. Path p;
  52721. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52722. p.addQuadrilateral (x, 0.0f,
  52723. x + stripeWidth * 0.5f, 0.0f,
  52724. x, (float) height,
  52725. x - stripeWidth * 0.5f, (float) height);
  52726. Image im (Image::ARGB, width, height, true);
  52727. {
  52728. Graphics g2 (im);
  52729. drawGlassLozenge (g2, 1.0f, 1.0f,
  52730. (float) (width - 2),
  52731. (float) (height - 2),
  52732. foreground,
  52733. 0.5f, 0.0f,
  52734. true, true, true, true);
  52735. }
  52736. g.setTiledImageFill (im, 0, 0, 0.85f);
  52737. g.fillPath (p);
  52738. }
  52739. if (textToShow.isNotEmpty())
  52740. {
  52741. g.setColour (Colour::contrasting (background, foreground));
  52742. g.setFont (height * 0.6f);
  52743. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52744. }
  52745. }
  52746. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52747. {
  52748. const float radius = jmin (w, h) * 0.4f;
  52749. const float thickness = radius * 0.15f;
  52750. Path p;
  52751. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52752. radius * 0.6f, thickness,
  52753. thickness * 0.5f);
  52754. const float cx = x + w * 0.5f;
  52755. const float cy = y + h * 0.5f;
  52756. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52757. for (int i = 0; i < 12; ++i)
  52758. {
  52759. const int n = (i + 12 - animationIndex) % 12;
  52760. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52761. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52762. .translated (cx, cy));
  52763. }
  52764. }
  52765. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52766. ScrollBar& scrollbar,
  52767. int width, int height,
  52768. int buttonDirection,
  52769. bool /*isScrollbarVertical*/,
  52770. bool /*isMouseOverButton*/,
  52771. bool isButtonDown)
  52772. {
  52773. Path p;
  52774. if (buttonDirection == 0)
  52775. p.addTriangle (width * 0.5f, height * 0.2f,
  52776. width * 0.1f, height * 0.7f,
  52777. width * 0.9f, height * 0.7f);
  52778. else if (buttonDirection == 1)
  52779. p.addTriangle (width * 0.8f, height * 0.5f,
  52780. width * 0.3f, height * 0.1f,
  52781. width * 0.3f, height * 0.9f);
  52782. else if (buttonDirection == 2)
  52783. p.addTriangle (width * 0.5f, height * 0.8f,
  52784. width * 0.1f, height * 0.3f,
  52785. width * 0.9f, height * 0.3f);
  52786. else if (buttonDirection == 3)
  52787. p.addTriangle (width * 0.2f, height * 0.5f,
  52788. width * 0.7f, height * 0.1f,
  52789. width * 0.7f, height * 0.9f);
  52790. if (isButtonDown)
  52791. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52792. else
  52793. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52794. g.fillPath (p);
  52795. g.setColour (Colour (0x80000000));
  52796. g.strokePath (p, PathStrokeType (0.5f));
  52797. }
  52798. void LookAndFeel::drawScrollbar (Graphics& g,
  52799. ScrollBar& scrollbar,
  52800. int x, int y,
  52801. int width, int height,
  52802. bool isScrollbarVertical,
  52803. int thumbStartPosition,
  52804. int thumbSize,
  52805. bool /*isMouseOver*/,
  52806. bool /*isMouseDown*/)
  52807. {
  52808. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52809. Path slotPath, thumbPath;
  52810. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52811. const float slotIndentx2 = slotIndent * 2.0f;
  52812. const float thumbIndent = slotIndent + 1.0f;
  52813. const float thumbIndentx2 = thumbIndent * 2.0f;
  52814. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52815. if (isScrollbarVertical)
  52816. {
  52817. slotPath.addRoundedRectangle (x + slotIndent,
  52818. y + slotIndent,
  52819. width - slotIndentx2,
  52820. height - slotIndentx2,
  52821. (width - slotIndentx2) * 0.5f);
  52822. if (thumbSize > 0)
  52823. thumbPath.addRoundedRectangle (x + thumbIndent,
  52824. thumbStartPosition + thumbIndent,
  52825. width - thumbIndentx2,
  52826. thumbSize - thumbIndentx2,
  52827. (width - thumbIndentx2) * 0.5f);
  52828. gx1 = (float) x;
  52829. gx2 = x + width * 0.7f;
  52830. }
  52831. else
  52832. {
  52833. slotPath.addRoundedRectangle (x + slotIndent,
  52834. y + slotIndent,
  52835. width - slotIndentx2,
  52836. height - slotIndentx2,
  52837. (height - slotIndentx2) * 0.5f);
  52838. if (thumbSize > 0)
  52839. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52840. y + thumbIndent,
  52841. thumbSize - thumbIndentx2,
  52842. height - thumbIndentx2,
  52843. (height - thumbIndentx2) * 0.5f);
  52844. gy1 = (float) y;
  52845. gy2 = y + height * 0.7f;
  52846. }
  52847. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52848. Colour trackColour1, trackColour2;
  52849. if (scrollbar.isColourSpecified (ScrollBar::trackColourId))
  52850. {
  52851. trackColour1 = trackColour2 = scrollbar.findColour (ScrollBar::trackColourId);
  52852. }
  52853. else
  52854. {
  52855. trackColour1 = thumbColour.overlaidWith (Colour (0x44000000));
  52856. trackColour2 = thumbColour.overlaidWith (Colour (0x19000000));
  52857. }
  52858. g.setGradientFill (ColourGradient (trackColour1, gx1, gy1,
  52859. trackColour2, gx2, gy2, false));
  52860. g.fillPath (slotPath);
  52861. if (isScrollbarVertical)
  52862. {
  52863. gx1 = x + width * 0.6f;
  52864. gx2 = (float) x + width;
  52865. }
  52866. else
  52867. {
  52868. gy1 = y + height * 0.6f;
  52869. gy2 = (float) y + height;
  52870. }
  52871. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52872. Colour (0x19000000), gx2, gy2, false));
  52873. g.fillPath (slotPath);
  52874. g.setColour (thumbColour);
  52875. g.fillPath (thumbPath);
  52876. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52877. Colours::transparentBlack, gx2, gy2, false));
  52878. g.saveState();
  52879. if (isScrollbarVertical)
  52880. g.reduceClipRegion (x + width / 2, y, width, height);
  52881. else
  52882. g.reduceClipRegion (x, y + height / 2, width, height);
  52883. g.fillPath (thumbPath);
  52884. g.restoreState();
  52885. g.setColour (Colour (0x4c000000));
  52886. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52887. }
  52888. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52889. {
  52890. return 0;
  52891. }
  52892. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52893. {
  52894. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52895. }
  52896. int LookAndFeel::getDefaultScrollbarWidth()
  52897. {
  52898. return 18;
  52899. }
  52900. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52901. {
  52902. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52903. : scrollbar.getHeight());
  52904. }
  52905. const Path LookAndFeel::getTickShape (const float height)
  52906. {
  52907. static const unsigned char tickShapeData[] =
  52908. {
  52909. 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,
  52910. 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,
  52911. 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,
  52912. 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,
  52913. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52914. };
  52915. Path p;
  52916. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52917. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52918. return p;
  52919. }
  52920. const Path LookAndFeel::getCrossShape (const float height)
  52921. {
  52922. static const unsigned char crossShapeData[] =
  52923. {
  52924. 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,
  52925. 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,
  52926. 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,
  52927. 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,
  52928. 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,
  52929. 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,
  52930. 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
  52931. };
  52932. Path p;
  52933. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52934. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52935. return p;
  52936. }
  52937. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52938. {
  52939. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52940. x += (w - boxSize) >> 1;
  52941. y += (h - boxSize) >> 1;
  52942. w = boxSize;
  52943. h = boxSize;
  52944. g.setColour (Colour (0xe5ffffff));
  52945. g.fillRect (x, y, w, h);
  52946. g.setColour (Colour (0x80000000));
  52947. g.drawRect (x, y, w, h);
  52948. const float size = boxSize / 2 + 1.0f;
  52949. const float centre = (float) (boxSize / 2);
  52950. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52951. if (isPlus)
  52952. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52953. }
  52954. void LookAndFeel::drawBubble (Graphics& g,
  52955. float tipX, float tipY,
  52956. float boxX, float boxY,
  52957. float boxW, float boxH)
  52958. {
  52959. int side = 0;
  52960. if (tipX < boxX)
  52961. side = 1;
  52962. else if (tipX > boxX + boxW)
  52963. side = 3;
  52964. else if (tipY > boxY + boxH)
  52965. side = 2;
  52966. const float indent = 2.0f;
  52967. Path p;
  52968. p.addBubble (boxX + indent,
  52969. boxY + indent,
  52970. boxW - indent * 2.0f,
  52971. boxH - indent * 2.0f,
  52972. 5.0f,
  52973. tipX, tipY,
  52974. side,
  52975. 0.5f,
  52976. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52977. //xxx need to take comp as param for colour
  52978. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52979. g.fillPath (p);
  52980. //xxx as above
  52981. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52982. g.strokePath (p, PathStrokeType (1.33f));
  52983. }
  52984. const Font LookAndFeel::getPopupMenuFont()
  52985. {
  52986. return Font (17.0f);
  52987. }
  52988. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52989. const bool isSeparator,
  52990. int standardMenuItemHeight,
  52991. int& idealWidth,
  52992. int& idealHeight)
  52993. {
  52994. if (isSeparator)
  52995. {
  52996. idealWidth = 50;
  52997. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52998. }
  52999. else
  53000. {
  53001. Font font (getPopupMenuFont());
  53002. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53003. font.setHeight (standardMenuItemHeight / 1.3f);
  53004. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53005. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53006. }
  53007. }
  53008. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53009. {
  53010. const Colour background (findColour (PopupMenu::backgroundColourId));
  53011. g.fillAll (background);
  53012. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53013. for (int i = 0; i < height; i += 3)
  53014. g.fillRect (0, i, width, 1);
  53015. #if ! JUCE_MAC
  53016. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53017. g.drawRect (0, 0, width, height);
  53018. #endif
  53019. }
  53020. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53021. int width, int height,
  53022. bool isScrollUpArrow)
  53023. {
  53024. const Colour background (findColour (PopupMenu::backgroundColourId));
  53025. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53026. background.withAlpha (0.0f),
  53027. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53028. false));
  53029. g.fillRect (1, 1, width - 2, height - 2);
  53030. const float hw = width * 0.5f;
  53031. const float arrowW = height * 0.3f;
  53032. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53033. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53034. Path p;
  53035. p.addTriangle (hw - arrowW, y1,
  53036. hw + arrowW, y1,
  53037. hw, y2);
  53038. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53039. g.fillPath (p);
  53040. }
  53041. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53042. int width, int height,
  53043. const bool isSeparator,
  53044. const bool isActive,
  53045. const bool isHighlighted,
  53046. const bool isTicked,
  53047. const bool hasSubMenu,
  53048. const String& text,
  53049. const String& shortcutKeyText,
  53050. Image* image,
  53051. const Colour* const textColourToUse)
  53052. {
  53053. const float halfH = height * 0.5f;
  53054. if (isSeparator)
  53055. {
  53056. const float separatorIndent = 5.5f;
  53057. g.setColour (Colour (0x33000000));
  53058. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53059. g.setColour (Colour (0x66ffffff));
  53060. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53061. }
  53062. else
  53063. {
  53064. Colour textColour (findColour (PopupMenu::textColourId));
  53065. if (textColourToUse != 0)
  53066. textColour = *textColourToUse;
  53067. if (isHighlighted)
  53068. {
  53069. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53070. g.fillRect (1, 1, width - 2, height - 2);
  53071. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53072. }
  53073. else
  53074. {
  53075. g.setColour (textColour);
  53076. }
  53077. if (! isActive)
  53078. g.setOpacity (0.3f);
  53079. Font font (getPopupMenuFont());
  53080. if (font.getHeight() > height / 1.3f)
  53081. font.setHeight (height / 1.3f);
  53082. g.setFont (font);
  53083. const int leftBorder = (height * 5) / 4;
  53084. const int rightBorder = 4;
  53085. if (image != 0)
  53086. {
  53087. g.drawImageWithin (*image,
  53088. 2, 1, leftBorder - 4, height - 2,
  53089. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53090. }
  53091. else if (isTicked)
  53092. {
  53093. const Path tick (getTickShape (1.0f));
  53094. const float th = font.getAscent();
  53095. const float ty = halfH - th * 0.5f;
  53096. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53097. th, true));
  53098. }
  53099. g.drawFittedText (text,
  53100. leftBorder, 0,
  53101. width - (leftBorder + rightBorder), height,
  53102. Justification::centredLeft, 1);
  53103. if (shortcutKeyText.isNotEmpty())
  53104. {
  53105. Font f2 (font);
  53106. f2.setHeight (f2.getHeight() * 0.75f);
  53107. f2.setHorizontalScale (0.95f);
  53108. g.setFont (f2);
  53109. g.drawText (shortcutKeyText,
  53110. leftBorder,
  53111. 0,
  53112. width - (leftBorder + rightBorder + 4),
  53113. height,
  53114. Justification::centredRight,
  53115. true);
  53116. }
  53117. if (hasSubMenu)
  53118. {
  53119. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53120. const float x = width - height * 0.6f;
  53121. Path p;
  53122. p.addTriangle (x, halfH - arrowH * 0.5f,
  53123. x, halfH + arrowH * 0.5f,
  53124. x + arrowH * 0.6f, halfH);
  53125. g.fillPath (p);
  53126. }
  53127. }
  53128. }
  53129. int LookAndFeel::getMenuWindowFlags()
  53130. {
  53131. return ComponentPeer::windowHasDropShadow;
  53132. }
  53133. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53134. bool, MenuBarComponent& menuBar)
  53135. {
  53136. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53137. if (menuBar.isEnabled())
  53138. {
  53139. drawShinyButtonShape (g,
  53140. -4.0f, 0.0f,
  53141. width + 8.0f, (float) height,
  53142. 0.0f,
  53143. baseColour,
  53144. 0.4f,
  53145. true, true, true, true);
  53146. }
  53147. else
  53148. {
  53149. g.fillAll (baseColour);
  53150. }
  53151. }
  53152. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53153. {
  53154. return Font (menuBar.getHeight() * 0.7f);
  53155. }
  53156. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53157. {
  53158. return getMenuBarFont (menuBar, itemIndex, itemText)
  53159. .getStringWidth (itemText) + menuBar.getHeight();
  53160. }
  53161. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53162. int width, int height,
  53163. int itemIndex,
  53164. const String& itemText,
  53165. bool isMouseOverItem,
  53166. bool isMenuOpen,
  53167. bool /*isMouseOverBar*/,
  53168. MenuBarComponent& menuBar)
  53169. {
  53170. if (! menuBar.isEnabled())
  53171. {
  53172. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53173. .withMultipliedAlpha (0.5f));
  53174. }
  53175. else if (isMenuOpen || isMouseOverItem)
  53176. {
  53177. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53178. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53179. }
  53180. else
  53181. {
  53182. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53183. }
  53184. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53185. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53186. }
  53187. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53188. TextEditor& textEditor)
  53189. {
  53190. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53191. }
  53192. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53193. {
  53194. if (textEditor.isEnabled())
  53195. {
  53196. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53197. {
  53198. const int border = 2;
  53199. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53200. g.drawRect (0, 0, width, height, border);
  53201. g.setOpacity (1.0f);
  53202. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53203. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53204. }
  53205. else
  53206. {
  53207. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53208. g.drawRect (0, 0, width, height);
  53209. g.setOpacity (1.0f);
  53210. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53211. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53212. }
  53213. }
  53214. }
  53215. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53216. const bool isButtonDown,
  53217. int buttonX, int buttonY,
  53218. int buttonW, int buttonH,
  53219. ComboBox& box)
  53220. {
  53221. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53222. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53223. {
  53224. g.setColour (box.findColour (TextButton::buttonColourId));
  53225. g.drawRect (0, 0, width, height, 2);
  53226. }
  53227. else
  53228. {
  53229. g.setColour (box.findColour (ComboBox::outlineColourId));
  53230. g.drawRect (0, 0, width, height);
  53231. }
  53232. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53233. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53234. box.hasKeyboardFocus (true),
  53235. false, isButtonDown)
  53236. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53237. drawGlassLozenge (g,
  53238. buttonX + outlineThickness, buttonY + outlineThickness,
  53239. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53240. baseColour, outlineThickness, -1.0f,
  53241. true, true, true, true);
  53242. if (box.isEnabled())
  53243. {
  53244. const float arrowX = 0.3f;
  53245. const float arrowH = 0.2f;
  53246. Path p;
  53247. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53248. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53249. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53250. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53251. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53252. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53253. g.setColour (box.findColour (ComboBox::arrowColourId));
  53254. g.fillPath (p);
  53255. }
  53256. }
  53257. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53258. {
  53259. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53260. }
  53261. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53262. {
  53263. return new Label (String::empty, String::empty);
  53264. }
  53265. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53266. {
  53267. label.setBounds (1, 1,
  53268. box.getWidth() + 3 - box.getHeight(),
  53269. box.getHeight() - 2);
  53270. label.setFont (getComboBoxFont (box));
  53271. }
  53272. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53273. {
  53274. g.fillAll (label.findColour (Label::backgroundColourId));
  53275. if (! label.isBeingEdited())
  53276. {
  53277. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53278. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53279. g.setFont (label.getFont());
  53280. g.drawFittedText (label.getText(),
  53281. label.getHorizontalBorderSize(),
  53282. label.getVerticalBorderSize(),
  53283. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53284. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53285. label.getJustificationType(),
  53286. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53287. label.getMinimumHorizontalScale());
  53288. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53289. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53290. }
  53291. else if (label.isEnabled())
  53292. {
  53293. g.setColour (label.findColour (Label::outlineColourId));
  53294. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53295. }
  53296. }
  53297. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53298. int x, int y,
  53299. int width, int height,
  53300. float /*sliderPos*/,
  53301. float /*minSliderPos*/,
  53302. float /*maxSliderPos*/,
  53303. const Slider::SliderStyle /*style*/,
  53304. Slider& slider)
  53305. {
  53306. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53307. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53308. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53309. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53310. Path indent;
  53311. if (slider.isHorizontal())
  53312. {
  53313. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53314. const float ih = sliderRadius;
  53315. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53316. gradCol2, 0.0f, iy + ih, false));
  53317. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53318. width + sliderRadius, ih,
  53319. 5.0f);
  53320. g.fillPath (indent);
  53321. }
  53322. else
  53323. {
  53324. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53325. const float iw = sliderRadius;
  53326. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53327. gradCol2, ix + iw, 0.0f, false));
  53328. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53329. iw, height + sliderRadius,
  53330. 5.0f);
  53331. g.fillPath (indent);
  53332. }
  53333. g.setColour (Colour (0x4c000000));
  53334. g.strokePath (indent, PathStrokeType (0.5f));
  53335. }
  53336. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53337. int x, int y,
  53338. int width, int height,
  53339. float sliderPos,
  53340. float minSliderPos,
  53341. float maxSliderPos,
  53342. const Slider::SliderStyle style,
  53343. Slider& slider)
  53344. {
  53345. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53346. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53347. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53348. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53349. slider.isMouseButtonDown() && slider.isEnabled()));
  53350. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53351. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53352. {
  53353. float kx, ky;
  53354. if (style == Slider::LinearVertical)
  53355. {
  53356. kx = x + width * 0.5f;
  53357. ky = sliderPos;
  53358. }
  53359. else
  53360. {
  53361. kx = sliderPos;
  53362. ky = y + height * 0.5f;
  53363. }
  53364. drawGlassSphere (g,
  53365. kx - sliderRadius,
  53366. ky - sliderRadius,
  53367. sliderRadius * 2.0f,
  53368. knobColour, outlineThickness);
  53369. }
  53370. else
  53371. {
  53372. if (style == Slider::ThreeValueVertical)
  53373. {
  53374. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53375. sliderPos - sliderRadius,
  53376. sliderRadius * 2.0f,
  53377. knobColour, outlineThickness);
  53378. }
  53379. else if (style == Slider::ThreeValueHorizontal)
  53380. {
  53381. drawGlassSphere (g,sliderPos - sliderRadius,
  53382. y + height * 0.5f - sliderRadius,
  53383. sliderRadius * 2.0f,
  53384. knobColour, outlineThickness);
  53385. }
  53386. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53387. {
  53388. const float sr = jmin (sliderRadius, width * 0.4f);
  53389. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53390. minSliderPos - sliderRadius,
  53391. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53392. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53393. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53394. }
  53395. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53396. {
  53397. const float sr = jmin (sliderRadius, height * 0.4f);
  53398. drawGlassPointer (g, minSliderPos - sr,
  53399. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53400. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53401. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53402. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53403. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53404. }
  53405. }
  53406. }
  53407. void LookAndFeel::drawLinearSlider (Graphics& g,
  53408. int x, int y,
  53409. int width, int height,
  53410. float sliderPos,
  53411. float minSliderPos,
  53412. float maxSliderPos,
  53413. const Slider::SliderStyle style,
  53414. Slider& slider)
  53415. {
  53416. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53417. if (style == Slider::LinearBar)
  53418. {
  53419. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53420. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53421. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53422. false, isMouseOver,
  53423. isMouseOver || slider.isMouseButtonDown()));
  53424. drawShinyButtonShape (g,
  53425. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53426. baseColour,
  53427. slider.isEnabled() ? 0.9f : 0.3f,
  53428. true, true, true, true);
  53429. }
  53430. else
  53431. {
  53432. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53433. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53434. }
  53435. }
  53436. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53437. {
  53438. return jmin (7,
  53439. slider.getHeight() / 2,
  53440. slider.getWidth() / 2) + 2;
  53441. }
  53442. void LookAndFeel::drawRotarySlider (Graphics& g,
  53443. int x, int y,
  53444. int width, int height,
  53445. float sliderPos,
  53446. const float rotaryStartAngle,
  53447. const float rotaryEndAngle,
  53448. Slider& slider)
  53449. {
  53450. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53451. const float centreX = x + width * 0.5f;
  53452. const float centreY = y + height * 0.5f;
  53453. const float rx = centreX - radius;
  53454. const float ry = centreY - radius;
  53455. const float rw = radius * 2.0f;
  53456. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53457. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53458. if (radius > 12.0f)
  53459. {
  53460. if (slider.isEnabled())
  53461. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53462. else
  53463. g.setColour (Colour (0x80808080));
  53464. const float thickness = 0.7f;
  53465. {
  53466. Path filledArc;
  53467. filledArc.addPieSegment (rx, ry, rw, rw,
  53468. rotaryStartAngle,
  53469. angle,
  53470. thickness);
  53471. g.fillPath (filledArc);
  53472. }
  53473. if (thickness > 0)
  53474. {
  53475. const float innerRadius = radius * 0.2f;
  53476. Path p;
  53477. p.addTriangle (-innerRadius, 0.0f,
  53478. 0.0f, -radius * thickness * 1.1f,
  53479. innerRadius, 0.0f);
  53480. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53481. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53482. }
  53483. if (slider.isEnabled())
  53484. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53485. else
  53486. g.setColour (Colour (0x80808080));
  53487. Path outlineArc;
  53488. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53489. outlineArc.closeSubPath();
  53490. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53491. }
  53492. else
  53493. {
  53494. if (slider.isEnabled())
  53495. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53496. else
  53497. g.setColour (Colour (0x80808080));
  53498. Path p;
  53499. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53500. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53501. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53502. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53503. }
  53504. }
  53505. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53506. {
  53507. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53508. }
  53509. class SliderLabelComp : public Label
  53510. {
  53511. public:
  53512. SliderLabelComp() : Label (String::empty, String::empty) {}
  53513. ~SliderLabelComp() {}
  53514. void mouseWheelMove (const MouseEvent&, float, float) {}
  53515. };
  53516. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53517. {
  53518. Label* const l = new SliderLabelComp();
  53519. l->setJustificationType (Justification::centred);
  53520. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53521. l->setColour (Label::backgroundColourId,
  53522. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53523. : slider.findColour (Slider::textBoxBackgroundColourId));
  53524. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53525. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53526. l->setColour (TextEditor::backgroundColourId,
  53527. slider.findColour (Slider::textBoxBackgroundColourId)
  53528. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53529. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53530. return l;
  53531. }
  53532. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53533. {
  53534. return 0;
  53535. }
  53536. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53537. {
  53538. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53539. width = tl.getWidth() + 14;
  53540. height = tl.getHeight() + 6;
  53541. }
  53542. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53543. {
  53544. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53545. const Colour textCol (findColour (TooltipWindow::textColourId));
  53546. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53547. g.setColour (findColour (TooltipWindow::outlineColourId));
  53548. g.drawRect (0, 0, width, height, 1);
  53549. #endif
  53550. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53551. g.setColour (findColour (TooltipWindow::textColourId));
  53552. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53553. }
  53554. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53555. {
  53556. return new TextButton (text, TRANS("click to browse for a different file"));
  53557. }
  53558. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53559. ComboBox* filenameBox,
  53560. Button* browseButton)
  53561. {
  53562. browseButton->setSize (80, filenameComp.getHeight());
  53563. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53564. if (tb != 0)
  53565. tb->changeWidthToFitText();
  53566. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53567. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53568. }
  53569. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53570. int imageX, int imageY, int imageW, int imageH,
  53571. const Colour& overlayColour,
  53572. float imageOpacity,
  53573. ImageButton& button)
  53574. {
  53575. if (! button.isEnabled())
  53576. imageOpacity *= 0.3f;
  53577. if (! overlayColour.isOpaque())
  53578. {
  53579. g.setOpacity (imageOpacity);
  53580. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53581. 0, 0, image->getWidth(), image->getHeight(), false);
  53582. }
  53583. if (! overlayColour.isTransparent())
  53584. {
  53585. g.setColour (overlayColour);
  53586. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53587. 0, 0, image->getWidth(), image->getHeight(), true);
  53588. }
  53589. }
  53590. void LookAndFeel::drawCornerResizer (Graphics& g,
  53591. int w, int h,
  53592. bool /*isMouseOver*/,
  53593. bool /*isMouseDragging*/)
  53594. {
  53595. const float lineThickness = jmin (w, h) * 0.075f;
  53596. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53597. {
  53598. g.setColour (Colours::lightgrey);
  53599. g.drawLine (w * i,
  53600. h + 1.0f,
  53601. w + 1.0f,
  53602. h * i,
  53603. lineThickness);
  53604. g.setColour (Colours::darkgrey);
  53605. g.drawLine (w * i + lineThickness,
  53606. h + 1.0f,
  53607. w + 1.0f,
  53608. h * i + lineThickness,
  53609. lineThickness);
  53610. }
  53611. }
  53612. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53613. {
  53614. if (! border.isEmpty())
  53615. {
  53616. const Rectangle<int> fullSize (0, 0, w, h);
  53617. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53618. g.saveState();
  53619. g.excludeClipRegion (centreArea);
  53620. g.setColour (Colour (0x50000000));
  53621. g.drawRect (fullSize);
  53622. g.setColour (Colour (0x19000000));
  53623. g.drawRect (centreArea.expanded (1, 1));
  53624. g.restoreState();
  53625. }
  53626. }
  53627. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53628. const BorderSize& /*border*/, ResizableWindow& window)
  53629. {
  53630. g.fillAll (window.getBackgroundColour());
  53631. }
  53632. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53633. const BorderSize& /*border*/, ResizableWindow&)
  53634. {
  53635. }
  53636. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53637. Graphics& g, int w, int h,
  53638. int titleSpaceX, int titleSpaceW,
  53639. const Image* icon,
  53640. bool drawTitleTextOnLeft)
  53641. {
  53642. const bool isActive = window.isActiveWindow();
  53643. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53644. 0.0f, 0.0f,
  53645. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53646. 0.0f, (float) h, false));
  53647. g.fillAll();
  53648. Font font (h * 0.65f, Font::bold);
  53649. g.setFont (font);
  53650. int textW = font.getStringWidth (window.getName());
  53651. int iconW = 0;
  53652. int iconH = 0;
  53653. if (icon != 0)
  53654. {
  53655. iconH = (int) font.getHeight();
  53656. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53657. }
  53658. textW = jmin (titleSpaceW, textW + iconW);
  53659. int textX = drawTitleTextOnLeft ? titleSpaceX
  53660. : jmax (titleSpaceX, (w - textW) / 2);
  53661. if (textX + textW > titleSpaceX + titleSpaceW)
  53662. textX = titleSpaceX + titleSpaceW - textW;
  53663. if (icon != 0)
  53664. {
  53665. g.setOpacity (isActive ? 1.0f : 0.6f);
  53666. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53667. RectanglePlacement::centred, false);
  53668. textX += iconW;
  53669. textW -= iconW;
  53670. }
  53671. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53672. g.setColour (findColour (DocumentWindow::textColourId));
  53673. else
  53674. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53675. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53676. }
  53677. class GlassWindowButton : public Button
  53678. {
  53679. public:
  53680. GlassWindowButton (const String& name, const Colour& col,
  53681. const Path& normalShape_,
  53682. const Path& toggledShape_) throw()
  53683. : Button (name),
  53684. colour (col),
  53685. normalShape (normalShape_),
  53686. toggledShape (toggledShape_)
  53687. {
  53688. }
  53689. ~GlassWindowButton()
  53690. {
  53691. }
  53692. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53693. {
  53694. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53695. if (! isEnabled())
  53696. alpha *= 0.5f;
  53697. float x = 0, y = 0, diam;
  53698. if (getWidth() < getHeight())
  53699. {
  53700. diam = (float) getWidth();
  53701. y = (getHeight() - getWidth()) * 0.5f;
  53702. }
  53703. else
  53704. {
  53705. diam = (float) getHeight();
  53706. y = (getWidth() - getHeight()) * 0.5f;
  53707. }
  53708. x += diam * 0.05f;
  53709. y += diam * 0.05f;
  53710. diam *= 0.9f;
  53711. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53712. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53713. g.fillEllipse (x, y, diam, diam);
  53714. x += 2.0f;
  53715. y += 2.0f;
  53716. diam -= 4.0f;
  53717. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53718. Path& p = getToggleState() ? toggledShape : normalShape;
  53719. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53720. diam * 0.4f, diam * 0.4f, true));
  53721. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53722. g.fillPath (p, t);
  53723. }
  53724. private:
  53725. Colour colour;
  53726. Path normalShape, toggledShape;
  53727. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlassWindowButton);
  53728. };
  53729. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53730. {
  53731. Path shape;
  53732. const float crossThickness = 0.25f;
  53733. if (buttonType == DocumentWindow::closeButton)
  53734. {
  53735. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53736. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53737. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53738. }
  53739. else if (buttonType == DocumentWindow::minimiseButton)
  53740. {
  53741. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53742. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53743. }
  53744. else if (buttonType == DocumentWindow::maximiseButton)
  53745. {
  53746. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53747. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53748. Path fullscreenShape;
  53749. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53750. fullscreenShape.lineTo (0.0f, 100.0f);
  53751. fullscreenShape.lineTo (0.0f, 0.0f);
  53752. fullscreenShape.lineTo (100.0f, 0.0f);
  53753. fullscreenShape.lineTo (100.0f, 45.0f);
  53754. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53755. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53756. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53757. }
  53758. jassertfalse;
  53759. return 0;
  53760. }
  53761. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53762. int titleBarX,
  53763. int titleBarY,
  53764. int titleBarW,
  53765. int titleBarH,
  53766. Button* minimiseButton,
  53767. Button* maximiseButton,
  53768. Button* closeButton,
  53769. bool positionTitleBarButtonsOnLeft)
  53770. {
  53771. const int buttonW = titleBarH - titleBarH / 8;
  53772. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53773. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53774. if (closeButton != 0)
  53775. {
  53776. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53777. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53778. }
  53779. if (positionTitleBarButtonsOnLeft)
  53780. swapVariables (minimiseButton, maximiseButton);
  53781. if (maximiseButton != 0)
  53782. {
  53783. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53784. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53785. }
  53786. if (minimiseButton != 0)
  53787. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53788. }
  53789. int LookAndFeel::getDefaultMenuBarHeight()
  53790. {
  53791. return 24;
  53792. }
  53793. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53794. {
  53795. return new DropShadower (0.4f, 1, 5, 10);
  53796. }
  53797. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53798. int w, int h,
  53799. bool /*isVerticalBar*/,
  53800. bool isMouseOver,
  53801. bool isMouseDragging)
  53802. {
  53803. float alpha = 0.5f;
  53804. if (isMouseOver || isMouseDragging)
  53805. {
  53806. g.fillAll (Colour (0x190000ff));
  53807. alpha = 1.0f;
  53808. }
  53809. const float cx = w * 0.5f;
  53810. const float cy = h * 0.5f;
  53811. const float cr = jmin (w, h) * 0.4f;
  53812. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53813. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53814. true));
  53815. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53816. }
  53817. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53818. const String& text,
  53819. const Justification& position,
  53820. GroupComponent& group)
  53821. {
  53822. const float textH = 15.0f;
  53823. const float indent = 3.0f;
  53824. const float textEdgeGap = 4.0f;
  53825. float cs = 5.0f;
  53826. Font f (textH);
  53827. Path p;
  53828. float x = indent;
  53829. float y = f.getAscent() - 3.0f;
  53830. float w = jmax (0.0f, width - x * 2.0f);
  53831. float h = jmax (0.0f, height - y - indent);
  53832. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53833. const float cs2 = 2.0f * cs;
  53834. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53835. float textX = cs + textEdgeGap;
  53836. if (position.testFlags (Justification::horizontallyCentred))
  53837. textX = cs + (w - cs2 - textW) * 0.5f;
  53838. else if (position.testFlags (Justification::right))
  53839. textX = w - cs - textW - textEdgeGap;
  53840. p.startNewSubPath (x + textX + textW, y);
  53841. p.lineTo (x + w - cs, y);
  53842. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53843. p.lineTo (x + w, y + h - cs);
  53844. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53845. p.lineTo (x + cs, y + h);
  53846. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53847. p.lineTo (x, y + cs);
  53848. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53849. p.lineTo (x + textX, y);
  53850. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53851. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53852. .withMultipliedAlpha (alpha));
  53853. g.strokePath (p, PathStrokeType (2.0f));
  53854. g.setColour (group.findColour (GroupComponent::textColourId)
  53855. .withMultipliedAlpha (alpha));
  53856. g.setFont (f);
  53857. g.drawText (text,
  53858. roundToInt (x + textX), 0,
  53859. roundToInt (textW),
  53860. roundToInt (textH),
  53861. Justification::centred, true);
  53862. }
  53863. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53864. {
  53865. return 1 + tabDepth / 3;
  53866. }
  53867. int LookAndFeel::getTabButtonSpaceAroundImage()
  53868. {
  53869. return 4;
  53870. }
  53871. void LookAndFeel::createTabButtonShape (Path& p,
  53872. int width, int height,
  53873. int /*tabIndex*/,
  53874. const String& /*text*/,
  53875. Button& /*button*/,
  53876. TabbedButtonBar::Orientation orientation,
  53877. const bool /*isMouseOver*/,
  53878. const bool /*isMouseDown*/,
  53879. const bool /*isFrontTab*/)
  53880. {
  53881. const float w = (float) width;
  53882. const float h = (float) height;
  53883. float length = w;
  53884. float depth = h;
  53885. if (orientation == TabbedButtonBar::TabsAtLeft
  53886. || orientation == TabbedButtonBar::TabsAtRight)
  53887. {
  53888. swapVariables (length, depth);
  53889. }
  53890. const float indent = (float) getTabButtonOverlap ((int) depth);
  53891. const float overhang = 4.0f;
  53892. if (orientation == TabbedButtonBar::TabsAtLeft)
  53893. {
  53894. p.startNewSubPath (w, 0.0f);
  53895. p.lineTo (0.0f, indent);
  53896. p.lineTo (0.0f, h - indent);
  53897. p.lineTo (w, h);
  53898. p.lineTo (w + overhang, h + overhang);
  53899. p.lineTo (w + overhang, -overhang);
  53900. }
  53901. else if (orientation == TabbedButtonBar::TabsAtRight)
  53902. {
  53903. p.startNewSubPath (0.0f, 0.0f);
  53904. p.lineTo (w, indent);
  53905. p.lineTo (w, h - indent);
  53906. p.lineTo (0.0f, h);
  53907. p.lineTo (-overhang, h + overhang);
  53908. p.lineTo (-overhang, -overhang);
  53909. }
  53910. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53911. {
  53912. p.startNewSubPath (0.0f, 0.0f);
  53913. p.lineTo (indent, h);
  53914. p.lineTo (w - indent, h);
  53915. p.lineTo (w, 0.0f);
  53916. p.lineTo (w + overhang, -overhang);
  53917. p.lineTo (-overhang, -overhang);
  53918. }
  53919. else
  53920. {
  53921. p.startNewSubPath (0.0f, h);
  53922. p.lineTo (indent, 0.0f);
  53923. p.lineTo (w - indent, 0.0f);
  53924. p.lineTo (w, h);
  53925. p.lineTo (w + overhang, h + overhang);
  53926. p.lineTo (-overhang, h + overhang);
  53927. }
  53928. p.closeSubPath();
  53929. p = p.createPathWithRoundedCorners (3.0f);
  53930. }
  53931. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53932. const Path& path,
  53933. const Colour& preferredColour,
  53934. int /*tabIndex*/,
  53935. const String& /*text*/,
  53936. Button& button,
  53937. TabbedButtonBar::Orientation /*orientation*/,
  53938. const bool /*isMouseOver*/,
  53939. const bool /*isMouseDown*/,
  53940. const bool isFrontTab)
  53941. {
  53942. g.setColour (isFrontTab ? preferredColour
  53943. : preferredColour.withMultipliedAlpha (0.9f));
  53944. g.fillPath (path);
  53945. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53946. : TabbedButtonBar::tabOutlineColourId, false)
  53947. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53948. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53949. }
  53950. void LookAndFeel::drawTabButtonText (Graphics& g,
  53951. int x, int y, int w, int h,
  53952. const Colour& preferredBackgroundColour,
  53953. int /*tabIndex*/,
  53954. const String& text,
  53955. Button& button,
  53956. TabbedButtonBar::Orientation orientation,
  53957. const bool isMouseOver,
  53958. const bool isMouseDown,
  53959. const bool isFrontTab)
  53960. {
  53961. int length = w;
  53962. int depth = h;
  53963. if (orientation == TabbedButtonBar::TabsAtLeft
  53964. || orientation == TabbedButtonBar::TabsAtRight)
  53965. {
  53966. swapVariables (length, depth);
  53967. }
  53968. Font font (depth * 0.6f);
  53969. font.setUnderline (button.hasKeyboardFocus (false));
  53970. GlyphArrangement textLayout;
  53971. textLayout.addFittedText (font, text.trim(),
  53972. 0.0f, 0.0f, (float) length, (float) depth,
  53973. Justification::centred,
  53974. jmax (1, depth / 12));
  53975. AffineTransform transform;
  53976. if (orientation == TabbedButtonBar::TabsAtLeft)
  53977. {
  53978. transform = transform.rotated (float_Pi * -0.5f)
  53979. .translated ((float) x, (float) (y + h));
  53980. }
  53981. else if (orientation == TabbedButtonBar::TabsAtRight)
  53982. {
  53983. transform = transform.rotated (float_Pi * 0.5f)
  53984. .translated ((float) (x + w), (float) y);
  53985. }
  53986. else
  53987. {
  53988. transform = transform.translated ((float) x, (float) y);
  53989. }
  53990. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53991. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53992. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53993. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53994. else
  53995. g.setColour (preferredBackgroundColour.contrasting());
  53996. if (! (isMouseOver || isMouseDown))
  53997. g.setOpacity (0.8f);
  53998. if (! button.isEnabled())
  53999. g.setOpacity (0.3f);
  54000. textLayout.draw (g, transform);
  54001. }
  54002. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54003. const String& text,
  54004. int tabDepth,
  54005. Button&)
  54006. {
  54007. Font f (tabDepth * 0.6f);
  54008. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54009. }
  54010. void LookAndFeel::drawTabButton (Graphics& g,
  54011. int w, int h,
  54012. const Colour& preferredColour,
  54013. int tabIndex,
  54014. const String& text,
  54015. Button& button,
  54016. TabbedButtonBar::Orientation orientation,
  54017. const bool isMouseOver,
  54018. const bool isMouseDown,
  54019. const bool isFrontTab)
  54020. {
  54021. int length = w;
  54022. int depth = h;
  54023. if (orientation == TabbedButtonBar::TabsAtLeft
  54024. || orientation == TabbedButtonBar::TabsAtRight)
  54025. {
  54026. swapVariables (length, depth);
  54027. }
  54028. Path tabShape;
  54029. createTabButtonShape (tabShape, w, h,
  54030. tabIndex, text, button, orientation,
  54031. isMouseOver, isMouseDown, isFrontTab);
  54032. fillTabButtonShape (g, tabShape, preferredColour,
  54033. tabIndex, text, button, orientation,
  54034. isMouseOver, isMouseDown, isFrontTab);
  54035. const int indent = getTabButtonOverlap (depth);
  54036. int x = 0, y = 0;
  54037. if (orientation == TabbedButtonBar::TabsAtLeft
  54038. || orientation == TabbedButtonBar::TabsAtRight)
  54039. {
  54040. y += indent;
  54041. h -= indent * 2;
  54042. }
  54043. else
  54044. {
  54045. x += indent;
  54046. w -= indent * 2;
  54047. }
  54048. drawTabButtonText (g, x, y, w, h, preferredColour,
  54049. tabIndex, text, button, orientation,
  54050. isMouseOver, isMouseDown, isFrontTab);
  54051. }
  54052. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54053. int w, int h,
  54054. TabbedButtonBar& tabBar,
  54055. TabbedButtonBar::Orientation orientation)
  54056. {
  54057. const float shadowSize = 0.2f;
  54058. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54059. Rectangle<int> shadowRect;
  54060. if (orientation == TabbedButtonBar::TabsAtLeft)
  54061. {
  54062. x1 = (float) w;
  54063. x2 = w * (1.0f - shadowSize);
  54064. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54065. }
  54066. else if (orientation == TabbedButtonBar::TabsAtRight)
  54067. {
  54068. x2 = w * shadowSize;
  54069. shadowRect.setBounds (0, 0, (int) x2, h);
  54070. }
  54071. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54072. {
  54073. y2 = h * shadowSize;
  54074. shadowRect.setBounds (0, 0, w, (int) y2);
  54075. }
  54076. else
  54077. {
  54078. y1 = (float) h;
  54079. y2 = h * (1.0f - shadowSize);
  54080. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54081. }
  54082. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54083. Colours::transparentBlack, x2, y2, false));
  54084. shadowRect.expand (2, 2);
  54085. g.fillRect (shadowRect);
  54086. g.setColour (Colour (0x80000000));
  54087. if (orientation == TabbedButtonBar::TabsAtLeft)
  54088. {
  54089. g.fillRect (w - 1, 0, 1, h);
  54090. }
  54091. else if (orientation == TabbedButtonBar::TabsAtRight)
  54092. {
  54093. g.fillRect (0, 0, 1, h);
  54094. }
  54095. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54096. {
  54097. g.fillRect (0, 0, w, 1);
  54098. }
  54099. else
  54100. {
  54101. g.fillRect (0, h - 1, w, 1);
  54102. }
  54103. }
  54104. Button* LookAndFeel::createTabBarExtrasButton()
  54105. {
  54106. const float thickness = 7.0f;
  54107. const float indent = 22.0f;
  54108. Path p;
  54109. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54110. DrawablePath ellipse;
  54111. ellipse.setPath (p);
  54112. ellipse.setFill (Colour (0x99ffffff));
  54113. p.clear();
  54114. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54115. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54116. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54117. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54118. p.setUsingNonZeroWinding (false);
  54119. DrawablePath dp;
  54120. dp.setPath (p);
  54121. dp.setFill (Colour (0x59000000));
  54122. DrawableComposite normalImage;
  54123. normalImage.addAndMakeVisible (ellipse.createCopy());
  54124. normalImage.addAndMakeVisible (dp.createCopy());
  54125. dp.setFill (Colour (0xcc000000));
  54126. DrawableComposite overImage;
  54127. overImage.addAndMakeVisible (ellipse.createCopy());
  54128. overImage.addAndMakeVisible (dp.createCopy());
  54129. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54130. db->setImages (&normalImage, &overImage, 0);
  54131. return db;
  54132. }
  54133. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54134. {
  54135. g.fillAll (Colours::white);
  54136. const int w = header.getWidth();
  54137. const int h = header.getHeight();
  54138. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54139. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54140. false));
  54141. g.fillRect (0, h / 2, w, h);
  54142. g.setColour (Colour (0x33000000));
  54143. g.fillRect (0, h - 1, w, 1);
  54144. for (int i = header.getNumColumns (true); --i >= 0;)
  54145. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54146. }
  54147. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54148. int width, int height,
  54149. bool isMouseOver, bool isMouseDown,
  54150. int columnFlags)
  54151. {
  54152. if (isMouseDown)
  54153. g.fillAll (Colour (0x8899aadd));
  54154. else if (isMouseOver)
  54155. g.fillAll (Colour (0x5599aadd));
  54156. int rightOfText = width - 4;
  54157. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54158. {
  54159. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54160. const float bottom = height - top;
  54161. const float w = height * 0.5f;
  54162. const float x = rightOfText - (w * 1.25f);
  54163. rightOfText = (int) x;
  54164. Path sortArrow;
  54165. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54166. g.setColour (Colour (0x99000000));
  54167. g.fillPath (sortArrow);
  54168. }
  54169. g.setColour (Colours::black);
  54170. g.setFont (height * 0.5f, Font::bold);
  54171. const int textX = 4;
  54172. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54173. }
  54174. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54175. {
  54176. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54177. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54178. background.darker (0.1f),
  54179. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54180. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54181. false));
  54182. g.fillAll();
  54183. }
  54184. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54185. {
  54186. return createTabBarExtrasButton();
  54187. }
  54188. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54189. bool isMouseOver, bool isMouseDown,
  54190. ToolbarItemComponent& component)
  54191. {
  54192. if (isMouseDown)
  54193. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54194. else if (isMouseOver)
  54195. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54196. }
  54197. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54198. const String& text, ToolbarItemComponent& component)
  54199. {
  54200. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54201. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54202. const float fontHeight = jmin (14.0f, height * 0.85f);
  54203. g.setFont (fontHeight);
  54204. g.drawFittedText (text,
  54205. x, y, width, height,
  54206. Justification::centred,
  54207. jmax (1, height / (int) fontHeight));
  54208. }
  54209. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54210. bool isOpen, int width, int height)
  54211. {
  54212. const int buttonSize = (height * 3) / 4;
  54213. const int buttonIndent = (height - buttonSize) / 2;
  54214. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54215. const int textX = buttonIndent * 2 + buttonSize + 2;
  54216. g.setColour (Colours::black);
  54217. g.setFont (height * 0.7f, Font::bold);
  54218. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54219. }
  54220. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54221. PropertyComponent&)
  54222. {
  54223. g.setColour (Colour (0x66ffffff));
  54224. g.fillRect (0, 0, width, height - 1);
  54225. }
  54226. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54227. PropertyComponent& component)
  54228. {
  54229. g.setColour (Colours::black);
  54230. if (! component.isEnabled())
  54231. g.setOpacity (0.6f);
  54232. g.setFont (jmin (height, 24) * 0.65f);
  54233. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54234. g.drawFittedText (component.getName(),
  54235. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54236. Justification::centredLeft, 2);
  54237. }
  54238. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54239. {
  54240. return Rectangle<int> (component.getWidth() / 3, 1,
  54241. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54242. }
  54243. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54244. {
  54245. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54246. {
  54247. Graphics g2 (content);
  54248. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54249. g2.fillPath (path);
  54250. g2.setColour (Colours::white.withAlpha (0.8f));
  54251. g2.strokePath (path, PathStrokeType (2.0f));
  54252. }
  54253. DropShadowEffect shadow;
  54254. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54255. shadow.applyEffect (content, g, 1.0f);
  54256. }
  54257. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54258. const String& instructions,
  54259. GlyphArrangement& text,
  54260. int width)
  54261. {
  54262. text.clear();
  54263. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54264. 8.0f, 22.0f, width - 16.0f,
  54265. Justification::centred);
  54266. text.addJustifiedText (Font (14.0f), instructions,
  54267. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54268. Justification::centred);
  54269. }
  54270. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54271. const String& filename, Image* icon,
  54272. const String& fileSizeDescription,
  54273. const String& fileTimeDescription,
  54274. const bool isDirectory,
  54275. const bool isItemSelected,
  54276. const int /*itemIndex*/,
  54277. DirectoryContentsDisplayComponent&)
  54278. {
  54279. if (isItemSelected)
  54280. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54281. const int x = 32;
  54282. g.setColour (Colours::black);
  54283. if (icon != 0 && icon->isValid())
  54284. {
  54285. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54286. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54287. false);
  54288. }
  54289. else
  54290. {
  54291. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54292. : getDefaultDocumentFileImage();
  54293. if (d != 0)
  54294. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54295. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54296. }
  54297. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54298. g.setFont (height * 0.7f);
  54299. if (width > 450 && ! isDirectory)
  54300. {
  54301. const int sizeX = roundToInt (width * 0.7f);
  54302. const int dateX = roundToInt (width * 0.8f);
  54303. g.drawFittedText (filename,
  54304. x, 0, sizeX - x, height,
  54305. Justification::centredLeft, 1);
  54306. g.setFont (height * 0.5f);
  54307. g.setColour (Colours::darkgrey);
  54308. if (! isDirectory)
  54309. {
  54310. g.drawFittedText (fileSizeDescription,
  54311. sizeX, 0, dateX - sizeX - 8, height,
  54312. Justification::centredRight, 1);
  54313. g.drawFittedText (fileTimeDescription,
  54314. dateX, 0, width - 8 - dateX, height,
  54315. Justification::centredRight, 1);
  54316. }
  54317. }
  54318. else
  54319. {
  54320. g.drawFittedText (filename,
  54321. x, 0, width - x, height,
  54322. Justification::centredLeft, 1);
  54323. }
  54324. }
  54325. Button* LookAndFeel::createFileBrowserGoUpButton()
  54326. {
  54327. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54328. Path arrowPath;
  54329. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54330. DrawablePath arrowImage;
  54331. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54332. arrowImage.setPath (arrowPath);
  54333. goUpButton->setImages (&arrowImage);
  54334. return goUpButton;
  54335. }
  54336. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54337. DirectoryContentsDisplayComponent* fileListComponent,
  54338. FilePreviewComponent* previewComp,
  54339. ComboBox* currentPathBox,
  54340. TextEditor* filenameBox,
  54341. Button* goUpButton)
  54342. {
  54343. const int x = 8;
  54344. int w = browserComp.getWidth() - x - x;
  54345. if (previewComp != 0)
  54346. {
  54347. const int previewWidth = w / 3;
  54348. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54349. w -= previewWidth + 4;
  54350. }
  54351. int y = 4;
  54352. const int controlsHeight = 22;
  54353. const int bottomSectionHeight = controlsHeight + 8;
  54354. const int upButtonWidth = 50;
  54355. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54356. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54357. y += controlsHeight + 4;
  54358. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54359. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54360. y = listAsComp->getBottom() + 4;
  54361. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54362. }
  54363. // Pulls a drawable out of compressed valuetree data..
  54364. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54365. {
  54366. MemoryInputStream m (data, numBytes, false);
  54367. GZIPDecompressorInputStream gz (m);
  54368. ValueTree drawable (ValueTree::readFromStream (gz));
  54369. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54370. }
  54371. const Drawable* LookAndFeel::getDefaultFolderImage()
  54372. {
  54373. if (folderImage == 0)
  54374. {
  54375. static const unsigned char drawableData[] =
  54376. { 120,218,197,86,77,111,27,55,16,229,182,161,237,6,61,39,233,77,63,192,38,56,195,225,215,209,105,210,2,141,13,20,201,193,109,111,178,181,178,183,145,181,130,180,110,145,127,159,199,93,73,137,87,53,218,91,109,192,160,151,179,156,55,111,222,188,229,155,247,
  54377. 231,87,231,175,47,222,170,234,155,229,244,190,86,213,115,253,102,61,253,123,122,189,168,85,51,83,213,119,250,238,221,47,231,151,175,223,169,170,250,121,221,62,172,84,245,172,60,63,209,243,118,49,171,215,170,107,87,23,245,188,83,213,145,182,167,19,91,
  54378. 254,127,223,220,222,117,37,68,82,40,143,174,219,174,107,239,135,168,147,18,37,108,85,245,237,46,207,70,33,249,175,211,238,78,85,186,28,253,76,175,73,109,186,117,251,177,190,106,102,229,241,247,58,24,103,203,15,101,245,103,219,44,187,15,221,39,0,172,142,
  54379. 245,125,211,1,196,205,116,181,125,114,164,175,31,186,78,45,219,229,31,245,186,189,106,150,179,102,121,139,100,154,240,231,167,102,177,64,72,247,105,213,23,122,187,158,206,154,122,217,169,85,57,18,1,47,53,101,107,18,135,204,167,147,192,201,216,20,114,
  54380. 244,195,62,171,234,7,125,198,100,136,216,145,149,211,9,57,103,40,249,72,219,8,167,170,87,250,140,162,199,123,226,3,34,82,202,134,131,13,172,74,170,233,162,0,177,234,166,93,180,15,235,141,170,206,180,157,204,231,150,156,159,207,39,195,50,214,88,18,150,
  54381. 245,205,124,250,104,169,212,135,158,19,144,53,20,112,172,55,237,2,132,13,199,149,130,230,115,145,112,147,147,82,61,157,32,238,178,253,11,145,213,138,10,52,138,38,103,111,99,164,211,137,139,198,35,177,35,167,212,143,15,215,205,13,160,109,163,172,225,152,
  54382. 16,232,17,149,140,103,144,158,146,90,113,217,12,6,197,167,236,3,54,5,181,101,73,54,138,90,245,165,227,120,18,252,150,77,15,242,188,228,204,81,169,139,102,249,5,68,192,145,14,244,112,1,145,29,94,137,96,235,49,136,151,58,246,32,88,192,161,88,176,76,226,
  54383. 36,247,24,176,7,232,62,16,83,42,155,201,160,30,222,65,72,98,82,76,33,198,254,197,96,124,10,150,243,8,130,48,228,36,94,124,6,4,43,38,0,142,205,99,30,4,221,13,33,230,220,71,177,65,49,142,243,150,7,1,51,20,2,5,96,96,84,225,56,217,188,3,33,46,24,228,112,
  54384. 69,69,12,68,228,108,242,99,16,165,118,208,28,51,200,98,87,42,74,62,209,24,4,206,48,22,153,125,132,220,196,56,15,234,99,216,130,0,141,38,74,162,130,48,35,163,141,94,196,245,32,94,104,7,154,132,209,40,108,162,165,232,153,165,17,4,138,201,176,135,58,49,
  54385. 165,130,122,108,114,54,28,240,64,17,89,188,79,177,116,149,10,4,246,91,30,94,104,112,96,226,144,131,144,142,98,78,177,7,128,81,242,224,140,36,249,80,208,145,196,12,202,15,16,60,161,200,69,187,169,213,86,198,123,87,224,255,199,21,94,105,134,72,40,177,245,
  54386. 14,182,32,232,54,196,231,100,111,11,189,168,201,39,177,84,102,38,139,177,168,74,210,87,174,64,20,138,160,67,111,10,4,98,196,97,60,158,118,133,25,111,173,224,171,37,97,185,119,133,221,242,63,184,194,140,71,174,240,252,145,43,72,32,147,146,147,4,104,104,
  54387. 117,134,10,18,12,107,212,40,72,148,57,6,71,69,135,222,248,16,160,168,3,169,144,55,201,69,41,147,137,134,99,50,97,8,178,85,43,217,140,201,151,192,152,10,242,190,24,11,59,183,29,25,42,115,236,98,14,229,252,32,80,66,0,162,17,136,72,6,67,5,45,242,224,10,
  54388. 193,102,71,50,6,17,129,212,18,115,105,150,80,169,45,123,222,141,76,178,70,32,55,24,90,217,132,71,73,200,57,238,204,3,136,49,144,185,55,183,190,20,137,52,246,47,113,232,158,69,35,49,145,208,129,193,56,178,77,135,230,145,113,22,140,69,74,20,146,2,120,218,
  54389. 155,135,48,32,10,89,30,156,165,204,254,222,193,160,12,19,49,6,210,59,11,70,62,4,31,15,64,196,2,157,98,33,58,1,104,32,152,50,31,128,64,148,183,197,108,209,89,107,240,41,75,36,123,16,208,108,180,44,236,250,182,227,27,20,137,118,76,60,165,137,221,92,94,
  54390. 78,215,31,235,245,230,183,242,229,30,214,251,251,195,145,94,148,15,253,170,221,52,93,211,46,7,109,171,81,208,177,94,247,119,132,47,81,186,92,22,246,7,255,254,15,7,107,141,171,197,191,156,123,162,135,187,198,227,131,113,219,80,159,1,4,239,223,231,0,0 };
  54391. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54392. }
  54393. return folderImage;
  54394. }
  54395. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54396. {
  54397. if (documentImage == 0)
  54398. {
  54399. static const unsigned char drawableData[] =
  54400. { 120,218,213,88,77,115,219,54,16,37,147,208,246,228,214,75,155,246,164,123,29,12,176,216,197,199,49,105,218,94,156,153,78,114,72,219,155,108,75,137,26,89,212,200,116,59,233,175,239,3,105,201,164,68,50,158,166,233,76,196,11,69,60,173,128,197,123,139,183,
  54401. 124,241,234,217,155,103,207,207,126,204,242,7,171,233,213,44,203,31,23,47,54,211,191,166,231,203,89,182,184,204,242,147,226,195,165,219,252,125,150,229,249,207,155,242,102,157,229,143,210,227,199,197,101,121,113,115,53,91,85,89,85,174,207,102,243,42,
  54402. 203,143,10,125,58,209,233,251,171,197,219,119,85,250,173,97,151,30,157,151,85,85,94,53,168,147,132,50,226,179,252,225,246,143,174,179,44,63,254,101,90,189,203,242,34,5,127,84,172,77,118,93,109,202,247,179,55,139,203,244,248,97,161,179,63,202,197,170,
  54403. 122,93,125,192,196,242,227,226,106,81,205,54,217,197,116,125,251,228,168,56,191,169,170,108,85,174,126,159,109,202,55,139,213,229,98,245,182,249,97,254,240,167,197,114,137,5,86,31,214,245,111,175,203,37,254,230,162,92,150,55,155,180,148,249,237,39,203,
  54404. 94,215,127,58,10,213,245,39,203,234,249,102,249,87,47,203,63,129,204,49,227,252,73,225,149,145,104,131,245,254,116,34,202,82,164,16,153,179,236,108,177,234,7,49,41,237,130,144,167,17,144,15,42,104,239,93,12,35,32,99,68,9,187,24,125,7,244,77,23,36,164,
  54405. 40,56,226,61,12,107,229,130,215,100,105,24,227,89,17,246,211,105,55,140,49,218,43,207,100,245,72,28,195,70,17,230,201,118,8,243,164,139,233,95,88,23,52,152,162,54,104,48,217,237,105,15,111,91,107,253,131,160,118,34,239,69,128,54,232,135,101,121,61,203,
  54406. 110,169,181,147,2,253,159,82,48,180,229,247,167,74,193,41,141,188,35,93,241,116,18,148,113,214,120,207,113,47,19,109,16,51,182,153,193,5,59,2,10,90,69,114,218,135,48,2,50,198,43,171,189,152,81,144,88,108,85,136,78,246,64,54,42,163,35,69,30,3,121,82,38,
  54407. 98,81,98,70,64,70,139,34,111,163,167,49,144,13,202,138,179,58,220,23,52,180,186,54,104,48,79,109,208,96,198,219,19,31,220,187,118,10,6,65,237,100,222,139,5,109,80,191,30,236,151,162,135,147,142,30,68,105,182,58,6,22,84,43,229,124,148,116,97,145,55,231,
  54408. 139,11,76,228,16,37,14,48,205,145,77,134,34,176,55,152,182,200,57,99,93,204,144,145,253,65,97,229,132,72,104,63,62,71,21,140,54,186,41,226,59,84,19,63,130,15,222,235,224,185,59,104,27,226,68,101,153,241,227,177,248,29,20,136,26,8,252,178,183,241,219,
  54409. 131,137,160,209,107,109,92,79,124,16,211,184,104,93,77,130,110,124,2,65,172,67,201,60,157,88,163,2,91,99,92,216,198,55,78,69,75,190,150,119,84,98,200,71,150,109,124,36,204,227,52,8,33,229,223,68,167,173,167,131,248,137,212,226,141,19,233,160,154,248,
  54410. 144,142,195,140,137,185,59,104,15,247,119,40,126,23,69,81,200,242,110,254,123,20,49,94,112,110,245,199,111,241,167,87,36,252,101,138,132,149,22,22,38,65,134,29,182,139,24,230,192,31,144,184,133,130,72,44,131,210,142,111,147,216,30,76,123,30,113,206,242,
  54411. 150,196,157,65,129,130,76,180,194,61,34,225,160,5,228,233,160,118,34,137,26,202,115,212,29,108,72,134,243,223,90,114,226,199,226,119,80,6,245,152,197,122,217,146,184,53,24,140,210,30,21,59,80,79,124,182,202,71,207,218,112,159,72,80,53,140,109,68,2,191,
  54412. 227,217,210,78,36,94,137,88,231,82,157,8,176,61,0,122,191,19,137,3,255,13,39,183,228,20,193,151,144,119,166,79,36,40,253,156,138,72,11,181,19,137,14,46,176,217,27,180,135,251,219,31,255,235,61,148,165,96,72,122,118,23,229,81,52,135,24,250,163,183,216,
  54413. 211,43,17,217,151,136,253,116,137,28,53,188,127,92,188,221,76,47,23,169,59,90,167,144,141,239,197,86,104,141,189,60,157,80,84,142,140,4,31,154,241,122,105,132,41,107,13,201,39,86,120,24,82,114,206,198,6,96,27,227,172,36,232,168,201,36,219,24,113,62,163,
  54414. 154,101,233,143,166,203,102,26,141,206,174,179,252,89,161,39,243,249,197,121,186,38,233,246,146,211,53,1,123,56,194,231,122,143,103,179,217,60,204,167,19,147,110,41,93,173,219,123,72,89,248,35,173,16,220,50,179,111,60,181,24,88,103,156,235,7,78,248,14,
  54415. 4,119,78,162,93,60,112,35,109,16,124,126,12,17,71,67,24,1,165,142,1,181,215,248,56,6,66,235,193,137,167,61,22,30,5,3,27,101,71,64,169,25,112,216,2,63,22,169,110,43,18,200,140,129,208,160,88,44,220,208,125,65,67,171,107,131,6,243,212,6,13,102,188,61,241,
  54416. 225,189,107,165,96,16,212,78,230,189,88,208,6,245,235,214,237,235,150,62,167,110,155,106,170,53,133,192,117,193,20,84,78,74,174,98,39,92,156,8,112,21,46,80,106,12,209,207,225,228,16,113,59,225,126,87,60,133,25,209,34,36,2,99,242,52,197,48,30,75,244,247,
  54417. 212,238,246,182,173,221,185,78,215,127,167,221,162,163,221,250,152,217,146,196,222,145,100,223,235,105,108,28,250,149,212,74,224,86,2,213,118,110,119,204,224,144,208,38,214,131,200,14,214,223,120,189,230,53,1,193,70,133,154,131,56,223,16,229,48,188,14,
  54418. 201,205,213,121,71,233,68,89,15,124,103,37,53,26,11,118,176,127,169,88,166,158,219,178,117,173,83,108,75,95,55,68,186,193,53,246,146,206,127,6,63,53,78,58,228,204,155,224,113,74,91,232,221,195,240,105,215,34,29,138,64,128,183,8,130,233,71,173,56,54,101,
  54419. 99,75,186,111,65,58,28,229,145,82,19,152,12,99,180,81,130,131,75,234,229,220,247,53,231,154,79,205,185,185,155,199,249,172,38,85,253,204,76,68,95,92,204,207,255,221,75,178,227,14,187,224,224,97,202,172,173,219,12,167,130,133,9,54,135,245,92,176,29,134,
  54420. 165,110,139,141,18,16,223,29,188,183,65,207,144,106,144,151,143,128,224,176,168,110,140,32,62,56,110,219,195,54,235,20,68,209,216,34,232,21,6,41,234,157,39,211,201,107,160,230,66,225,56,153,9,101,21,37,237,150,204,14,115,208,22,221,54,216,230,33,116,
  54421. 14,65,14,44,19,8,236,73,71,246,182,110,125,224,75,132,195,214,247,163,36,51,252,84,76,124,37,212,100,88,62,183,179,76,67,217,218,242,244,229,116,243,126,182,185,254,21,105,126,208,220,239,94,229,30,21,203,244,202,117,93,94,47,170,69,185,106,246,60,219,
  54422. 3,29,23,155,250,109,237,29,170,72,175,109,119,129,127,235,9,92,20,85,185,254,72,220,147,162,121,235,219,13,44,144,225,63,241,244,165,51,0,0 };
  54423. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54424. }
  54425. return documentImage;
  54426. }
  54427. void LookAndFeel::playAlertSound()
  54428. {
  54429. PlatformUtilities::beep();
  54430. }
  54431. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54432. {
  54433. g.setColour (Colours::white.withAlpha (0.7f));
  54434. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54435. g.setColour (Colours::black.withAlpha (0.2f));
  54436. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54437. const int totalBlocks = 7;
  54438. const int numBlocks = roundToInt (totalBlocks * level);
  54439. const float w = (width - 6.0f) / (float) totalBlocks;
  54440. for (int i = 0; i < totalBlocks; ++i)
  54441. {
  54442. if (i >= numBlocks)
  54443. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54444. else
  54445. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54446. : Colours::red);
  54447. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54448. }
  54449. }
  54450. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54451. {
  54452. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54453. if (keyDescription.isNotEmpty())
  54454. {
  54455. if (button.isEnabled())
  54456. {
  54457. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54458. g.fillAll (textColour.withAlpha (alpha));
  54459. g.setOpacity (0.3f);
  54460. g.drawBevel (0, 0, width, height, 2);
  54461. }
  54462. g.setColour (textColour);
  54463. g.setFont (height * 0.6f);
  54464. g.drawFittedText (keyDescription,
  54465. 3, 0, width - 6, height,
  54466. Justification::centred, 1);
  54467. }
  54468. else
  54469. {
  54470. const float thickness = 7.0f;
  54471. const float indent = 22.0f;
  54472. Path p;
  54473. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54474. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54475. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54476. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54477. p.setUsingNonZeroWinding (false);
  54478. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54479. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54480. }
  54481. if (button.hasKeyboardFocus (false))
  54482. {
  54483. g.setColour (textColour.withAlpha (0.4f));
  54484. g.drawRect (0, 0, width, height);
  54485. }
  54486. }
  54487. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54488. float x, float y, float w, float h,
  54489. float maxCornerSize,
  54490. const Colour& baseColour,
  54491. const float strokeWidth,
  54492. const bool flatOnLeft,
  54493. const bool flatOnRight,
  54494. const bool flatOnTop,
  54495. const bool flatOnBottom) throw()
  54496. {
  54497. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54498. return;
  54499. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54500. Path outline;
  54501. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54502. ! (flatOnLeft || flatOnTop),
  54503. ! (flatOnRight || flatOnTop),
  54504. ! (flatOnLeft || flatOnBottom),
  54505. ! (flatOnRight || flatOnBottom));
  54506. ColourGradient cg (baseColour, 0.0f, y,
  54507. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54508. false);
  54509. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54510. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54511. g.setGradientFill (cg);
  54512. g.fillPath (outline);
  54513. g.setColour (Colour (0x80000000));
  54514. g.strokePath (outline, PathStrokeType (strokeWidth));
  54515. }
  54516. void LookAndFeel::drawGlassSphere (Graphics& g,
  54517. const float x, const float y,
  54518. const float diameter,
  54519. const Colour& colour,
  54520. const float outlineThickness) throw()
  54521. {
  54522. if (diameter <= outlineThickness)
  54523. return;
  54524. Path p;
  54525. p.addEllipse (x, y, diameter, diameter);
  54526. {
  54527. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54528. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54529. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54530. g.setGradientFill (cg);
  54531. g.fillPath (p);
  54532. }
  54533. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54534. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54535. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54536. ColourGradient cg (Colours::transparentBlack,
  54537. x + diameter * 0.5f, y + diameter * 0.5f,
  54538. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54539. x, y + diameter * 0.5f, true);
  54540. cg.addColour (0.7, Colours::transparentBlack);
  54541. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54542. g.setGradientFill (cg);
  54543. g.fillPath (p);
  54544. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54545. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54546. }
  54547. void LookAndFeel::drawGlassPointer (Graphics& g,
  54548. const float x, const float y,
  54549. const float diameter,
  54550. const Colour& colour, const float outlineThickness,
  54551. const int direction) throw()
  54552. {
  54553. if (diameter <= outlineThickness)
  54554. return;
  54555. Path p;
  54556. p.startNewSubPath (x + diameter * 0.5f, y);
  54557. p.lineTo (x + diameter, y + diameter * 0.6f);
  54558. p.lineTo (x + diameter, y + diameter);
  54559. p.lineTo (x, y + diameter);
  54560. p.lineTo (x, y + diameter * 0.6f);
  54561. p.closeSubPath();
  54562. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54563. {
  54564. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54565. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54566. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54567. g.setGradientFill (cg);
  54568. g.fillPath (p);
  54569. }
  54570. ColourGradient cg (Colours::transparentBlack,
  54571. x + diameter * 0.5f, y + diameter * 0.5f,
  54572. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54573. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54574. cg.addColour (0.5, Colours::transparentBlack);
  54575. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54576. g.setGradientFill (cg);
  54577. g.fillPath (p);
  54578. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54579. g.strokePath (p, PathStrokeType (outlineThickness));
  54580. }
  54581. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54582. const float x, const float y,
  54583. const float width, const float height,
  54584. const Colour& colour,
  54585. const float outlineThickness,
  54586. const float cornerSize,
  54587. const bool flatOnLeft,
  54588. const bool flatOnRight,
  54589. const bool flatOnTop,
  54590. const bool flatOnBottom) throw()
  54591. {
  54592. if (width <= outlineThickness || height <= outlineThickness)
  54593. return;
  54594. const int intX = (int) x;
  54595. const int intY = (int) y;
  54596. const int intW = (int) width;
  54597. const int intH = (int) height;
  54598. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54599. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54600. const int intEdge = (int) edgeBlurRadius;
  54601. Path outline;
  54602. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54603. ! (flatOnLeft || flatOnTop),
  54604. ! (flatOnRight || flatOnTop),
  54605. ! (flatOnLeft || flatOnBottom),
  54606. ! (flatOnRight || flatOnBottom));
  54607. {
  54608. ColourGradient cg (colour.darker (0.2f), 0, y,
  54609. colour.darker (0.2f), 0, y + height, false);
  54610. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54611. cg.addColour (0.4, colour);
  54612. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54613. g.setGradientFill (cg);
  54614. g.fillPath (outline);
  54615. }
  54616. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54617. colour.darker (0.2f), x, y + height * 0.5f, true);
  54618. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54619. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54620. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54621. {
  54622. g.saveState();
  54623. g.setGradientFill (cg);
  54624. g.reduceClipRegion (intX, intY, intEdge, intH);
  54625. g.fillPath (outline);
  54626. g.restoreState();
  54627. }
  54628. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54629. {
  54630. cg.point1.setX (x + width - edgeBlurRadius);
  54631. cg.point2.setX (x + width);
  54632. g.saveState();
  54633. g.setGradientFill (cg);
  54634. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54635. g.fillPath (outline);
  54636. g.restoreState();
  54637. }
  54638. {
  54639. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54640. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54641. Path highlight;
  54642. LookAndFeelHelpers::createRoundedPath (highlight,
  54643. x + leftIndent,
  54644. y + cs * 0.1f,
  54645. width - (leftIndent + rightIndent),
  54646. height * 0.4f, cs * 0.4f,
  54647. ! (flatOnLeft || flatOnTop),
  54648. ! (flatOnRight || flatOnTop),
  54649. ! (flatOnLeft || flatOnBottom),
  54650. ! (flatOnRight || flatOnBottom));
  54651. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54652. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54653. g.fillPath (highlight);
  54654. }
  54655. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54656. g.strokePath (outline, PathStrokeType (outlineThickness));
  54657. }
  54658. END_JUCE_NAMESPACE
  54659. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54660. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54661. BEGIN_JUCE_NAMESPACE
  54662. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54663. {
  54664. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54665. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54666. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54667. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54668. setColour (Slider::thumbColourId, Colours::white);
  54669. setColour (Slider::trackColourId, Colour (0x7f000000));
  54670. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54671. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54672. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54673. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54674. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54675. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54676. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54677. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54678. }
  54679. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54680. {
  54681. }
  54682. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54683. Button& button,
  54684. const Colour& backgroundColour,
  54685. bool isMouseOverButton,
  54686. bool isButtonDown)
  54687. {
  54688. const int width = button.getWidth();
  54689. const int height = button.getHeight();
  54690. const float indent = 2.0f;
  54691. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54692. roundToInt (height * 0.4f));
  54693. Path p;
  54694. p.addRoundedRectangle (indent, indent,
  54695. width - indent * 2.0f,
  54696. height - indent * 2.0f,
  54697. (float) cornerSize);
  54698. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54699. if (isMouseOverButton)
  54700. {
  54701. if (isButtonDown)
  54702. bc = bc.brighter();
  54703. else if (bc.getBrightness() > 0.5f)
  54704. bc = bc.darker (0.1f);
  54705. else
  54706. bc = bc.brighter (0.1f);
  54707. }
  54708. g.setColour (bc);
  54709. g.fillPath (p);
  54710. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54711. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54712. }
  54713. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54714. Component& /*component*/,
  54715. float x, float y, float w, float h,
  54716. const bool ticked,
  54717. const bool isEnabled,
  54718. const bool /*isMouseOverButton*/,
  54719. const bool isButtonDown)
  54720. {
  54721. Path box;
  54722. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54723. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54724. : Colours::lightgrey.withAlpha (0.1f));
  54725. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54726. g.fillPath (box, trans);
  54727. g.setColour (Colours::black.withAlpha (0.6f));
  54728. g.strokePath (box, PathStrokeType (0.9f), trans);
  54729. if (ticked)
  54730. {
  54731. Path tick;
  54732. tick.startNewSubPath (1.5f, 3.0f);
  54733. tick.lineTo (3.0f, 6.0f);
  54734. tick.lineTo (6.0f, 0.0f);
  54735. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54736. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54737. }
  54738. }
  54739. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54740. ToggleButton& button,
  54741. bool isMouseOverButton,
  54742. bool isButtonDown)
  54743. {
  54744. if (button.hasKeyboardFocus (true))
  54745. {
  54746. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54747. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54748. }
  54749. const int tickWidth = jmin (20, button.getHeight() - 4);
  54750. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54751. (float) tickWidth, (float) tickWidth,
  54752. button.getToggleState(),
  54753. button.isEnabled(),
  54754. isMouseOverButton,
  54755. isButtonDown);
  54756. g.setColour (button.findColour (ToggleButton::textColourId));
  54757. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54758. if (! button.isEnabled())
  54759. g.setOpacity (0.5f);
  54760. const int textX = tickWidth + 5;
  54761. g.drawFittedText (button.getButtonText(),
  54762. textX, 4,
  54763. button.getWidth() - textX - 2, button.getHeight() - 8,
  54764. Justification::centredLeft, 10);
  54765. }
  54766. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54767. int width, int height,
  54768. double progress, const String& textToShow)
  54769. {
  54770. if (progress < 0 || progress >= 1.0)
  54771. {
  54772. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54773. }
  54774. else
  54775. {
  54776. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54777. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54778. g.fillAll (background);
  54779. g.setColour (foreground);
  54780. g.fillRect (1, 1,
  54781. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54782. height - 2);
  54783. if (textToShow.isNotEmpty())
  54784. {
  54785. g.setColour (Colour::contrasting (background, foreground));
  54786. g.setFont (height * 0.6f);
  54787. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54788. }
  54789. }
  54790. }
  54791. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54792. ScrollBar& bar,
  54793. int width, int height,
  54794. int buttonDirection,
  54795. bool isScrollbarVertical,
  54796. bool isMouseOverButton,
  54797. bool isButtonDown)
  54798. {
  54799. if (isScrollbarVertical)
  54800. width -= 2;
  54801. else
  54802. height -= 2;
  54803. Path p;
  54804. if (buttonDirection == 0)
  54805. p.addTriangle (width * 0.5f, height * 0.2f,
  54806. width * 0.1f, height * 0.7f,
  54807. width * 0.9f, height * 0.7f);
  54808. else if (buttonDirection == 1)
  54809. p.addTriangle (width * 0.8f, height * 0.5f,
  54810. width * 0.3f, height * 0.1f,
  54811. width * 0.3f, height * 0.9f);
  54812. else if (buttonDirection == 2)
  54813. p.addTriangle (width * 0.5f, height * 0.8f,
  54814. width * 0.1f, height * 0.3f,
  54815. width * 0.9f, height * 0.3f);
  54816. else if (buttonDirection == 3)
  54817. p.addTriangle (width * 0.2f, height * 0.5f,
  54818. width * 0.7f, height * 0.1f,
  54819. width * 0.7f, height * 0.9f);
  54820. if (isButtonDown)
  54821. g.setColour (Colours::white);
  54822. else if (isMouseOverButton)
  54823. g.setColour (Colours::white.withAlpha (0.7f));
  54824. else
  54825. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54826. g.fillPath (p);
  54827. g.setColour (Colours::black.withAlpha (0.5f));
  54828. g.strokePath (p, PathStrokeType (0.5f));
  54829. }
  54830. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54831. ScrollBar& bar,
  54832. int x, int y,
  54833. int width, int height,
  54834. bool isScrollbarVertical,
  54835. int thumbStartPosition,
  54836. int thumbSize,
  54837. bool isMouseOver,
  54838. bool isMouseDown)
  54839. {
  54840. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54841. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54842. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54843. if (thumbSize > 0.0f)
  54844. {
  54845. Rectangle<int> thumb;
  54846. if (isScrollbarVertical)
  54847. {
  54848. width -= 2;
  54849. g.fillRect (x + roundToInt (width * 0.35f), y,
  54850. roundToInt (width * 0.3f), height);
  54851. thumb.setBounds (x + 1, thumbStartPosition,
  54852. width - 2, thumbSize);
  54853. }
  54854. else
  54855. {
  54856. height -= 2;
  54857. g.fillRect (x, y + roundToInt (height * 0.35f),
  54858. width, roundToInt (height * 0.3f));
  54859. thumb.setBounds (thumbStartPosition, y + 1,
  54860. thumbSize, height - 2);
  54861. }
  54862. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54863. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54864. g.fillRect (thumb);
  54865. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54866. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54867. if (thumbSize > 16)
  54868. {
  54869. for (int i = 3; --i >= 0;)
  54870. {
  54871. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54872. g.setColour (Colours::black.withAlpha (0.15f));
  54873. if (isScrollbarVertical)
  54874. {
  54875. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54876. g.setColour (Colours::white.withAlpha (0.15f));
  54877. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54878. }
  54879. else
  54880. {
  54881. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54882. g.setColour (Colours::white.withAlpha (0.15f));
  54883. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54884. }
  54885. }
  54886. }
  54887. }
  54888. }
  54889. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54890. {
  54891. return &scrollbarShadow;
  54892. }
  54893. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54894. {
  54895. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54896. g.setColour (Colours::black.withAlpha (0.6f));
  54897. g.drawRect (0, 0, width, height);
  54898. }
  54899. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54900. bool, MenuBarComponent& menuBar)
  54901. {
  54902. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54903. }
  54904. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54905. {
  54906. if (textEditor.isEnabled())
  54907. {
  54908. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54909. g.drawRect (0, 0, width, height);
  54910. }
  54911. }
  54912. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54913. const bool isButtonDown,
  54914. int buttonX, int buttonY,
  54915. int buttonW, int buttonH,
  54916. ComboBox& box)
  54917. {
  54918. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54919. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54920. : ComboBox::backgroundColourId));
  54921. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54922. g.setColour (box.findColour (ComboBox::outlineColourId));
  54923. g.drawRect (0, 0, width, height);
  54924. const float arrowX = 0.2f;
  54925. const float arrowH = 0.3f;
  54926. if (box.isEnabled())
  54927. {
  54928. Path p;
  54929. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54930. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54931. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54932. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54933. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54934. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54935. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54936. : ComboBox::buttonColourId));
  54937. g.fillPath (p);
  54938. }
  54939. }
  54940. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54941. {
  54942. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54943. f.setHorizontalScale (0.9f);
  54944. return f;
  54945. }
  54946. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54947. {
  54948. Path p;
  54949. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54950. g.setColour (fill);
  54951. g.fillPath (p);
  54952. g.setColour (outline);
  54953. g.strokePath (p, PathStrokeType (0.3f));
  54954. }
  54955. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54956. int x, int y,
  54957. int w, int h,
  54958. float sliderPos,
  54959. float minSliderPos,
  54960. float maxSliderPos,
  54961. const Slider::SliderStyle style,
  54962. Slider& slider)
  54963. {
  54964. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54965. if (style == Slider::LinearBar)
  54966. {
  54967. g.setColour (slider.findColour (Slider::thumbColourId));
  54968. g.fillRect (x, y, (int) sliderPos - x, h);
  54969. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54970. g.drawRect (x, y, (int) sliderPos - x, h);
  54971. }
  54972. else
  54973. {
  54974. g.setColour (slider.findColour (Slider::trackColourId)
  54975. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54976. if (slider.isHorizontal())
  54977. {
  54978. g.fillRect (x, y + roundToInt (h * 0.6f),
  54979. w, roundToInt (h * 0.2f));
  54980. }
  54981. else
  54982. {
  54983. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54984. jmin (4, roundToInt (w * 0.2f)), h);
  54985. }
  54986. float alpha = 0.35f;
  54987. if (slider.isEnabled())
  54988. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54989. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54990. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54991. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54992. {
  54993. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54994. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54995. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54996. fill, outline);
  54997. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54998. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54999. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55000. fill, outline);
  55001. }
  55002. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55003. {
  55004. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55005. minSliderPos - 7.0f, y + h * 0.9f ,
  55006. minSliderPos, y + h * 0.9f,
  55007. fill, outline);
  55008. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55009. maxSliderPos, y + h * 0.9f,
  55010. maxSliderPos + 7.0f, y + h * 0.9f,
  55011. fill, outline);
  55012. }
  55013. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55014. {
  55015. drawTriangle (g, sliderPos, y + h * 0.9f,
  55016. sliderPos - 7.0f, y + h * 0.2f,
  55017. sliderPos + 7.0f, y + h * 0.2f,
  55018. fill, outline);
  55019. }
  55020. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55021. {
  55022. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55023. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55024. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55025. fill, outline);
  55026. }
  55027. }
  55028. }
  55029. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55030. {
  55031. if (isIncrement)
  55032. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55033. else
  55034. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55035. }
  55036. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55037. {
  55038. return &scrollbarShadow;
  55039. }
  55040. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55041. {
  55042. return 8;
  55043. }
  55044. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55045. int w, int h,
  55046. bool isMouseOver,
  55047. bool isMouseDragging)
  55048. {
  55049. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55050. : Colours::darkgrey);
  55051. const float lineThickness = jmin (w, h) * 0.1f;
  55052. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55053. {
  55054. g.drawLine (w * i,
  55055. h + 1.0f,
  55056. w + 1.0f,
  55057. h * i,
  55058. lineThickness);
  55059. }
  55060. }
  55061. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55062. {
  55063. Path shape;
  55064. if (buttonType == DocumentWindow::closeButton)
  55065. {
  55066. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55067. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55068. ShapeButton* const b = new ShapeButton ("close",
  55069. Colour (0x7fff3333),
  55070. Colour (0xd7ff3333),
  55071. Colour (0xf7ff3333));
  55072. b->setShape (shape, true, true, true);
  55073. return b;
  55074. }
  55075. else if (buttonType == DocumentWindow::minimiseButton)
  55076. {
  55077. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55078. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55079. DrawablePath dp;
  55080. dp.setPath (shape);
  55081. dp.setFill (Colours::black.withAlpha (0.3f));
  55082. b->setImages (&dp);
  55083. return b;
  55084. }
  55085. else if (buttonType == DocumentWindow::maximiseButton)
  55086. {
  55087. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55088. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55089. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55090. DrawablePath dp;
  55091. dp.setPath (shape);
  55092. dp.setFill (Colours::black.withAlpha (0.3f));
  55093. b->setImages (&dp);
  55094. return b;
  55095. }
  55096. jassertfalse;
  55097. return 0;
  55098. }
  55099. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55100. int titleBarX,
  55101. int titleBarY,
  55102. int titleBarW,
  55103. int titleBarH,
  55104. Button* minimiseButton,
  55105. Button* maximiseButton,
  55106. Button* closeButton,
  55107. bool positionTitleBarButtonsOnLeft)
  55108. {
  55109. titleBarY += titleBarH / 8;
  55110. titleBarH -= titleBarH / 4;
  55111. const int buttonW = titleBarH;
  55112. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55113. : titleBarX + titleBarW - buttonW - 4;
  55114. if (closeButton != 0)
  55115. {
  55116. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55117. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55118. : -(buttonW + buttonW / 5);
  55119. }
  55120. if (positionTitleBarButtonsOnLeft)
  55121. swapVariables (minimiseButton, maximiseButton);
  55122. if (maximiseButton != 0)
  55123. {
  55124. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55125. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55126. }
  55127. if (minimiseButton != 0)
  55128. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55129. }
  55130. END_JUCE_NAMESPACE
  55131. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55132. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55133. BEGIN_JUCE_NAMESPACE
  55134. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55135. : model (0),
  55136. itemUnderMouse (-1),
  55137. currentPopupIndex (-1),
  55138. topLevelIndexClicked (0),
  55139. lastMouseX (0),
  55140. lastMouseY (0)
  55141. {
  55142. setRepaintsOnMouseActivity (true);
  55143. setWantsKeyboardFocus (false);
  55144. setMouseClickGrabsKeyboardFocus (false);
  55145. setModel (model_);
  55146. }
  55147. MenuBarComponent::~MenuBarComponent()
  55148. {
  55149. setModel (0);
  55150. Desktop::getInstance().removeGlobalMouseListener (this);
  55151. }
  55152. MenuBarModel* MenuBarComponent::getModel() const throw()
  55153. {
  55154. return model;
  55155. }
  55156. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55157. {
  55158. if (model != newModel)
  55159. {
  55160. if (model != 0)
  55161. model->removeListener (this);
  55162. model = newModel;
  55163. if (model != 0)
  55164. model->addListener (this);
  55165. repaint();
  55166. menuBarItemsChanged (0);
  55167. }
  55168. }
  55169. void MenuBarComponent::paint (Graphics& g)
  55170. {
  55171. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55172. getLookAndFeel().drawMenuBarBackground (g,
  55173. getWidth(),
  55174. getHeight(),
  55175. isMouseOverBar,
  55176. *this);
  55177. if (model != 0)
  55178. {
  55179. for (int i = 0; i < menuNames.size(); ++i)
  55180. {
  55181. Graphics::ScopedSaveState ss (g);
  55182. g.setOrigin (xPositions [i], 0);
  55183. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55184. getLookAndFeel().drawMenuBarItem (g,
  55185. xPositions[i + 1] - xPositions[i],
  55186. getHeight(),
  55187. i,
  55188. menuNames[i],
  55189. i == itemUnderMouse,
  55190. i == currentPopupIndex,
  55191. isMouseOverBar,
  55192. *this);
  55193. }
  55194. }
  55195. }
  55196. void MenuBarComponent::resized()
  55197. {
  55198. xPositions.clear();
  55199. int x = 0;
  55200. xPositions.add (x);
  55201. for (int i = 0; i < menuNames.size(); ++i)
  55202. {
  55203. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55204. xPositions.add (x);
  55205. }
  55206. }
  55207. int MenuBarComponent::getItemAt (const int x, const int y)
  55208. {
  55209. for (int i = 0; i < xPositions.size(); ++i)
  55210. if (x >= xPositions[i] && x < xPositions[i + 1])
  55211. return reallyContains (Point<int> (x, y), true) ? i : -1;
  55212. return -1;
  55213. }
  55214. void MenuBarComponent::repaintMenuItem (int index)
  55215. {
  55216. if (isPositiveAndBelow (index, xPositions.size()))
  55217. {
  55218. const int x1 = xPositions [index];
  55219. const int x2 = xPositions [index + 1];
  55220. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55221. }
  55222. }
  55223. void MenuBarComponent::setItemUnderMouse (const int index)
  55224. {
  55225. if (itemUnderMouse != index)
  55226. {
  55227. repaintMenuItem (itemUnderMouse);
  55228. itemUnderMouse = index;
  55229. repaintMenuItem (itemUnderMouse);
  55230. }
  55231. }
  55232. void MenuBarComponent::setOpenItem (int index)
  55233. {
  55234. if (currentPopupIndex != index)
  55235. {
  55236. repaintMenuItem (currentPopupIndex);
  55237. currentPopupIndex = index;
  55238. repaintMenuItem (currentPopupIndex);
  55239. if (index >= 0)
  55240. Desktop::getInstance().addGlobalMouseListener (this);
  55241. else
  55242. Desktop::getInstance().removeGlobalMouseListener (this);
  55243. }
  55244. }
  55245. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55246. {
  55247. setItemUnderMouse (getItemAt (x, y));
  55248. }
  55249. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55250. {
  55251. public:
  55252. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55253. : bar (bar_), topLevelIndex (topLevelIndex_)
  55254. {
  55255. }
  55256. void modalStateFinished (int returnValue)
  55257. {
  55258. if (bar != 0)
  55259. bar->menuDismissed (topLevelIndex, returnValue);
  55260. }
  55261. private:
  55262. Component::SafePointer<MenuBarComponent> bar;
  55263. const int topLevelIndex;
  55264. JUCE_DECLARE_NON_COPYABLE (AsyncCallback);
  55265. };
  55266. void MenuBarComponent::showMenu (int index)
  55267. {
  55268. if (index != currentPopupIndex)
  55269. {
  55270. PopupMenu::dismissAllActiveMenus();
  55271. menuBarItemsChanged (0);
  55272. setOpenItem (index);
  55273. setItemUnderMouse (index);
  55274. if (index >= 0)
  55275. {
  55276. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55277. menuNames [itemUnderMouse]));
  55278. if (m.lookAndFeel == 0)
  55279. m.setLookAndFeel (&getLookAndFeel());
  55280. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55281. m.showMenu (localAreaToGlobal (itemPos),
  55282. 0, itemPos.getWidth(), 0, 0, this,
  55283. new AsyncCallback (this, index));
  55284. }
  55285. }
  55286. }
  55287. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55288. {
  55289. topLevelIndexClicked = topLevelIndex;
  55290. postCommandMessage (itemId);
  55291. }
  55292. void MenuBarComponent::handleCommandMessage (int commandId)
  55293. {
  55294. const Point<int> mousePos (getMouseXYRelative());
  55295. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55296. if (currentPopupIndex == topLevelIndexClicked)
  55297. setOpenItem (-1);
  55298. if (commandId != 0 && model != 0)
  55299. model->menuItemSelected (commandId, topLevelIndexClicked);
  55300. }
  55301. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55302. {
  55303. if (e.eventComponent == this)
  55304. updateItemUnderMouse (e.x, e.y);
  55305. }
  55306. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55307. {
  55308. if (e.eventComponent == this)
  55309. updateItemUnderMouse (e.x, e.y);
  55310. }
  55311. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55312. {
  55313. if (currentPopupIndex < 0)
  55314. {
  55315. const MouseEvent e2 (e.getEventRelativeTo (this));
  55316. updateItemUnderMouse (e2.x, e2.y);
  55317. currentPopupIndex = -2;
  55318. showMenu (itemUnderMouse);
  55319. }
  55320. }
  55321. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55322. {
  55323. const MouseEvent e2 (e.getEventRelativeTo (this));
  55324. const int item = getItemAt (e2.x, e2.y);
  55325. if (item >= 0)
  55326. showMenu (item);
  55327. }
  55328. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55329. {
  55330. const MouseEvent e2 (e.getEventRelativeTo (this));
  55331. updateItemUnderMouse (e2.x, e2.y);
  55332. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55333. {
  55334. setOpenItem (-1);
  55335. PopupMenu::dismissAllActiveMenus();
  55336. }
  55337. }
  55338. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55339. {
  55340. const MouseEvent e2 (e.getEventRelativeTo (this));
  55341. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55342. {
  55343. if (currentPopupIndex >= 0)
  55344. {
  55345. const int item = getItemAt (e2.x, e2.y);
  55346. if (item >= 0)
  55347. showMenu (item);
  55348. }
  55349. else
  55350. {
  55351. updateItemUnderMouse (e2.x, e2.y);
  55352. }
  55353. lastMouseX = e2.x;
  55354. lastMouseY = e2.y;
  55355. }
  55356. }
  55357. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55358. {
  55359. bool used = false;
  55360. const int numMenus = menuNames.size();
  55361. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55362. if (key.isKeyCode (KeyPress::leftKey))
  55363. {
  55364. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55365. used = true;
  55366. }
  55367. else if (key.isKeyCode (KeyPress::rightKey))
  55368. {
  55369. showMenu ((currentIndex + 1) % numMenus);
  55370. used = true;
  55371. }
  55372. return used;
  55373. }
  55374. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55375. {
  55376. StringArray newNames;
  55377. if (model != 0)
  55378. newNames = model->getMenuBarNames();
  55379. if (newNames != menuNames)
  55380. {
  55381. menuNames = newNames;
  55382. repaint();
  55383. resized();
  55384. }
  55385. }
  55386. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55387. const ApplicationCommandTarget::InvocationInfo& info)
  55388. {
  55389. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55390. return;
  55391. for (int i = 0; i < menuNames.size(); ++i)
  55392. {
  55393. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55394. if (menu.containsCommandItem (info.commandID))
  55395. {
  55396. setItemUnderMouse (i);
  55397. startTimer (200);
  55398. break;
  55399. }
  55400. }
  55401. }
  55402. void MenuBarComponent::timerCallback()
  55403. {
  55404. stopTimer();
  55405. const Point<int> mousePos (getMouseXYRelative());
  55406. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55407. }
  55408. END_JUCE_NAMESPACE
  55409. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55410. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55411. BEGIN_JUCE_NAMESPACE
  55412. MenuBarModel::MenuBarModel() throw()
  55413. : manager (0)
  55414. {
  55415. }
  55416. MenuBarModel::~MenuBarModel()
  55417. {
  55418. setApplicationCommandManagerToWatch (0);
  55419. }
  55420. void MenuBarModel::menuItemsChanged()
  55421. {
  55422. triggerAsyncUpdate();
  55423. }
  55424. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55425. {
  55426. if (manager != newManager)
  55427. {
  55428. if (manager != 0)
  55429. manager->removeListener (this);
  55430. manager = newManager;
  55431. if (manager != 0)
  55432. manager->addListener (this);
  55433. }
  55434. }
  55435. void MenuBarModel::addListener (Listener* const newListener) throw()
  55436. {
  55437. listeners.add (newListener);
  55438. }
  55439. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55440. {
  55441. // Trying to remove a listener that isn't on the list!
  55442. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55443. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55444. jassert (listeners.contains (listenerToRemove));
  55445. listeners.remove (listenerToRemove);
  55446. }
  55447. void MenuBarModel::handleAsyncUpdate()
  55448. {
  55449. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55450. }
  55451. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55452. {
  55453. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55454. }
  55455. void MenuBarModel::applicationCommandListChanged()
  55456. {
  55457. menuItemsChanged();
  55458. }
  55459. END_JUCE_NAMESPACE
  55460. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55461. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55462. BEGIN_JUCE_NAMESPACE
  55463. class PopupMenu::Item
  55464. {
  55465. public:
  55466. Item()
  55467. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55468. usesColour (false), customComp (0), commandManager (0)
  55469. {
  55470. }
  55471. Item (const int itemId_,
  55472. const String& text_,
  55473. const bool active_,
  55474. const bool isTicked_,
  55475. const Image& im,
  55476. const Colour& textColour_,
  55477. const bool usesColour_,
  55478. CustomComponent* const customComp_,
  55479. const PopupMenu* const subMenu_,
  55480. ApplicationCommandManager* const commandManager_)
  55481. : itemId (itemId_), text (text_), textColour (textColour_),
  55482. active (active_), isSeparator (false), isTicked (isTicked_),
  55483. usesColour (usesColour_), image (im), customComp (customComp_),
  55484. commandManager (commandManager_)
  55485. {
  55486. if (subMenu_ != 0)
  55487. subMenu = new PopupMenu (*subMenu_);
  55488. if (commandManager_ != 0 && itemId_ != 0)
  55489. {
  55490. String shortcutKey;
  55491. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55492. ->getKeyPressesAssignedToCommand (itemId_));
  55493. for (int i = 0; i < keyPresses.size(); ++i)
  55494. {
  55495. const String key (keyPresses.getReference(i).getTextDescription());
  55496. if (shortcutKey.isNotEmpty())
  55497. shortcutKey << ", ";
  55498. if (key.length() == 1)
  55499. shortcutKey << "shortcut: '" << key << '\'';
  55500. else
  55501. shortcutKey << key;
  55502. }
  55503. shortcutKey = shortcutKey.trim();
  55504. if (shortcutKey.isNotEmpty())
  55505. text << "<end>" << shortcutKey;
  55506. }
  55507. }
  55508. Item (const Item& other)
  55509. : itemId (other.itemId),
  55510. text (other.text),
  55511. textColour (other.textColour),
  55512. active (other.active),
  55513. isSeparator (other.isSeparator),
  55514. isTicked (other.isTicked),
  55515. usesColour (other.usesColour),
  55516. image (other.image),
  55517. customComp (other.customComp),
  55518. commandManager (other.commandManager)
  55519. {
  55520. if (other.subMenu != 0)
  55521. subMenu = new PopupMenu (*(other.subMenu));
  55522. }
  55523. bool canBeTriggered() const throw() { return active && ! (isSeparator || (subMenu != 0)); }
  55524. bool hasActiveSubMenu() const throw() { return active && (subMenu != 0); }
  55525. const int itemId;
  55526. String text;
  55527. const Colour textColour;
  55528. const bool active, isSeparator, isTicked, usesColour;
  55529. Image image;
  55530. ReferenceCountedObjectPtr <CustomComponent> customComp;
  55531. ScopedPointer <PopupMenu> subMenu;
  55532. ApplicationCommandManager* const commandManager;
  55533. private:
  55534. Item& operator= (const Item&);
  55535. JUCE_LEAK_DETECTOR (Item);
  55536. };
  55537. class PopupMenu::ItemComponent : public Component
  55538. {
  55539. public:
  55540. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight)
  55541. : itemInfo (itemInfo_),
  55542. isHighlighted (false)
  55543. {
  55544. if (itemInfo.customComp != 0)
  55545. addAndMakeVisible (itemInfo.customComp);
  55546. int itemW = 80;
  55547. int itemH = 16;
  55548. getIdealSize (itemW, itemH, standardItemHeight);
  55549. setSize (itemW, jlimit (2, 600, itemH));
  55550. }
  55551. ~ItemComponent()
  55552. {
  55553. if (itemInfo.customComp != 0)
  55554. removeChildComponent (itemInfo.customComp);
  55555. }
  55556. void getIdealSize (int& idealWidth, int& idealHeight, const int standardItemHeight)
  55557. {
  55558. if (itemInfo.customComp != 0)
  55559. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55560. else
  55561. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55562. itemInfo.isSeparator,
  55563. standardItemHeight,
  55564. idealWidth, idealHeight);
  55565. }
  55566. void paint (Graphics& g)
  55567. {
  55568. if (itemInfo.customComp == 0)
  55569. {
  55570. String mainText (itemInfo.text);
  55571. String endText;
  55572. const int endIndex = mainText.indexOf ("<end>");
  55573. if (endIndex >= 0)
  55574. {
  55575. endText = mainText.substring (endIndex + 5).trim();
  55576. mainText = mainText.substring (0, endIndex);
  55577. }
  55578. getLookAndFeel()
  55579. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55580. itemInfo.isSeparator,
  55581. itemInfo.active,
  55582. isHighlighted,
  55583. itemInfo.isTicked,
  55584. itemInfo.subMenu != 0,
  55585. mainText, endText,
  55586. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55587. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55588. }
  55589. }
  55590. void resized()
  55591. {
  55592. if (getNumChildComponents() > 0)
  55593. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55594. }
  55595. void setHighlighted (bool shouldBeHighlighted)
  55596. {
  55597. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55598. if (isHighlighted != shouldBeHighlighted)
  55599. {
  55600. isHighlighted = shouldBeHighlighted;
  55601. if (itemInfo.customComp != 0)
  55602. itemInfo.customComp->setHighlighted (shouldBeHighlighted);
  55603. repaint();
  55604. }
  55605. }
  55606. PopupMenu::Item itemInfo;
  55607. private:
  55608. bool isHighlighted;
  55609. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  55610. };
  55611. namespace PopupMenuSettings
  55612. {
  55613. const int scrollZone = 24;
  55614. const int borderSize = 2;
  55615. const int timerInterval = 50;
  55616. const int dismissCommandId = 0x6287345f;
  55617. }
  55618. class PopupMenu::Window : public Component,
  55619. private Timer
  55620. {
  55621. public:
  55622. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55623. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55624. const int minimumWidth_, const int maximumNumColumns_,
  55625. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55626. ApplicationCommandManager** const managerOfChosenCommand_,
  55627. Component* const componentAttachedTo_)
  55628. : Component ("menu"),
  55629. owner (owner_),
  55630. activeSubMenu (0),
  55631. managerOfChosenCommand (managerOfChosenCommand_),
  55632. componentAttachedTo (componentAttachedTo_),
  55633. componentAttachedToOriginal (componentAttachedTo_),
  55634. minimumWidth (minimumWidth_),
  55635. maximumNumColumns (maximumNumColumns_),
  55636. standardItemHeight (standardItemHeight_),
  55637. isOver (false),
  55638. hasBeenOver (false),
  55639. isDown (false),
  55640. needsToScroll (false),
  55641. dismissOnMouseUp (dismissOnMouseUp_),
  55642. hideOnExit (false),
  55643. disableMouseMoves (false),
  55644. hasAnyJuceCompHadFocus (false),
  55645. numColumns (0),
  55646. contentHeight (0),
  55647. childYOffset (0),
  55648. menuCreationTime (Time::getMillisecondCounter()),
  55649. lastMouseMoveTime (0),
  55650. timeEnteredCurrentChildComp (0),
  55651. scrollAcceleration (1.0)
  55652. {
  55653. lastFocused = lastScroll = menuCreationTime;
  55654. setWantsKeyboardFocus (false);
  55655. setMouseClickGrabsKeyboardFocus (false);
  55656. setAlwaysOnTop (true);
  55657. setLookAndFeel (menu.lookAndFeel);
  55658. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55659. for (int i = 0; i < menu.items.size(); ++i)
  55660. {
  55661. PopupMenu::ItemComponent* const itemComp = new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight);
  55662. items.add (itemComp);
  55663. addAndMakeVisible (itemComp);
  55664. itemComp->addMouseListener (this, false);
  55665. }
  55666. calculateWindowPos (target, alignToRectangle);
  55667. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55668. updateYPositions();
  55669. if (itemIdThatMustBeVisible != 0)
  55670. {
  55671. const int y = target.getY() - windowPos.getY();
  55672. ensureItemIsVisible (itemIdThatMustBeVisible,
  55673. isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  55674. }
  55675. resizeToBestWindowPos();
  55676. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55677. getActiveWindows().add (this);
  55678. Desktop::getInstance().addGlobalMouseListener (this);
  55679. }
  55680. ~Window()
  55681. {
  55682. getActiveWindows().removeValue (this);
  55683. Desktop::getInstance().removeGlobalMouseListener (this);
  55684. activeSubMenu = 0;
  55685. items.clear();
  55686. }
  55687. static Window* create (const PopupMenu& menu,
  55688. bool dismissOnMouseUp,
  55689. Window* const owner_,
  55690. const Rectangle<int>& target,
  55691. int minimumWidth,
  55692. int maximumNumColumns,
  55693. int standardItemHeight,
  55694. bool alignToRectangle,
  55695. int itemIdThatMustBeVisible,
  55696. ApplicationCommandManager** managerOfChosenCommand,
  55697. Component* componentAttachedTo)
  55698. {
  55699. if (menu.items.size() > 0)
  55700. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55701. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55702. managerOfChosenCommand, componentAttachedTo);
  55703. return 0;
  55704. }
  55705. void paint (Graphics& g)
  55706. {
  55707. if (isOpaque())
  55708. g.fillAll (Colours::white);
  55709. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55710. }
  55711. void paintOverChildren (Graphics& g)
  55712. {
  55713. if (isScrolling())
  55714. {
  55715. LookAndFeel& lf = getLookAndFeel();
  55716. if (isScrollZoneActive (false))
  55717. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55718. if (isScrollZoneActive (true))
  55719. {
  55720. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55721. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55722. }
  55723. }
  55724. }
  55725. bool isScrollZoneActive (bool bottomOne) const
  55726. {
  55727. return isScrolling()
  55728. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55729. : childYOffset > 0);
  55730. }
  55731. // hide this and all sub-comps
  55732. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55733. {
  55734. if (isVisible())
  55735. {
  55736. activeSubMenu = 0;
  55737. currentChild = 0;
  55738. exitModalState (item != 0 ? item->itemId : 0);
  55739. if (makeInvisible)
  55740. setVisible (false);
  55741. if (item != 0
  55742. && item->commandManager != 0
  55743. && item->itemId != 0)
  55744. {
  55745. *managerOfChosenCommand = item->commandManager;
  55746. }
  55747. }
  55748. }
  55749. void dismissMenu (const PopupMenu::Item* const item)
  55750. {
  55751. if (owner != 0)
  55752. {
  55753. owner->dismissMenu (item);
  55754. }
  55755. else
  55756. {
  55757. if (item != 0)
  55758. {
  55759. // need a copy of this on the stack as the one passed in will get deleted during this call
  55760. const PopupMenu::Item mi (*item);
  55761. hide (&mi, false);
  55762. }
  55763. else
  55764. {
  55765. hide (0, false);
  55766. }
  55767. }
  55768. }
  55769. void mouseMove (const MouseEvent&) { timerCallback(); }
  55770. void mouseDown (const MouseEvent&) { timerCallback(); }
  55771. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55772. void mouseUp (const MouseEvent&) { timerCallback(); }
  55773. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55774. {
  55775. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55776. lastMouse = Point<int> (-1, -1);
  55777. }
  55778. bool keyPressed (const KeyPress& key)
  55779. {
  55780. if (key.isKeyCode (KeyPress::downKey))
  55781. {
  55782. selectNextItem (1);
  55783. }
  55784. else if (key.isKeyCode (KeyPress::upKey))
  55785. {
  55786. selectNextItem (-1);
  55787. }
  55788. else if (key.isKeyCode (KeyPress::leftKey))
  55789. {
  55790. if (owner != 0)
  55791. {
  55792. Component::SafePointer<Window> parentWindow (owner);
  55793. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55794. hide (0, true);
  55795. if (parentWindow != 0)
  55796. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55797. disableTimerUntilMouseMoves();
  55798. }
  55799. else if (componentAttachedTo != 0)
  55800. {
  55801. componentAttachedTo->keyPressed (key);
  55802. }
  55803. }
  55804. else if (key.isKeyCode (KeyPress::rightKey))
  55805. {
  55806. disableTimerUntilMouseMoves();
  55807. if (showSubMenuFor (currentChild))
  55808. {
  55809. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55810. activeSubMenu->selectNextItem (1);
  55811. }
  55812. else if (componentAttachedTo != 0)
  55813. {
  55814. componentAttachedTo->keyPressed (key);
  55815. }
  55816. }
  55817. else if (key.isKeyCode (KeyPress::returnKey))
  55818. {
  55819. triggerCurrentlyHighlightedItem();
  55820. }
  55821. else if (key.isKeyCode (KeyPress::escapeKey))
  55822. {
  55823. dismissMenu (0);
  55824. }
  55825. else
  55826. {
  55827. return false;
  55828. }
  55829. return true;
  55830. }
  55831. void inputAttemptWhenModal()
  55832. {
  55833. WeakReference<Component> deletionChecker (this);
  55834. timerCallback();
  55835. if (deletionChecker != 0 && ! isOverAnyMenu())
  55836. {
  55837. if (componentAttachedTo != 0)
  55838. {
  55839. // we want to dismiss the menu, but if we do it synchronously, then
  55840. // the mouse-click will be allowed to pass through. That's good, except
  55841. // when the user clicks on the button that orginally popped the menu up,
  55842. // as they'll expect the menu to go away, and in fact it'll just
  55843. // come back. So only dismiss synchronously if they're not on the original
  55844. // comp that we're attached to.
  55845. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55846. if (componentAttachedTo->reallyContains (mousePos, true))
  55847. {
  55848. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55849. return;
  55850. }
  55851. }
  55852. dismissMenu (0);
  55853. }
  55854. }
  55855. void handleCommandMessage (int commandId)
  55856. {
  55857. Component::handleCommandMessage (commandId);
  55858. if (commandId == PopupMenuSettings::dismissCommandId)
  55859. dismissMenu (0);
  55860. }
  55861. void timerCallback()
  55862. {
  55863. if (! isVisible())
  55864. return;
  55865. if (componentAttachedTo != componentAttachedToOriginal)
  55866. {
  55867. dismissMenu (0);
  55868. return;
  55869. }
  55870. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55871. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55872. return;
  55873. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55874. // move rather than a real timer callback
  55875. const Point<int> globalMousePos (Desktop::getMousePosition());
  55876. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  55877. const uint32 now = Time::getMillisecondCounter();
  55878. if (now > timeEnteredCurrentChildComp + 100
  55879. && reallyContains (localMousePos, true)
  55880. && currentChild != 0
  55881. && (! disableMouseMoves)
  55882. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55883. {
  55884. showSubMenuFor (currentChild);
  55885. }
  55886. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55887. {
  55888. highlightItemUnderMouse (globalMousePos, localMousePos);
  55889. }
  55890. bool overScrollArea = false;
  55891. if (isScrolling()
  55892. && (isOver || (isDown && isPositiveAndBelow (localMousePos.getX(), getWidth())))
  55893. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55894. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55895. {
  55896. if (now > lastScroll + 20)
  55897. {
  55898. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55899. int amount = 0;
  55900. for (int i = 0; i < items.size() && amount == 0; ++i)
  55901. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  55902. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55903. lastScroll = now;
  55904. }
  55905. overScrollArea = true;
  55906. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55907. }
  55908. else
  55909. {
  55910. scrollAcceleration = 1.0;
  55911. }
  55912. const bool wasDown = isDown;
  55913. bool isOverAny = isOverAnyMenu();
  55914. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55915. {
  55916. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55917. isOverAny = isOverAnyMenu();
  55918. }
  55919. if (hideOnExit && hasBeenOver && ! isOverAny)
  55920. {
  55921. hide (0, true);
  55922. }
  55923. else
  55924. {
  55925. isDown = hasBeenOver
  55926. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55927. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55928. bool anyFocused = Process::isForegroundProcess();
  55929. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55930. {
  55931. // because no component at all may have focus, our test here will
  55932. // only be triggered when something has focus and then loses it.
  55933. anyFocused = ! hasAnyJuceCompHadFocus;
  55934. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55935. {
  55936. if (ComponentPeer::getPeer (i)->isFocused())
  55937. {
  55938. anyFocused = true;
  55939. hasAnyJuceCompHadFocus = true;
  55940. break;
  55941. }
  55942. }
  55943. }
  55944. if (! anyFocused)
  55945. {
  55946. if (now > lastFocused + 10)
  55947. {
  55948. wasHiddenBecauseOfAppChange() = true;
  55949. dismissMenu (0);
  55950. return; // may have been deleted by the previous call..
  55951. }
  55952. }
  55953. else if (wasDown && now > menuCreationTime + 250
  55954. && ! (isDown || overScrollArea))
  55955. {
  55956. isOver = reallyContains (localMousePos, true);
  55957. if (isOver)
  55958. {
  55959. triggerCurrentlyHighlightedItem();
  55960. }
  55961. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55962. {
  55963. dismissMenu (0);
  55964. }
  55965. return; // may have been deleted by the previous calls..
  55966. }
  55967. else
  55968. {
  55969. lastFocused = now;
  55970. }
  55971. }
  55972. }
  55973. static Array<Window*>& getActiveWindows()
  55974. {
  55975. static Array<Window*> activeMenuWindows;
  55976. return activeMenuWindows;
  55977. }
  55978. static bool& wasHiddenBecauseOfAppChange() throw()
  55979. {
  55980. static bool b = false;
  55981. return b;
  55982. }
  55983. private:
  55984. Window* owner;
  55985. OwnedArray <PopupMenu::ItemComponent> items;
  55986. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  55987. ScopedPointer <Window> activeSubMenu;
  55988. ApplicationCommandManager** managerOfChosenCommand;
  55989. WeakReference<Component> componentAttachedTo;
  55990. Component* componentAttachedToOriginal;
  55991. Rectangle<int> windowPos;
  55992. Point<int> lastMouse;
  55993. int minimumWidth, maximumNumColumns, standardItemHeight;
  55994. bool isOver, hasBeenOver, isDown, needsToScroll;
  55995. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55996. int numColumns, contentHeight, childYOffset;
  55997. Array <int> columnWidths;
  55998. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55999. double scrollAcceleration;
  56000. bool overlaps (const Rectangle<int>& r) const
  56001. {
  56002. return r.intersects (getBounds())
  56003. || (owner != 0 && owner->overlaps (r));
  56004. }
  56005. bool isOverAnyMenu() const
  56006. {
  56007. return (owner != 0) ? owner->isOverAnyMenu()
  56008. : isOverChildren();
  56009. }
  56010. bool isOverChildren() const
  56011. {
  56012. return isVisible()
  56013. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56014. }
  56015. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56016. {
  56017. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  56018. isOver = reallyContains (relPos, true);
  56019. if (activeSubMenu != 0)
  56020. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56021. }
  56022. bool treeContains (const Window* const window) const throw()
  56023. {
  56024. const Window* mw = this;
  56025. while (mw->owner != 0)
  56026. mw = mw->owner;
  56027. while (mw != 0)
  56028. {
  56029. if (mw == window)
  56030. return true;
  56031. mw = mw->activeSubMenu;
  56032. }
  56033. return false;
  56034. }
  56035. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56036. {
  56037. const Rectangle<int> mon (Desktop::getInstance()
  56038. .getMonitorAreaContaining (target.getCentre(),
  56039. #if JUCE_MAC
  56040. true));
  56041. #else
  56042. false)); // on windows, don't stop the menu overlapping the taskbar
  56043. #endif
  56044. int x, y, widthToUse, heightToUse;
  56045. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56046. if (alignToRectangle)
  56047. {
  56048. x = target.getX();
  56049. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56050. const int spaceOver = target.getY() - mon.getY();
  56051. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56052. y = target.getBottom();
  56053. else
  56054. y = target.getY() - heightToUse;
  56055. }
  56056. else
  56057. {
  56058. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56059. if (owner != 0)
  56060. {
  56061. if (owner->owner != 0)
  56062. {
  56063. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56064. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56065. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56066. tendTowardsRight = true;
  56067. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56068. tendTowardsRight = false;
  56069. }
  56070. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56071. {
  56072. tendTowardsRight = true;
  56073. }
  56074. }
  56075. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56076. target.getX() - mon.getX()) - 32;
  56077. if (biggestSpace < widthToUse)
  56078. {
  56079. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56080. if (numColumns > 1)
  56081. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56082. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56083. }
  56084. if (tendTowardsRight)
  56085. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56086. else
  56087. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56088. y = target.getY();
  56089. if (target.getCentreY() > mon.getCentreY())
  56090. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56091. }
  56092. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56093. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56094. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56095. // sets this flag if it's big enough to obscure any of its parent menus
  56096. hideOnExit = (owner != 0)
  56097. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56098. }
  56099. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56100. {
  56101. numColumns = 0;
  56102. contentHeight = 0;
  56103. const int maxMenuH = getParentHeight() - 24;
  56104. int totalW;
  56105. do
  56106. {
  56107. ++numColumns;
  56108. totalW = workOutBestSize (maxMenuW);
  56109. if (totalW > maxMenuW)
  56110. {
  56111. numColumns = jmax (1, numColumns - 1);
  56112. totalW = workOutBestSize (maxMenuW); // to update col widths
  56113. break;
  56114. }
  56115. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56116. {
  56117. break;
  56118. }
  56119. } while (numColumns < maximumNumColumns);
  56120. const int actualH = jmin (contentHeight, maxMenuH);
  56121. needsToScroll = contentHeight > actualH;
  56122. width = updateYPositions();
  56123. height = actualH + PopupMenuSettings::borderSize * 2;
  56124. }
  56125. int workOutBestSize (const int maxMenuW)
  56126. {
  56127. int totalW = 0;
  56128. contentHeight = 0;
  56129. int childNum = 0;
  56130. for (int col = 0; col < numColumns; ++col)
  56131. {
  56132. int i, colW = 50, colH = 0;
  56133. const int numChildren = jmin (items.size() - childNum,
  56134. (items.size() + numColumns - 1) / numColumns);
  56135. for (i = numChildren; --i >= 0;)
  56136. {
  56137. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  56138. colH += items.getUnchecked (childNum + i)->getHeight();
  56139. }
  56140. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56141. columnWidths.set (col, colW);
  56142. totalW += colW;
  56143. contentHeight = jmax (contentHeight, colH);
  56144. childNum += numChildren;
  56145. }
  56146. if (totalW < minimumWidth)
  56147. {
  56148. totalW = minimumWidth;
  56149. for (int col = 0; col < numColumns; ++col)
  56150. columnWidths.set (0, totalW / numColumns);
  56151. }
  56152. return totalW;
  56153. }
  56154. void ensureItemIsVisible (const int itemId, int wantedY)
  56155. {
  56156. jassert (itemId != 0)
  56157. for (int i = items.size(); --i >= 0;)
  56158. {
  56159. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  56160. if (m != 0
  56161. && m->itemInfo.itemId == itemId
  56162. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56163. {
  56164. const int currentY = m->getY();
  56165. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56166. {
  56167. if (wantedY < 0)
  56168. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56169. jmax (PopupMenuSettings::scrollZone,
  56170. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56171. currentY);
  56172. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56173. int deltaY = wantedY - currentY;
  56174. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56175. jmin (windowPos.getHeight(), mon.getHeight()));
  56176. const int newY = jlimit (mon.getY(),
  56177. mon.getBottom() - windowPos.getHeight(),
  56178. windowPos.getY() + deltaY);
  56179. deltaY -= newY - windowPos.getY();
  56180. childYOffset -= deltaY;
  56181. windowPos.setPosition (windowPos.getX(), newY);
  56182. updateYPositions();
  56183. }
  56184. break;
  56185. }
  56186. }
  56187. }
  56188. void resizeToBestWindowPos()
  56189. {
  56190. Rectangle<int> r (windowPos);
  56191. if (childYOffset < 0)
  56192. {
  56193. r.setBounds (r.getX(), r.getY() - childYOffset,
  56194. r.getWidth(), r.getHeight() + childYOffset);
  56195. }
  56196. else if (childYOffset > 0)
  56197. {
  56198. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56199. if (spaceAtBottom > 0)
  56200. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56201. }
  56202. setBounds (r);
  56203. updateYPositions();
  56204. }
  56205. void alterChildYPos (const int delta)
  56206. {
  56207. if (isScrolling())
  56208. {
  56209. childYOffset += delta;
  56210. if (delta < 0)
  56211. {
  56212. childYOffset = jmax (childYOffset, 0);
  56213. }
  56214. else if (delta > 0)
  56215. {
  56216. childYOffset = jmin (childYOffset,
  56217. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56218. }
  56219. updateYPositions();
  56220. }
  56221. else
  56222. {
  56223. childYOffset = 0;
  56224. }
  56225. resizeToBestWindowPos();
  56226. repaint();
  56227. }
  56228. int updateYPositions()
  56229. {
  56230. int x = 0;
  56231. int childNum = 0;
  56232. for (int col = 0; col < numColumns; ++col)
  56233. {
  56234. const int numChildren = jmin (items.size() - childNum,
  56235. (items.size() + numColumns - 1) / numColumns);
  56236. const int colW = columnWidths [col];
  56237. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56238. for (int i = 0; i < numChildren; ++i)
  56239. {
  56240. Component* const c = items.getUnchecked (childNum + i);
  56241. c->setBounds (x, y, colW, c->getHeight());
  56242. y += c->getHeight();
  56243. }
  56244. x += colW;
  56245. childNum += numChildren;
  56246. }
  56247. return x;
  56248. }
  56249. bool isScrolling() const throw()
  56250. {
  56251. return childYOffset != 0 || needsToScroll;
  56252. }
  56253. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56254. {
  56255. if (currentChild != 0)
  56256. currentChild->setHighlighted (false);
  56257. currentChild = child;
  56258. if (currentChild != 0)
  56259. {
  56260. currentChild->setHighlighted (true);
  56261. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56262. }
  56263. }
  56264. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56265. {
  56266. activeSubMenu = 0;
  56267. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56268. {
  56269. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56270. dismissOnMouseUp,
  56271. this,
  56272. childComp->getScreenBounds(),
  56273. 0, maximumNumColumns,
  56274. standardItemHeight,
  56275. false, 0, managerOfChosenCommand,
  56276. componentAttachedTo);
  56277. if (activeSubMenu != 0)
  56278. {
  56279. activeSubMenu->setVisible (true);
  56280. activeSubMenu->enterModalState (false);
  56281. activeSubMenu->toFront (false);
  56282. return true;
  56283. }
  56284. }
  56285. return false;
  56286. }
  56287. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56288. {
  56289. isOver = reallyContains (localMousePos, true);
  56290. if (isOver)
  56291. hasBeenOver = true;
  56292. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56293. {
  56294. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56295. if (disableMouseMoves && isOver)
  56296. disableMouseMoves = false;
  56297. }
  56298. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56299. return;
  56300. bool isMovingTowardsMenu = false;
  56301. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56302. {
  56303. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56304. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56305. // extends from the last mouse pos to the submenu's rectangle..
  56306. float subX = (float) activeSubMenu->getScreenX();
  56307. if (activeSubMenu->getX() > getX())
  56308. {
  56309. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56310. }
  56311. else
  56312. {
  56313. lastMouse += Point<int> (2, 0);
  56314. subX += activeSubMenu->getWidth();
  56315. }
  56316. Path areaTowardsSubMenu;
  56317. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56318. subX, (float) activeSubMenu->getScreenY(),
  56319. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56320. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56321. }
  56322. lastMouse = globalMousePos;
  56323. if (! isMovingTowardsMenu)
  56324. {
  56325. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56326. if (c == this)
  56327. c = 0;
  56328. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56329. if (mic == 0 && c != 0)
  56330. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56331. if (mic != currentChild
  56332. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56333. {
  56334. if (isOver && (c != 0) && (activeSubMenu != 0))
  56335. activeSubMenu->hide (0, true);
  56336. if (! isOver)
  56337. mic = 0;
  56338. setCurrentlyHighlightedChild (mic);
  56339. }
  56340. }
  56341. }
  56342. void triggerCurrentlyHighlightedItem()
  56343. {
  56344. if (currentChild != 0
  56345. && currentChild->itemInfo.canBeTriggered()
  56346. && (currentChild->itemInfo.customComp == 0
  56347. || currentChild->itemInfo.customComp->isTriggeredAutomatically()))
  56348. {
  56349. dismissMenu (&currentChild->itemInfo);
  56350. }
  56351. }
  56352. void selectNextItem (const int delta)
  56353. {
  56354. disableTimerUntilMouseMoves();
  56355. PopupMenu::ItemComponent* mic = 0;
  56356. bool wasLastOne = (currentChild == 0);
  56357. const int numItems = items.size();
  56358. for (int i = 0; i < numItems + 1; ++i)
  56359. {
  56360. int index = (delta > 0) ? i : (numItems - 1 - i);
  56361. index = (index + numItems) % numItems;
  56362. mic = items.getUnchecked (index);
  56363. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56364. && wasLastOne)
  56365. break;
  56366. if (mic == currentChild)
  56367. wasLastOne = true;
  56368. }
  56369. setCurrentlyHighlightedChild (mic);
  56370. }
  56371. void disableTimerUntilMouseMoves()
  56372. {
  56373. disableMouseMoves = true;
  56374. if (owner != 0)
  56375. owner->disableTimerUntilMouseMoves();
  56376. }
  56377. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Window);
  56378. };
  56379. PopupMenu::PopupMenu()
  56380. : lookAndFeel (0),
  56381. separatorPending (false)
  56382. {
  56383. }
  56384. PopupMenu::PopupMenu (const PopupMenu& other)
  56385. : lookAndFeel (other.lookAndFeel),
  56386. separatorPending (false)
  56387. {
  56388. items.addCopiesOf (other.items);
  56389. }
  56390. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56391. {
  56392. if (this != &other)
  56393. {
  56394. lookAndFeel = other.lookAndFeel;
  56395. clear();
  56396. items.addCopiesOf (other.items);
  56397. }
  56398. return *this;
  56399. }
  56400. PopupMenu::~PopupMenu()
  56401. {
  56402. clear();
  56403. }
  56404. void PopupMenu::clear()
  56405. {
  56406. items.clear();
  56407. separatorPending = false;
  56408. }
  56409. void PopupMenu::addSeparatorIfPending()
  56410. {
  56411. if (separatorPending)
  56412. {
  56413. separatorPending = false;
  56414. if (items.size() > 0)
  56415. items.add (new Item());
  56416. }
  56417. }
  56418. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56419. const bool isActive, const bool isTicked, const Image& iconToUse)
  56420. {
  56421. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56422. // didn't pick anything, so you shouldn't use it as the id
  56423. // for an item..
  56424. addSeparatorIfPending();
  56425. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56426. Colours::black, false, 0, 0, 0));
  56427. }
  56428. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56429. const int commandID,
  56430. const String& displayName)
  56431. {
  56432. jassert (commandManager != 0 && commandID != 0);
  56433. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56434. if (registeredInfo != 0)
  56435. {
  56436. ApplicationCommandInfo info (*registeredInfo);
  56437. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56438. addSeparatorIfPending();
  56439. items.add (new Item (commandID,
  56440. displayName.isNotEmpty() ? displayName
  56441. : info.shortName,
  56442. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56443. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56444. Image::null,
  56445. Colours::black,
  56446. false,
  56447. 0, 0,
  56448. commandManager));
  56449. }
  56450. }
  56451. void PopupMenu::addColouredItem (const int itemResultId,
  56452. const String& itemText,
  56453. const Colour& itemTextColour,
  56454. const bool isActive,
  56455. const bool isTicked,
  56456. const Image& iconToUse)
  56457. {
  56458. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56459. // didn't pick anything, so you shouldn't use it as the id
  56460. // for an item..
  56461. addSeparatorIfPending();
  56462. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56463. itemTextColour, true, 0, 0, 0));
  56464. }
  56465. void PopupMenu::addCustomItem (const int itemResultId, CustomComponent* const customComponent)
  56466. {
  56467. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56468. // didn't pick anything, so you shouldn't use it as the id
  56469. // for an item..
  56470. addSeparatorIfPending();
  56471. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56472. Colours::black, false, customComponent, 0, 0));
  56473. }
  56474. class NormalComponentWrapper : public PopupMenu::CustomComponent
  56475. {
  56476. public:
  56477. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56478. const bool triggerMenuItemAutomaticallyWhenClicked)
  56479. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56480. width (w), height (h)
  56481. {
  56482. addAndMakeVisible (comp);
  56483. }
  56484. void getIdealSize (int& idealWidth, int& idealHeight)
  56485. {
  56486. idealWidth = width;
  56487. idealHeight = height;
  56488. }
  56489. void resized()
  56490. {
  56491. if (getChildComponent(0) != 0)
  56492. getChildComponent(0)->setBounds (getLocalBounds());
  56493. }
  56494. private:
  56495. const int width, height;
  56496. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper);
  56497. };
  56498. void PopupMenu::addCustomItem (const int itemResultId,
  56499. Component* customComponent,
  56500. int idealWidth, int idealHeight,
  56501. const bool triggerMenuItemAutomaticallyWhenClicked)
  56502. {
  56503. addCustomItem (itemResultId,
  56504. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56505. triggerMenuItemAutomaticallyWhenClicked));
  56506. }
  56507. void PopupMenu::addSubMenu (const String& subMenuName,
  56508. const PopupMenu& subMenu,
  56509. const bool isActive,
  56510. const Image& iconToUse,
  56511. const bool isTicked)
  56512. {
  56513. addSeparatorIfPending();
  56514. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56515. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56516. }
  56517. void PopupMenu::addSeparator()
  56518. {
  56519. separatorPending = true;
  56520. }
  56521. class HeaderItemComponent : public PopupMenu::CustomComponent
  56522. {
  56523. public:
  56524. HeaderItemComponent (const String& name)
  56525. : PopupMenu::CustomComponent (false)
  56526. {
  56527. setName (name);
  56528. }
  56529. void paint (Graphics& g)
  56530. {
  56531. Font f (getLookAndFeel().getPopupMenuFont());
  56532. f.setBold (true);
  56533. g.setFont (f);
  56534. g.setColour (findColour (PopupMenu::headerTextColourId));
  56535. g.drawFittedText (getName(),
  56536. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56537. Justification::bottomLeft, 1);
  56538. }
  56539. void getIdealSize (int& idealWidth, int& idealHeight)
  56540. {
  56541. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56542. idealHeight += idealHeight / 2;
  56543. idealWidth += idealWidth / 4;
  56544. }
  56545. private:
  56546. JUCE_LEAK_DETECTOR (HeaderItemComponent);
  56547. };
  56548. void PopupMenu::addSectionHeader (const String& title)
  56549. {
  56550. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56551. }
  56552. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56553. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56554. {
  56555. public:
  56556. PopupMenuCompletionCallback()
  56557. : managerOfChosenCommand (0)
  56558. {
  56559. }
  56560. void modalStateFinished (int result)
  56561. {
  56562. if (managerOfChosenCommand != 0 && result != 0)
  56563. {
  56564. ApplicationCommandTarget::InvocationInfo info (result);
  56565. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56566. managerOfChosenCommand->invoke (info, true);
  56567. }
  56568. // (this would be the place to fade out the component, if that's what's required)
  56569. component = 0;
  56570. }
  56571. ApplicationCommandManager* managerOfChosenCommand;
  56572. ScopedPointer<Component> component;
  56573. private:
  56574. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback);
  56575. };
  56576. int PopupMenu::showMenu (const Rectangle<int>& target,
  56577. const int itemIdThatMustBeVisible,
  56578. const int minimumWidth,
  56579. const int maximumNumColumns,
  56580. const int standardItemHeight,
  56581. Component* const componentAttachedTo,
  56582. ModalComponentManager::Callback* userCallback)
  56583. {
  56584. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56585. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56586. WeakReference<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56587. Window::wasHiddenBecauseOfAppChange() = false;
  56588. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56589. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56590. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56591. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56592. standardItemHeight, ! target.isEmpty(), itemIdThatMustBeVisible,
  56593. &callback->managerOfChosenCommand, componentAttachedTo);
  56594. if (callback->component == 0)
  56595. return 0;
  56596. callback->component->enterModalState (false, userCallbackDeleter.release());
  56597. callback->component->toFront (false); // need to do this after making it modal, or it could
  56598. // be stuck behind other comps that are already modal..
  56599. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56600. callbackDeleter.release();
  56601. if (userCallback != 0)
  56602. return 0;
  56603. const int result = callback->component->runModalLoop();
  56604. if (! Window::wasHiddenBecauseOfAppChange())
  56605. {
  56606. if (prevTopLevel != 0)
  56607. prevTopLevel->toFront (true);
  56608. if (prevFocused != 0)
  56609. prevFocused->grabKeyboardFocus();
  56610. }
  56611. return result;
  56612. }
  56613. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56614. const int minimumWidth, const int maximumNumColumns,
  56615. const int standardItemHeight,
  56616. ModalComponentManager::Callback* callback)
  56617. {
  56618. return showMenu (Rectangle<int>().withPosition (Desktop::getMousePosition()),
  56619. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56620. standardItemHeight, 0, callback);
  56621. }
  56622. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  56623. const int itemIdThatMustBeVisible,
  56624. const int minimumWidth, const int maximumNumColumns,
  56625. const int standardItemHeight,
  56626. ModalComponentManager::Callback* callback)
  56627. {
  56628. return showMenu (screenAreaToAttachTo,
  56629. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56630. standardItemHeight, 0, callback);
  56631. }
  56632. int PopupMenu::showAt (Component* componentToAttachTo,
  56633. const int itemIdThatMustBeVisible,
  56634. const int minimumWidth, const int maximumNumColumns,
  56635. const int standardItemHeight,
  56636. ModalComponentManager::Callback* callback)
  56637. {
  56638. if (componentToAttachTo != 0)
  56639. {
  56640. return showMenu (componentToAttachTo->getScreenBounds(),
  56641. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56642. standardItemHeight, componentToAttachTo, callback);
  56643. }
  56644. else
  56645. {
  56646. return show (itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56647. standardItemHeight, callback);
  56648. }
  56649. }
  56650. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56651. {
  56652. const int numWindows = Window::getActiveWindows().size();
  56653. for (int i = numWindows; --i >= 0;)
  56654. {
  56655. Window* const pmw = Window::getActiveWindows()[i];
  56656. if (pmw != 0)
  56657. pmw->dismissMenu (0);
  56658. }
  56659. return numWindows > 0;
  56660. }
  56661. int PopupMenu::getNumItems() const throw()
  56662. {
  56663. int num = 0;
  56664. for (int i = items.size(); --i >= 0;)
  56665. if (! (items.getUnchecked(i))->isSeparator)
  56666. ++num;
  56667. return num;
  56668. }
  56669. bool PopupMenu::containsCommandItem (const int commandID) const
  56670. {
  56671. for (int i = items.size(); --i >= 0;)
  56672. {
  56673. const Item* mi = items.getUnchecked (i);
  56674. if ((mi->itemId == commandID && mi->commandManager != 0)
  56675. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56676. {
  56677. return true;
  56678. }
  56679. }
  56680. return false;
  56681. }
  56682. bool PopupMenu::containsAnyActiveItems() const throw()
  56683. {
  56684. for (int i = items.size(); --i >= 0;)
  56685. {
  56686. const Item* const mi = items.getUnchecked (i);
  56687. if (mi->subMenu != 0)
  56688. {
  56689. if (mi->subMenu->containsAnyActiveItems())
  56690. return true;
  56691. }
  56692. else if (mi->active)
  56693. {
  56694. return true;
  56695. }
  56696. }
  56697. return false;
  56698. }
  56699. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56700. {
  56701. lookAndFeel = newLookAndFeel;
  56702. }
  56703. PopupMenu::CustomComponent::CustomComponent (const bool isTriggeredAutomatically_)
  56704. : isHighlighted (false),
  56705. triggeredAutomatically (isTriggeredAutomatically_)
  56706. {
  56707. }
  56708. PopupMenu::CustomComponent::~CustomComponent()
  56709. {
  56710. }
  56711. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  56712. {
  56713. isHighlighted = shouldBeHighlighted;
  56714. repaint();
  56715. }
  56716. void PopupMenu::CustomComponent::triggerMenuItem()
  56717. {
  56718. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56719. if (mic != 0)
  56720. {
  56721. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56722. if (pmw != 0)
  56723. {
  56724. pmw->dismissMenu (&mic->itemInfo);
  56725. }
  56726. else
  56727. {
  56728. // something must have gone wrong with the component hierarchy if this happens..
  56729. jassertfalse;
  56730. }
  56731. }
  56732. else
  56733. {
  56734. // why isn't this component inside a menu? Not much point triggering the item if
  56735. // there's no menu.
  56736. jassertfalse;
  56737. }
  56738. }
  56739. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56740. : subMenu (0),
  56741. itemId (0),
  56742. isSeparator (false),
  56743. isTicked (false),
  56744. isEnabled (false),
  56745. isCustomComponent (false),
  56746. isSectionHeader (false),
  56747. customColour (0),
  56748. customImage (0),
  56749. menu (menu_),
  56750. index (0)
  56751. {
  56752. }
  56753. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56754. {
  56755. }
  56756. bool PopupMenu::MenuItemIterator::next()
  56757. {
  56758. if (index >= menu.items.size())
  56759. return false;
  56760. const Item* const item = menu.items.getUnchecked (index);
  56761. ++index;
  56762. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56763. subMenu = item->subMenu;
  56764. itemId = item->itemId;
  56765. isSeparator = item->isSeparator;
  56766. isTicked = item->isTicked;
  56767. isEnabled = item->active;
  56768. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <CustomComponent*> (item->customComp)) != 0;
  56769. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56770. customColour = item->usesColour ? &(item->textColour) : 0;
  56771. customImage = item->image;
  56772. commandManager = item->commandManager;
  56773. return true;
  56774. }
  56775. END_JUCE_NAMESPACE
  56776. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56777. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56778. BEGIN_JUCE_NAMESPACE
  56779. ComponentDragger::ComponentDragger()
  56780. {
  56781. }
  56782. ComponentDragger::~ComponentDragger()
  56783. {
  56784. }
  56785. void ComponentDragger::startDraggingComponent (Component* const componentToDrag, const MouseEvent& e)
  56786. {
  56787. jassert (componentToDrag != 0);
  56788. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56789. if (componentToDrag != 0)
  56790. mouseDownWithinTarget = e.getEventRelativeTo (componentToDrag).getMouseDownPosition();
  56791. }
  56792. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e,
  56793. ComponentBoundsConstrainer* const constrainer)
  56794. {
  56795. jassert (componentToDrag != 0);
  56796. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56797. if (componentToDrag != 0)
  56798. {
  56799. Rectangle<int> bounds (componentToDrag->getBounds());
  56800. // If the component is a window, multiple mouse events can get queued while it's in the same position,
  56801. // so their coordinates become wrong after the first one moves the window, so in that case, we'll use
  56802. // the current mouse position instead of the one that the event contains...
  56803. if (componentToDrag->isOnDesktop())
  56804. bounds += componentToDrag->getMouseXYRelative() - mouseDownWithinTarget;
  56805. else
  56806. bounds += e.getEventRelativeTo (componentToDrag).getPosition() - mouseDownWithinTarget;
  56807. if (constrainer != 0)
  56808. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56809. else
  56810. componentToDrag->setBounds (bounds);
  56811. }
  56812. }
  56813. END_JUCE_NAMESPACE
  56814. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56815. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56816. BEGIN_JUCE_NAMESPACE
  56817. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56818. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56819. class DragImageComponent : public Component,
  56820. public Timer
  56821. {
  56822. public:
  56823. DragImageComponent (const Image& im,
  56824. const String& desc,
  56825. Component* const sourceComponent,
  56826. Component* const mouseDragSource_,
  56827. DragAndDropContainer* const o,
  56828. const Point<int>& imageOffset_)
  56829. : image (im),
  56830. source (sourceComponent),
  56831. mouseDragSource (mouseDragSource_),
  56832. owner (o),
  56833. dragDesc (desc),
  56834. imageOffset (imageOffset_),
  56835. hasCheckedForExternalDrag (false),
  56836. drawImage (true)
  56837. {
  56838. setSize (im.getWidth(), im.getHeight());
  56839. if (mouseDragSource == 0)
  56840. mouseDragSource = source;
  56841. mouseDragSource->addMouseListener (this, false);
  56842. startTimer (200);
  56843. setInterceptsMouseClicks (false, false);
  56844. setAlwaysOnTop (true);
  56845. }
  56846. ~DragImageComponent()
  56847. {
  56848. if (owner->dragImageComponent == this)
  56849. owner->dragImageComponent.release();
  56850. if (mouseDragSource != 0)
  56851. {
  56852. mouseDragSource->removeMouseListener (this);
  56853. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56854. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56855. }
  56856. }
  56857. void paint (Graphics& g)
  56858. {
  56859. if (isOpaque())
  56860. g.fillAll (Colours::white);
  56861. if (drawImage)
  56862. {
  56863. g.setOpacity (1.0f);
  56864. g.drawImageAt (image, 0, 0);
  56865. }
  56866. }
  56867. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56868. {
  56869. Component* hit = getParentComponent();
  56870. if (hit == 0)
  56871. {
  56872. hit = Desktop::getInstance().findComponentAt (screenPos);
  56873. }
  56874. else
  56875. {
  56876. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  56877. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56878. }
  56879. // (note: use a local copy of the dragDesc member in case the callback runs
  56880. // a modal loop and deletes this object before the method completes)
  56881. const String dragDescLocal (dragDesc);
  56882. while (hit != 0)
  56883. {
  56884. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56885. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56886. {
  56887. relativePos = hit->getLocalPoint (0, screenPos);
  56888. return ddt;
  56889. }
  56890. hit = hit->getParentComponent();
  56891. }
  56892. return 0;
  56893. }
  56894. void mouseUp (const MouseEvent& e)
  56895. {
  56896. if (e.originalComponent != this)
  56897. {
  56898. if (mouseDragSource != 0)
  56899. mouseDragSource->removeMouseListener (this);
  56900. bool dropAccepted = false;
  56901. DragAndDropTarget* ddt = 0;
  56902. Point<int> relPos;
  56903. if (isVisible())
  56904. {
  56905. setVisible (false);
  56906. ddt = findTarget (e.getScreenPosition(), relPos);
  56907. // fade this component and remove it - it'll be deleted later by the timer callback
  56908. dropAccepted = ddt != 0;
  56909. setVisible (true);
  56910. if (dropAccepted || source == 0)
  56911. {
  56912. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  56913. }
  56914. else
  56915. {
  56916. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  56917. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  56918. Desktop::getInstance().getAnimator().animateComponent (this,
  56919. getBounds() + (target - ourCentre),
  56920. 0.0f, 120,
  56921. true, 1.0, 1.0);
  56922. }
  56923. }
  56924. if (getParentComponent() != 0)
  56925. getParentComponent()->removeChildComponent (this);
  56926. if (dropAccepted && ddt != 0)
  56927. {
  56928. // (note: use a local copy of the dragDesc member in case the callback runs
  56929. // a modal loop and deletes this object before the method completes)
  56930. const String dragDescLocal (dragDesc);
  56931. currentlyOverComp = 0;
  56932. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56933. }
  56934. // careful - this object could now be deleted..
  56935. }
  56936. }
  56937. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56938. {
  56939. // (note: use a local copy of the dragDesc member in case the callback runs
  56940. // a modal loop and deletes this object before it returns)
  56941. const String dragDescLocal (dragDesc);
  56942. Point<int> newPos (screenPos + imageOffset);
  56943. if (getParentComponent() != 0)
  56944. newPos = getParentComponent()->getLocalPoint (0, newPos);
  56945. //if (newX != getX() || newY != getY())
  56946. {
  56947. setTopLeftPosition (newPos.getX(), newPos.getY());
  56948. Point<int> relPos;
  56949. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56950. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56951. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56952. if (ddtComp != currentlyOverComp)
  56953. {
  56954. if (currentlyOverComp != 0 && source != 0
  56955. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56956. {
  56957. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56958. }
  56959. currentlyOverComp = ddtComp;
  56960. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56961. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56962. }
  56963. DragAndDropTarget* target = getCurrentlyOver();
  56964. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56965. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56966. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56967. {
  56968. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56969. {
  56970. hasCheckedForExternalDrag = true;
  56971. StringArray files;
  56972. bool canMoveFiles = false;
  56973. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56974. && files.size() > 0)
  56975. {
  56976. WeakReference<Component> cdw (this);
  56977. setVisible (false);
  56978. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56979. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56980. if (cdw != 0)
  56981. delete this;
  56982. return;
  56983. }
  56984. }
  56985. }
  56986. }
  56987. }
  56988. void mouseDrag (const MouseEvent& e)
  56989. {
  56990. if (e.originalComponent != this)
  56991. updateLocation (true, e.getScreenPosition());
  56992. }
  56993. void timerCallback()
  56994. {
  56995. if (source == 0)
  56996. {
  56997. delete this;
  56998. }
  56999. else if (! isMouseButtonDownAnywhere())
  57000. {
  57001. if (mouseDragSource != 0)
  57002. mouseDragSource->removeMouseListener (this);
  57003. delete this;
  57004. }
  57005. }
  57006. private:
  57007. Image image;
  57008. WeakReference<Component> source;
  57009. WeakReference<Component> mouseDragSource;
  57010. DragAndDropContainer* const owner;
  57011. WeakReference<Component> currentlyOverComp;
  57012. DragAndDropTarget* getCurrentlyOver()
  57013. {
  57014. return dynamic_cast <DragAndDropTarget*> (currentlyOverComp.get());
  57015. }
  57016. String dragDesc;
  57017. const Point<int> imageOffset;
  57018. bool hasCheckedForExternalDrag, drawImage;
  57019. JUCE_DECLARE_NON_COPYABLE (DragImageComponent);
  57020. };
  57021. DragAndDropContainer::DragAndDropContainer()
  57022. {
  57023. }
  57024. DragAndDropContainer::~DragAndDropContainer()
  57025. {
  57026. dragImageComponent = 0;
  57027. }
  57028. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57029. Component* sourceComponent,
  57030. const Image& dragImage_,
  57031. const bool allowDraggingToExternalWindows,
  57032. const Point<int>* imageOffsetFromMouse)
  57033. {
  57034. Image dragImage (dragImage_);
  57035. if (dragImageComponent == 0)
  57036. {
  57037. Component* const thisComp = dynamic_cast <Component*> (this);
  57038. if (thisComp == 0)
  57039. {
  57040. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57041. return;
  57042. }
  57043. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57044. if (draggingSource == 0 || ! draggingSource->isDragging())
  57045. {
  57046. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57047. return;
  57048. }
  57049. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57050. Point<int> imageOffset;
  57051. if (dragImage.isNull())
  57052. {
  57053. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57054. .convertedToFormat (Image::ARGB);
  57055. dragImage.multiplyAllAlphas (0.6f);
  57056. const int lo = 150;
  57057. const int hi = 400;
  57058. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  57059. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57060. for (int y = dragImage.getHeight(); --y >= 0;)
  57061. {
  57062. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57063. for (int x = dragImage.getWidth(); --x >= 0;)
  57064. {
  57065. const int dx = x - clipped.getX();
  57066. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57067. if (distance > lo)
  57068. {
  57069. const float alpha = (distance > hi) ? 0
  57070. : (hi - distance) / (float) (hi - lo)
  57071. + Random::getSystemRandom().nextFloat() * 0.008f;
  57072. dragImage.multiplyAlphaAt (x, y, alpha);
  57073. }
  57074. }
  57075. }
  57076. imageOffset = -clipped;
  57077. }
  57078. else
  57079. {
  57080. if (imageOffsetFromMouse == 0)
  57081. imageOffset = -dragImage.getBounds().getCentre();
  57082. else
  57083. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57084. }
  57085. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57086. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57087. currentDragDesc = sourceDescription;
  57088. if (allowDraggingToExternalWindows)
  57089. {
  57090. if (! Desktop::canUseSemiTransparentWindows())
  57091. dragImageComponent->setOpaque (true);
  57092. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57093. | ComponentPeer::windowIsTemporary
  57094. | ComponentPeer::windowIgnoresKeyPresses);
  57095. }
  57096. else
  57097. thisComp->addChildComponent (dragImageComponent);
  57098. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57099. dragImageComponent->setVisible (true);
  57100. }
  57101. }
  57102. bool DragAndDropContainer::isDragAndDropActive() const
  57103. {
  57104. return dragImageComponent != 0;
  57105. }
  57106. const String DragAndDropContainer::getCurrentDragDescription() const
  57107. {
  57108. return (dragImageComponent != 0) ? currentDragDesc
  57109. : String::empty;
  57110. }
  57111. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57112. {
  57113. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57114. }
  57115. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57116. {
  57117. return false;
  57118. }
  57119. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57120. {
  57121. }
  57122. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57123. {
  57124. }
  57125. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57126. {
  57127. }
  57128. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57129. {
  57130. return true;
  57131. }
  57132. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57133. {
  57134. }
  57135. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57136. {
  57137. }
  57138. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57139. {
  57140. }
  57141. END_JUCE_NAMESPACE
  57142. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57143. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57144. BEGIN_JUCE_NAMESPACE
  57145. class MouseCursor::SharedCursorHandle
  57146. {
  57147. public:
  57148. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57149. : handle (createStandardMouseCursor (type)),
  57150. refCount (1),
  57151. standardType (type),
  57152. isStandard (true)
  57153. {
  57154. }
  57155. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57156. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57157. refCount (1),
  57158. standardType (MouseCursor::NormalCursor),
  57159. isStandard (false)
  57160. {
  57161. }
  57162. ~SharedCursorHandle()
  57163. {
  57164. deleteMouseCursor (handle, isStandard);
  57165. }
  57166. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57167. {
  57168. const ScopedLock sl (getLock());
  57169. for (int i = 0; i < getCursors().size(); ++i)
  57170. {
  57171. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57172. if (sc->standardType == type)
  57173. return sc->retain();
  57174. }
  57175. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57176. getCursors().add (sc);
  57177. return sc;
  57178. }
  57179. SharedCursorHandle* retain() throw()
  57180. {
  57181. ++refCount;
  57182. return this;
  57183. }
  57184. void release()
  57185. {
  57186. if (--refCount == 0)
  57187. {
  57188. if (isStandard)
  57189. {
  57190. const ScopedLock sl (getLock());
  57191. getCursors().removeValue (this);
  57192. }
  57193. delete this;
  57194. }
  57195. }
  57196. void* getHandle() const throw() { return handle; }
  57197. private:
  57198. void* const handle;
  57199. Atomic <int> refCount;
  57200. const MouseCursor::StandardCursorType standardType;
  57201. const bool isStandard;
  57202. static CriticalSection& getLock()
  57203. {
  57204. static CriticalSection lock;
  57205. return lock;
  57206. }
  57207. static Array <SharedCursorHandle*>& getCursors()
  57208. {
  57209. static Array <SharedCursorHandle*> cursors;
  57210. return cursors;
  57211. }
  57212. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedCursorHandle);
  57213. };
  57214. MouseCursor::MouseCursor()
  57215. : cursorHandle (0)
  57216. {
  57217. }
  57218. MouseCursor::MouseCursor (const StandardCursorType type)
  57219. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57220. {
  57221. }
  57222. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57223. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57224. {
  57225. }
  57226. MouseCursor::MouseCursor (const MouseCursor& other)
  57227. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57228. {
  57229. }
  57230. MouseCursor::~MouseCursor()
  57231. {
  57232. if (cursorHandle != 0)
  57233. cursorHandle->release();
  57234. }
  57235. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57236. {
  57237. if (other.cursorHandle != 0)
  57238. other.cursorHandle->retain();
  57239. if (cursorHandle != 0)
  57240. cursorHandle->release();
  57241. cursorHandle = other.cursorHandle;
  57242. return *this;
  57243. }
  57244. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57245. {
  57246. return getHandle() == other.getHandle();
  57247. }
  57248. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57249. {
  57250. return getHandle() != other.getHandle();
  57251. }
  57252. void* MouseCursor::getHandle() const throw()
  57253. {
  57254. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57255. }
  57256. void MouseCursor::showWaitCursor()
  57257. {
  57258. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57259. }
  57260. void MouseCursor::hideWaitCursor()
  57261. {
  57262. Desktop::getInstance().getMainMouseSource().revealCursor();
  57263. }
  57264. END_JUCE_NAMESPACE
  57265. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57266. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57267. BEGIN_JUCE_NAMESPACE
  57268. MouseEvent::MouseEvent (MouseInputSource& source_,
  57269. const Point<int>& position,
  57270. const ModifierKeys& mods_,
  57271. Component* const eventComponent_,
  57272. Component* const originator,
  57273. const Time& eventTime_,
  57274. const Point<int> mouseDownPos_,
  57275. const Time& mouseDownTime_,
  57276. const int numberOfClicks_,
  57277. const bool mouseWasDragged) throw()
  57278. : x (position.getX()),
  57279. y (position.getY()),
  57280. mods (mods_),
  57281. eventComponent (eventComponent_),
  57282. originalComponent (originator),
  57283. eventTime (eventTime_),
  57284. source (source_),
  57285. mouseDownPos (mouseDownPos_),
  57286. mouseDownTime (mouseDownTime_),
  57287. numberOfClicks (numberOfClicks_),
  57288. wasMovedSinceMouseDown (mouseWasDragged)
  57289. {
  57290. }
  57291. MouseEvent::~MouseEvent() throw()
  57292. {
  57293. }
  57294. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57295. {
  57296. if (otherComponent == 0)
  57297. {
  57298. jassertfalse;
  57299. return *this;
  57300. }
  57301. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57302. mods, otherComponent, originalComponent, eventTime,
  57303. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57304. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57305. }
  57306. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57307. {
  57308. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57309. eventTime, mouseDownPos, mouseDownTime,
  57310. numberOfClicks, wasMovedSinceMouseDown);
  57311. }
  57312. bool MouseEvent::mouseWasClicked() const throw()
  57313. {
  57314. return ! wasMovedSinceMouseDown;
  57315. }
  57316. int MouseEvent::getMouseDownX() const throw()
  57317. {
  57318. return mouseDownPos.getX();
  57319. }
  57320. int MouseEvent::getMouseDownY() const throw()
  57321. {
  57322. return mouseDownPos.getY();
  57323. }
  57324. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57325. {
  57326. return mouseDownPos;
  57327. }
  57328. int MouseEvent::getDistanceFromDragStartX() const throw()
  57329. {
  57330. return x - mouseDownPos.getX();
  57331. }
  57332. int MouseEvent::getDistanceFromDragStartY() const throw()
  57333. {
  57334. return y - mouseDownPos.getY();
  57335. }
  57336. int MouseEvent::getDistanceFromDragStart() const throw()
  57337. {
  57338. return mouseDownPos.getDistanceFrom (getPosition());
  57339. }
  57340. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57341. {
  57342. return getPosition() - mouseDownPos;
  57343. }
  57344. int MouseEvent::getLengthOfMousePress() const throw()
  57345. {
  57346. if (mouseDownTime.toMilliseconds() > 0)
  57347. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57348. return 0;
  57349. }
  57350. const Point<int> MouseEvent::getPosition() const throw()
  57351. {
  57352. return Point<int> (x, y);
  57353. }
  57354. int MouseEvent::getScreenX() const
  57355. {
  57356. return getScreenPosition().getX();
  57357. }
  57358. int MouseEvent::getScreenY() const
  57359. {
  57360. return getScreenPosition().getY();
  57361. }
  57362. const Point<int> MouseEvent::getScreenPosition() const
  57363. {
  57364. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57365. }
  57366. int MouseEvent::getMouseDownScreenX() const
  57367. {
  57368. return getMouseDownScreenPosition().getX();
  57369. }
  57370. int MouseEvent::getMouseDownScreenY() const
  57371. {
  57372. return getMouseDownScreenPosition().getY();
  57373. }
  57374. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57375. {
  57376. return eventComponent->localPointToGlobal (mouseDownPos);
  57377. }
  57378. int MouseEvent::doubleClickTimeOutMs = 400;
  57379. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57380. {
  57381. doubleClickTimeOutMs = newTime;
  57382. }
  57383. int MouseEvent::getDoubleClickTimeout() throw()
  57384. {
  57385. return doubleClickTimeOutMs;
  57386. }
  57387. END_JUCE_NAMESPACE
  57388. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57389. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57390. BEGIN_JUCE_NAMESPACE
  57391. class MouseInputSourceInternal : public AsyncUpdater
  57392. {
  57393. public:
  57394. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57395. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57396. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57397. mouseEventCounter (0)
  57398. {
  57399. }
  57400. bool isDragging() const throw()
  57401. {
  57402. return buttonState.isAnyMouseButtonDown();
  57403. }
  57404. Component* getComponentUnderMouse() const
  57405. {
  57406. return static_cast <Component*> (componentUnderMouse);
  57407. }
  57408. const ModifierKeys getCurrentModifiers() const
  57409. {
  57410. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57411. }
  57412. ComponentPeer* getPeer()
  57413. {
  57414. if (! ComponentPeer::isValidPeer (lastPeer))
  57415. lastPeer = 0;
  57416. return lastPeer;
  57417. }
  57418. Component* findComponentAt (const Point<int>& screenPos)
  57419. {
  57420. ComponentPeer* const peer = getPeer();
  57421. if (peer != 0)
  57422. {
  57423. Component* const comp = peer->getComponent();
  57424. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57425. // (the contains() call is needed to test for overlapping desktop windows)
  57426. if (comp->contains (relativePos))
  57427. return comp->getComponentAt (relativePos);
  57428. }
  57429. return 0;
  57430. }
  57431. const Point<int> getScreenPosition() const
  57432. {
  57433. // This needs to return the live position if possible, but it mustn't update the lastScreenPos
  57434. // value, because that can cause continuity problems.
  57435. return unboundedMouseOffset + (isMouseDevice ? MouseInputSource::getCurrentMousePosition()
  57436. : lastScreenPos);
  57437. }
  57438. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const Time& time)
  57439. {
  57440. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57441. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57442. }
  57443. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const Time& time)
  57444. {
  57445. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57446. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57447. }
  57448. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const Time& time)
  57449. {
  57450. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57451. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57452. }
  57453. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const Time& time)
  57454. {
  57455. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57456. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57457. }
  57458. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const Time& time)
  57459. {
  57460. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57461. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57462. }
  57463. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const Time& time)
  57464. {
  57465. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57466. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57467. }
  57468. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const Time& time, float x, float y)
  57469. {
  57470. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57471. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57472. }
  57473. // (returns true if the button change caused a modal event loop)
  57474. bool setButtons (const Point<int>& screenPos, const Time& time, const ModifierKeys& newButtonState)
  57475. {
  57476. if (buttonState == newButtonState)
  57477. return false;
  57478. setScreenPos (screenPos, time, false);
  57479. // (ignore secondary clicks when there's already a button down)
  57480. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57481. {
  57482. buttonState = newButtonState;
  57483. return false;
  57484. }
  57485. const int lastCounter = mouseEventCounter;
  57486. if (buttonState.isAnyMouseButtonDown())
  57487. {
  57488. Component* const current = getComponentUnderMouse();
  57489. if (current != 0)
  57490. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57491. enableUnboundedMouseMovement (false, false);
  57492. }
  57493. buttonState = newButtonState;
  57494. if (buttonState.isAnyMouseButtonDown())
  57495. {
  57496. Desktop::getInstance().incrementMouseClickCounter();
  57497. Component* const current = getComponentUnderMouse();
  57498. if (current != 0)
  57499. {
  57500. registerMouseDown (screenPos, time, current, buttonState);
  57501. sendMouseDown (current, screenPos, time);
  57502. }
  57503. }
  57504. return lastCounter != mouseEventCounter;
  57505. }
  57506. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const Time& time)
  57507. {
  57508. Component* current = getComponentUnderMouse();
  57509. if (newComponent != current)
  57510. {
  57511. WeakReference<Component> safeNewComp (newComponent);
  57512. const ModifierKeys originalButtonState (buttonState);
  57513. if (current != 0)
  57514. {
  57515. setButtons (screenPos, time, ModifierKeys());
  57516. sendMouseExit (current, screenPos, time);
  57517. buttonState = originalButtonState;
  57518. }
  57519. componentUnderMouse = safeNewComp;
  57520. current = getComponentUnderMouse();
  57521. if (current != 0)
  57522. sendMouseEnter (current, screenPos, time);
  57523. revealCursor (false);
  57524. setButtons (screenPos, time, originalButtonState);
  57525. }
  57526. }
  57527. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const Time& time)
  57528. {
  57529. ModifierKeys::updateCurrentModifiers();
  57530. if (newPeer != lastPeer)
  57531. {
  57532. setComponentUnderMouse (0, screenPos, time);
  57533. lastPeer = newPeer;
  57534. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57535. }
  57536. }
  57537. void setScreenPos (const Point<int>& newScreenPos, const Time& time, const bool forceUpdate)
  57538. {
  57539. if (! isDragging())
  57540. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57541. if (newScreenPos != lastScreenPos || forceUpdate)
  57542. {
  57543. cancelPendingUpdate();
  57544. lastScreenPos = newScreenPos;
  57545. Component* const current = getComponentUnderMouse();
  57546. if (current != 0)
  57547. {
  57548. if (isDragging())
  57549. {
  57550. registerMouseDrag (newScreenPos);
  57551. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57552. if (isUnboundedMouseModeOn)
  57553. handleUnboundedDrag (current);
  57554. }
  57555. else
  57556. {
  57557. sendMouseMove (current, newScreenPos, time);
  57558. }
  57559. }
  57560. revealCursor (false);
  57561. }
  57562. }
  57563. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const Time& time, const ModifierKeys& newMods)
  57564. {
  57565. jassert (newPeer != 0);
  57566. lastTime = time;
  57567. ++mouseEventCounter;
  57568. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57569. if (isDragging() && newMods.isAnyMouseButtonDown())
  57570. {
  57571. setScreenPos (screenPos, time, false);
  57572. }
  57573. else
  57574. {
  57575. setPeer (newPeer, screenPos, time);
  57576. ComponentPeer* peer = getPeer();
  57577. if (peer != 0)
  57578. {
  57579. if (setButtons (screenPos, time, newMods))
  57580. return; // some modal events have been dispatched, so the current event is now out-of-date
  57581. peer = getPeer();
  57582. if (peer != 0)
  57583. setScreenPos (screenPos, time, false);
  57584. }
  57585. }
  57586. }
  57587. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const Time& time, float x, float y)
  57588. {
  57589. jassert (peer != 0);
  57590. lastTime = time;
  57591. ++mouseEventCounter;
  57592. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57593. setPeer (peer, screenPos, time);
  57594. setScreenPos (screenPos, time, false);
  57595. triggerFakeMove();
  57596. if (! isDragging())
  57597. {
  57598. Component* current = getComponentUnderMouse();
  57599. if (current != 0)
  57600. sendMouseWheel (current, screenPos, time, x, y);
  57601. }
  57602. }
  57603. const Time getLastMouseDownTime() const throw()
  57604. {
  57605. return Time (mouseDowns[0].time);
  57606. }
  57607. const Point<int> getLastMouseDownPosition() const throw()
  57608. {
  57609. return mouseDowns[0].position;
  57610. }
  57611. int getNumberOfMultipleClicks() const throw()
  57612. {
  57613. int numClicks = 0;
  57614. if (mouseDowns[0].time != Time())
  57615. {
  57616. if (! mouseMovedSignificantlySincePressed)
  57617. ++numClicks;
  57618. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57619. {
  57620. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57621. ++numClicks;
  57622. else
  57623. break;
  57624. }
  57625. }
  57626. return numClicks;
  57627. }
  57628. bool hasMouseMovedSignificantlySincePressed() const throw()
  57629. {
  57630. return mouseMovedSignificantlySincePressed
  57631. || lastTime > mouseDowns[0].time + RelativeTime::milliseconds (300);
  57632. }
  57633. void triggerFakeMove()
  57634. {
  57635. triggerAsyncUpdate();
  57636. }
  57637. void handleAsyncUpdate()
  57638. {
  57639. setScreenPos (lastScreenPos, jmax (lastTime, Time::getCurrentTime()), true);
  57640. }
  57641. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57642. {
  57643. enable = enable && isDragging();
  57644. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57645. if (enable != isUnboundedMouseModeOn)
  57646. {
  57647. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57648. {
  57649. // when released, return the mouse to within the component's bounds
  57650. Component* current = getComponentUnderMouse();
  57651. if (current != 0)
  57652. Desktop::setMousePosition (current->getScreenBounds()
  57653. .getConstrainedPoint (lastScreenPos));
  57654. }
  57655. isUnboundedMouseModeOn = enable;
  57656. unboundedMouseOffset = Point<int>();
  57657. revealCursor (true);
  57658. }
  57659. }
  57660. void handleUnboundedDrag (Component* current)
  57661. {
  57662. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57663. if (! screenArea.contains (lastScreenPos))
  57664. {
  57665. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57666. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57667. Desktop::setMousePosition (componentCentre);
  57668. }
  57669. else if (isCursorVisibleUntilOffscreen
  57670. && (! unboundedMouseOffset.isOrigin())
  57671. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57672. {
  57673. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57674. unboundedMouseOffset = Point<int>();
  57675. }
  57676. }
  57677. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57678. {
  57679. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57680. {
  57681. cursor = MouseCursor::NoCursor;
  57682. forcedUpdate = true;
  57683. }
  57684. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57685. {
  57686. currentCursorHandle = cursor.getHandle();
  57687. cursor.showInWindow (getPeer());
  57688. }
  57689. }
  57690. void hideCursor()
  57691. {
  57692. showMouseCursor (MouseCursor::NoCursor, true);
  57693. }
  57694. void revealCursor (bool forcedUpdate)
  57695. {
  57696. MouseCursor mc (MouseCursor::NormalCursor);
  57697. Component* current = getComponentUnderMouse();
  57698. if (current != 0)
  57699. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57700. showMouseCursor (mc, forcedUpdate);
  57701. }
  57702. const int index;
  57703. const bool isMouseDevice;
  57704. Point<int> lastScreenPos;
  57705. ModifierKeys buttonState;
  57706. private:
  57707. MouseInputSource& source;
  57708. WeakReference<Component> componentUnderMouse;
  57709. ComponentPeer* lastPeer;
  57710. Point<int> unboundedMouseOffset;
  57711. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57712. void* currentCursorHandle;
  57713. int mouseEventCounter;
  57714. struct RecentMouseDown
  57715. {
  57716. RecentMouseDown() : component (0)
  57717. {
  57718. }
  57719. Point<int> position;
  57720. Time time;
  57721. Component* component;
  57722. ModifierKeys buttons;
  57723. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, const int maxTimeBetweenMs) const
  57724. {
  57725. return time - other.time < RelativeTime::milliseconds (maxTimeBetweenMs)
  57726. && abs (position.getX() - other.position.getX()) < 8
  57727. && abs (position.getY() - other.position.getY()) < 8
  57728. && buttons == other.buttons;;
  57729. }
  57730. };
  57731. RecentMouseDown mouseDowns[4];
  57732. bool mouseMovedSignificantlySincePressed;
  57733. Time lastTime;
  57734. void registerMouseDown (const Point<int>& screenPos, const Time& time,
  57735. Component* const component, const ModifierKeys& modifiers) throw()
  57736. {
  57737. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57738. mouseDowns[i] = mouseDowns[i - 1];
  57739. mouseDowns[0].position = screenPos;
  57740. mouseDowns[0].time = time;
  57741. mouseDowns[0].component = component;
  57742. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57743. mouseMovedSignificantlySincePressed = false;
  57744. }
  57745. void registerMouseDrag (const Point<int>& screenPos) throw()
  57746. {
  57747. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57748. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57749. }
  57750. JUCE_DECLARE_NON_COPYABLE (MouseInputSourceInternal);
  57751. };
  57752. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57753. {
  57754. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57755. }
  57756. MouseInputSource::~MouseInputSource()
  57757. {
  57758. }
  57759. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57760. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57761. bool MouseInputSource::canHover() const { return isMouse(); }
  57762. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57763. int MouseInputSource::getIndex() const { return pimpl->index; }
  57764. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57765. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57766. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57767. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57768. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57769. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57770. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57771. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57772. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57773. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57774. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57775. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57776. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57777. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57778. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57779. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57780. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57781. {
  57782. pimpl->handleEvent (peer, positionWithinPeer, Time (time), mods.withOnlyMouseButtons());
  57783. }
  57784. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57785. {
  57786. pimpl->handleWheel (peer, positionWithinPeer, Time (time), x, y);
  57787. }
  57788. END_JUCE_NAMESPACE
  57789. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57790. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57791. BEGIN_JUCE_NAMESPACE
  57792. void MouseListener::mouseEnter (const MouseEvent&)
  57793. {
  57794. }
  57795. void MouseListener::mouseExit (const MouseEvent&)
  57796. {
  57797. }
  57798. void MouseListener::mouseDown (const MouseEvent&)
  57799. {
  57800. }
  57801. void MouseListener::mouseUp (const MouseEvent&)
  57802. {
  57803. }
  57804. void MouseListener::mouseDrag (const MouseEvent&)
  57805. {
  57806. }
  57807. void MouseListener::mouseMove (const MouseEvent&)
  57808. {
  57809. }
  57810. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57811. {
  57812. }
  57813. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57814. {
  57815. }
  57816. END_JUCE_NAMESPACE
  57817. /*** End of inlined file: juce_MouseListener.cpp ***/
  57818. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57819. BEGIN_JUCE_NAMESPACE
  57820. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57821. const String& buttonTextWhenTrue,
  57822. const String& buttonTextWhenFalse)
  57823. : PropertyComponent (name),
  57824. onText (buttonTextWhenTrue),
  57825. offText (buttonTextWhenFalse)
  57826. {
  57827. addAndMakeVisible (&button);
  57828. button.setClickingTogglesState (false);
  57829. button.addListener (this);
  57830. }
  57831. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57832. const String& name,
  57833. const String& buttonText)
  57834. : PropertyComponent (name),
  57835. onText (buttonText),
  57836. offText (buttonText)
  57837. {
  57838. addAndMakeVisible (&button);
  57839. button.setClickingTogglesState (false);
  57840. button.setButtonText (buttonText);
  57841. button.getToggleStateValue().referTo (valueToControl);
  57842. button.setClickingTogglesState (true);
  57843. }
  57844. BooleanPropertyComponent::~BooleanPropertyComponent()
  57845. {
  57846. }
  57847. void BooleanPropertyComponent::setState (const bool newState)
  57848. {
  57849. button.setToggleState (newState, true);
  57850. }
  57851. bool BooleanPropertyComponent::getState() const
  57852. {
  57853. return button.getToggleState();
  57854. }
  57855. void BooleanPropertyComponent::paint (Graphics& g)
  57856. {
  57857. PropertyComponent::paint (g);
  57858. g.setColour (Colours::white);
  57859. g.fillRect (button.getBounds());
  57860. g.setColour (findColour (ComboBox::outlineColourId));
  57861. g.drawRect (button.getBounds());
  57862. }
  57863. void BooleanPropertyComponent::refresh()
  57864. {
  57865. button.setToggleState (getState(), false);
  57866. button.setButtonText (button.getToggleState() ? onText : offText);
  57867. }
  57868. void BooleanPropertyComponent::buttonClicked (Button*)
  57869. {
  57870. setState (! getState());
  57871. }
  57872. END_JUCE_NAMESPACE
  57873. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57874. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57875. BEGIN_JUCE_NAMESPACE
  57876. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57877. const bool triggerOnMouseDown)
  57878. : PropertyComponent (name)
  57879. {
  57880. addAndMakeVisible (&button);
  57881. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57882. button.addListener (this);
  57883. }
  57884. ButtonPropertyComponent::~ButtonPropertyComponent()
  57885. {
  57886. }
  57887. void ButtonPropertyComponent::refresh()
  57888. {
  57889. button.setButtonText (getButtonText());
  57890. }
  57891. void ButtonPropertyComponent::buttonClicked (Button*)
  57892. {
  57893. buttonClicked();
  57894. }
  57895. END_JUCE_NAMESPACE
  57896. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57897. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57898. BEGIN_JUCE_NAMESPACE
  57899. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57900. public ValueListener
  57901. {
  57902. public:
  57903. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57904. : sourceValue (sourceValue_),
  57905. mappings (mappings_)
  57906. {
  57907. sourceValue.addListener (this);
  57908. }
  57909. ~RemapperValueSource() {}
  57910. const var getValue() const
  57911. {
  57912. return mappings.indexOf (sourceValue.getValue()) + 1;
  57913. }
  57914. void setValue (const var& newValue)
  57915. {
  57916. const var remappedVal (mappings [(int) newValue - 1]);
  57917. if (remappedVal != sourceValue)
  57918. sourceValue = remappedVal;
  57919. }
  57920. void valueChanged (Value&)
  57921. {
  57922. sendChangeMessage (true);
  57923. }
  57924. protected:
  57925. Value sourceValue;
  57926. Array<var> mappings;
  57927. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RemapperValueSource);
  57928. };
  57929. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57930. : PropertyComponent (name),
  57931. isCustomClass (true)
  57932. {
  57933. }
  57934. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57935. const String& name,
  57936. const StringArray& choices_,
  57937. const Array <var>& correspondingValues)
  57938. : PropertyComponent (name),
  57939. choices (choices_),
  57940. isCustomClass (false)
  57941. {
  57942. // The array of corresponding values must contain one value for each of the items in
  57943. // the choices array!
  57944. jassert (correspondingValues.size() == choices.size());
  57945. createComboBox();
  57946. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57947. }
  57948. ChoicePropertyComponent::~ChoicePropertyComponent()
  57949. {
  57950. }
  57951. void ChoicePropertyComponent::createComboBox()
  57952. {
  57953. addAndMakeVisible (&comboBox);
  57954. for (int i = 0; i < choices.size(); ++i)
  57955. {
  57956. if (choices[i].isNotEmpty())
  57957. comboBox.addItem (choices[i], i + 1);
  57958. else
  57959. comboBox.addSeparator();
  57960. }
  57961. comboBox.setEditableText (false);
  57962. }
  57963. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57964. {
  57965. jassertfalse; // you need to override this method in your subclass!
  57966. }
  57967. int ChoicePropertyComponent::getIndex() const
  57968. {
  57969. jassertfalse; // you need to override this method in your subclass!
  57970. return -1;
  57971. }
  57972. const StringArray& ChoicePropertyComponent::getChoices() const
  57973. {
  57974. return choices;
  57975. }
  57976. void ChoicePropertyComponent::refresh()
  57977. {
  57978. if (isCustomClass)
  57979. {
  57980. if (! comboBox.isVisible())
  57981. {
  57982. createComboBox();
  57983. comboBox.addListener (this);
  57984. }
  57985. comboBox.setSelectedId (getIndex() + 1, true);
  57986. }
  57987. }
  57988. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57989. {
  57990. if (isCustomClass)
  57991. {
  57992. const int newIndex = comboBox.getSelectedId() - 1;
  57993. if (newIndex != getIndex())
  57994. setIndex (newIndex);
  57995. }
  57996. }
  57997. END_JUCE_NAMESPACE
  57998. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57999. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58000. BEGIN_JUCE_NAMESPACE
  58001. PropertyComponent::PropertyComponent (const String& name,
  58002. const int preferredHeight_)
  58003. : Component (name),
  58004. preferredHeight (preferredHeight_)
  58005. {
  58006. jassert (name.isNotEmpty());
  58007. }
  58008. PropertyComponent::~PropertyComponent()
  58009. {
  58010. }
  58011. void PropertyComponent::paint (Graphics& g)
  58012. {
  58013. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58014. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58015. }
  58016. void PropertyComponent::resized()
  58017. {
  58018. if (getNumChildComponents() > 0)
  58019. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58020. }
  58021. void PropertyComponent::enablementChanged()
  58022. {
  58023. repaint();
  58024. }
  58025. END_JUCE_NAMESPACE
  58026. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58027. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58028. BEGIN_JUCE_NAMESPACE
  58029. class PropertySectionComponent : public Component
  58030. {
  58031. public:
  58032. PropertySectionComponent (const String& sectionTitle,
  58033. const Array <PropertyComponent*>& newProperties,
  58034. const bool sectionIsOpen_)
  58035. : Component (sectionTitle),
  58036. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58037. sectionIsOpen (sectionIsOpen_)
  58038. {
  58039. propertyComps.addArray (newProperties);
  58040. for (int i = propertyComps.size(); --i >= 0;)
  58041. {
  58042. addAndMakeVisible (propertyComps.getUnchecked(i));
  58043. propertyComps.getUnchecked(i)->refresh();
  58044. }
  58045. }
  58046. ~PropertySectionComponent()
  58047. {
  58048. propertyComps.clear();
  58049. }
  58050. void paint (Graphics& g)
  58051. {
  58052. if (titleHeight > 0)
  58053. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58054. }
  58055. void resized()
  58056. {
  58057. int y = titleHeight;
  58058. for (int i = 0; i < propertyComps.size(); ++i)
  58059. {
  58060. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  58061. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  58062. y = pec->getBottom();
  58063. }
  58064. }
  58065. int getPreferredHeight() const
  58066. {
  58067. int y = titleHeight;
  58068. if (isOpen())
  58069. {
  58070. for (int i = propertyComps.size(); --i >= 0;)
  58071. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  58072. }
  58073. return y;
  58074. }
  58075. void setOpen (const bool open)
  58076. {
  58077. if (sectionIsOpen != open)
  58078. {
  58079. sectionIsOpen = open;
  58080. for (int i = propertyComps.size(); --i >= 0;)
  58081. propertyComps.getUnchecked(i)->setVisible (open);
  58082. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58083. if (pp != 0)
  58084. pp->resized();
  58085. }
  58086. }
  58087. bool isOpen() const
  58088. {
  58089. return sectionIsOpen;
  58090. }
  58091. void refreshAll() const
  58092. {
  58093. for (int i = propertyComps.size(); --i >= 0;)
  58094. propertyComps.getUnchecked (i)->refresh();
  58095. }
  58096. void mouseUp (const MouseEvent& e)
  58097. {
  58098. if (e.getMouseDownX() < titleHeight
  58099. && e.x < titleHeight
  58100. && e.y < titleHeight
  58101. && e.getNumberOfClicks() != 2)
  58102. {
  58103. setOpen (! isOpen());
  58104. }
  58105. }
  58106. void mouseDoubleClick (const MouseEvent& e)
  58107. {
  58108. if (e.y < titleHeight)
  58109. setOpen (! isOpen());
  58110. }
  58111. private:
  58112. OwnedArray <PropertyComponent> propertyComps;
  58113. int titleHeight;
  58114. bool sectionIsOpen;
  58115. JUCE_DECLARE_NON_COPYABLE (PropertySectionComponent);
  58116. };
  58117. class PropertyPanel::PropertyHolderComponent : public Component
  58118. {
  58119. public:
  58120. PropertyHolderComponent() {}
  58121. void paint (Graphics&) {}
  58122. void updateLayout (int width)
  58123. {
  58124. int y = 0;
  58125. for (int i = 0; i < sections.size(); ++i)
  58126. {
  58127. PropertySectionComponent* const section = sections.getUnchecked(i);
  58128. section->setBounds (0, y, width, section->getPreferredHeight());
  58129. y = section->getBottom();
  58130. }
  58131. setSize (width, y);
  58132. repaint();
  58133. }
  58134. void refreshAll() const
  58135. {
  58136. for (int i = 0; i < sections.size(); ++i)
  58137. sections.getUnchecked(i)->refreshAll();
  58138. }
  58139. void clear()
  58140. {
  58141. sections.clear();
  58142. }
  58143. void addSection (PropertySectionComponent* newSection)
  58144. {
  58145. sections.add (newSection);
  58146. addAndMakeVisible (newSection, 0);
  58147. }
  58148. int getNumSections() const throw() { return sections.size(); }
  58149. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  58150. private:
  58151. OwnedArray<PropertySectionComponent> sections;
  58152. JUCE_DECLARE_NON_COPYABLE (PropertyHolderComponent);
  58153. };
  58154. PropertyPanel::PropertyPanel()
  58155. {
  58156. messageWhenEmpty = TRANS("(nothing selected)");
  58157. addAndMakeVisible (&viewport);
  58158. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58159. viewport.setFocusContainer (true);
  58160. }
  58161. PropertyPanel::~PropertyPanel()
  58162. {
  58163. clear();
  58164. }
  58165. void PropertyPanel::paint (Graphics& g)
  58166. {
  58167. if (propertyHolderComponent->getNumSections() == 0)
  58168. {
  58169. g.setColour (Colours::black.withAlpha (0.5f));
  58170. g.setFont (14.0f);
  58171. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58172. Justification::centred, true);
  58173. }
  58174. }
  58175. void PropertyPanel::resized()
  58176. {
  58177. viewport.setBounds (getLocalBounds());
  58178. updatePropHolderLayout();
  58179. }
  58180. void PropertyPanel::clear()
  58181. {
  58182. if (propertyHolderComponent->getNumSections() > 0)
  58183. {
  58184. propertyHolderComponent->clear();
  58185. repaint();
  58186. }
  58187. }
  58188. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58189. {
  58190. if (propertyHolderComponent->getNumSections() == 0)
  58191. repaint();
  58192. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58193. updatePropHolderLayout();
  58194. }
  58195. void PropertyPanel::addSection (const String& sectionTitle,
  58196. const Array <PropertyComponent*>& newProperties,
  58197. const bool shouldBeOpen)
  58198. {
  58199. jassert (sectionTitle.isNotEmpty());
  58200. if (propertyHolderComponent->getNumSections() == 0)
  58201. repaint();
  58202. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58203. updatePropHolderLayout();
  58204. }
  58205. void PropertyPanel::updatePropHolderLayout() const
  58206. {
  58207. const int maxWidth = viewport.getMaximumVisibleWidth();
  58208. propertyHolderComponent->updateLayout (maxWidth);
  58209. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58210. if (maxWidth != newMaxWidth)
  58211. {
  58212. // need to do this twice because of scrollbars changing the size, etc.
  58213. propertyHolderComponent->updateLayout (newMaxWidth);
  58214. }
  58215. }
  58216. void PropertyPanel::refreshAll() const
  58217. {
  58218. propertyHolderComponent->refreshAll();
  58219. }
  58220. const StringArray PropertyPanel::getSectionNames() const
  58221. {
  58222. StringArray s;
  58223. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58224. {
  58225. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58226. if (section->getName().isNotEmpty())
  58227. s.add (section->getName());
  58228. }
  58229. return s;
  58230. }
  58231. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58232. {
  58233. int index = 0;
  58234. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58235. {
  58236. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58237. if (section->getName().isNotEmpty())
  58238. {
  58239. if (index == sectionIndex)
  58240. return section->isOpen();
  58241. ++index;
  58242. }
  58243. }
  58244. return false;
  58245. }
  58246. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58247. {
  58248. int index = 0;
  58249. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58250. {
  58251. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58252. if (section->getName().isNotEmpty())
  58253. {
  58254. if (index == sectionIndex)
  58255. {
  58256. section->setOpen (shouldBeOpen);
  58257. break;
  58258. }
  58259. ++index;
  58260. }
  58261. }
  58262. }
  58263. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58264. {
  58265. int index = 0;
  58266. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58267. {
  58268. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58269. if (section->getName().isNotEmpty())
  58270. {
  58271. if (index == sectionIndex)
  58272. {
  58273. section->setEnabled (shouldBeEnabled);
  58274. break;
  58275. }
  58276. ++index;
  58277. }
  58278. }
  58279. }
  58280. XmlElement* PropertyPanel::getOpennessState() const
  58281. {
  58282. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58283. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58284. const StringArray sections (getSectionNames());
  58285. for (int i = 0; i < sections.size(); ++i)
  58286. {
  58287. if (sections[i].isNotEmpty())
  58288. {
  58289. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58290. e->setAttribute ("name", sections[i]);
  58291. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58292. }
  58293. }
  58294. return xml;
  58295. }
  58296. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58297. {
  58298. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58299. {
  58300. const StringArray sections (getSectionNames());
  58301. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58302. {
  58303. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58304. e->getBoolAttribute ("open"));
  58305. }
  58306. viewport.setViewPosition (viewport.getViewPositionX(),
  58307. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58308. }
  58309. }
  58310. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58311. {
  58312. if (messageWhenEmpty != newMessage)
  58313. {
  58314. messageWhenEmpty = newMessage;
  58315. repaint();
  58316. }
  58317. }
  58318. const String& PropertyPanel::getMessageWhenEmpty() const
  58319. {
  58320. return messageWhenEmpty;
  58321. }
  58322. END_JUCE_NAMESPACE
  58323. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58324. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58325. BEGIN_JUCE_NAMESPACE
  58326. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58327. const double rangeMin,
  58328. const double rangeMax,
  58329. const double interval,
  58330. const double skewFactor)
  58331. : PropertyComponent (name)
  58332. {
  58333. addAndMakeVisible (&slider);
  58334. slider.setRange (rangeMin, rangeMax, interval);
  58335. slider.setSkewFactor (skewFactor);
  58336. slider.setSliderStyle (Slider::LinearBar);
  58337. slider.addListener (this);
  58338. }
  58339. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58340. const String& name,
  58341. const double rangeMin,
  58342. const double rangeMax,
  58343. const double interval,
  58344. const double skewFactor)
  58345. : PropertyComponent (name)
  58346. {
  58347. addAndMakeVisible (&slider);
  58348. slider.setRange (rangeMin, rangeMax, interval);
  58349. slider.setSkewFactor (skewFactor);
  58350. slider.setSliderStyle (Slider::LinearBar);
  58351. slider.getValueObject().referTo (valueToControl);
  58352. }
  58353. SliderPropertyComponent::~SliderPropertyComponent()
  58354. {
  58355. }
  58356. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58357. {
  58358. }
  58359. double SliderPropertyComponent::getValue() const
  58360. {
  58361. return slider.getValue();
  58362. }
  58363. void SliderPropertyComponent::refresh()
  58364. {
  58365. slider.setValue (getValue(), false);
  58366. }
  58367. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58368. {
  58369. if (getValue() != slider.getValue())
  58370. setValue (slider.getValue());
  58371. }
  58372. END_JUCE_NAMESPACE
  58373. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58374. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58375. BEGIN_JUCE_NAMESPACE
  58376. class TextPropLabel : public Label
  58377. {
  58378. public:
  58379. TextPropLabel (TextPropertyComponent& owner_,
  58380. const int maxChars_, const bool isMultiline_)
  58381. : Label (String::empty, String::empty),
  58382. owner (owner_),
  58383. maxChars (maxChars_),
  58384. isMultiline (isMultiline_)
  58385. {
  58386. setEditable (true, true, false);
  58387. setColour (backgroundColourId, Colours::white);
  58388. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58389. }
  58390. TextEditor* createEditorComponent()
  58391. {
  58392. TextEditor* const textEditor = Label::createEditorComponent();
  58393. textEditor->setInputRestrictions (maxChars);
  58394. if (isMultiline)
  58395. {
  58396. textEditor->setMultiLine (true, true);
  58397. textEditor->setReturnKeyStartsNewLine (true);
  58398. }
  58399. return textEditor;
  58400. }
  58401. void textWasEdited()
  58402. {
  58403. owner.textWasEdited();
  58404. }
  58405. private:
  58406. TextPropertyComponent& owner;
  58407. int maxChars;
  58408. bool isMultiline;
  58409. };
  58410. TextPropertyComponent::TextPropertyComponent (const String& name,
  58411. const int maxNumChars,
  58412. const bool isMultiLine)
  58413. : PropertyComponent (name)
  58414. {
  58415. createEditor (maxNumChars, isMultiLine);
  58416. }
  58417. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58418. const String& name,
  58419. const int maxNumChars,
  58420. const bool isMultiLine)
  58421. : PropertyComponent (name)
  58422. {
  58423. createEditor (maxNumChars, isMultiLine);
  58424. textEditor->getTextValue().referTo (valueToControl);
  58425. }
  58426. TextPropertyComponent::~TextPropertyComponent()
  58427. {
  58428. }
  58429. void TextPropertyComponent::setText (const String& newText)
  58430. {
  58431. textEditor->setText (newText, true);
  58432. }
  58433. const String TextPropertyComponent::getText() const
  58434. {
  58435. return textEditor->getText();
  58436. }
  58437. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58438. {
  58439. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58440. if (isMultiLine)
  58441. {
  58442. textEditor->setJustificationType (Justification::topLeft);
  58443. preferredHeight = 120;
  58444. }
  58445. }
  58446. void TextPropertyComponent::refresh()
  58447. {
  58448. textEditor->setText (getText(), false);
  58449. }
  58450. void TextPropertyComponent::textWasEdited()
  58451. {
  58452. const String newText (textEditor->getText());
  58453. if (getText() != newText)
  58454. setText (newText);
  58455. }
  58456. END_JUCE_NAMESPACE
  58457. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58458. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58459. BEGIN_JUCE_NAMESPACE
  58460. class SimpleDeviceManagerInputLevelMeter : public Component,
  58461. public Timer
  58462. {
  58463. public:
  58464. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58465. : manager (manager_),
  58466. level (0)
  58467. {
  58468. startTimer (50);
  58469. manager->enableInputLevelMeasurement (true);
  58470. }
  58471. ~SimpleDeviceManagerInputLevelMeter()
  58472. {
  58473. manager->enableInputLevelMeasurement (false);
  58474. }
  58475. void timerCallback()
  58476. {
  58477. const float newLevel = (float) manager->getCurrentInputLevel();
  58478. if (std::abs (level - newLevel) > 0.005f)
  58479. {
  58480. level = newLevel;
  58481. repaint();
  58482. }
  58483. }
  58484. void paint (Graphics& g)
  58485. {
  58486. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58487. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58488. }
  58489. private:
  58490. AudioDeviceManager* const manager;
  58491. float level;
  58492. JUCE_DECLARE_NON_COPYABLE (SimpleDeviceManagerInputLevelMeter);
  58493. };
  58494. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58495. public ListBoxModel
  58496. {
  58497. public:
  58498. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58499. const String& noItemsMessage_,
  58500. const int minNumber_,
  58501. const int maxNumber_)
  58502. : ListBox (String::empty, 0),
  58503. deviceManager (deviceManager_),
  58504. noItemsMessage (noItemsMessage_),
  58505. minNumber (minNumber_),
  58506. maxNumber (maxNumber_)
  58507. {
  58508. items = MidiInput::getDevices();
  58509. setModel (this);
  58510. setOutlineThickness (1);
  58511. }
  58512. ~MidiInputSelectorComponentListBox()
  58513. {
  58514. }
  58515. int getNumRows()
  58516. {
  58517. return items.size();
  58518. }
  58519. void paintListBoxItem (int row,
  58520. Graphics& g,
  58521. int width, int height,
  58522. bool rowIsSelected)
  58523. {
  58524. if (isPositiveAndBelow (row, items.size()))
  58525. {
  58526. if (rowIsSelected)
  58527. g.fillAll (findColour (TextEditor::highlightColourId)
  58528. .withMultipliedAlpha (0.3f));
  58529. const String item (items [row]);
  58530. bool enabled = deviceManager.isMidiInputEnabled (item);
  58531. const int x = getTickX();
  58532. const float tickW = height * 0.75f;
  58533. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58534. enabled, true, true, false);
  58535. g.setFont (height * 0.6f);
  58536. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58537. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58538. }
  58539. }
  58540. void listBoxItemClicked (int row, const MouseEvent& e)
  58541. {
  58542. selectRow (row);
  58543. if (e.x < getTickX())
  58544. flipEnablement (row);
  58545. }
  58546. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58547. {
  58548. flipEnablement (row);
  58549. }
  58550. void returnKeyPressed (int row)
  58551. {
  58552. flipEnablement (row);
  58553. }
  58554. void paint (Graphics& g)
  58555. {
  58556. ListBox::paint (g);
  58557. if (items.size() == 0)
  58558. {
  58559. g.setColour (Colours::grey);
  58560. g.setFont (13.0f);
  58561. g.drawText (noItemsMessage,
  58562. 0, 0, getWidth(), getHeight() / 2,
  58563. Justification::centred, true);
  58564. }
  58565. }
  58566. int getBestHeight (const int preferredHeight)
  58567. {
  58568. const int extra = getOutlineThickness() * 2;
  58569. return jmax (getRowHeight() * 2 + extra,
  58570. jmin (getRowHeight() * getNumRows() + extra,
  58571. preferredHeight));
  58572. }
  58573. private:
  58574. AudioDeviceManager& deviceManager;
  58575. const String noItemsMessage;
  58576. StringArray items;
  58577. int minNumber, maxNumber;
  58578. void flipEnablement (const int row)
  58579. {
  58580. if (isPositiveAndBelow (row, items.size()))
  58581. {
  58582. const String item (items [row]);
  58583. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58584. }
  58585. }
  58586. int getTickX() const
  58587. {
  58588. return getRowHeight() + 5;
  58589. }
  58590. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox);
  58591. };
  58592. class AudioDeviceSettingsPanel : public Component,
  58593. public ChangeListener,
  58594. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58595. public ButtonListener
  58596. {
  58597. public:
  58598. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58599. AudioIODeviceType::DeviceSetupDetails& setup_,
  58600. const bool hideAdvancedOptionsWithButton)
  58601. : type (type_),
  58602. setup (setup_)
  58603. {
  58604. if (hideAdvancedOptionsWithButton)
  58605. {
  58606. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58607. showAdvancedSettingsButton->addListener (this);
  58608. }
  58609. type->scanForDevices();
  58610. setup.manager->addChangeListener (this);
  58611. changeListenerCallback (0);
  58612. }
  58613. ~AudioDeviceSettingsPanel()
  58614. {
  58615. setup.manager->removeChangeListener (this);
  58616. }
  58617. void resized()
  58618. {
  58619. const int lx = proportionOfWidth (0.35f);
  58620. const int w = proportionOfWidth (0.4f);
  58621. const int h = 24;
  58622. const int space = 6;
  58623. const int dh = h + space;
  58624. int y = 0;
  58625. if (outputDeviceDropDown != 0)
  58626. {
  58627. outputDeviceDropDown->setBounds (lx, y, w, h);
  58628. if (testButton != 0)
  58629. testButton->setBounds (proportionOfWidth (0.77f),
  58630. outputDeviceDropDown->getY(),
  58631. proportionOfWidth (0.18f),
  58632. h);
  58633. y += dh;
  58634. }
  58635. if (inputDeviceDropDown != 0)
  58636. {
  58637. inputDeviceDropDown->setBounds (lx, y, w, h);
  58638. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58639. inputDeviceDropDown->getY(),
  58640. proportionOfWidth (0.18f),
  58641. h);
  58642. y += dh;
  58643. }
  58644. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58645. if (outputChanList != 0)
  58646. {
  58647. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58648. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58649. y += bh + space;
  58650. }
  58651. if (inputChanList != 0)
  58652. {
  58653. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58654. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58655. y += bh + space;
  58656. }
  58657. y += space * 2;
  58658. if (showAdvancedSettingsButton != 0)
  58659. {
  58660. showAdvancedSettingsButton->changeWidthToFitText (h);
  58661. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58662. }
  58663. if (sampleRateDropDown != 0)
  58664. {
  58665. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58666. || ! showAdvancedSettingsButton->isVisible());
  58667. sampleRateDropDown->setBounds (lx, y, w, h);
  58668. y += dh;
  58669. }
  58670. if (bufferSizeDropDown != 0)
  58671. {
  58672. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58673. || ! showAdvancedSettingsButton->isVisible());
  58674. bufferSizeDropDown->setBounds (lx, y, w, h);
  58675. y += dh;
  58676. }
  58677. if (showUIButton != 0)
  58678. {
  58679. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58680. || ! showAdvancedSettingsButton->isVisible());
  58681. showUIButton->changeWidthToFitText (h);
  58682. showUIButton->setTopLeftPosition (lx, y);
  58683. }
  58684. }
  58685. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58686. {
  58687. if (comboBoxThatHasChanged == 0)
  58688. return;
  58689. AudioDeviceManager::AudioDeviceSetup config;
  58690. setup.manager->getAudioDeviceSetup (config);
  58691. String error;
  58692. if (comboBoxThatHasChanged == outputDeviceDropDown
  58693. || comboBoxThatHasChanged == inputDeviceDropDown)
  58694. {
  58695. if (outputDeviceDropDown != 0)
  58696. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58697. : outputDeviceDropDown->getText();
  58698. if (inputDeviceDropDown != 0)
  58699. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58700. : inputDeviceDropDown->getText();
  58701. if (! type->hasSeparateInputsAndOutputs())
  58702. config.inputDeviceName = config.outputDeviceName;
  58703. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58704. config.useDefaultInputChannels = true;
  58705. else
  58706. config.useDefaultOutputChannels = true;
  58707. error = setup.manager->setAudioDeviceSetup (config, true);
  58708. showCorrectDeviceName (inputDeviceDropDown, true);
  58709. showCorrectDeviceName (outputDeviceDropDown, false);
  58710. updateControlPanelButton();
  58711. resized();
  58712. }
  58713. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58714. {
  58715. if (sampleRateDropDown->getSelectedId() > 0)
  58716. {
  58717. config.sampleRate = sampleRateDropDown->getSelectedId();
  58718. error = setup.manager->setAudioDeviceSetup (config, true);
  58719. }
  58720. }
  58721. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58722. {
  58723. if (bufferSizeDropDown->getSelectedId() > 0)
  58724. {
  58725. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58726. error = setup.manager->setAudioDeviceSetup (config, true);
  58727. }
  58728. }
  58729. if (error.isNotEmpty())
  58730. {
  58731. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58732. "Error when trying to open audio device!",
  58733. error);
  58734. }
  58735. }
  58736. void buttonClicked (Button* button)
  58737. {
  58738. if (button == showAdvancedSettingsButton)
  58739. {
  58740. showAdvancedSettingsButton->setVisible (false);
  58741. resized();
  58742. }
  58743. else if (button == showUIButton)
  58744. {
  58745. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58746. if (device != 0 && device->showControlPanel())
  58747. {
  58748. setup.manager->closeAudioDevice();
  58749. setup.manager->restartLastAudioDevice();
  58750. getTopLevelComponent()->toFront (true);
  58751. }
  58752. }
  58753. else if (button == testButton && testButton != 0)
  58754. {
  58755. setup.manager->playTestSound();
  58756. }
  58757. }
  58758. void updateControlPanelButton()
  58759. {
  58760. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58761. showUIButton = 0;
  58762. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58763. {
  58764. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58765. TRANS ("opens the device's own control panel")));
  58766. showUIButton->addListener (this);
  58767. }
  58768. resized();
  58769. }
  58770. void changeListenerCallback (ChangeBroadcaster*)
  58771. {
  58772. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58773. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58774. {
  58775. if (outputDeviceDropDown == 0)
  58776. {
  58777. outputDeviceDropDown = new ComboBox (String::empty);
  58778. outputDeviceDropDown->addListener (this);
  58779. addAndMakeVisible (outputDeviceDropDown);
  58780. outputDeviceLabel = new Label (String::empty,
  58781. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58782. : TRANS ("device:"));
  58783. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58784. if (setup.maxNumOutputChannels > 0)
  58785. {
  58786. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58787. testButton->addListener (this);
  58788. }
  58789. }
  58790. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58791. }
  58792. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58793. {
  58794. if (inputDeviceDropDown == 0)
  58795. {
  58796. inputDeviceDropDown = new ComboBox (String::empty);
  58797. inputDeviceDropDown->addListener (this);
  58798. addAndMakeVisible (inputDeviceDropDown);
  58799. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58800. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58801. addAndMakeVisible (inputLevelMeter
  58802. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58803. }
  58804. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58805. }
  58806. updateControlPanelButton();
  58807. showCorrectDeviceName (inputDeviceDropDown, true);
  58808. showCorrectDeviceName (outputDeviceDropDown, false);
  58809. if (currentDevice != 0)
  58810. {
  58811. if (setup.maxNumOutputChannels > 0
  58812. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58813. {
  58814. if (outputChanList == 0)
  58815. {
  58816. addAndMakeVisible (outputChanList
  58817. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58818. TRANS ("(no audio output channels found)")));
  58819. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58820. outputChanLabel->attachToComponent (outputChanList, true);
  58821. }
  58822. outputChanList->refresh();
  58823. }
  58824. else
  58825. {
  58826. outputChanLabel = 0;
  58827. outputChanList = 0;
  58828. }
  58829. if (setup.maxNumInputChannels > 0
  58830. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58831. {
  58832. if (inputChanList == 0)
  58833. {
  58834. addAndMakeVisible (inputChanList
  58835. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58836. TRANS ("(no audio input channels found)")));
  58837. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58838. inputChanLabel->attachToComponent (inputChanList, true);
  58839. }
  58840. inputChanList->refresh();
  58841. }
  58842. else
  58843. {
  58844. inputChanLabel = 0;
  58845. inputChanList = 0;
  58846. }
  58847. // sample rate..
  58848. {
  58849. if (sampleRateDropDown == 0)
  58850. {
  58851. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58852. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58853. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58854. }
  58855. else
  58856. {
  58857. sampleRateDropDown->clear();
  58858. sampleRateDropDown->removeListener (this);
  58859. }
  58860. const int numRates = currentDevice->getNumSampleRates();
  58861. for (int i = 0; i < numRates; ++i)
  58862. {
  58863. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58864. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58865. }
  58866. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58867. sampleRateDropDown->addListener (this);
  58868. }
  58869. // buffer size
  58870. {
  58871. if (bufferSizeDropDown == 0)
  58872. {
  58873. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58874. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58875. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58876. }
  58877. else
  58878. {
  58879. bufferSizeDropDown->clear();
  58880. bufferSizeDropDown->removeListener (this);
  58881. }
  58882. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58883. double currentRate = currentDevice->getCurrentSampleRate();
  58884. if (currentRate == 0)
  58885. currentRate = 48000.0;
  58886. for (int i = 0; i < numBufferSizes; ++i)
  58887. {
  58888. const int bs = currentDevice->getBufferSizeSamples (i);
  58889. bufferSizeDropDown->addItem (String (bs)
  58890. + " samples ("
  58891. + String (bs * 1000.0 / currentRate, 1)
  58892. + " ms)",
  58893. bs);
  58894. }
  58895. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58896. bufferSizeDropDown->addListener (this);
  58897. }
  58898. }
  58899. else
  58900. {
  58901. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58902. sampleRateLabel = 0;
  58903. bufferSizeLabel = 0;
  58904. sampleRateDropDown = 0;
  58905. bufferSizeDropDown = 0;
  58906. if (outputDeviceDropDown != 0)
  58907. outputDeviceDropDown->setSelectedId (-1, true);
  58908. if (inputDeviceDropDown != 0)
  58909. inputDeviceDropDown->setSelectedId (-1, true);
  58910. }
  58911. resized();
  58912. setSize (getWidth(), getLowestY() + 4);
  58913. }
  58914. private:
  58915. AudioIODeviceType* const type;
  58916. const AudioIODeviceType::DeviceSetupDetails setup;
  58917. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58918. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58919. ScopedPointer<TextButton> testButton;
  58920. ScopedPointer<Component> inputLevelMeter;
  58921. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58922. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58923. {
  58924. if (box != 0)
  58925. {
  58926. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58927. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58928. box->setSelectedId (index + 1, true);
  58929. if (testButton != 0 && ! isInput)
  58930. testButton->setEnabled (index >= 0);
  58931. }
  58932. }
  58933. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58934. {
  58935. const StringArray devs (type->getDeviceNames (isInputs));
  58936. combo.clear (true);
  58937. for (int i = 0; i < devs.size(); ++i)
  58938. combo.addItem (devs[i], i + 1);
  58939. combo.addItem (TRANS("<< none >>"), -1);
  58940. combo.setSelectedId (-1, true);
  58941. }
  58942. int getLowestY() const
  58943. {
  58944. int y = 0;
  58945. for (int i = getNumChildComponents(); --i >= 0;)
  58946. y = jmax (y, getChildComponent (i)->getBottom());
  58947. return y;
  58948. }
  58949. public:
  58950. class ChannelSelectorListBox : public ListBox,
  58951. public ListBoxModel
  58952. {
  58953. public:
  58954. enum BoxType
  58955. {
  58956. audioInputType,
  58957. audioOutputType
  58958. };
  58959. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58960. const BoxType type_,
  58961. const String& noItemsMessage_)
  58962. : ListBox (String::empty, 0),
  58963. setup (setup_),
  58964. type (type_),
  58965. noItemsMessage (noItemsMessage_)
  58966. {
  58967. refresh();
  58968. setModel (this);
  58969. setOutlineThickness (1);
  58970. }
  58971. ~ChannelSelectorListBox()
  58972. {
  58973. }
  58974. void refresh()
  58975. {
  58976. items.clear();
  58977. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58978. if (currentDevice != 0)
  58979. {
  58980. if (type == audioInputType)
  58981. items = currentDevice->getInputChannelNames();
  58982. else if (type == audioOutputType)
  58983. items = currentDevice->getOutputChannelNames();
  58984. if (setup.useStereoPairs)
  58985. {
  58986. StringArray pairs;
  58987. for (int i = 0; i < items.size(); i += 2)
  58988. {
  58989. const String name (items[i]);
  58990. const String name2 (items[i + 1]);
  58991. String commonBit;
  58992. for (int j = 0; j < name.length(); ++j)
  58993. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58994. commonBit = name.substring (0, j);
  58995. // Make sure we only split the name at a space, because otherwise, things
  58996. // like "input 11" + "input 12" would become "input 11 + 2"
  58997. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58998. commonBit = commonBit.dropLastCharacters (1);
  58999. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59000. }
  59001. items = pairs;
  59002. }
  59003. }
  59004. updateContent();
  59005. repaint();
  59006. }
  59007. int getNumRows()
  59008. {
  59009. return items.size();
  59010. }
  59011. void paintListBoxItem (int row,
  59012. Graphics& g,
  59013. int width, int height,
  59014. bool rowIsSelected)
  59015. {
  59016. if (isPositiveAndBelow (row, items.size()))
  59017. {
  59018. if (rowIsSelected)
  59019. g.fillAll (findColour (TextEditor::highlightColourId)
  59020. .withMultipliedAlpha (0.3f));
  59021. const String item (items [row]);
  59022. bool enabled = false;
  59023. AudioDeviceManager::AudioDeviceSetup config;
  59024. setup.manager->getAudioDeviceSetup (config);
  59025. if (setup.useStereoPairs)
  59026. {
  59027. if (type == audioInputType)
  59028. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59029. else if (type == audioOutputType)
  59030. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59031. }
  59032. else
  59033. {
  59034. if (type == audioInputType)
  59035. enabled = config.inputChannels [row];
  59036. else if (type == audioOutputType)
  59037. enabled = config.outputChannels [row];
  59038. }
  59039. const int x = getTickX();
  59040. const float tickW = height * 0.75f;
  59041. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59042. enabled, true, true, false);
  59043. g.setFont (height * 0.6f);
  59044. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59045. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59046. }
  59047. }
  59048. void listBoxItemClicked (int row, const MouseEvent& e)
  59049. {
  59050. selectRow (row);
  59051. if (e.x < getTickX())
  59052. flipEnablement (row);
  59053. }
  59054. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59055. {
  59056. flipEnablement (row);
  59057. }
  59058. void returnKeyPressed (int row)
  59059. {
  59060. flipEnablement (row);
  59061. }
  59062. void paint (Graphics& g)
  59063. {
  59064. ListBox::paint (g);
  59065. if (items.size() == 0)
  59066. {
  59067. g.setColour (Colours::grey);
  59068. g.setFont (13.0f);
  59069. g.drawText (noItemsMessage,
  59070. 0, 0, getWidth(), getHeight() / 2,
  59071. Justification::centred, true);
  59072. }
  59073. }
  59074. int getBestHeight (int maxHeight)
  59075. {
  59076. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59077. getNumRows())
  59078. + getOutlineThickness() * 2;
  59079. }
  59080. private:
  59081. const AudioIODeviceType::DeviceSetupDetails setup;
  59082. const BoxType type;
  59083. const String noItemsMessage;
  59084. StringArray items;
  59085. void flipEnablement (const int row)
  59086. {
  59087. jassert (type == audioInputType || type == audioOutputType);
  59088. if (isPositiveAndBelow (row, items.size()))
  59089. {
  59090. AudioDeviceManager::AudioDeviceSetup config;
  59091. setup.manager->getAudioDeviceSetup (config);
  59092. if (setup.useStereoPairs)
  59093. {
  59094. BigInteger bits;
  59095. BigInteger& original = (type == audioInputType ? config.inputChannels
  59096. : config.outputChannels);
  59097. int i;
  59098. for (i = 0; i < 256; i += 2)
  59099. bits.setBit (i / 2, original [i] || original [i + 1]);
  59100. if (type == audioInputType)
  59101. {
  59102. config.useDefaultInputChannels = false;
  59103. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59104. }
  59105. else
  59106. {
  59107. config.useDefaultOutputChannels = false;
  59108. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59109. }
  59110. for (i = 0; i < 256; ++i)
  59111. original.setBit (i, bits [i / 2]);
  59112. }
  59113. else
  59114. {
  59115. if (type == audioInputType)
  59116. {
  59117. config.useDefaultInputChannels = false;
  59118. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59119. }
  59120. else
  59121. {
  59122. config.useDefaultOutputChannels = false;
  59123. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59124. }
  59125. }
  59126. String error (setup.manager->setAudioDeviceSetup (config, true));
  59127. if (! error.isEmpty())
  59128. {
  59129. //xxx
  59130. }
  59131. }
  59132. }
  59133. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59134. {
  59135. const int numActive = chans.countNumberOfSetBits();
  59136. if (chans [index])
  59137. {
  59138. if (numActive > minNumber)
  59139. chans.setBit (index, false);
  59140. }
  59141. else
  59142. {
  59143. if (numActive >= maxNumber)
  59144. {
  59145. const int firstActiveChan = chans.findNextSetBit();
  59146. chans.setBit (index > firstActiveChan
  59147. ? firstActiveChan : chans.getHighestBit(),
  59148. false);
  59149. }
  59150. chans.setBit (index, true);
  59151. }
  59152. }
  59153. int getTickX() const
  59154. {
  59155. return getRowHeight() + 5;
  59156. }
  59157. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox);
  59158. };
  59159. private:
  59160. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59161. JUCE_DECLARE_NON_COPYABLE (AudioDeviceSettingsPanel);
  59162. };
  59163. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59164. const int minInputChannels_,
  59165. const int maxInputChannels_,
  59166. const int minOutputChannels_,
  59167. const int maxOutputChannels_,
  59168. const bool showMidiInputOptions,
  59169. const bool showMidiOutputSelector,
  59170. const bool showChannelsAsStereoPairs_,
  59171. const bool hideAdvancedOptionsWithButton_)
  59172. : deviceManager (deviceManager_),
  59173. deviceTypeDropDown (0),
  59174. deviceTypeDropDownLabel (0),
  59175. minOutputChannels (minOutputChannels_),
  59176. maxOutputChannels (maxOutputChannels_),
  59177. minInputChannels (minInputChannels_),
  59178. maxInputChannels (maxInputChannels_),
  59179. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59180. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59181. {
  59182. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59183. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59184. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59185. {
  59186. deviceTypeDropDown = new ComboBox (String::empty);
  59187. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59188. {
  59189. deviceTypeDropDown
  59190. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59191. i + 1);
  59192. }
  59193. addAndMakeVisible (deviceTypeDropDown);
  59194. deviceTypeDropDown->addListener (this);
  59195. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59196. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59197. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59198. }
  59199. if (showMidiInputOptions)
  59200. {
  59201. addAndMakeVisible (midiInputsList
  59202. = new MidiInputSelectorComponentListBox (deviceManager,
  59203. TRANS("(no midi inputs available)"),
  59204. 0, 0));
  59205. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59206. midiInputsLabel->setJustificationType (Justification::topRight);
  59207. midiInputsLabel->attachToComponent (midiInputsList, true);
  59208. }
  59209. else
  59210. {
  59211. midiInputsList = 0;
  59212. midiInputsLabel = 0;
  59213. }
  59214. if (showMidiOutputSelector)
  59215. {
  59216. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59217. midiOutputSelector->addListener (this);
  59218. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59219. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59220. }
  59221. else
  59222. {
  59223. midiOutputSelector = 0;
  59224. midiOutputLabel = 0;
  59225. }
  59226. deviceManager_.addChangeListener (this);
  59227. changeListenerCallback (0);
  59228. }
  59229. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59230. {
  59231. deviceManager.removeChangeListener (this);
  59232. }
  59233. void AudioDeviceSelectorComponent::resized()
  59234. {
  59235. const int lx = proportionOfWidth (0.35f);
  59236. const int w = proportionOfWidth (0.4f);
  59237. const int h = 24;
  59238. const int space = 6;
  59239. const int dh = h + space;
  59240. int y = 15;
  59241. if (deviceTypeDropDown != 0)
  59242. {
  59243. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59244. y += dh + space * 2;
  59245. }
  59246. if (audioDeviceSettingsComp != 0)
  59247. {
  59248. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59249. y += audioDeviceSettingsComp->getHeight() + space;
  59250. }
  59251. if (midiInputsList != 0)
  59252. {
  59253. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59254. midiInputsList->setBounds (lx, y, w, bh);
  59255. y += bh + space;
  59256. }
  59257. if (midiOutputSelector != 0)
  59258. midiOutputSelector->setBounds (lx, y, w, h);
  59259. }
  59260. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59261. {
  59262. if (child == audioDeviceSettingsComp)
  59263. resized();
  59264. }
  59265. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59266. {
  59267. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59268. if (device != 0 && device->hasControlPanel())
  59269. {
  59270. if (device->showControlPanel())
  59271. deviceManager.restartLastAudioDevice();
  59272. getTopLevelComponent()->toFront (true);
  59273. }
  59274. }
  59275. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59276. {
  59277. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59278. {
  59279. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59280. if (type != 0)
  59281. {
  59282. audioDeviceSettingsComp = 0;
  59283. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59284. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59285. }
  59286. }
  59287. else if (comboBoxThatHasChanged == midiOutputSelector)
  59288. {
  59289. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59290. }
  59291. }
  59292. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59293. {
  59294. if (deviceTypeDropDown != 0)
  59295. {
  59296. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59297. }
  59298. if (audioDeviceSettingsComp == 0
  59299. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59300. {
  59301. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59302. audioDeviceSettingsComp = 0;
  59303. AudioIODeviceType* const type
  59304. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59305. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59306. if (type != 0)
  59307. {
  59308. AudioIODeviceType::DeviceSetupDetails details;
  59309. details.manager = &deviceManager;
  59310. details.minNumInputChannels = minInputChannels;
  59311. details.maxNumInputChannels = maxInputChannels;
  59312. details.minNumOutputChannels = minOutputChannels;
  59313. details.maxNumOutputChannels = maxOutputChannels;
  59314. details.useStereoPairs = showChannelsAsStereoPairs;
  59315. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59316. if (audioDeviceSettingsComp != 0)
  59317. {
  59318. addAndMakeVisible (audioDeviceSettingsComp);
  59319. audioDeviceSettingsComp->resized();
  59320. }
  59321. }
  59322. }
  59323. if (midiInputsList != 0)
  59324. {
  59325. midiInputsList->updateContent();
  59326. midiInputsList->repaint();
  59327. }
  59328. if (midiOutputSelector != 0)
  59329. {
  59330. midiOutputSelector->clear();
  59331. const StringArray midiOuts (MidiOutput::getDevices());
  59332. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59333. midiOutputSelector->addSeparator();
  59334. for (int i = 0; i < midiOuts.size(); ++i)
  59335. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59336. int current = -1;
  59337. if (deviceManager.getDefaultMidiOutput() != 0)
  59338. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59339. midiOutputSelector->setSelectedId (current, true);
  59340. }
  59341. resized();
  59342. }
  59343. END_JUCE_NAMESPACE
  59344. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59345. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59346. BEGIN_JUCE_NAMESPACE
  59347. BubbleComponent::BubbleComponent()
  59348. : side (0),
  59349. allowablePlacements (above | below | left | right),
  59350. arrowTipX (0.0f),
  59351. arrowTipY (0.0f)
  59352. {
  59353. setInterceptsMouseClicks (false, false);
  59354. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59355. setComponentEffect (&shadow);
  59356. }
  59357. BubbleComponent::~BubbleComponent()
  59358. {
  59359. }
  59360. void BubbleComponent::paint (Graphics& g)
  59361. {
  59362. int x = content.getX();
  59363. int y = content.getY();
  59364. int w = content.getWidth();
  59365. int h = content.getHeight();
  59366. int cw, ch;
  59367. getContentSize (cw, ch);
  59368. if (side == 3)
  59369. x += w - cw;
  59370. else if (side != 1)
  59371. x += (w - cw) / 2;
  59372. w = cw;
  59373. if (side == 2)
  59374. y += h - ch;
  59375. else if (side != 0)
  59376. y += (h - ch) / 2;
  59377. h = ch;
  59378. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59379. (float) x, (float) y,
  59380. (float) w, (float) h);
  59381. const int cx = x + (w - cw) / 2;
  59382. const int cy = y + (h - ch) / 2;
  59383. const int indent = 3;
  59384. g.setOrigin (cx + indent, cy + indent);
  59385. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59386. paintContent (g, cw - indent * 2, ch - indent * 2);
  59387. }
  59388. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59389. {
  59390. allowablePlacements = newPlacement;
  59391. }
  59392. void BubbleComponent::setPosition (Component* componentToPointTo)
  59393. {
  59394. jassert (componentToPointTo != 0);
  59395. Point<int> pos;
  59396. if (getParentComponent() != 0)
  59397. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59398. else
  59399. pos = componentToPointTo->localPointToGlobal (pos);
  59400. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59401. }
  59402. void BubbleComponent::setPosition (const int arrowTipX_,
  59403. const int arrowTipY_)
  59404. {
  59405. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59406. }
  59407. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59408. {
  59409. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59410. : getParentMonitorArea());
  59411. int x = 0;
  59412. int y = 0;
  59413. int w = 150;
  59414. int h = 30;
  59415. getContentSize (w, h);
  59416. w += 30;
  59417. h += 30;
  59418. const float edgeIndent = 2.0f;
  59419. const int arrowLength = jmin (10, h / 3, w / 3);
  59420. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59421. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59422. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59423. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59424. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59425. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59426. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59427. {
  59428. spaceLeft = spaceRight = 0;
  59429. }
  59430. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59431. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59432. {
  59433. spaceAbove = spaceBelow = 0;
  59434. }
  59435. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59436. {
  59437. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59438. arrowTipX = w * 0.5f;
  59439. content.setSize (w, h - arrowLength);
  59440. if (spaceAbove >= spaceBelow)
  59441. {
  59442. // above
  59443. y = rectangleToPointTo.getY() - h;
  59444. content.setPosition (0, 0);
  59445. arrowTipY = h - edgeIndent;
  59446. side = 2;
  59447. }
  59448. else
  59449. {
  59450. // below
  59451. y = rectangleToPointTo.getBottom();
  59452. content.setPosition (0, arrowLength);
  59453. arrowTipY = edgeIndent;
  59454. side = 0;
  59455. }
  59456. }
  59457. else
  59458. {
  59459. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59460. arrowTipY = h * 0.5f;
  59461. content.setSize (w - arrowLength, h);
  59462. if (spaceLeft > spaceRight)
  59463. {
  59464. // on the left
  59465. x = rectangleToPointTo.getX() - w;
  59466. content.setPosition (0, 0);
  59467. arrowTipX = w - edgeIndent;
  59468. side = 3;
  59469. }
  59470. else
  59471. {
  59472. // on the right
  59473. x = rectangleToPointTo.getRight();
  59474. content.setPosition (arrowLength, 0);
  59475. arrowTipX = edgeIndent;
  59476. side = 1;
  59477. }
  59478. }
  59479. setBounds (x, y, w, h);
  59480. }
  59481. END_JUCE_NAMESPACE
  59482. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59483. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59484. BEGIN_JUCE_NAMESPACE
  59485. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59486. : fadeOutLength (fadeOutLengthMs),
  59487. deleteAfterUse (false)
  59488. {
  59489. }
  59490. BubbleMessageComponent::~BubbleMessageComponent()
  59491. {
  59492. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59493. }
  59494. void BubbleMessageComponent::showAt (int x, int y,
  59495. const String& text,
  59496. const int numMillisecondsBeforeRemoving,
  59497. const bool removeWhenMouseClicked,
  59498. const bool deleteSelfAfterUse)
  59499. {
  59500. textLayout.clear();
  59501. textLayout.setText (text, Font (14.0f));
  59502. textLayout.layout (256, Justification::centredLeft, true);
  59503. setPosition (x, y);
  59504. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59505. }
  59506. void BubbleMessageComponent::showAt (Component* const component,
  59507. const String& text,
  59508. const int numMillisecondsBeforeRemoving,
  59509. const bool removeWhenMouseClicked,
  59510. const bool deleteSelfAfterUse)
  59511. {
  59512. textLayout.clear();
  59513. textLayout.setText (text, Font (14.0f));
  59514. textLayout.layout (256, Justification::centredLeft, true);
  59515. setPosition (component);
  59516. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59517. }
  59518. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59519. const bool removeWhenMouseClicked,
  59520. const bool deleteSelfAfterUse)
  59521. {
  59522. setVisible (true);
  59523. deleteAfterUse = deleteSelfAfterUse;
  59524. if (numMillisecondsBeforeRemoving > 0)
  59525. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59526. else
  59527. expiryTime = 0;
  59528. startTimer (77);
  59529. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59530. if (! (removeWhenMouseClicked && isShowing()))
  59531. mouseClickCounter += 0xfffff;
  59532. repaint();
  59533. }
  59534. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59535. {
  59536. w = textLayout.getWidth() + 16;
  59537. h = textLayout.getHeight() + 16;
  59538. }
  59539. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59540. {
  59541. g.setColour (findColour (TooltipWindow::textColourId));
  59542. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59543. }
  59544. void BubbleMessageComponent::timerCallback()
  59545. {
  59546. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59547. {
  59548. stopTimer();
  59549. setVisible (false);
  59550. if (deleteAfterUse)
  59551. delete this;
  59552. }
  59553. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59554. {
  59555. stopTimer();
  59556. if (deleteAfterUse)
  59557. delete this;
  59558. else
  59559. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59560. }
  59561. }
  59562. END_JUCE_NAMESPACE
  59563. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59564. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59565. BEGIN_JUCE_NAMESPACE
  59566. class ColourComponentSlider : public Slider
  59567. {
  59568. public:
  59569. ColourComponentSlider (const String& name)
  59570. : Slider (name)
  59571. {
  59572. setRange (0.0, 255.0, 1.0);
  59573. }
  59574. const String getTextFromValue (double value)
  59575. {
  59576. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59577. }
  59578. double getValueFromText (const String& text)
  59579. {
  59580. return (double) text.getHexValue32();
  59581. }
  59582. private:
  59583. JUCE_DECLARE_NON_COPYABLE (ColourComponentSlider);
  59584. };
  59585. class ColourSpaceMarker : public Component
  59586. {
  59587. public:
  59588. ColourSpaceMarker()
  59589. {
  59590. setInterceptsMouseClicks (false, false);
  59591. }
  59592. void paint (Graphics& g)
  59593. {
  59594. g.setColour (Colour::greyLevel (0.1f));
  59595. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59596. g.setColour (Colour::greyLevel (0.9f));
  59597. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59598. }
  59599. private:
  59600. JUCE_DECLARE_NON_COPYABLE (ColourSpaceMarker);
  59601. };
  59602. class ColourSelector::ColourSpaceView : public Component
  59603. {
  59604. public:
  59605. ColourSpaceView (ColourSelector& owner_,
  59606. float& h_, float& s_, float& v_,
  59607. const int edgeSize)
  59608. : owner (owner_),
  59609. h (h_), s (s_), v (v_),
  59610. lastHue (0.0f),
  59611. edge (edgeSize)
  59612. {
  59613. addAndMakeVisible (&marker);
  59614. setMouseCursor (MouseCursor::CrosshairCursor);
  59615. }
  59616. void paint (Graphics& g)
  59617. {
  59618. if (colours.isNull())
  59619. {
  59620. const int width = getWidth() / 2;
  59621. const int height = getHeight() / 2;
  59622. colours = Image (Image::RGB, width, height, false);
  59623. Image::BitmapData pixels (colours, true);
  59624. for (int y = 0; y < height; ++y)
  59625. {
  59626. const float val = 1.0f - y / (float) height;
  59627. for (int x = 0; x < width; ++x)
  59628. {
  59629. const float sat = x / (float) width;
  59630. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59631. }
  59632. }
  59633. }
  59634. g.setOpacity (1.0f);
  59635. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59636. 0, 0, colours.getWidth(), colours.getHeight());
  59637. }
  59638. void mouseDown (const MouseEvent& e)
  59639. {
  59640. mouseDrag (e);
  59641. }
  59642. void mouseDrag (const MouseEvent& e)
  59643. {
  59644. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59645. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59646. owner.setSV (sat, val);
  59647. }
  59648. void updateIfNeeded()
  59649. {
  59650. if (lastHue != h)
  59651. {
  59652. lastHue = h;
  59653. colours = Image::null;
  59654. repaint();
  59655. }
  59656. updateMarker();
  59657. }
  59658. void resized()
  59659. {
  59660. colours = Image::null;
  59661. updateMarker();
  59662. }
  59663. private:
  59664. ColourSelector& owner;
  59665. float& h;
  59666. float& s;
  59667. float& v;
  59668. float lastHue;
  59669. ColourSpaceMarker marker;
  59670. const int edge;
  59671. Image colours;
  59672. void updateMarker()
  59673. {
  59674. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59675. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59676. edge * 2, edge * 2);
  59677. }
  59678. JUCE_DECLARE_NON_COPYABLE (ColourSpaceView);
  59679. };
  59680. class HueSelectorMarker : public Component
  59681. {
  59682. public:
  59683. HueSelectorMarker()
  59684. {
  59685. setInterceptsMouseClicks (false, false);
  59686. }
  59687. void paint (Graphics& g)
  59688. {
  59689. Path p;
  59690. p.addTriangle (1.0f, 1.0f,
  59691. getWidth() * 0.3f, getHeight() * 0.5f,
  59692. 1.0f, getHeight() - 1.0f);
  59693. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59694. getWidth() * 0.7f, getHeight() * 0.5f,
  59695. getWidth() - 1.0f, getHeight() - 1.0f);
  59696. g.setColour (Colours::white.withAlpha (0.75f));
  59697. g.fillPath (p);
  59698. g.setColour (Colours::black.withAlpha (0.75f));
  59699. g.strokePath (p, PathStrokeType (1.2f));
  59700. }
  59701. private:
  59702. JUCE_DECLARE_NON_COPYABLE (HueSelectorMarker);
  59703. };
  59704. class ColourSelector::HueSelectorComp : public Component
  59705. {
  59706. public:
  59707. HueSelectorComp (ColourSelector& owner_,
  59708. float& h_, float& s_, float& v_,
  59709. const int edgeSize)
  59710. : owner (owner_),
  59711. h (h_), s (s_), v (v_),
  59712. lastHue (0.0f),
  59713. edge (edgeSize)
  59714. {
  59715. addAndMakeVisible (&marker);
  59716. }
  59717. void paint (Graphics& g)
  59718. {
  59719. const float yScale = 1.0f / (getHeight() - edge * 2);
  59720. const Rectangle<int> clip (g.getClipBounds());
  59721. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59722. {
  59723. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59724. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59725. }
  59726. }
  59727. void resized()
  59728. {
  59729. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59730. getWidth(), edge * 2);
  59731. }
  59732. void mouseDown (const MouseEvent& e)
  59733. {
  59734. mouseDrag (e);
  59735. }
  59736. void mouseDrag (const MouseEvent& e)
  59737. {
  59738. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  59739. }
  59740. void updateIfNeeded()
  59741. {
  59742. resized();
  59743. }
  59744. private:
  59745. ColourSelector& owner;
  59746. float& h;
  59747. float& s;
  59748. float& v;
  59749. float lastHue;
  59750. HueSelectorMarker marker;
  59751. const int edge;
  59752. JUCE_DECLARE_NON_COPYABLE (HueSelectorComp);
  59753. };
  59754. class ColourSelector::SwatchComponent : public Component
  59755. {
  59756. public:
  59757. SwatchComponent (ColourSelector& owner_, int index_)
  59758. : owner (owner_), index (index_)
  59759. {
  59760. }
  59761. void paint (Graphics& g)
  59762. {
  59763. const Colour colour (owner.getSwatchColour (index));
  59764. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59765. Colour (0xffdddddd).overlaidWith (colour),
  59766. Colour (0xffffffff).overlaidWith (colour));
  59767. }
  59768. void mouseDown (const MouseEvent&)
  59769. {
  59770. PopupMenu m;
  59771. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59772. m.addSeparator();
  59773. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59774. const int r = m.showAt (this);
  59775. if (r == 1)
  59776. {
  59777. owner.setCurrentColour (owner.getSwatchColour (index));
  59778. }
  59779. else if (r == 2)
  59780. {
  59781. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  59782. {
  59783. owner.setSwatchColour (index, owner.getCurrentColour());
  59784. repaint();
  59785. }
  59786. }
  59787. }
  59788. private:
  59789. ColourSelector& owner;
  59790. const int index;
  59791. JUCE_DECLARE_NON_COPYABLE (SwatchComponent);
  59792. };
  59793. ColourSelector::ColourSelector (const int flags_,
  59794. const int edgeGap_,
  59795. const int gapAroundColourSpaceComponent)
  59796. : colour (Colours::white),
  59797. flags (flags_),
  59798. edgeGap (edgeGap_)
  59799. {
  59800. // not much point having a selector with no components in it!
  59801. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59802. updateHSV();
  59803. if ((flags & showSliders) != 0)
  59804. {
  59805. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59806. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59807. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59808. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59809. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59810. for (int i = 4; --i >= 0;)
  59811. sliders[i]->addListener (this);
  59812. }
  59813. if ((flags & showColourspace) != 0)
  59814. {
  59815. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  59816. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  59817. }
  59818. update();
  59819. }
  59820. ColourSelector::~ColourSelector()
  59821. {
  59822. dispatchPendingMessages();
  59823. swatchComponents.clear();
  59824. }
  59825. const Colour ColourSelector::getCurrentColour() const
  59826. {
  59827. return ((flags & showAlphaChannel) != 0) ? colour
  59828. : colour.withAlpha ((uint8) 0xff);
  59829. }
  59830. void ColourSelector::setCurrentColour (const Colour& c)
  59831. {
  59832. if (c != colour)
  59833. {
  59834. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59835. updateHSV();
  59836. update();
  59837. }
  59838. }
  59839. void ColourSelector::setHue (float newH)
  59840. {
  59841. newH = jlimit (0.0f, 1.0f, newH);
  59842. if (h != newH)
  59843. {
  59844. h = newH;
  59845. colour = Colour (h, s, v, colour.getFloatAlpha());
  59846. update();
  59847. }
  59848. }
  59849. void ColourSelector::setSV (float newS, float newV)
  59850. {
  59851. newS = jlimit (0.0f, 1.0f, newS);
  59852. newV = jlimit (0.0f, 1.0f, newV);
  59853. if (s != newS || v != newV)
  59854. {
  59855. s = newS;
  59856. v = newV;
  59857. colour = Colour (h, s, v, colour.getFloatAlpha());
  59858. update();
  59859. }
  59860. }
  59861. void ColourSelector::updateHSV()
  59862. {
  59863. colour.getHSB (h, s, v);
  59864. }
  59865. void ColourSelector::update()
  59866. {
  59867. if (sliders[0] != 0)
  59868. {
  59869. sliders[0]->setValue ((int) colour.getRed());
  59870. sliders[1]->setValue ((int) colour.getGreen());
  59871. sliders[2]->setValue ((int) colour.getBlue());
  59872. sliders[3]->setValue ((int) colour.getAlpha());
  59873. }
  59874. if (colourSpace != 0)
  59875. {
  59876. colourSpace->updateIfNeeded();
  59877. hueSelector->updateIfNeeded();
  59878. }
  59879. if ((flags & showColourAtTop) != 0)
  59880. repaint (previewArea);
  59881. sendChangeMessage();
  59882. }
  59883. void ColourSelector::paint (Graphics& g)
  59884. {
  59885. g.fillAll (findColour (backgroundColourId));
  59886. if ((flags & showColourAtTop) != 0)
  59887. {
  59888. const Colour currentColour (getCurrentColour());
  59889. g.fillCheckerBoard (previewArea, 10, 10,
  59890. Colour (0xffdddddd).overlaidWith (currentColour),
  59891. Colour (0xffffffff).overlaidWith (currentColour));
  59892. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59893. g.setFont (14.0f, true);
  59894. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59895. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59896. Justification::centred, false);
  59897. }
  59898. if ((flags & showSliders) != 0)
  59899. {
  59900. g.setColour (findColour (labelTextColourId));
  59901. g.setFont (11.0f);
  59902. for (int i = 4; --i >= 0;)
  59903. {
  59904. if (sliders[i]->isVisible())
  59905. g.drawText (sliders[i]->getName() + ":",
  59906. 0, sliders[i]->getY(),
  59907. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59908. Justification::centredRight, false);
  59909. }
  59910. }
  59911. }
  59912. void ColourSelector::resized()
  59913. {
  59914. const int swatchesPerRow = 8;
  59915. const int swatchHeight = 22;
  59916. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59917. const int numSwatches = getNumSwatches();
  59918. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59919. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59920. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59921. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59922. int y = topSpace;
  59923. if ((flags & showColourspace) != 0)
  59924. {
  59925. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59926. colourSpace->setBounds (edgeGap, y,
  59927. getWidth() - hueWidth - edgeGap - 4,
  59928. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59929. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59930. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59931. colourSpace->getHeight());
  59932. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59933. }
  59934. if ((flags & showSliders) != 0)
  59935. {
  59936. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59937. for (int i = 0; i < numSliders; ++i)
  59938. {
  59939. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59940. proportionOfWidth (0.72f), sliderHeight - 2);
  59941. y += sliderHeight;
  59942. }
  59943. }
  59944. if (numSwatches > 0)
  59945. {
  59946. const int startX = 8;
  59947. const int xGap = 4;
  59948. const int yGap = 4;
  59949. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59950. y += edgeGap;
  59951. if (swatchComponents.size() != numSwatches)
  59952. {
  59953. swatchComponents.clear();
  59954. for (int i = 0; i < numSwatches; ++i)
  59955. {
  59956. SwatchComponent* const sc = new SwatchComponent (*this, i);
  59957. swatchComponents.add (sc);
  59958. addAndMakeVisible (sc);
  59959. }
  59960. }
  59961. int x = startX;
  59962. for (int i = 0; i < swatchComponents.size(); ++i)
  59963. {
  59964. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59965. sc->setBounds (x + xGap / 2,
  59966. y + yGap / 2,
  59967. swatchWidth - xGap,
  59968. swatchHeight - yGap);
  59969. if (((i + 1) % swatchesPerRow) == 0)
  59970. {
  59971. x = startX;
  59972. y += swatchHeight;
  59973. }
  59974. else
  59975. {
  59976. x += swatchWidth;
  59977. }
  59978. }
  59979. }
  59980. }
  59981. void ColourSelector::sliderValueChanged (Slider*)
  59982. {
  59983. if (sliders[0] != 0)
  59984. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59985. (uint8) sliders[1]->getValue(),
  59986. (uint8) sliders[2]->getValue(),
  59987. (uint8) sliders[3]->getValue()));
  59988. }
  59989. int ColourSelector::getNumSwatches() const
  59990. {
  59991. return 0;
  59992. }
  59993. const Colour ColourSelector::getSwatchColour (const int) const
  59994. {
  59995. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59996. return Colours::black;
  59997. }
  59998. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59999. {
  60000. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60001. }
  60002. END_JUCE_NAMESPACE
  60003. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60004. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60005. BEGIN_JUCE_NAMESPACE
  60006. class ShadowWindow : public Component
  60007. {
  60008. public:
  60009. ShadowWindow (Component& owner, const int type_, const Image shadowImageSections [12])
  60010. : topLeft (shadowImageSections [type_ * 3]),
  60011. bottomRight (shadowImageSections [type_ * 3 + 1]),
  60012. filler (shadowImageSections [type_ * 3 + 2]),
  60013. type (type_)
  60014. {
  60015. setInterceptsMouseClicks (false, false);
  60016. if (owner.isOnDesktop())
  60017. {
  60018. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60019. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60020. | ComponentPeer::windowIsTemporary
  60021. | ComponentPeer::windowIgnoresKeyPresses);
  60022. }
  60023. else if (owner.getParentComponent() != 0)
  60024. {
  60025. owner.getParentComponent()->addChildComponent (this);
  60026. }
  60027. }
  60028. void paint (Graphics& g)
  60029. {
  60030. g.setOpacity (1.0f);
  60031. if (type < 2)
  60032. {
  60033. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60034. g.drawImage (topLeft,
  60035. 0, 0, topLeft.getWidth(), imH,
  60036. 0, 0, topLeft.getWidth(), imH);
  60037. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60038. g.drawImage (bottomRight,
  60039. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60040. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60041. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60042. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60043. }
  60044. else
  60045. {
  60046. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60047. g.drawImage (topLeft,
  60048. 0, 0, imW, topLeft.getHeight(),
  60049. 0, 0, imW, topLeft.getHeight());
  60050. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60051. g.drawImage (bottomRight,
  60052. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60053. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60054. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60055. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60056. }
  60057. }
  60058. void resized()
  60059. {
  60060. repaint(); // (needed for correct repainting)
  60061. }
  60062. private:
  60063. const Image topLeft, bottomRight, filler;
  60064. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60065. JUCE_DECLARE_NON_COPYABLE (ShadowWindow);
  60066. };
  60067. DropShadower::DropShadower (const float alpha_,
  60068. const int xOffset_,
  60069. const int yOffset_,
  60070. const float blurRadius_)
  60071. : owner (0),
  60072. xOffset (xOffset_),
  60073. yOffset (yOffset_),
  60074. alpha (alpha_),
  60075. blurRadius (blurRadius_),
  60076. reentrant (false)
  60077. {
  60078. }
  60079. DropShadower::~DropShadower()
  60080. {
  60081. if (owner != 0)
  60082. owner->removeComponentListener (this);
  60083. reentrant = true;
  60084. shadowWindows.clear();
  60085. }
  60086. void DropShadower::setOwner (Component* componentToFollow)
  60087. {
  60088. if (componentToFollow != owner)
  60089. {
  60090. if (owner != 0)
  60091. owner->removeComponentListener (this);
  60092. // (the component can't be null)
  60093. jassert (componentToFollow != 0);
  60094. owner = componentToFollow;
  60095. jassert (owner != 0);
  60096. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60097. owner->addComponentListener (this);
  60098. updateShadows();
  60099. }
  60100. }
  60101. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60102. {
  60103. updateShadows();
  60104. }
  60105. void DropShadower::componentBroughtToFront (Component&)
  60106. {
  60107. bringShadowWindowsToFront();
  60108. }
  60109. void DropShadower::componentParentHierarchyChanged (Component&)
  60110. {
  60111. shadowWindows.clear();
  60112. updateShadows();
  60113. }
  60114. void DropShadower::componentVisibilityChanged (Component&)
  60115. {
  60116. updateShadows();
  60117. }
  60118. void DropShadower::updateShadows()
  60119. {
  60120. if (reentrant || owner == 0)
  60121. return;
  60122. reentrant = true;
  60123. ComponentPeer* const peer = owner->getPeer();
  60124. const bool isOwnerVisible = owner->isVisible() && (peer == 0 || ! peer->isMinimised());
  60125. const bool createShadowWindows = shadowWindows.size() == 0
  60126. && owner->getWidth() > 0
  60127. && owner->getHeight() > 0
  60128. && isOwnerVisible
  60129. && (Desktop::canUseSemiTransparentWindows()
  60130. || owner->getParentComponent() != 0);
  60131. const int shadowEdge = jmax (xOffset, yOffset) + (int) blurRadius;
  60132. if (createShadowWindows)
  60133. {
  60134. // keep a cached version of the image to save doing the gaussian too often
  60135. String imageId;
  60136. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60137. const int hash = imageId.hashCode();
  60138. Image bigIm (ImageCache::getFromHashCode (hash));
  60139. if (bigIm.isNull())
  60140. {
  60141. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60142. Graphics bigG (bigIm);
  60143. bigG.setColour (Colours::black.withAlpha (alpha));
  60144. bigG.fillRect (shadowEdge + xOffset,
  60145. shadowEdge + yOffset,
  60146. bigIm.getWidth() - (shadowEdge * 2),
  60147. bigIm.getHeight() - (shadowEdge * 2));
  60148. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60149. blurKernel.createGaussianBlur (blurRadius);
  60150. blurKernel.applyToImage (bigIm, bigIm,
  60151. Rectangle<int> (xOffset, yOffset,
  60152. bigIm.getWidth(), bigIm.getHeight()));
  60153. ImageCache::addImageToCache (bigIm, hash);
  60154. }
  60155. const int iw = bigIm.getWidth();
  60156. const int ih = bigIm.getHeight();
  60157. const int shadowEdge2 = shadowEdge * 2;
  60158. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60159. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60160. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60161. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60162. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60163. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60164. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60165. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60166. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60167. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60168. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60169. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60170. for (int i = 0; i < 4; ++i)
  60171. shadowWindows.add (new ShadowWindow (*owner, i, shadowImageSections));
  60172. }
  60173. if (shadowWindows.size() >= 4)
  60174. {
  60175. for (int i = shadowWindows.size(); --i >= 0;)
  60176. {
  60177. shadowWindows.getUnchecked(i)->setAlwaysOnTop (owner->isAlwaysOnTop());
  60178. shadowWindows.getUnchecked(i)->setVisible (isOwnerVisible);
  60179. }
  60180. const int x = owner->getX();
  60181. const int y = owner->getY() - shadowEdge;
  60182. const int w = owner->getWidth();
  60183. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60184. shadowWindows.getUnchecked(0)->setBounds (x - shadowEdge, y, shadowEdge, h);
  60185. shadowWindows.getUnchecked(1)->setBounds (x + w, y, shadowEdge, h);
  60186. shadowWindows.getUnchecked(2)->setBounds (x, y, w, shadowEdge);
  60187. shadowWindows.getUnchecked(3)->setBounds (x, owner->getBottom(), w, shadowEdge);
  60188. }
  60189. reentrant = false;
  60190. if (createShadowWindows)
  60191. bringShadowWindowsToFront();
  60192. }
  60193. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60194. const int sx, const int sy)
  60195. {
  60196. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60197. Graphics g (shadowImageSections[num]);
  60198. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60199. }
  60200. void DropShadower::bringShadowWindowsToFront()
  60201. {
  60202. if (! reentrant)
  60203. {
  60204. updateShadows();
  60205. reentrant = true;
  60206. for (int i = shadowWindows.size(); --i >= 0;)
  60207. shadowWindows.getUnchecked(i)->toBehind (owner);
  60208. reentrant = false;
  60209. }
  60210. }
  60211. END_JUCE_NAMESPACE
  60212. /*** End of inlined file: juce_DropShadower.cpp ***/
  60213. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60214. BEGIN_JUCE_NAMESPACE
  60215. class MidiKeyboardUpDownButton : public Button
  60216. {
  60217. public:
  60218. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60219. : Button (String::empty),
  60220. owner (owner_),
  60221. delta (delta_)
  60222. {
  60223. setOpaque (true);
  60224. }
  60225. void clicked()
  60226. {
  60227. int note = owner.getLowestVisibleKey();
  60228. if (delta < 0)
  60229. note = (note - 1) / 12;
  60230. else
  60231. note = note / 12 + 1;
  60232. owner.setLowestVisibleKey (note * 12);
  60233. }
  60234. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60235. {
  60236. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60237. isMouseOverButton, isButtonDown,
  60238. delta > 0);
  60239. }
  60240. private:
  60241. MidiKeyboardComponent& owner;
  60242. const int delta;
  60243. JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
  60244. };
  60245. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60246. const Orientation orientation_)
  60247. : state (state_),
  60248. xOffset (0),
  60249. blackNoteLength (1),
  60250. keyWidth (16.0f),
  60251. orientation (orientation_),
  60252. midiChannel (1),
  60253. midiInChannelMask (0xffff),
  60254. velocity (1.0f),
  60255. noteUnderMouse (-1),
  60256. mouseDownNote (-1),
  60257. rangeStart (0),
  60258. rangeEnd (127),
  60259. firstKey (12 * 4),
  60260. canScroll (true),
  60261. mouseDragging (false),
  60262. useMousePositionForVelocity (true),
  60263. keyMappingOctave (6),
  60264. octaveNumForMiddleC (3)
  60265. {
  60266. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60267. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60268. // initialise with a default set of querty key-mappings..
  60269. const char* const keymap = "awsedftgyhujkolp;";
  60270. for (int i = String (keymap).length(); --i >= 0;)
  60271. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60272. setOpaque (true);
  60273. setWantsKeyboardFocus (true);
  60274. state.addListener (this);
  60275. }
  60276. MidiKeyboardComponent::~MidiKeyboardComponent()
  60277. {
  60278. state.removeListener (this);
  60279. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60280. }
  60281. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60282. {
  60283. keyWidth = widthInPixels;
  60284. resized();
  60285. }
  60286. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60287. {
  60288. if (orientation != newOrientation)
  60289. {
  60290. orientation = newOrientation;
  60291. resized();
  60292. }
  60293. }
  60294. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60295. const int highestNote)
  60296. {
  60297. jassert (lowestNote >= 0 && lowestNote <= 127);
  60298. jassert (highestNote >= 0 && highestNote <= 127);
  60299. jassert (lowestNote <= highestNote);
  60300. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60301. {
  60302. rangeStart = jlimit (0, 127, lowestNote);
  60303. rangeEnd = jlimit (0, 127, highestNote);
  60304. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60305. resized();
  60306. }
  60307. }
  60308. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60309. {
  60310. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60311. if (noteNumber != firstKey)
  60312. {
  60313. firstKey = noteNumber;
  60314. sendChangeMessage();
  60315. resized();
  60316. }
  60317. }
  60318. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60319. {
  60320. if (canScroll != canScroll_)
  60321. {
  60322. canScroll = canScroll_;
  60323. resized();
  60324. }
  60325. }
  60326. void MidiKeyboardComponent::colourChanged()
  60327. {
  60328. repaint();
  60329. }
  60330. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60331. {
  60332. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60333. if (midiChannel != midiChannelNumber)
  60334. {
  60335. resetAnyKeysInUse();
  60336. midiChannel = jlimit (1, 16, midiChannelNumber);
  60337. }
  60338. }
  60339. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60340. {
  60341. midiInChannelMask = midiChannelMask;
  60342. triggerAsyncUpdate();
  60343. }
  60344. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60345. {
  60346. velocity = jlimit (0.0f, 1.0f, velocity_);
  60347. useMousePositionForVelocity = useMousePositionForVelocity_;
  60348. }
  60349. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60350. {
  60351. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60352. static const float blackNoteWidth = 0.7f;
  60353. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60354. 1.0f, 2 - blackNoteWidth * 0.4f,
  60355. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60356. 4.0f, 5 - blackNoteWidth * 0.5f,
  60357. 5.0f, 6 - blackNoteWidth * 0.3f,
  60358. 6.0f };
  60359. static const float widths[] = { 1.0f, blackNoteWidth,
  60360. 1.0f, blackNoteWidth,
  60361. 1.0f, 1.0f, blackNoteWidth,
  60362. 1.0f, blackNoteWidth,
  60363. 1.0f, blackNoteWidth,
  60364. 1.0f };
  60365. const int octave = midiNoteNumber / 12;
  60366. const int note = midiNoteNumber % 12;
  60367. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60368. w = roundToInt (widths [note] * keyWidth_);
  60369. }
  60370. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60371. {
  60372. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60373. int rx, rw;
  60374. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60375. x -= xOffset + rx;
  60376. }
  60377. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60378. {
  60379. int x, y;
  60380. getKeyPos (midiNoteNumber, x, y);
  60381. return x;
  60382. }
  60383. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60384. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60385. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60386. {
  60387. if (! reallyContains (pos, false))
  60388. return -1;
  60389. Point<int> p (pos);
  60390. if (orientation != horizontalKeyboard)
  60391. {
  60392. p = Point<int> (p.getY(), p.getX());
  60393. if (orientation == verticalKeyboardFacingLeft)
  60394. p = Point<int> (p.getX(), getWidth() - p.getY());
  60395. else
  60396. p = Point<int> (getHeight() - p.getX(), p.getY());
  60397. }
  60398. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60399. }
  60400. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60401. {
  60402. if (pos.getY() < blackNoteLength)
  60403. {
  60404. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60405. {
  60406. for (int i = 0; i < 5; ++i)
  60407. {
  60408. const int note = octaveStart + blackNotes [i];
  60409. if (note >= rangeStart && note <= rangeEnd)
  60410. {
  60411. int kx, kw;
  60412. getKeyPos (note, kx, kw);
  60413. kx += xOffset;
  60414. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60415. {
  60416. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60417. return note;
  60418. }
  60419. }
  60420. }
  60421. }
  60422. }
  60423. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60424. {
  60425. for (int i = 0; i < 7; ++i)
  60426. {
  60427. const int note = octaveStart + whiteNotes [i];
  60428. if (note >= rangeStart && note <= rangeEnd)
  60429. {
  60430. int kx, kw;
  60431. getKeyPos (note, kx, kw);
  60432. kx += xOffset;
  60433. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60434. {
  60435. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60436. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60437. return note;
  60438. }
  60439. }
  60440. }
  60441. }
  60442. mousePositionVelocity = 0;
  60443. return -1;
  60444. }
  60445. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60446. {
  60447. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60448. {
  60449. int x, w;
  60450. getKeyPos (noteNum, x, w);
  60451. if (orientation == horizontalKeyboard)
  60452. repaint (x, 0, w, getHeight());
  60453. else if (orientation == verticalKeyboardFacingLeft)
  60454. repaint (0, x, getWidth(), w);
  60455. else if (orientation == verticalKeyboardFacingRight)
  60456. repaint (0, getHeight() - x - w, getWidth(), w);
  60457. }
  60458. }
  60459. void MidiKeyboardComponent::paint (Graphics& g)
  60460. {
  60461. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60462. const Colour lineColour (findColour (keySeparatorLineColourId));
  60463. const Colour textColour (findColour (textLabelColourId));
  60464. int x, w, octave;
  60465. for (octave = 0; octave < 128; octave += 12)
  60466. {
  60467. for (int white = 0; white < 7; ++white)
  60468. {
  60469. const int noteNum = octave + whiteNotes [white];
  60470. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60471. {
  60472. getKeyPos (noteNum, x, w);
  60473. if (orientation == horizontalKeyboard)
  60474. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60475. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60476. noteUnderMouse == noteNum,
  60477. lineColour, textColour);
  60478. else if (orientation == verticalKeyboardFacingLeft)
  60479. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60480. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60481. noteUnderMouse == noteNum,
  60482. lineColour, textColour);
  60483. else if (orientation == verticalKeyboardFacingRight)
  60484. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60485. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60486. noteUnderMouse == noteNum,
  60487. lineColour, textColour);
  60488. }
  60489. }
  60490. }
  60491. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60492. if (orientation == verticalKeyboardFacingLeft)
  60493. {
  60494. x1 = getWidth() - 1.0f;
  60495. x2 = getWidth() - 5.0f;
  60496. }
  60497. else if (orientation == verticalKeyboardFacingRight)
  60498. x2 = 5.0f;
  60499. else
  60500. y2 = 5.0f;
  60501. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60502. Colours::transparentBlack, x2, y2, false));
  60503. getKeyPos (rangeEnd, x, w);
  60504. x += w;
  60505. if (orientation == verticalKeyboardFacingLeft)
  60506. g.fillRect (getWidth() - 5, 0, 5, x);
  60507. else if (orientation == verticalKeyboardFacingRight)
  60508. g.fillRect (0, 0, 5, x);
  60509. else
  60510. g.fillRect (0, 0, x, 5);
  60511. g.setColour (lineColour);
  60512. if (orientation == verticalKeyboardFacingLeft)
  60513. g.fillRect (0, 0, 1, x);
  60514. else if (orientation == verticalKeyboardFacingRight)
  60515. g.fillRect (getWidth() - 1, 0, 1, x);
  60516. else
  60517. g.fillRect (0, getHeight() - 1, x, 1);
  60518. const Colour blackNoteColour (findColour (blackNoteColourId));
  60519. for (octave = 0; octave < 128; octave += 12)
  60520. {
  60521. for (int black = 0; black < 5; ++black)
  60522. {
  60523. const int noteNum = octave + blackNotes [black];
  60524. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60525. {
  60526. getKeyPos (noteNum, x, w);
  60527. if (orientation == horizontalKeyboard)
  60528. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60529. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60530. noteUnderMouse == noteNum,
  60531. blackNoteColour);
  60532. else if (orientation == verticalKeyboardFacingLeft)
  60533. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60534. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60535. noteUnderMouse == noteNum,
  60536. blackNoteColour);
  60537. else if (orientation == verticalKeyboardFacingRight)
  60538. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60539. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60540. noteUnderMouse == noteNum,
  60541. blackNoteColour);
  60542. }
  60543. }
  60544. }
  60545. }
  60546. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60547. Graphics& g, int x, int y, int w, int h,
  60548. bool isDown, bool isOver,
  60549. const Colour& lineColour,
  60550. const Colour& textColour)
  60551. {
  60552. Colour c (Colours::transparentWhite);
  60553. if (isDown)
  60554. c = findColour (keyDownOverlayColourId);
  60555. if (isOver)
  60556. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60557. g.setColour (c);
  60558. g.fillRect (x, y, w, h);
  60559. const String text (getWhiteNoteText (midiNoteNumber));
  60560. if (! text.isEmpty())
  60561. {
  60562. g.setColour (textColour);
  60563. Font f (jmin (12.0f, keyWidth * 0.9f));
  60564. f.setHorizontalScale (0.8f);
  60565. g.setFont (f);
  60566. Justification justification (Justification::centredBottom);
  60567. if (orientation == verticalKeyboardFacingLeft)
  60568. justification = Justification::centredLeft;
  60569. else if (orientation == verticalKeyboardFacingRight)
  60570. justification = Justification::centredRight;
  60571. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60572. }
  60573. g.setColour (lineColour);
  60574. if (orientation == horizontalKeyboard)
  60575. g.fillRect (x, y, 1, h);
  60576. else if (orientation == verticalKeyboardFacingLeft)
  60577. g.fillRect (x, y, w, 1);
  60578. else if (orientation == verticalKeyboardFacingRight)
  60579. g.fillRect (x, y + h - 1, w, 1);
  60580. if (midiNoteNumber == rangeEnd)
  60581. {
  60582. if (orientation == horizontalKeyboard)
  60583. g.fillRect (x + w, y, 1, h);
  60584. else if (orientation == verticalKeyboardFacingLeft)
  60585. g.fillRect (x, y + h, w, 1);
  60586. else if (orientation == verticalKeyboardFacingRight)
  60587. g.fillRect (x, y - 1, w, 1);
  60588. }
  60589. }
  60590. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60591. Graphics& g, int x, int y, int w, int h,
  60592. bool isDown, bool isOver,
  60593. const Colour& noteFillColour)
  60594. {
  60595. Colour c (noteFillColour);
  60596. if (isDown)
  60597. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60598. if (isOver)
  60599. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60600. g.setColour (c);
  60601. g.fillRect (x, y, w, h);
  60602. if (isDown)
  60603. {
  60604. g.setColour (noteFillColour);
  60605. g.drawRect (x, y, w, h);
  60606. }
  60607. else
  60608. {
  60609. const int xIndent = jmax (1, jmin (w, h) / 8);
  60610. g.setColour (c.brighter());
  60611. if (orientation == horizontalKeyboard)
  60612. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60613. else if (orientation == verticalKeyboardFacingLeft)
  60614. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60615. else if (orientation == verticalKeyboardFacingRight)
  60616. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60617. }
  60618. }
  60619. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60620. {
  60621. octaveNumForMiddleC = octaveNumForMiddleC_;
  60622. repaint();
  60623. }
  60624. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60625. {
  60626. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60627. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60628. return String::empty;
  60629. }
  60630. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60631. const bool isMouseOver_,
  60632. const bool isButtonDown,
  60633. const bool movesOctavesUp)
  60634. {
  60635. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60636. float angle;
  60637. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60638. angle = movesOctavesUp ? 0.0f : 0.5f;
  60639. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60640. angle = movesOctavesUp ? 0.25f : 0.75f;
  60641. else
  60642. angle = movesOctavesUp ? 0.75f : 0.25f;
  60643. Path path;
  60644. path.lineTo (0.0f, 1.0f);
  60645. path.lineTo (1.0f, 0.5f);
  60646. path.closeSubPath();
  60647. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60648. g.setColour (findColour (upDownButtonArrowColourId)
  60649. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60650. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60651. w - 2.0f,
  60652. h - 2.0f,
  60653. true));
  60654. }
  60655. void MidiKeyboardComponent::resized()
  60656. {
  60657. int w = getWidth();
  60658. int h = getHeight();
  60659. if (w > 0 && h > 0)
  60660. {
  60661. if (orientation != horizontalKeyboard)
  60662. swapVariables (w, h);
  60663. blackNoteLength = roundToInt (h * 0.7f);
  60664. int kx2, kw2;
  60665. getKeyPos (rangeEnd, kx2, kw2);
  60666. kx2 += kw2;
  60667. if (firstKey != rangeStart)
  60668. {
  60669. int kx1, kw1;
  60670. getKeyPos (rangeStart, kx1, kw1);
  60671. if (kx2 - kx1 <= w)
  60672. {
  60673. firstKey = rangeStart;
  60674. sendChangeMessage();
  60675. repaint();
  60676. }
  60677. }
  60678. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60679. scrollDown->setVisible (showScrollButtons);
  60680. scrollUp->setVisible (showScrollButtons);
  60681. xOffset = 0;
  60682. if (showScrollButtons)
  60683. {
  60684. const int scrollButtonW = jmin (12, w / 2);
  60685. if (orientation == horizontalKeyboard)
  60686. {
  60687. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60688. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60689. }
  60690. else if (orientation == verticalKeyboardFacingLeft)
  60691. {
  60692. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60693. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60694. }
  60695. else if (orientation == verticalKeyboardFacingRight)
  60696. {
  60697. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60698. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60699. }
  60700. int endOfLastKey, kw;
  60701. getKeyPos (rangeEnd, endOfLastKey, kw);
  60702. endOfLastKey += kw;
  60703. float mousePositionVelocity;
  60704. const int spaceAvailable = w - scrollButtonW * 2;
  60705. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60706. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60707. {
  60708. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60709. sendChangeMessage();
  60710. }
  60711. int newOffset = 0;
  60712. getKeyPos (firstKey, newOffset, kw);
  60713. xOffset = newOffset - scrollButtonW;
  60714. }
  60715. else
  60716. {
  60717. firstKey = rangeStart;
  60718. }
  60719. timerCallback();
  60720. repaint();
  60721. }
  60722. }
  60723. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60724. {
  60725. triggerAsyncUpdate();
  60726. }
  60727. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60728. {
  60729. triggerAsyncUpdate();
  60730. }
  60731. void MidiKeyboardComponent::handleAsyncUpdate()
  60732. {
  60733. for (int i = rangeStart; i <= rangeEnd; ++i)
  60734. {
  60735. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60736. {
  60737. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60738. repaintNote (i);
  60739. }
  60740. }
  60741. }
  60742. void MidiKeyboardComponent::resetAnyKeysInUse()
  60743. {
  60744. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60745. {
  60746. state.allNotesOff (midiChannel);
  60747. keysPressed.clear();
  60748. mouseDownNote = -1;
  60749. }
  60750. }
  60751. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60752. {
  60753. float mousePositionVelocity = 0.0f;
  60754. const int newNote = (mouseDragging || isMouseOver())
  60755. ? xyToNote (pos, mousePositionVelocity) : -1;
  60756. if (noteUnderMouse != newNote)
  60757. {
  60758. if (mouseDownNote >= 0)
  60759. {
  60760. state.noteOff (midiChannel, mouseDownNote);
  60761. mouseDownNote = -1;
  60762. }
  60763. if (mouseDragging && newNote >= 0)
  60764. {
  60765. if (! useMousePositionForVelocity)
  60766. mousePositionVelocity = 1.0f;
  60767. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60768. mouseDownNote = newNote;
  60769. }
  60770. repaintNote (noteUnderMouse);
  60771. noteUnderMouse = newNote;
  60772. repaintNote (noteUnderMouse);
  60773. }
  60774. else if (mouseDownNote >= 0 && ! mouseDragging)
  60775. {
  60776. state.noteOff (midiChannel, mouseDownNote);
  60777. mouseDownNote = -1;
  60778. }
  60779. }
  60780. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60781. {
  60782. updateNoteUnderMouse (e.getPosition());
  60783. stopTimer();
  60784. }
  60785. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60786. {
  60787. float mousePositionVelocity;
  60788. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60789. if (newNote >= 0)
  60790. mouseDraggedToKey (newNote, e);
  60791. updateNoteUnderMouse (e.getPosition());
  60792. }
  60793. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60794. {
  60795. return true;
  60796. }
  60797. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60798. {
  60799. }
  60800. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60801. {
  60802. float mousePositionVelocity;
  60803. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60804. mouseDragging = false;
  60805. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60806. {
  60807. repaintNote (noteUnderMouse);
  60808. noteUnderMouse = -1;
  60809. mouseDragging = true;
  60810. updateNoteUnderMouse (e.getPosition());
  60811. startTimer (500);
  60812. }
  60813. }
  60814. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60815. {
  60816. mouseDragging = false;
  60817. updateNoteUnderMouse (e.getPosition());
  60818. stopTimer();
  60819. }
  60820. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60821. {
  60822. updateNoteUnderMouse (e.getPosition());
  60823. }
  60824. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60825. {
  60826. updateNoteUnderMouse (e.getPosition());
  60827. }
  60828. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60829. {
  60830. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60831. }
  60832. void MidiKeyboardComponent::timerCallback()
  60833. {
  60834. updateNoteUnderMouse (getMouseXYRelative());
  60835. }
  60836. void MidiKeyboardComponent::clearKeyMappings()
  60837. {
  60838. resetAnyKeysInUse();
  60839. keyPressNotes.clear();
  60840. keyPresses.clear();
  60841. }
  60842. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60843. const int midiNoteOffsetFromC)
  60844. {
  60845. removeKeyPressForNote (midiNoteOffsetFromC);
  60846. keyPressNotes.add (midiNoteOffsetFromC);
  60847. keyPresses.add (key);
  60848. }
  60849. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60850. {
  60851. for (int i = keyPressNotes.size(); --i >= 0;)
  60852. {
  60853. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60854. {
  60855. keyPressNotes.remove (i);
  60856. keyPresses.remove (i);
  60857. }
  60858. }
  60859. }
  60860. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60861. {
  60862. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60863. keyMappingOctave = newOctaveNumber;
  60864. }
  60865. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60866. {
  60867. bool keyPressUsed = false;
  60868. for (int i = keyPresses.size(); --i >= 0;)
  60869. {
  60870. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60871. if (keyPresses.getReference(i).isCurrentlyDown())
  60872. {
  60873. if (! keysPressed [note])
  60874. {
  60875. keysPressed.setBit (note);
  60876. state.noteOn (midiChannel, note, velocity);
  60877. keyPressUsed = true;
  60878. }
  60879. }
  60880. else
  60881. {
  60882. if (keysPressed [note])
  60883. {
  60884. keysPressed.clearBit (note);
  60885. state.noteOff (midiChannel, note);
  60886. keyPressUsed = true;
  60887. }
  60888. }
  60889. }
  60890. return keyPressUsed;
  60891. }
  60892. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60893. {
  60894. resetAnyKeysInUse();
  60895. }
  60896. END_JUCE_NAMESPACE
  60897. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60898. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60899. #if JUCE_OPENGL
  60900. BEGIN_JUCE_NAMESPACE
  60901. extern void juce_glViewport (const int w, const int h);
  60902. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60903. const int alphaBits_,
  60904. const int depthBufferBits_,
  60905. const int stencilBufferBits_)
  60906. : redBits (bitsPerRGBComponent),
  60907. greenBits (bitsPerRGBComponent),
  60908. blueBits (bitsPerRGBComponent),
  60909. alphaBits (alphaBits_),
  60910. depthBufferBits (depthBufferBits_),
  60911. stencilBufferBits (stencilBufferBits_),
  60912. accumulationBufferRedBits (0),
  60913. accumulationBufferGreenBits (0),
  60914. accumulationBufferBlueBits (0),
  60915. accumulationBufferAlphaBits (0),
  60916. fullSceneAntiAliasingNumSamples (0)
  60917. {
  60918. }
  60919. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60920. : redBits (other.redBits),
  60921. greenBits (other.greenBits),
  60922. blueBits (other.blueBits),
  60923. alphaBits (other.alphaBits),
  60924. depthBufferBits (other.depthBufferBits),
  60925. stencilBufferBits (other.stencilBufferBits),
  60926. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60927. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60928. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60929. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60930. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60931. {
  60932. }
  60933. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60934. {
  60935. redBits = other.redBits;
  60936. greenBits = other.greenBits;
  60937. blueBits = other.blueBits;
  60938. alphaBits = other.alphaBits;
  60939. depthBufferBits = other.depthBufferBits;
  60940. stencilBufferBits = other.stencilBufferBits;
  60941. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60942. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60943. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60944. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60945. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60946. return *this;
  60947. }
  60948. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60949. {
  60950. return redBits == other.redBits
  60951. && greenBits == other.greenBits
  60952. && blueBits == other.blueBits
  60953. && alphaBits == other.alphaBits
  60954. && depthBufferBits == other.depthBufferBits
  60955. && stencilBufferBits == other.stencilBufferBits
  60956. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60957. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60958. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60959. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60960. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60961. }
  60962. static Array<OpenGLContext*> knownContexts;
  60963. OpenGLContext::OpenGLContext() throw()
  60964. {
  60965. knownContexts.add (this);
  60966. }
  60967. OpenGLContext::~OpenGLContext()
  60968. {
  60969. knownContexts.removeValue (this);
  60970. }
  60971. OpenGLContext* OpenGLContext::getCurrentContext()
  60972. {
  60973. for (int i = knownContexts.size(); --i >= 0;)
  60974. {
  60975. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60976. if (oglc->isActive())
  60977. return oglc;
  60978. }
  60979. return 0;
  60980. }
  60981. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60982. {
  60983. public:
  60984. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60985. : ComponentMovementWatcher (owner_),
  60986. owner (owner_)
  60987. {
  60988. }
  60989. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60990. {
  60991. owner->updateContextPosition();
  60992. }
  60993. void componentPeerChanged()
  60994. {
  60995. const ScopedLock sl (owner->getContextLock());
  60996. owner->deleteContext();
  60997. }
  60998. void componentVisibilityChanged()
  60999. {
  61000. if (! owner->isShowing())
  61001. {
  61002. const ScopedLock sl (owner->getContextLock());
  61003. owner->deleteContext();
  61004. }
  61005. }
  61006. private:
  61007. OpenGLComponent* const owner;
  61008. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponentWatcher);
  61009. };
  61010. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61011. : type (type_),
  61012. contextToShareListsWith (0),
  61013. needToUpdateViewport (true)
  61014. {
  61015. setOpaque (true);
  61016. componentWatcher = new OpenGLComponentWatcher (this);
  61017. }
  61018. OpenGLComponent::~OpenGLComponent()
  61019. {
  61020. deleteContext();
  61021. componentWatcher = 0;
  61022. }
  61023. void OpenGLComponent::deleteContext()
  61024. {
  61025. const ScopedLock sl (contextLock);
  61026. context = 0;
  61027. }
  61028. void OpenGLComponent::updateContextPosition()
  61029. {
  61030. needToUpdateViewport = true;
  61031. if (getWidth() > 0 && getHeight() > 0)
  61032. {
  61033. Component* const topComp = getTopLevelComponent();
  61034. if (topComp->getPeer() != 0)
  61035. {
  61036. const ScopedLock sl (contextLock);
  61037. if (context != 0)
  61038. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61039. getScreenY() - topComp->getScreenY(),
  61040. getWidth(),
  61041. getHeight(),
  61042. topComp->getHeight());
  61043. }
  61044. }
  61045. }
  61046. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61047. {
  61048. OpenGLPixelFormat pf;
  61049. const ScopedLock sl (contextLock);
  61050. if (context != 0)
  61051. pf = context->getPixelFormat();
  61052. return pf;
  61053. }
  61054. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61055. {
  61056. if (! (preferredPixelFormat == formatToUse))
  61057. {
  61058. const ScopedLock sl (contextLock);
  61059. deleteContext();
  61060. preferredPixelFormat = formatToUse;
  61061. }
  61062. }
  61063. void OpenGLComponent::shareWith (OpenGLContext* c)
  61064. {
  61065. if (contextToShareListsWith != c)
  61066. {
  61067. const ScopedLock sl (contextLock);
  61068. deleteContext();
  61069. contextToShareListsWith = c;
  61070. }
  61071. }
  61072. bool OpenGLComponent::makeCurrentContextActive()
  61073. {
  61074. if (context == 0)
  61075. {
  61076. const ScopedLock sl (contextLock);
  61077. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61078. {
  61079. context = createContext();
  61080. if (context != 0)
  61081. {
  61082. updateContextPosition();
  61083. if (context->makeActive())
  61084. newOpenGLContextCreated();
  61085. }
  61086. }
  61087. }
  61088. return context != 0 && context->makeActive();
  61089. }
  61090. void OpenGLComponent::makeCurrentContextInactive()
  61091. {
  61092. if (context != 0)
  61093. context->makeInactive();
  61094. }
  61095. bool OpenGLComponent::isActiveContext() const throw()
  61096. {
  61097. return context != 0 && context->isActive();
  61098. }
  61099. void OpenGLComponent::swapBuffers()
  61100. {
  61101. if (context != 0)
  61102. context->swapBuffers();
  61103. }
  61104. void OpenGLComponent::paint (Graphics&)
  61105. {
  61106. if (renderAndSwapBuffers())
  61107. {
  61108. ComponentPeer* const peer = getPeer();
  61109. if (peer != 0)
  61110. {
  61111. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61112. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61113. }
  61114. }
  61115. }
  61116. bool OpenGLComponent::renderAndSwapBuffers()
  61117. {
  61118. const ScopedLock sl (contextLock);
  61119. if (! makeCurrentContextActive())
  61120. return false;
  61121. if (needToUpdateViewport)
  61122. {
  61123. needToUpdateViewport = false;
  61124. juce_glViewport (getWidth(), getHeight());
  61125. }
  61126. renderOpenGL();
  61127. swapBuffers();
  61128. return true;
  61129. }
  61130. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61131. {
  61132. Component::internalRepaint (x, y, w, h);
  61133. if (context != 0)
  61134. context->repaint();
  61135. }
  61136. END_JUCE_NAMESPACE
  61137. #endif
  61138. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61139. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61140. BEGIN_JUCE_NAMESPACE
  61141. PreferencesPanel::PreferencesPanel()
  61142. : buttonSize (70)
  61143. {
  61144. }
  61145. PreferencesPanel::~PreferencesPanel()
  61146. {
  61147. }
  61148. void PreferencesPanel::addSettingsPage (const String& title,
  61149. const Drawable* icon,
  61150. const Drawable* overIcon,
  61151. const Drawable* downIcon)
  61152. {
  61153. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61154. buttons.add (button);
  61155. button->setImages (icon, overIcon, downIcon);
  61156. button->setRadioGroupId (1);
  61157. button->addListener (this);
  61158. button->setClickingTogglesState (true);
  61159. button->setWantsKeyboardFocus (false);
  61160. addAndMakeVisible (button);
  61161. resized();
  61162. if (currentPage == 0)
  61163. setCurrentPage (title);
  61164. }
  61165. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61166. {
  61167. DrawableImage icon, iconOver, iconDown;
  61168. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61169. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61170. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61171. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61172. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61173. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61174. }
  61175. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61176. {
  61177. setSize (dialogWidth, dialogHeight);
  61178. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61179. }
  61180. void PreferencesPanel::resized()
  61181. {
  61182. for (int i = 0; i < buttons.size(); ++i)
  61183. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61184. if (currentPage != 0)
  61185. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61186. }
  61187. void PreferencesPanel::paint (Graphics& g)
  61188. {
  61189. g.setColour (Colours::grey);
  61190. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61191. }
  61192. void PreferencesPanel::setCurrentPage (const String& pageName)
  61193. {
  61194. if (currentPageName != pageName)
  61195. {
  61196. currentPageName = pageName;
  61197. currentPage = 0;
  61198. currentPage = createComponentForPage (pageName);
  61199. if (currentPage != 0)
  61200. {
  61201. addAndMakeVisible (currentPage);
  61202. currentPage->toBack();
  61203. resized();
  61204. }
  61205. for (int i = 0; i < buttons.size(); ++i)
  61206. {
  61207. if (buttons.getUnchecked(i)->getName() == pageName)
  61208. {
  61209. buttons.getUnchecked(i)->setToggleState (true, false);
  61210. break;
  61211. }
  61212. }
  61213. }
  61214. }
  61215. void PreferencesPanel::buttonClicked (Button*)
  61216. {
  61217. for (int i = 0; i < buttons.size(); ++i)
  61218. {
  61219. if (buttons.getUnchecked(i)->getToggleState())
  61220. {
  61221. setCurrentPage (buttons.getUnchecked(i)->getName());
  61222. break;
  61223. }
  61224. }
  61225. }
  61226. END_JUCE_NAMESPACE
  61227. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61228. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61229. #if JUCE_WINDOWS || JUCE_LINUX
  61230. BEGIN_JUCE_NAMESPACE
  61231. SystemTrayIconComponent::SystemTrayIconComponent()
  61232. {
  61233. addToDesktop (0);
  61234. }
  61235. SystemTrayIconComponent::~SystemTrayIconComponent()
  61236. {
  61237. }
  61238. END_JUCE_NAMESPACE
  61239. #endif
  61240. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61241. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61242. BEGIN_JUCE_NAMESPACE
  61243. class AlertWindowTextEditor : public TextEditor
  61244. {
  61245. public:
  61246. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61247. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61248. {
  61249. setSelectAllWhenFocused (true);
  61250. }
  61251. void returnPressed()
  61252. {
  61253. // pass these up the component hierarchy to be trigger the buttons
  61254. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61255. }
  61256. void escapePressed()
  61257. {
  61258. // pass these up the component hierarchy to be trigger the buttons
  61259. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61260. }
  61261. private:
  61262. JUCE_DECLARE_NON_COPYABLE (AlertWindowTextEditor);
  61263. static juce_wchar getDefaultPasswordChar() throw()
  61264. {
  61265. #if JUCE_LINUX
  61266. return 0x2022;
  61267. #else
  61268. return 0x25cf;
  61269. #endif
  61270. }
  61271. };
  61272. AlertWindow::AlertWindow (const String& title,
  61273. const String& message,
  61274. AlertIconType iconType,
  61275. Component* associatedComponent_)
  61276. : TopLevelWindow (title, true),
  61277. alertIconType (iconType),
  61278. associatedComponent (associatedComponent_)
  61279. {
  61280. if (message.isEmpty())
  61281. text = " "; // to force an update if the message is empty
  61282. setMessage (message);
  61283. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61284. {
  61285. Component* const c = Desktop::getInstance().getComponent (i);
  61286. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61287. {
  61288. setAlwaysOnTop (true);
  61289. break;
  61290. }
  61291. }
  61292. if (! JUCEApplication::isStandaloneApp())
  61293. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61294. lookAndFeelChanged();
  61295. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61296. }
  61297. AlertWindow::~AlertWindow()
  61298. {
  61299. removeAllChildren();
  61300. }
  61301. void AlertWindow::userTriedToCloseWindow()
  61302. {
  61303. exitModalState (0);
  61304. }
  61305. void AlertWindow::setMessage (const String& message)
  61306. {
  61307. const String newMessage (message.substring (0, 2048));
  61308. if (text != newMessage)
  61309. {
  61310. text = newMessage;
  61311. font = getLookAndFeel().getAlertWindowMessageFont();
  61312. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61313. textLayout.setText (getName() + "\n\n", titleFont);
  61314. textLayout.appendText (text, font);
  61315. updateLayout (true);
  61316. repaint();
  61317. }
  61318. }
  61319. void AlertWindow::buttonClicked (Button* button)
  61320. {
  61321. if (button->getParentComponent() != 0)
  61322. button->getParentComponent()->exitModalState (button->getCommandID());
  61323. }
  61324. void AlertWindow::addButton (const String& name,
  61325. const int returnValue,
  61326. const KeyPress& shortcutKey1,
  61327. const KeyPress& shortcutKey2)
  61328. {
  61329. TextButton* const b = new TextButton (name, String::empty);
  61330. buttons.add (b);
  61331. b->setWantsKeyboardFocus (true);
  61332. b->setMouseClickGrabsKeyboardFocus (false);
  61333. b->setCommandToTrigger (0, returnValue, false);
  61334. b->addShortcut (shortcutKey1);
  61335. b->addShortcut (shortcutKey2);
  61336. b->addListener (this);
  61337. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61338. addAndMakeVisible (b, 0);
  61339. updateLayout (false);
  61340. }
  61341. int AlertWindow::getNumButtons() const
  61342. {
  61343. return buttons.size();
  61344. }
  61345. void AlertWindow::triggerButtonClick (const String& buttonName)
  61346. {
  61347. for (int i = buttons.size(); --i >= 0;)
  61348. {
  61349. TextButton* const b = buttons.getUnchecked(i);
  61350. if (buttonName == b->getName())
  61351. {
  61352. b->triggerClick();
  61353. break;
  61354. }
  61355. }
  61356. }
  61357. void AlertWindow::addTextEditor (const String& name,
  61358. const String& initialContents,
  61359. const String& onScreenLabel,
  61360. const bool isPasswordBox)
  61361. {
  61362. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61363. textBoxes.add (tc);
  61364. allComps.add (tc);
  61365. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61366. tc->setFont (font);
  61367. tc->setText (initialContents);
  61368. tc->setCaretPosition (initialContents.length());
  61369. addAndMakeVisible (tc);
  61370. textboxNames.add (onScreenLabel);
  61371. updateLayout (false);
  61372. }
  61373. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61374. {
  61375. for (int i = textBoxes.size(); --i >= 0;)
  61376. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61377. return textBoxes.getUnchecked(i);
  61378. return 0;
  61379. }
  61380. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61381. {
  61382. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61383. return t != 0 ? t->getText() : String::empty;
  61384. }
  61385. void AlertWindow::addComboBox (const String& name,
  61386. const StringArray& items,
  61387. const String& onScreenLabel)
  61388. {
  61389. ComboBox* const cb = new ComboBox (name);
  61390. comboBoxes.add (cb);
  61391. allComps.add (cb);
  61392. for (int i = 0; i < items.size(); ++i)
  61393. cb->addItem (items[i], i + 1);
  61394. addAndMakeVisible (cb);
  61395. cb->setSelectedItemIndex (0);
  61396. comboBoxNames.add (onScreenLabel);
  61397. updateLayout (false);
  61398. }
  61399. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61400. {
  61401. for (int i = comboBoxes.size(); --i >= 0;)
  61402. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61403. return comboBoxes.getUnchecked(i);
  61404. return 0;
  61405. }
  61406. class AlertTextComp : public TextEditor
  61407. {
  61408. public:
  61409. AlertTextComp (const String& message,
  61410. const Font& font)
  61411. {
  61412. setReadOnly (true);
  61413. setMultiLine (true, true);
  61414. setCaretVisible (false);
  61415. setScrollbarsShown (true);
  61416. lookAndFeelChanged();
  61417. setWantsKeyboardFocus (false);
  61418. setFont (font);
  61419. setText (message, false);
  61420. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61421. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61422. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61423. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61424. }
  61425. ~AlertTextComp()
  61426. {
  61427. }
  61428. int getPreferredWidth() const throw() { return bestWidth; }
  61429. void updateLayout (const int width)
  61430. {
  61431. TextLayout text;
  61432. text.appendText (getText(), getFont());
  61433. text.layout (width - 8, Justification::topLeft, true);
  61434. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61435. }
  61436. private:
  61437. int bestWidth;
  61438. JUCE_DECLARE_NON_COPYABLE (AlertTextComp);
  61439. };
  61440. void AlertWindow::addTextBlock (const String& textBlock)
  61441. {
  61442. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61443. textBlocks.add (c);
  61444. allComps.add (c);
  61445. addAndMakeVisible (c);
  61446. updateLayout (false);
  61447. }
  61448. void AlertWindow::addProgressBarComponent (double& progressValue)
  61449. {
  61450. ProgressBar* const pb = new ProgressBar (progressValue);
  61451. progressBars.add (pb);
  61452. allComps.add (pb);
  61453. addAndMakeVisible (pb);
  61454. updateLayout (false);
  61455. }
  61456. void AlertWindow::addCustomComponent (Component* const component)
  61457. {
  61458. customComps.add (component);
  61459. allComps.add (component);
  61460. addAndMakeVisible (component);
  61461. updateLayout (false);
  61462. }
  61463. int AlertWindow::getNumCustomComponents() const
  61464. {
  61465. return customComps.size();
  61466. }
  61467. Component* AlertWindow::getCustomComponent (const int index) const
  61468. {
  61469. return customComps [index];
  61470. }
  61471. Component* AlertWindow::removeCustomComponent (const int index)
  61472. {
  61473. Component* const c = getCustomComponent (index);
  61474. if (c != 0)
  61475. {
  61476. customComps.removeValue (c);
  61477. allComps.removeValue (c);
  61478. removeChildComponent (c);
  61479. updateLayout (false);
  61480. }
  61481. return c;
  61482. }
  61483. void AlertWindow::paint (Graphics& g)
  61484. {
  61485. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61486. g.setColour (findColour (textColourId));
  61487. g.setFont (getLookAndFeel().getAlertWindowFont());
  61488. int i;
  61489. for (i = textBoxes.size(); --i >= 0;)
  61490. {
  61491. const TextEditor* const te = textBoxes.getUnchecked(i);
  61492. g.drawFittedText (textboxNames[i],
  61493. te->getX(), te->getY() - 14,
  61494. te->getWidth(), 14,
  61495. Justification::centredLeft, 1);
  61496. }
  61497. for (i = comboBoxNames.size(); --i >= 0;)
  61498. {
  61499. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61500. g.drawFittedText (comboBoxNames[i],
  61501. cb->getX(), cb->getY() - 14,
  61502. cb->getWidth(), 14,
  61503. Justification::centredLeft, 1);
  61504. }
  61505. for (i = customComps.size(); --i >= 0;)
  61506. {
  61507. const Component* const c = customComps.getUnchecked(i);
  61508. g.drawFittedText (c->getName(),
  61509. c->getX(), c->getY() - 14,
  61510. c->getWidth(), 14,
  61511. Justification::centredLeft, 1);
  61512. }
  61513. }
  61514. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61515. {
  61516. const int titleH = 24;
  61517. const int iconWidth = 80;
  61518. const int wid = jmax (font.getStringWidth (text),
  61519. font.getStringWidth (getName()));
  61520. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61521. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61522. const int edgeGap = 10;
  61523. const int labelHeight = 18;
  61524. int iconSpace;
  61525. if (alertIconType == NoIcon)
  61526. {
  61527. textLayout.layout (w, Justification::horizontallyCentred, true);
  61528. iconSpace = 0;
  61529. }
  61530. else
  61531. {
  61532. textLayout.layout (w, Justification::left, true);
  61533. iconSpace = iconWidth;
  61534. }
  61535. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61536. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61537. const int textLayoutH = textLayout.getHeight();
  61538. const int textBottom = 16 + titleH + textLayoutH;
  61539. int h = textBottom;
  61540. int buttonW = 40;
  61541. int i;
  61542. for (i = 0; i < buttons.size(); ++i)
  61543. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61544. w = jmax (buttonW, w);
  61545. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61546. if (buttons.size() > 0)
  61547. h += 20 + buttons.getUnchecked(0)->getHeight();
  61548. for (i = customComps.size(); --i >= 0;)
  61549. {
  61550. Component* c = customComps.getUnchecked(i);
  61551. w = jmax (w, (c->getWidth() * 100) / 80);
  61552. h += 10 + c->getHeight();
  61553. if (c->getName().isNotEmpty())
  61554. h += labelHeight;
  61555. }
  61556. for (i = textBlocks.size(); --i >= 0;)
  61557. {
  61558. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61559. w = jmax (w, ac->getPreferredWidth());
  61560. }
  61561. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61562. for (i = textBlocks.size(); --i >= 0;)
  61563. {
  61564. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61565. ac->updateLayout ((int) (w * 0.8f));
  61566. h += ac->getHeight() + 10;
  61567. }
  61568. h = jmin (getParentHeight() - 50, h);
  61569. if (onlyIncreaseSize)
  61570. {
  61571. w = jmax (w, getWidth());
  61572. h = jmax (h, getHeight());
  61573. }
  61574. if (! isVisible())
  61575. {
  61576. centreAroundComponent (associatedComponent, w, h);
  61577. }
  61578. else
  61579. {
  61580. const int cx = getX() + getWidth() / 2;
  61581. const int cy = getY() + getHeight() / 2;
  61582. setBounds (cx - w / 2,
  61583. cy - h / 2,
  61584. w, h);
  61585. }
  61586. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61587. const int spacer = 16;
  61588. int totalWidth = -spacer;
  61589. for (i = buttons.size(); --i >= 0;)
  61590. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  61591. int x = (w - totalWidth) / 2;
  61592. int y = (int) (getHeight() * 0.95f);
  61593. for (i = 0; i < buttons.size(); ++i)
  61594. {
  61595. TextButton* const c = buttons.getUnchecked(i);
  61596. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61597. c->setTopLeftPosition (x, ny);
  61598. if (ny < y)
  61599. y = ny;
  61600. x += c->getWidth() + spacer;
  61601. c->toFront (false);
  61602. }
  61603. y = textBottom;
  61604. for (i = 0; i < allComps.size(); ++i)
  61605. {
  61606. Component* const c = allComps.getUnchecked(i);
  61607. h = 22;
  61608. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  61609. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61610. y += labelHeight;
  61611. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  61612. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61613. y += labelHeight;
  61614. if (customComps.contains (c))
  61615. {
  61616. if (c->getName().isNotEmpty())
  61617. y += labelHeight;
  61618. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61619. h = c->getHeight();
  61620. }
  61621. else if (textBlocks.contains (c))
  61622. {
  61623. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61624. h = c->getHeight();
  61625. }
  61626. else
  61627. {
  61628. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61629. }
  61630. y += h + 10;
  61631. }
  61632. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61633. }
  61634. bool AlertWindow::containsAnyExtraComponents() const
  61635. {
  61636. return allComps.size() > 0;
  61637. }
  61638. void AlertWindow::mouseDown (const MouseEvent& e)
  61639. {
  61640. dragger.startDraggingComponent (this, e);
  61641. }
  61642. void AlertWindow::mouseDrag (const MouseEvent& e)
  61643. {
  61644. dragger.dragComponent (this, e, &constrainer);
  61645. }
  61646. bool AlertWindow::keyPressed (const KeyPress& key)
  61647. {
  61648. for (int i = buttons.size(); --i >= 0;)
  61649. {
  61650. TextButton* const b = buttons.getUnchecked(i);
  61651. if (b->isRegisteredForShortcut (key))
  61652. {
  61653. b->triggerClick();
  61654. return true;
  61655. }
  61656. }
  61657. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61658. {
  61659. exitModalState (0);
  61660. return true;
  61661. }
  61662. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61663. {
  61664. buttons.getUnchecked(0)->triggerClick();
  61665. return true;
  61666. }
  61667. return false;
  61668. }
  61669. void AlertWindow::lookAndFeelChanged()
  61670. {
  61671. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61672. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61673. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61674. }
  61675. int AlertWindow::getDesktopWindowStyleFlags() const
  61676. {
  61677. return getLookAndFeel().getAlertBoxWindowFlags();
  61678. }
  61679. class AlertWindowInfo
  61680. {
  61681. public:
  61682. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  61683. AlertWindow::AlertIconType iconType_, int numButtons_)
  61684. : title (title_), message (message_), iconType (iconType_),
  61685. numButtons (numButtons_), returnValue (0), associatedComponent (component)
  61686. {
  61687. }
  61688. String title, message, button1, button2, button3;
  61689. AlertWindow::AlertIconType iconType;
  61690. int numButtons, returnValue;
  61691. WeakReference<Component> associatedComponent;
  61692. int showModal() const
  61693. {
  61694. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61695. return returnValue;
  61696. }
  61697. private:
  61698. void show()
  61699. {
  61700. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61701. : LookAndFeel::getDefaultLookAndFeel();
  61702. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61703. iconType, numButtons, associatedComponent));
  61704. jassert (alertBox != 0); // you have to return one of these!
  61705. returnValue = alertBox->runModalLoop();
  61706. }
  61707. static void* showCallback (void* userData)
  61708. {
  61709. static_cast <AlertWindowInfo*> (userData)->show();
  61710. return 0;
  61711. }
  61712. };
  61713. void AlertWindow::showMessageBox (AlertIconType iconType,
  61714. const String& title,
  61715. const String& message,
  61716. const String& buttonText,
  61717. Component* associatedComponent)
  61718. {
  61719. AlertWindowInfo info (title, message, associatedComponent, iconType, 1);
  61720. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61721. info.showModal();
  61722. }
  61723. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61724. const String& title,
  61725. const String& message,
  61726. const String& button1Text,
  61727. const String& button2Text,
  61728. Component* associatedComponent)
  61729. {
  61730. AlertWindowInfo info (title, message, associatedComponent, iconType, 2);
  61731. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61732. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61733. return info.showModal() != 0;
  61734. }
  61735. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61736. const String& title,
  61737. const String& message,
  61738. const String& button1Text,
  61739. const String& button2Text,
  61740. const String& button3Text,
  61741. Component* associatedComponent)
  61742. {
  61743. AlertWindowInfo info (title, message, associatedComponent, iconType, 3);
  61744. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61745. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61746. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61747. return info.showModal();
  61748. }
  61749. END_JUCE_NAMESPACE
  61750. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61751. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61752. BEGIN_JUCE_NAMESPACE
  61753. CallOutBox::CallOutBox (Component& contentComponent,
  61754. Component& componentToPointTo,
  61755. Component* const parentComponent)
  61756. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61757. {
  61758. addAndMakeVisible (&content);
  61759. if (parentComponent != 0)
  61760. {
  61761. parentComponent->addChildComponent (this);
  61762. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  61763. parentComponent->getLocalBounds());
  61764. setVisible (true);
  61765. }
  61766. else
  61767. {
  61768. if (! JUCEApplication::isStandaloneApp())
  61769. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61770. updatePosition (componentToPointTo.getScreenBounds(),
  61771. componentToPointTo.getParentMonitorArea());
  61772. addToDesktop (ComponentPeer::windowIsTemporary);
  61773. }
  61774. }
  61775. CallOutBox::~CallOutBox()
  61776. {
  61777. }
  61778. void CallOutBox::setArrowSize (const float newSize)
  61779. {
  61780. arrowSize = newSize;
  61781. borderSpace = jmax (20, (int) arrowSize);
  61782. refreshPath();
  61783. }
  61784. void CallOutBox::paint (Graphics& g)
  61785. {
  61786. if (background.isNull())
  61787. {
  61788. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61789. Graphics g2 (background);
  61790. getLookAndFeel().drawCallOutBoxBackground (*this, g2, outline);
  61791. }
  61792. g.setColour (Colours::black);
  61793. g.drawImageAt (background, 0, 0);
  61794. }
  61795. void CallOutBox::resized()
  61796. {
  61797. content.setTopLeftPosition (borderSpace, borderSpace);
  61798. refreshPath();
  61799. }
  61800. void CallOutBox::moved()
  61801. {
  61802. refreshPath();
  61803. }
  61804. void CallOutBox::childBoundsChanged (Component*)
  61805. {
  61806. updatePosition (targetArea, availableArea);
  61807. }
  61808. bool CallOutBox::hitTest (int x, int y)
  61809. {
  61810. return outline.contains ((float) x, (float) y);
  61811. }
  61812. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61813. void CallOutBox::inputAttemptWhenModal()
  61814. {
  61815. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61816. if (targetArea.contains (mousePos))
  61817. {
  61818. // if you click on the area that originally popped-up the callout, you expect it
  61819. // to get rid of the box, but deleting the box here allows the click to pass through and
  61820. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61821. postCommandMessage (callOutBoxDismissCommandId);
  61822. }
  61823. else
  61824. {
  61825. exitModalState (0);
  61826. setVisible (false);
  61827. }
  61828. }
  61829. void CallOutBox::handleCommandMessage (int commandId)
  61830. {
  61831. Component::handleCommandMessage (commandId);
  61832. if (commandId == callOutBoxDismissCommandId)
  61833. {
  61834. exitModalState (0);
  61835. setVisible (false);
  61836. }
  61837. }
  61838. bool CallOutBox::keyPressed (const KeyPress& key)
  61839. {
  61840. if (key.isKeyCode (KeyPress::escapeKey))
  61841. {
  61842. inputAttemptWhenModal();
  61843. return true;
  61844. }
  61845. return false;
  61846. }
  61847. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61848. {
  61849. targetArea = newAreaToPointTo;
  61850. availableArea = newAreaToFitIn;
  61851. Rectangle<int> bounds (0, 0,
  61852. content.getWidth() + borderSpace * 2,
  61853. content.getHeight() + borderSpace * 2);
  61854. const int hw = bounds.getWidth() / 2;
  61855. const int hh = bounds.getHeight() / 2;
  61856. const float hwReduced = (float) (hw - borderSpace * 3);
  61857. const float hhReduced = (float) (hh - borderSpace * 3);
  61858. const float arrowIndent = borderSpace - arrowSize;
  61859. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61860. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61861. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61862. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61863. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61864. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61865. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61866. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61867. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61868. float nearest = 1.0e9f;
  61869. for (int i = 0; i < 4; ++i)
  61870. {
  61871. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61872. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61873. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61874. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61875. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61876. distanceFromCentre *= 2.0f;
  61877. if (distanceFromCentre < nearest)
  61878. {
  61879. nearest = distanceFromCentre;
  61880. targetPoint = targets[i];
  61881. bounds.setPosition ((int) (centre.getX() - hw),
  61882. (int) (centre.getY() - hh));
  61883. }
  61884. }
  61885. setBounds (bounds);
  61886. }
  61887. void CallOutBox::refreshPath()
  61888. {
  61889. repaint();
  61890. background = Image::null;
  61891. outline.clear();
  61892. const float gap = 4.5f;
  61893. const float cornerSize = 9.0f;
  61894. const float cornerSize2 = 2.0f * cornerSize;
  61895. const float arrowBaseWidth = arrowSize * 0.7f;
  61896. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61897. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61898. outline.startNewSubPath (left + cornerSize, top);
  61899. if (targetY <= top)
  61900. {
  61901. outline.lineTo (targetX - arrowBaseWidth, top);
  61902. outline.lineTo (targetX, targetY);
  61903. outline.lineTo (targetX + arrowBaseWidth, top);
  61904. }
  61905. outline.lineTo (right - cornerSize, top);
  61906. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61907. if (targetX >= right)
  61908. {
  61909. outline.lineTo (right, targetY - arrowBaseWidth);
  61910. outline.lineTo (targetX, targetY);
  61911. outline.lineTo (right, targetY + arrowBaseWidth);
  61912. }
  61913. outline.lineTo (right, bottom - cornerSize);
  61914. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61915. if (targetY >= bottom)
  61916. {
  61917. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61918. outline.lineTo (targetX, targetY);
  61919. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61920. }
  61921. outline.lineTo (left + cornerSize, bottom);
  61922. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61923. if (targetX <= left)
  61924. {
  61925. outline.lineTo (left, targetY + arrowBaseWidth);
  61926. outline.lineTo (targetX, targetY);
  61927. outline.lineTo (left, targetY - arrowBaseWidth);
  61928. }
  61929. outline.lineTo (left, top + cornerSize);
  61930. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61931. outline.closeSubPath();
  61932. }
  61933. END_JUCE_NAMESPACE
  61934. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61935. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61936. BEGIN_JUCE_NAMESPACE
  61937. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61938. static Array <ComponentPeer*> heavyweightPeers;
  61939. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61940. : component (component_),
  61941. styleFlags (styleFlags_),
  61942. lastPaintTime (0),
  61943. constrainer (0),
  61944. lastDragAndDropCompUnderMouse (0),
  61945. fakeMouseMessageSent (false),
  61946. isWindowMinimised (false)
  61947. {
  61948. heavyweightPeers.add (this);
  61949. }
  61950. ComponentPeer::~ComponentPeer()
  61951. {
  61952. heavyweightPeers.removeValue (this);
  61953. Desktop::getInstance().triggerFocusCallback();
  61954. }
  61955. int ComponentPeer::getNumPeers() throw()
  61956. {
  61957. return heavyweightPeers.size();
  61958. }
  61959. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61960. {
  61961. return heavyweightPeers [index];
  61962. }
  61963. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61964. {
  61965. for (int i = heavyweightPeers.size(); --i >= 0;)
  61966. {
  61967. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61968. if (peer->getComponent() == component)
  61969. return peer;
  61970. }
  61971. return 0;
  61972. }
  61973. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61974. {
  61975. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61976. }
  61977. void ComponentPeer::updateCurrentModifiers() throw()
  61978. {
  61979. ModifierKeys::updateCurrentModifiers();
  61980. }
  61981. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61982. {
  61983. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61984. jassert (mouse != 0); // not enough sources!
  61985. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61986. }
  61987. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61988. {
  61989. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61990. jassert (mouse != 0); // not enough sources!
  61991. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61992. }
  61993. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61994. {
  61995. Graphics g (&contextToPaintTo);
  61996. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61997. g.saveState();
  61998. #endif
  61999. JUCE_TRY
  62000. {
  62001. component->paintEntireComponent (g, true);
  62002. }
  62003. JUCE_CATCH_EXCEPTION
  62004. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62005. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62006. // clearly when things are being repainted.
  62007. g.restoreState();
  62008. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62009. (uint8) Random::getSystemRandom().nextInt (255),
  62010. (uint8) Random::getSystemRandom().nextInt (255),
  62011. (uint8) 0x50));
  62012. #endif
  62013. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62014. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62015. mess up a lot of the calculations that the library needs to do.
  62016. */
  62017. jassert (roundToInt (10.1f) == 10);
  62018. }
  62019. bool ComponentPeer::handleKeyPress (const int keyCode,
  62020. const juce_wchar textCharacter)
  62021. {
  62022. updateCurrentModifiers();
  62023. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62024. ? Component::getCurrentlyFocusedComponent()
  62025. : component;
  62026. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62027. {
  62028. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62029. if (currentModalComp != 0)
  62030. target = currentModalComp;
  62031. }
  62032. const KeyPress keyInfo (keyCode,
  62033. ModifierKeys::getCurrentModifiers().getRawFlags()
  62034. & ModifierKeys::allKeyboardModifiers,
  62035. textCharacter);
  62036. bool keyWasUsed = false;
  62037. while (target != 0)
  62038. {
  62039. const WeakReference<Component> deletionChecker (target);
  62040. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  62041. if (keyListeners != 0)
  62042. {
  62043. for (int i = keyListeners->size(); --i >= 0;)
  62044. {
  62045. keyWasUsed = keyListeners->getUnchecked(i)->keyPressed (keyInfo, target);
  62046. if (keyWasUsed || deletionChecker == 0)
  62047. return keyWasUsed;
  62048. i = jmin (i, keyListeners->size());
  62049. }
  62050. }
  62051. keyWasUsed = target->keyPressed (keyInfo);
  62052. if (keyWasUsed || deletionChecker == 0)
  62053. break;
  62054. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62055. {
  62056. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62057. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62058. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62059. break;
  62060. }
  62061. target = target->getParentComponent();
  62062. }
  62063. return keyWasUsed;
  62064. }
  62065. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62066. {
  62067. updateCurrentModifiers();
  62068. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62069. ? Component::getCurrentlyFocusedComponent()
  62070. : component;
  62071. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62072. {
  62073. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62074. if (currentModalComp != 0)
  62075. target = currentModalComp;
  62076. }
  62077. bool keyWasUsed = false;
  62078. while (target != 0)
  62079. {
  62080. const WeakReference<Component> deletionChecker (target);
  62081. keyWasUsed = target->keyStateChanged (isKeyDown);
  62082. if (keyWasUsed || deletionChecker == 0)
  62083. break;
  62084. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  62085. if (keyListeners != 0)
  62086. {
  62087. for (int i = keyListeners->size(); --i >= 0;)
  62088. {
  62089. keyWasUsed = keyListeners->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62090. if (keyWasUsed || deletionChecker == 0)
  62091. return keyWasUsed;
  62092. i = jmin (i, keyListeners->size());
  62093. }
  62094. }
  62095. target = target->getParentComponent();
  62096. }
  62097. return keyWasUsed;
  62098. }
  62099. void ComponentPeer::handleModifierKeysChange()
  62100. {
  62101. updateCurrentModifiers();
  62102. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62103. if (target == 0)
  62104. target = Component::getCurrentlyFocusedComponent();
  62105. if (target == 0)
  62106. target = component;
  62107. if (target != 0)
  62108. target->internalModifierKeysChanged();
  62109. }
  62110. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62111. {
  62112. Component* const c = Component::getCurrentlyFocusedComponent();
  62113. if (component->isParentOf (c))
  62114. {
  62115. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62116. if (ti != 0 && ti->isTextInputActive())
  62117. return ti;
  62118. }
  62119. return 0;
  62120. }
  62121. void ComponentPeer::handleBroughtToFront()
  62122. {
  62123. updateCurrentModifiers();
  62124. if (component != 0)
  62125. component->internalBroughtToFront();
  62126. }
  62127. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62128. {
  62129. constrainer = newConstrainer;
  62130. }
  62131. void ComponentPeer::handleMovedOrResized()
  62132. {
  62133. updateCurrentModifiers();
  62134. const bool nowMinimised = isMinimised();
  62135. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62136. {
  62137. const WeakReference<Component> deletionChecker (component);
  62138. const Rectangle<int> newBounds (getBounds());
  62139. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62140. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62141. if (wasMoved || wasResized)
  62142. {
  62143. component->bounds = newBounds;
  62144. if (wasResized)
  62145. component->repaint();
  62146. component->sendMovedResizedMessages (wasMoved, wasResized);
  62147. if (deletionChecker == 0)
  62148. return;
  62149. }
  62150. }
  62151. if (isWindowMinimised != nowMinimised)
  62152. {
  62153. isWindowMinimised = nowMinimised;
  62154. component->minimisationStateChanged (nowMinimised);
  62155. component->sendVisibilityChangeMessage();
  62156. }
  62157. if (! isFullScreen())
  62158. lastNonFullscreenBounds = component->getBounds();
  62159. }
  62160. void ComponentPeer::handleFocusGain()
  62161. {
  62162. updateCurrentModifiers();
  62163. if (component->isParentOf (lastFocusedComponent))
  62164. {
  62165. Component::currentlyFocusedComponent = lastFocusedComponent;
  62166. Desktop::getInstance().triggerFocusCallback();
  62167. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62168. }
  62169. else
  62170. {
  62171. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62172. component->grabKeyboardFocus();
  62173. else
  62174. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62175. }
  62176. }
  62177. void ComponentPeer::handleFocusLoss()
  62178. {
  62179. updateCurrentModifiers();
  62180. if (component->hasKeyboardFocus (true))
  62181. {
  62182. lastFocusedComponent = Component::currentlyFocusedComponent;
  62183. if (lastFocusedComponent != 0)
  62184. {
  62185. Component::currentlyFocusedComponent = 0;
  62186. Desktop::getInstance().triggerFocusCallback();
  62187. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62188. }
  62189. }
  62190. }
  62191. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62192. {
  62193. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62194. ? static_cast <Component*> (lastFocusedComponent)
  62195. : component;
  62196. }
  62197. void ComponentPeer::handleScreenSizeChange()
  62198. {
  62199. updateCurrentModifiers();
  62200. component->parentSizeChanged();
  62201. handleMovedOrResized();
  62202. }
  62203. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62204. {
  62205. lastNonFullscreenBounds = newBounds;
  62206. }
  62207. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62208. {
  62209. return lastNonFullscreenBounds;
  62210. }
  62211. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62212. {
  62213. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62214. }
  62215. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62216. {
  62217. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62218. }
  62219. namespace ComponentPeerHelpers
  62220. {
  62221. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62222. const StringArray& files,
  62223. FileDragAndDropTarget* const lastOne)
  62224. {
  62225. while (c != 0)
  62226. {
  62227. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62228. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62229. return t;
  62230. c = c->getParentComponent();
  62231. }
  62232. return 0;
  62233. }
  62234. }
  62235. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62236. {
  62237. updateCurrentModifiers();
  62238. FileDragAndDropTarget* lastTarget
  62239. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62240. FileDragAndDropTarget* newTarget = 0;
  62241. Component* const compUnderMouse = component->getComponentAt (position);
  62242. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62243. {
  62244. lastDragAndDropCompUnderMouse = compUnderMouse;
  62245. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62246. if (newTarget != lastTarget)
  62247. {
  62248. if (lastTarget != 0)
  62249. lastTarget->fileDragExit (files);
  62250. dragAndDropTargetComponent = 0;
  62251. if (newTarget != 0)
  62252. {
  62253. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62254. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62255. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62256. }
  62257. }
  62258. }
  62259. else
  62260. {
  62261. newTarget = lastTarget;
  62262. }
  62263. if (newTarget != 0)
  62264. {
  62265. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62266. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62267. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62268. }
  62269. }
  62270. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62271. {
  62272. handleFileDragMove (files, Point<int> (-1, -1));
  62273. jassert (dragAndDropTargetComponent == 0);
  62274. lastDragAndDropCompUnderMouse = 0;
  62275. }
  62276. // We'll use an async message to deliver the drop, because if the target decides
  62277. // to run a modal loop, it can gum-up the operating system..
  62278. class AsyncFileDropMessage : public CallbackMessage
  62279. {
  62280. public:
  62281. AsyncFileDropMessage (Component* target_, FileDragAndDropTarget* dropTarget_,
  62282. const Point<int>& position_, const StringArray& files_)
  62283. : target (target_), dropTarget (dropTarget_), position (position_), files (files_)
  62284. {
  62285. }
  62286. void messageCallback()
  62287. {
  62288. if (target != 0)
  62289. dropTarget->filesDropped (files, position.getX(), position.getY());
  62290. }
  62291. private:
  62292. WeakReference<Component> target;
  62293. FileDragAndDropTarget* const dropTarget;
  62294. const Point<int> position;
  62295. const StringArray files;
  62296. JUCE_DECLARE_NON_COPYABLE (AsyncFileDropMessage);
  62297. };
  62298. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62299. {
  62300. handleFileDragMove (files, position);
  62301. if (dragAndDropTargetComponent != 0)
  62302. {
  62303. FileDragAndDropTarget* const target
  62304. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62305. dragAndDropTargetComponent = 0;
  62306. lastDragAndDropCompUnderMouse = 0;
  62307. if (target != 0)
  62308. {
  62309. Component* const targetComp = dynamic_cast <Component*> (target);
  62310. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62311. {
  62312. targetComp->internalModalInputAttempt();
  62313. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62314. return;
  62315. }
  62316. (new AsyncFileDropMessage (targetComp, target, targetComp->getLocalPoint (component, position), files))->post();
  62317. }
  62318. }
  62319. }
  62320. void ComponentPeer::handleUserClosingWindow()
  62321. {
  62322. updateCurrentModifiers();
  62323. component->userTriedToCloseWindow();
  62324. }
  62325. void ComponentPeer::clearMaskedRegion()
  62326. {
  62327. maskedRegion.clear();
  62328. }
  62329. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62330. {
  62331. maskedRegion.add (x, y, w, h);
  62332. }
  62333. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62334. {
  62335. StringArray s;
  62336. s.add ("Software Renderer");
  62337. return s;
  62338. }
  62339. int ComponentPeer::getCurrentRenderingEngine() throw()
  62340. {
  62341. return 0;
  62342. }
  62343. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62344. {
  62345. }
  62346. END_JUCE_NAMESPACE
  62347. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62348. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62349. BEGIN_JUCE_NAMESPACE
  62350. DialogWindow::DialogWindow (const String& name,
  62351. const Colour& backgroundColour_,
  62352. const bool escapeKeyTriggersCloseButton_,
  62353. const bool addToDesktop_)
  62354. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62355. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62356. {
  62357. }
  62358. DialogWindow::~DialogWindow()
  62359. {
  62360. }
  62361. void DialogWindow::resized()
  62362. {
  62363. DocumentWindow::resized();
  62364. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62365. if (escapeKeyTriggersCloseButton
  62366. && getCloseButton() != 0
  62367. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62368. {
  62369. getCloseButton()->addShortcut (esc);
  62370. }
  62371. }
  62372. // (Sadly, this can't be made a local class inside the showModalDialog function, because the
  62373. // VC compiler complains about the undefined copy constructor)
  62374. class TempDialogWindow : public DialogWindow
  62375. {
  62376. public:
  62377. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62378. : DialogWindow (title, colour, escapeCloses, true)
  62379. {
  62380. if (! JUCEApplication::isStandaloneApp())
  62381. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62382. }
  62383. void closeButtonPressed()
  62384. {
  62385. setVisible (false);
  62386. }
  62387. private:
  62388. JUCE_DECLARE_NON_COPYABLE (TempDialogWindow);
  62389. };
  62390. int DialogWindow::showModalDialog (const String& dialogTitle,
  62391. Component* contentComponent,
  62392. Component* componentToCentreAround,
  62393. const Colour& colour,
  62394. const bool escapeKeyTriggersCloseButton,
  62395. const bool shouldBeResizable,
  62396. const bool useBottomRightCornerResizer)
  62397. {
  62398. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62399. dw.setContentComponent (contentComponent, true, true);
  62400. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62401. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62402. const int result = dw.runModalLoop();
  62403. dw.setContentComponent (0, false);
  62404. return result;
  62405. }
  62406. END_JUCE_NAMESPACE
  62407. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62408. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62409. BEGIN_JUCE_NAMESPACE
  62410. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62411. {
  62412. public:
  62413. ButtonListenerProxy (DocumentWindow& owner_)
  62414. : owner (owner_)
  62415. {
  62416. }
  62417. void buttonClicked (Button* button)
  62418. {
  62419. if (button == owner.getMinimiseButton())
  62420. owner.minimiseButtonPressed();
  62421. else if (button == owner.getMaximiseButton())
  62422. owner.maximiseButtonPressed();
  62423. else if (button == owner.getCloseButton())
  62424. owner.closeButtonPressed();
  62425. }
  62426. private:
  62427. DocumentWindow& owner;
  62428. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonListenerProxy);
  62429. };
  62430. DocumentWindow::DocumentWindow (const String& title,
  62431. const Colour& backgroundColour,
  62432. const int requiredButtons_,
  62433. const bool addToDesktop_)
  62434. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62435. titleBarHeight (26),
  62436. menuBarHeight (24),
  62437. requiredButtons (requiredButtons_),
  62438. #if JUCE_MAC
  62439. positionTitleBarButtonsOnLeft (true),
  62440. #else
  62441. positionTitleBarButtonsOnLeft (false),
  62442. #endif
  62443. drawTitleTextCentred (true),
  62444. menuBarModel (0)
  62445. {
  62446. setResizeLimits (128, 128, 32768, 32768);
  62447. lookAndFeelChanged();
  62448. }
  62449. DocumentWindow::~DocumentWindow()
  62450. {
  62451. // Don't delete or remove the resizer components yourself! They're managed by the
  62452. // DocumentWindow, and you should leave them alone! You may have deleted them
  62453. // accidentally by careless use of deleteAllChildren()..?
  62454. jassert (menuBar == 0 || getIndexOfChildComponent (menuBar) >= 0);
  62455. jassert (titleBarButtons[0] == 0 || getIndexOfChildComponent (titleBarButtons[0]) >= 0);
  62456. jassert (titleBarButtons[1] == 0 || getIndexOfChildComponent (titleBarButtons[1]) >= 0);
  62457. jassert (titleBarButtons[2] == 0 || getIndexOfChildComponent (titleBarButtons[2]) >= 0);
  62458. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62459. titleBarButtons[i] = 0;
  62460. menuBar = 0;
  62461. }
  62462. void DocumentWindow::repaintTitleBar()
  62463. {
  62464. repaint (getTitleBarArea());
  62465. }
  62466. void DocumentWindow::setName (const String& newName)
  62467. {
  62468. if (newName != getName())
  62469. {
  62470. Component::setName (newName);
  62471. repaintTitleBar();
  62472. }
  62473. }
  62474. void DocumentWindow::setIcon (const Image& imageToUse)
  62475. {
  62476. titleBarIcon = imageToUse;
  62477. repaintTitleBar();
  62478. }
  62479. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62480. {
  62481. titleBarHeight = newHeight;
  62482. resized();
  62483. repaintTitleBar();
  62484. }
  62485. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62486. const bool positionTitleBarButtonsOnLeft_)
  62487. {
  62488. requiredButtons = requiredButtons_;
  62489. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62490. lookAndFeelChanged();
  62491. }
  62492. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62493. {
  62494. drawTitleTextCentred = textShouldBeCentred;
  62495. repaintTitleBar();
  62496. }
  62497. void DocumentWindow::setMenuBar (MenuBarModel* newMenuBarModel, const int newMenuBarHeight)
  62498. {
  62499. if (menuBarModel != newMenuBarModel)
  62500. {
  62501. menuBar = 0;
  62502. menuBarModel = newMenuBarModel;
  62503. menuBarHeight = newMenuBarHeight > 0 ? newMenuBarHeight
  62504. : getLookAndFeel().getDefaultMenuBarHeight();
  62505. if (menuBarModel != 0)
  62506. setMenuBarComponent (new MenuBarComponent (menuBarModel));
  62507. resized();
  62508. }
  62509. }
  62510. Component* DocumentWindow::getMenuBarComponent() const throw()
  62511. {
  62512. return menuBar;
  62513. }
  62514. void DocumentWindow::setMenuBarComponent (Component* newMenuBarComponent)
  62515. {
  62516. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62517. Component::addAndMakeVisible (menuBar = newMenuBarComponent);
  62518. if (menuBar != 0)
  62519. menuBar->setEnabled (isActiveWindow());
  62520. resized();
  62521. }
  62522. void DocumentWindow::closeButtonPressed()
  62523. {
  62524. /* If you've got a close button, you have to override this method to get
  62525. rid of your window!
  62526. If the window is just a pop-up, you should override this method and make
  62527. it delete the window in whatever way is appropriate for your app. E.g. you
  62528. might just want to call "delete this".
  62529. If your app is centred around this window such that the whole app should quit when
  62530. the window is closed, then you will probably want to use this method as an opportunity
  62531. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62532. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62533. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62534. or closing it via the taskbar icon on Windows).
  62535. */
  62536. jassertfalse;
  62537. }
  62538. void DocumentWindow::minimiseButtonPressed()
  62539. {
  62540. setMinimised (true);
  62541. }
  62542. void DocumentWindow::maximiseButtonPressed()
  62543. {
  62544. setFullScreen (! isFullScreen());
  62545. }
  62546. void DocumentWindow::paint (Graphics& g)
  62547. {
  62548. ResizableWindow::paint (g);
  62549. if (resizableBorder == 0)
  62550. {
  62551. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62552. const BorderSize border (getBorderThickness());
  62553. g.fillRect (0, 0, getWidth(), border.getTop());
  62554. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62555. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62556. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62557. }
  62558. const Rectangle<int> titleBarArea (getTitleBarArea());
  62559. g.reduceClipRegion (titleBarArea);
  62560. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62561. int titleSpaceX1 = 6;
  62562. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62563. for (int i = 0; i < 3; ++i)
  62564. {
  62565. if (titleBarButtons[i] != 0)
  62566. {
  62567. if (positionTitleBarButtonsOnLeft)
  62568. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62569. else
  62570. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62571. }
  62572. }
  62573. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62574. titleBarArea.getWidth(),
  62575. titleBarArea.getHeight(),
  62576. titleSpaceX1,
  62577. jmax (1, titleSpaceX2 - titleSpaceX1),
  62578. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62579. ! drawTitleTextCentred);
  62580. }
  62581. void DocumentWindow::resized()
  62582. {
  62583. ResizableWindow::resized();
  62584. if (titleBarButtons[1] != 0)
  62585. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62586. const Rectangle<int> titleBarArea (getTitleBarArea());
  62587. getLookAndFeel()
  62588. .positionDocumentWindowButtons (*this,
  62589. titleBarArea.getX(), titleBarArea.getY(),
  62590. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62591. titleBarButtons[0],
  62592. titleBarButtons[1],
  62593. titleBarButtons[2],
  62594. positionTitleBarButtonsOnLeft);
  62595. if (menuBar != 0)
  62596. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62597. titleBarArea.getWidth(), menuBarHeight);
  62598. }
  62599. const BorderSize DocumentWindow::getBorderThickness()
  62600. {
  62601. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62602. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62603. }
  62604. const BorderSize DocumentWindow::getContentComponentBorder()
  62605. {
  62606. BorderSize border (getBorderThickness());
  62607. border.setTop (border.getTop()
  62608. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62609. + (menuBar != 0 ? menuBarHeight : 0));
  62610. return border;
  62611. }
  62612. int DocumentWindow::getTitleBarHeight() const
  62613. {
  62614. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62615. }
  62616. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62617. {
  62618. const BorderSize border (getBorderThickness());
  62619. return Rectangle<int> (border.getLeft(), border.getTop(),
  62620. getWidth() - border.getLeftAndRight(),
  62621. getTitleBarHeight());
  62622. }
  62623. Button* DocumentWindow::getCloseButton() const throw() { return titleBarButtons[2]; }
  62624. Button* DocumentWindow::getMinimiseButton() const throw() { return titleBarButtons[0]; }
  62625. Button* DocumentWindow::getMaximiseButton() const throw() { return titleBarButtons[1]; }
  62626. int DocumentWindow::getDesktopWindowStyleFlags() const
  62627. {
  62628. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62629. if ((requiredButtons & minimiseButton) != 0)
  62630. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62631. if ((requiredButtons & maximiseButton) != 0)
  62632. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62633. if ((requiredButtons & closeButton) != 0)
  62634. styleFlags |= ComponentPeer::windowHasCloseButton;
  62635. return styleFlags;
  62636. }
  62637. void DocumentWindow::lookAndFeelChanged()
  62638. {
  62639. int i;
  62640. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62641. titleBarButtons[i] = 0;
  62642. if (! isUsingNativeTitleBar())
  62643. {
  62644. LookAndFeel& lf = getLookAndFeel();
  62645. if ((requiredButtons & minimiseButton) != 0)
  62646. titleBarButtons[0] = lf.createDocumentWindowButton (minimiseButton);
  62647. if ((requiredButtons & maximiseButton) != 0)
  62648. titleBarButtons[1] = lf.createDocumentWindowButton (maximiseButton);
  62649. if ((requiredButtons & closeButton) != 0)
  62650. titleBarButtons[2] = lf.createDocumentWindowButton (closeButton);
  62651. for (i = 0; i < 3; ++i)
  62652. {
  62653. if (titleBarButtons[i] != 0)
  62654. {
  62655. if (buttonListener == 0)
  62656. buttonListener = new ButtonListenerProxy (*this);
  62657. titleBarButtons[i]->addListener (buttonListener);
  62658. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62659. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62660. Component::addAndMakeVisible (titleBarButtons[i]);
  62661. }
  62662. }
  62663. if (getCloseButton() != 0)
  62664. {
  62665. #if JUCE_MAC
  62666. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62667. #else
  62668. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62669. #endif
  62670. }
  62671. }
  62672. activeWindowStatusChanged();
  62673. ResizableWindow::lookAndFeelChanged();
  62674. }
  62675. void DocumentWindow::parentHierarchyChanged()
  62676. {
  62677. lookAndFeelChanged();
  62678. }
  62679. void DocumentWindow::activeWindowStatusChanged()
  62680. {
  62681. ResizableWindow::activeWindowStatusChanged();
  62682. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62683. if (titleBarButtons[i] != 0)
  62684. titleBarButtons[i]->setEnabled (isActiveWindow());
  62685. if (menuBar != 0)
  62686. menuBar->setEnabled (isActiveWindow());
  62687. }
  62688. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62689. {
  62690. if (getTitleBarArea().contains (e.x, e.y)
  62691. && getMaximiseButton() != 0)
  62692. {
  62693. getMaximiseButton()->triggerClick();
  62694. }
  62695. }
  62696. void DocumentWindow::userTriedToCloseWindow()
  62697. {
  62698. closeButtonPressed();
  62699. }
  62700. END_JUCE_NAMESPACE
  62701. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62702. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62703. BEGIN_JUCE_NAMESPACE
  62704. ResizableWindow::ResizableWindow (const String& name,
  62705. const bool addToDesktop_)
  62706. : TopLevelWindow (name, addToDesktop_),
  62707. resizeToFitContent (false),
  62708. fullscreen (false),
  62709. lastNonFullScreenPos (50, 50, 256, 256),
  62710. constrainer (0)
  62711. #if JUCE_DEBUG
  62712. , hasBeenResized (false)
  62713. #endif
  62714. {
  62715. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62716. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62717. if (addToDesktop_)
  62718. Component::addToDesktop (getDesktopWindowStyleFlags());
  62719. }
  62720. ResizableWindow::ResizableWindow (const String& name,
  62721. const Colour& backgroundColour_,
  62722. const bool addToDesktop_)
  62723. : TopLevelWindow (name, addToDesktop_),
  62724. resizeToFitContent (false),
  62725. fullscreen (false),
  62726. lastNonFullScreenPos (50, 50, 256, 256),
  62727. constrainer (0)
  62728. #if JUCE_DEBUG
  62729. , hasBeenResized (false)
  62730. #endif
  62731. {
  62732. setBackgroundColour (backgroundColour_);
  62733. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62734. if (addToDesktop_)
  62735. Component::addToDesktop (getDesktopWindowStyleFlags());
  62736. }
  62737. ResizableWindow::~ResizableWindow()
  62738. {
  62739. // Don't delete or remove the resizer components yourself! They're managed by the
  62740. // ResizableWindow, and you should leave them alone! You may have deleted them
  62741. // accidentally by careless use of deleteAllChildren()..?
  62742. jassert (resizableCorner == 0 || getIndexOfChildComponent (resizableCorner) >= 0);
  62743. jassert (resizableBorder == 0 || getIndexOfChildComponent (resizableBorder) >= 0);
  62744. resizableCorner = 0;
  62745. resizableBorder = 0;
  62746. contentComponent.deleteAndZero();
  62747. // have you been adding your own components directly to this window..? tut tut tut.
  62748. // Read the instructions for using a ResizableWindow!
  62749. jassert (getNumChildComponents() == 0);
  62750. }
  62751. int ResizableWindow::getDesktopWindowStyleFlags() const
  62752. {
  62753. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62754. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62755. styleFlags |= ComponentPeer::windowIsResizable;
  62756. return styleFlags;
  62757. }
  62758. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62759. const bool deleteOldOne,
  62760. const bool resizeToFit)
  62761. {
  62762. resizeToFitContent = resizeToFit;
  62763. if (newContentComponent != static_cast <Component*> (contentComponent))
  62764. {
  62765. if (deleteOldOne)
  62766. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  62767. // external deletion of the content comp)
  62768. else
  62769. removeChildComponent (contentComponent);
  62770. contentComponent = newContentComponent;
  62771. Component::addAndMakeVisible (contentComponent);
  62772. }
  62773. if (resizeToFit)
  62774. childBoundsChanged (contentComponent);
  62775. resized(); // must always be called to position the new content comp
  62776. }
  62777. void ResizableWindow::setContentComponentSize (int width, int height)
  62778. {
  62779. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62780. const BorderSize border (getContentComponentBorder());
  62781. setSize (width + border.getLeftAndRight(),
  62782. height + border.getTopAndBottom());
  62783. }
  62784. const BorderSize ResizableWindow::getBorderThickness()
  62785. {
  62786. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62787. }
  62788. const BorderSize ResizableWindow::getContentComponentBorder()
  62789. {
  62790. return getBorderThickness();
  62791. }
  62792. void ResizableWindow::moved()
  62793. {
  62794. updateLastPos();
  62795. }
  62796. void ResizableWindow::visibilityChanged()
  62797. {
  62798. TopLevelWindow::visibilityChanged();
  62799. updateLastPos();
  62800. }
  62801. void ResizableWindow::resized()
  62802. {
  62803. if (resizableBorder != 0)
  62804. {
  62805. #if JUCE_WINDOWS || JUCE_LINUX
  62806. // hide the resizable border if the OS already provides one..
  62807. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62808. #else
  62809. resizableBorder->setVisible (! isFullScreen());
  62810. #endif
  62811. resizableBorder->setBorderThickness (getBorderThickness());
  62812. resizableBorder->setSize (getWidth(), getHeight());
  62813. resizableBorder->toBack();
  62814. }
  62815. if (resizableCorner != 0)
  62816. {
  62817. #if JUCE_MAC
  62818. // hide the resizable border if the OS already provides one..
  62819. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62820. #else
  62821. resizableCorner->setVisible (! isFullScreen());
  62822. #endif
  62823. const int resizerSize = 18;
  62824. resizableCorner->setBounds (getWidth() - resizerSize,
  62825. getHeight() - resizerSize,
  62826. resizerSize, resizerSize);
  62827. }
  62828. if (contentComponent != 0)
  62829. contentComponent->setBoundsInset (getContentComponentBorder());
  62830. updateLastPos();
  62831. #if JUCE_DEBUG
  62832. hasBeenResized = true;
  62833. #endif
  62834. }
  62835. void ResizableWindow::childBoundsChanged (Component* child)
  62836. {
  62837. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62838. {
  62839. // not going to look very good if this component has a zero size..
  62840. jassert (child->getWidth() > 0);
  62841. jassert (child->getHeight() > 0);
  62842. const BorderSize borders (getContentComponentBorder());
  62843. setSize (child->getWidth() + borders.getLeftAndRight(),
  62844. child->getHeight() + borders.getTopAndBottom());
  62845. }
  62846. }
  62847. void ResizableWindow::activeWindowStatusChanged()
  62848. {
  62849. const BorderSize border (getContentComponentBorder());
  62850. Rectangle<int> area (getLocalBounds());
  62851. repaint (area.removeFromTop (border.getTop()));
  62852. repaint (area.removeFromLeft (border.getLeft()));
  62853. repaint (area.removeFromRight (border.getRight()));
  62854. repaint (area.removeFromBottom (border.getBottom()));
  62855. }
  62856. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62857. const bool useBottomRightCornerResizer)
  62858. {
  62859. if (shouldBeResizable)
  62860. {
  62861. if (useBottomRightCornerResizer)
  62862. {
  62863. resizableBorder = 0;
  62864. if (resizableCorner == 0)
  62865. {
  62866. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62867. resizableCorner->setAlwaysOnTop (true);
  62868. }
  62869. }
  62870. else
  62871. {
  62872. resizableCorner = 0;
  62873. if (resizableBorder == 0)
  62874. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62875. }
  62876. }
  62877. else
  62878. {
  62879. resizableCorner = 0;
  62880. resizableBorder = 0;
  62881. }
  62882. if (isUsingNativeTitleBar())
  62883. recreateDesktopWindow();
  62884. childBoundsChanged (contentComponent);
  62885. resized();
  62886. }
  62887. bool ResizableWindow::isResizable() const throw()
  62888. {
  62889. return resizableCorner != 0
  62890. || resizableBorder != 0;
  62891. }
  62892. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62893. const int newMinimumHeight,
  62894. const int newMaximumWidth,
  62895. const int newMaximumHeight) throw()
  62896. {
  62897. // if you've set up a custom constrainer then these settings won't have any effect..
  62898. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62899. if (constrainer == 0)
  62900. setConstrainer (&defaultConstrainer);
  62901. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62902. newMaximumWidth, newMaximumHeight);
  62903. setBoundsConstrained (getBounds());
  62904. }
  62905. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62906. {
  62907. if (constrainer != newConstrainer)
  62908. {
  62909. constrainer = newConstrainer;
  62910. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62911. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62912. resizableCorner = 0;
  62913. resizableBorder = 0;
  62914. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62915. ComponentPeer* const peer = getPeer();
  62916. if (peer != 0)
  62917. peer->setConstrainer (newConstrainer);
  62918. }
  62919. }
  62920. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62921. {
  62922. if (constrainer != 0)
  62923. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62924. else
  62925. setBounds (bounds);
  62926. }
  62927. void ResizableWindow::paint (Graphics& g)
  62928. {
  62929. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62930. getBorderThickness(), *this);
  62931. if (! isFullScreen())
  62932. {
  62933. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62934. getBorderThickness(), *this);
  62935. }
  62936. #if JUCE_DEBUG
  62937. /* If this fails, then you've probably written a subclass with a resized()
  62938. callback but forgotten to make it call its parent class's resized() method.
  62939. It's important when you override methods like resized(), moved(),
  62940. etc., that you make sure the base class methods also get called.
  62941. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62942. because your content should all be inside the content component - and it's the
  62943. content component's resized() method that you should be using to do your
  62944. layout.
  62945. */
  62946. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62947. #endif
  62948. }
  62949. void ResizableWindow::lookAndFeelChanged()
  62950. {
  62951. resized();
  62952. if (isOnDesktop())
  62953. {
  62954. Component::addToDesktop (getDesktopWindowStyleFlags());
  62955. ComponentPeer* const peer = getPeer();
  62956. if (peer != 0)
  62957. peer->setConstrainer (constrainer);
  62958. }
  62959. }
  62960. const Colour ResizableWindow::getBackgroundColour() const throw()
  62961. {
  62962. return findColour (backgroundColourId, false);
  62963. }
  62964. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62965. {
  62966. Colour backgroundColour (newColour);
  62967. if (! Desktop::canUseSemiTransparentWindows())
  62968. backgroundColour = newColour.withAlpha (1.0f);
  62969. setColour (backgroundColourId, backgroundColour);
  62970. setOpaque (backgroundColour.isOpaque());
  62971. repaint();
  62972. }
  62973. bool ResizableWindow::isFullScreen() const
  62974. {
  62975. if (isOnDesktop())
  62976. {
  62977. ComponentPeer* const peer = getPeer();
  62978. return peer != 0 && peer->isFullScreen();
  62979. }
  62980. return fullscreen;
  62981. }
  62982. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62983. {
  62984. if (shouldBeFullScreen != isFullScreen())
  62985. {
  62986. updateLastPos();
  62987. fullscreen = shouldBeFullScreen;
  62988. if (isOnDesktop())
  62989. {
  62990. ComponentPeer* const peer = getPeer();
  62991. if (peer != 0)
  62992. {
  62993. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62994. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62995. peer->setFullScreen (shouldBeFullScreen);
  62996. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  62997. setBounds (lastPos);
  62998. }
  62999. else
  63000. {
  63001. jassertfalse;
  63002. }
  63003. }
  63004. else
  63005. {
  63006. if (shouldBeFullScreen)
  63007. setBounds (0, 0, getParentWidth(), getParentHeight());
  63008. else
  63009. setBounds (lastNonFullScreenPos);
  63010. }
  63011. resized();
  63012. }
  63013. }
  63014. bool ResizableWindow::isMinimised() const
  63015. {
  63016. ComponentPeer* const peer = getPeer();
  63017. return (peer != 0) && peer->isMinimised();
  63018. }
  63019. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63020. {
  63021. if (shouldMinimise != isMinimised())
  63022. {
  63023. ComponentPeer* const peer = getPeer();
  63024. if (peer != 0)
  63025. {
  63026. updateLastPos();
  63027. peer->setMinimised (shouldMinimise);
  63028. }
  63029. else
  63030. {
  63031. jassertfalse;
  63032. }
  63033. }
  63034. }
  63035. void ResizableWindow::updateLastPos()
  63036. {
  63037. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63038. {
  63039. lastNonFullScreenPos = getBounds();
  63040. }
  63041. }
  63042. void ResizableWindow::parentSizeChanged()
  63043. {
  63044. if (isFullScreen() && getParentComponent() != 0)
  63045. {
  63046. setBounds (0, 0, getParentWidth(), getParentHeight());
  63047. }
  63048. }
  63049. const String ResizableWindow::getWindowStateAsString()
  63050. {
  63051. updateLastPos();
  63052. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63053. }
  63054. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63055. {
  63056. StringArray tokens;
  63057. tokens.addTokens (s, false);
  63058. tokens.removeEmptyStrings();
  63059. tokens.trim();
  63060. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63061. const int firstCoord = fs ? 1 : 0;
  63062. if (tokens.size() != firstCoord + 4)
  63063. return false;
  63064. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63065. tokens[firstCoord + 1].getIntValue(),
  63066. tokens[firstCoord + 2].getIntValue(),
  63067. tokens[firstCoord + 3].getIntValue());
  63068. if (newPos.isEmpty())
  63069. return false;
  63070. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63071. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63072. if (peer != 0)
  63073. peer->getFrameSize().addTo (newPos);
  63074. if (! screen.contains (newPos))
  63075. {
  63076. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63077. jmin (newPos.getHeight(), screen.getHeight()));
  63078. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63079. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63080. }
  63081. if (peer != 0)
  63082. {
  63083. peer->getFrameSize().subtractFrom (newPos);
  63084. peer->setNonFullScreenBounds (newPos);
  63085. }
  63086. lastNonFullScreenPos = newPos;
  63087. setFullScreen (fs);
  63088. if (! fs)
  63089. setBoundsConstrained (newPos);
  63090. return true;
  63091. }
  63092. void ResizableWindow::mouseDown (const MouseEvent& e)
  63093. {
  63094. if (! isFullScreen())
  63095. dragger.startDraggingComponent (this, e);
  63096. }
  63097. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63098. {
  63099. if (! isFullScreen())
  63100. dragger.dragComponent (this, e, constrainer);
  63101. }
  63102. #if JUCE_DEBUG
  63103. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63104. {
  63105. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63106. manages its child components automatically, and if you add your own it'll cause
  63107. trouble. Instead, use setContentComponent() to give it a component which
  63108. will be automatically resized and kept in the right place - then you can add
  63109. subcomponents to the content comp. See the notes for the ResizableWindow class
  63110. for more info.
  63111. If you really know what you're doing and want to avoid this assertion, just call
  63112. Component::addChildComponent directly.
  63113. */
  63114. jassertfalse;
  63115. Component::addChildComponent (child, zOrder);
  63116. }
  63117. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63118. {
  63119. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63120. manages its child components automatically, and if you add your own it'll cause
  63121. trouble. Instead, use setContentComponent() to give it a component which
  63122. will be automatically resized and kept in the right place - then you can add
  63123. subcomponents to the content comp. See the notes for the ResizableWindow class
  63124. for more info.
  63125. If you really know what you're doing and want to avoid this assertion, just call
  63126. Component::addAndMakeVisible directly.
  63127. */
  63128. jassertfalse;
  63129. Component::addAndMakeVisible (child, zOrder);
  63130. }
  63131. #endif
  63132. END_JUCE_NAMESPACE
  63133. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63134. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63135. BEGIN_JUCE_NAMESPACE
  63136. SplashScreen::SplashScreen()
  63137. {
  63138. setOpaque (true);
  63139. }
  63140. SplashScreen::~SplashScreen()
  63141. {
  63142. }
  63143. void SplashScreen::show (const String& title,
  63144. const Image& backgroundImage_,
  63145. const int minimumTimeToDisplayFor,
  63146. const bool useDropShadow,
  63147. const bool removeOnMouseClick)
  63148. {
  63149. backgroundImage = backgroundImage_;
  63150. jassert (backgroundImage_.isValid());
  63151. if (backgroundImage_.isValid())
  63152. {
  63153. setOpaque (! backgroundImage_.hasAlphaChannel());
  63154. show (title,
  63155. backgroundImage_.getWidth(),
  63156. backgroundImage_.getHeight(),
  63157. minimumTimeToDisplayFor,
  63158. useDropShadow,
  63159. removeOnMouseClick);
  63160. }
  63161. }
  63162. void SplashScreen::show (const String& title,
  63163. const int width,
  63164. const int height,
  63165. const int minimumTimeToDisplayFor,
  63166. const bool useDropShadow,
  63167. const bool removeOnMouseClick)
  63168. {
  63169. setName (title);
  63170. setAlwaysOnTop (true);
  63171. setVisible (true);
  63172. centreWithSize (width, height);
  63173. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63174. toFront (false);
  63175. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63176. repaint();
  63177. originalClickCounter = removeOnMouseClick
  63178. ? Desktop::getMouseButtonClickCounter()
  63179. : std::numeric_limits<int>::max();
  63180. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63181. startTimer (50);
  63182. }
  63183. void SplashScreen::paint (Graphics& g)
  63184. {
  63185. g.setOpacity (1.0f);
  63186. g.drawImage (backgroundImage,
  63187. 0, 0, getWidth(), getHeight(),
  63188. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63189. }
  63190. void SplashScreen::timerCallback()
  63191. {
  63192. if (Time::getCurrentTime() > earliestTimeToDelete
  63193. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63194. {
  63195. delete this;
  63196. }
  63197. }
  63198. END_JUCE_NAMESPACE
  63199. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63200. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63201. BEGIN_JUCE_NAMESPACE
  63202. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63203. const bool hasProgressBar,
  63204. const bool hasCancelButton,
  63205. const int timeOutMsWhenCancelling_,
  63206. const String& cancelButtonText)
  63207. : Thread ("Juce Progress Window"),
  63208. progress (0.0),
  63209. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63210. {
  63211. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63212. .createAlertWindow (title, String::empty, cancelButtonText,
  63213. String::empty, String::empty,
  63214. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63215. if (hasProgressBar)
  63216. alertWindow->addProgressBarComponent (progress);
  63217. }
  63218. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63219. {
  63220. stopThread (timeOutMsWhenCancelling);
  63221. }
  63222. bool ThreadWithProgressWindow::runThread (const int priority)
  63223. {
  63224. startThread (priority);
  63225. startTimer (100);
  63226. {
  63227. const ScopedLock sl (messageLock);
  63228. alertWindow->setMessage (message);
  63229. }
  63230. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63231. stopThread (timeOutMsWhenCancelling);
  63232. alertWindow->setVisible (false);
  63233. return finishedNaturally;
  63234. }
  63235. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63236. {
  63237. progress = newProgress;
  63238. }
  63239. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63240. {
  63241. const ScopedLock sl (messageLock);
  63242. message = newStatusMessage;
  63243. }
  63244. void ThreadWithProgressWindow::timerCallback()
  63245. {
  63246. if (! isThreadRunning())
  63247. {
  63248. // thread has finished normally..
  63249. alertWindow->exitModalState (1);
  63250. alertWindow->setVisible (false);
  63251. }
  63252. else
  63253. {
  63254. const ScopedLock sl (messageLock);
  63255. alertWindow->setMessage (message);
  63256. }
  63257. }
  63258. END_JUCE_NAMESPACE
  63259. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63260. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63261. BEGIN_JUCE_NAMESPACE
  63262. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63263. const int millisecondsBeforeTipAppears_)
  63264. : Component ("tooltip"),
  63265. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63266. mouseClicks (0),
  63267. lastHideTime (0),
  63268. lastComponentUnderMouse (0),
  63269. changedCompsSinceShown (true)
  63270. {
  63271. if (Desktop::getInstance().getMainMouseSource().canHover())
  63272. startTimer (123);
  63273. setAlwaysOnTop (true);
  63274. setOpaque (true);
  63275. if (parentComponent != 0)
  63276. parentComponent->addChildComponent (this);
  63277. }
  63278. TooltipWindow::~TooltipWindow()
  63279. {
  63280. hide();
  63281. }
  63282. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63283. {
  63284. millisecondsBeforeTipAppears = newTimeMs;
  63285. }
  63286. void TooltipWindow::paint (Graphics& g)
  63287. {
  63288. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63289. }
  63290. void TooltipWindow::mouseEnter (const MouseEvent&)
  63291. {
  63292. hide();
  63293. }
  63294. void TooltipWindow::showFor (const String& tip)
  63295. {
  63296. jassert (tip.isNotEmpty());
  63297. if (tipShowing != tip)
  63298. repaint();
  63299. tipShowing = tip;
  63300. Point<int> mousePos (Desktop::getMousePosition());
  63301. if (getParentComponent() != 0)
  63302. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63303. int x, y, w, h;
  63304. getLookAndFeel().getTooltipSize (tip, w, h);
  63305. if (mousePos.getX() > getParentWidth() / 2)
  63306. x = mousePos.getX() - (w + 12);
  63307. else
  63308. x = mousePos.getX() + 24;
  63309. if (mousePos.getY() > getParentHeight() / 2)
  63310. y = mousePos.getY() - (h + 6);
  63311. else
  63312. y = mousePos.getY() + 6;
  63313. setBounds (x, y, w, h);
  63314. setVisible (true);
  63315. if (getParentComponent() == 0)
  63316. {
  63317. addToDesktop (ComponentPeer::windowHasDropShadow
  63318. | ComponentPeer::windowIsTemporary
  63319. | ComponentPeer::windowIgnoresKeyPresses);
  63320. }
  63321. toFront (false);
  63322. }
  63323. const String TooltipWindow::getTipFor (Component* const c)
  63324. {
  63325. if (c != 0
  63326. && Process::isForegroundProcess()
  63327. && ! Component::isMouseButtonDownAnywhere())
  63328. {
  63329. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63330. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63331. return ttc->getTooltip();
  63332. }
  63333. return String::empty;
  63334. }
  63335. void TooltipWindow::hide()
  63336. {
  63337. tipShowing = String::empty;
  63338. removeFromDesktop();
  63339. setVisible (false);
  63340. }
  63341. void TooltipWindow::timerCallback()
  63342. {
  63343. const unsigned int now = Time::getApproximateMillisecondCounter();
  63344. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63345. const String newTip (getTipFor (newComp));
  63346. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63347. lastComponentUnderMouse = newComp;
  63348. lastTipUnderMouse = newTip;
  63349. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63350. const bool mouseWasClicked = clickCount > mouseClicks;
  63351. mouseClicks = clickCount;
  63352. const Point<int> mousePos (Desktop::getMousePosition());
  63353. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63354. lastMousePos = mousePos;
  63355. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63356. lastCompChangeTime = now;
  63357. if (isVisible() || now < lastHideTime + 500)
  63358. {
  63359. // if a tip is currently visible (or has just disappeared), update to a new one
  63360. // immediately if needed..
  63361. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63362. {
  63363. if (isVisible())
  63364. {
  63365. lastHideTime = now;
  63366. hide();
  63367. }
  63368. }
  63369. else if (tipChanged)
  63370. {
  63371. showFor (newTip);
  63372. }
  63373. }
  63374. else
  63375. {
  63376. // if there isn't currently a tip, but one is needed, only let it
  63377. // appear after a timeout..
  63378. if (newTip.isNotEmpty()
  63379. && newTip != tipShowing
  63380. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63381. {
  63382. showFor (newTip);
  63383. }
  63384. }
  63385. }
  63386. END_JUCE_NAMESPACE
  63387. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63388. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63389. BEGIN_JUCE_NAMESPACE
  63390. /** Keeps track of the active top level window.
  63391. */
  63392. class TopLevelWindowManager : public Timer,
  63393. public DeletedAtShutdown
  63394. {
  63395. public:
  63396. TopLevelWindowManager()
  63397. : currentActive (0)
  63398. {
  63399. }
  63400. ~TopLevelWindowManager()
  63401. {
  63402. clearSingletonInstance();
  63403. }
  63404. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63405. void timerCallback()
  63406. {
  63407. startTimer (jmin (1731, getTimerInterval() * 2));
  63408. TopLevelWindow* active = 0;
  63409. if (Process::isForegroundProcess())
  63410. {
  63411. active = currentActive;
  63412. Component* const c = Component::getCurrentlyFocusedComponent();
  63413. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63414. if (tlw == 0 && c != 0)
  63415. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63416. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63417. if (tlw != 0)
  63418. active = tlw;
  63419. }
  63420. if (active != currentActive)
  63421. {
  63422. currentActive = active;
  63423. for (int i = windows.size(); --i >= 0;)
  63424. {
  63425. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63426. tlw->setWindowActive (isWindowActive (tlw));
  63427. i = jmin (i, windows.size() - 1);
  63428. }
  63429. Desktop::getInstance().triggerFocusCallback();
  63430. }
  63431. }
  63432. bool addWindow (TopLevelWindow* const w)
  63433. {
  63434. windows.add (w);
  63435. startTimer (10);
  63436. return isWindowActive (w);
  63437. }
  63438. void removeWindow (TopLevelWindow* const w)
  63439. {
  63440. startTimer (10);
  63441. if (currentActive == w)
  63442. currentActive = 0;
  63443. windows.removeValue (w);
  63444. if (windows.size() == 0)
  63445. deleteInstance();
  63446. }
  63447. Array <TopLevelWindow*> windows;
  63448. private:
  63449. TopLevelWindow* currentActive;
  63450. bool isWindowActive (TopLevelWindow* const tlw) const
  63451. {
  63452. return (tlw == currentActive
  63453. || tlw->isParentOf (currentActive)
  63454. || tlw->hasKeyboardFocus (true))
  63455. && tlw->isShowing();
  63456. }
  63457. JUCE_DECLARE_NON_COPYABLE (TopLevelWindowManager);
  63458. };
  63459. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63460. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63461. {
  63462. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63463. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63464. }
  63465. TopLevelWindow::TopLevelWindow (const String& name,
  63466. const bool addToDesktop_)
  63467. : Component (name),
  63468. useDropShadow (true),
  63469. useNativeTitleBar (false),
  63470. windowIsActive_ (false)
  63471. {
  63472. setOpaque (true);
  63473. if (addToDesktop_)
  63474. Component::addToDesktop (getDesktopWindowStyleFlags());
  63475. else
  63476. setDropShadowEnabled (true);
  63477. setWantsKeyboardFocus (true);
  63478. setBroughtToFrontOnMouseClick (true);
  63479. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63480. }
  63481. TopLevelWindow::~TopLevelWindow()
  63482. {
  63483. shadower = 0;
  63484. TopLevelWindowManager::getInstance()->removeWindow (this);
  63485. }
  63486. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63487. {
  63488. if (hasKeyboardFocus (true))
  63489. TopLevelWindowManager::getInstance()->timerCallback();
  63490. else
  63491. TopLevelWindowManager::getInstance()->startTimer (10);
  63492. }
  63493. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63494. {
  63495. if (windowIsActive_ != isNowActive)
  63496. {
  63497. windowIsActive_ = isNowActive;
  63498. activeWindowStatusChanged();
  63499. }
  63500. }
  63501. void TopLevelWindow::activeWindowStatusChanged()
  63502. {
  63503. }
  63504. void TopLevelWindow::visibilityChanged()
  63505. {
  63506. if (isShowing()
  63507. && (getPeer()->getStyleFlags() & (ComponentPeer::windowIsTemporary
  63508. | ComponentPeer::windowIgnoresKeyPresses)) == 0)
  63509. {
  63510. toFront (true);
  63511. }
  63512. }
  63513. void TopLevelWindow::parentHierarchyChanged()
  63514. {
  63515. setDropShadowEnabled (useDropShadow);
  63516. }
  63517. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63518. {
  63519. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63520. if (useDropShadow)
  63521. styleFlags |= ComponentPeer::windowHasDropShadow;
  63522. if (useNativeTitleBar)
  63523. styleFlags |= ComponentPeer::windowHasTitleBar;
  63524. return styleFlags;
  63525. }
  63526. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63527. {
  63528. useDropShadow = useShadow;
  63529. if (isOnDesktop())
  63530. {
  63531. shadower = 0;
  63532. Component::addToDesktop (getDesktopWindowStyleFlags());
  63533. }
  63534. else
  63535. {
  63536. if (useShadow && isOpaque())
  63537. {
  63538. if (shadower == 0)
  63539. {
  63540. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63541. if (shadower != 0)
  63542. shadower->setOwner (this);
  63543. }
  63544. }
  63545. else
  63546. {
  63547. shadower = 0;
  63548. }
  63549. }
  63550. }
  63551. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63552. {
  63553. if (useNativeTitleBar != useNativeTitleBar_)
  63554. {
  63555. useNativeTitleBar = useNativeTitleBar_;
  63556. recreateDesktopWindow();
  63557. sendLookAndFeelChange();
  63558. }
  63559. }
  63560. void TopLevelWindow::recreateDesktopWindow()
  63561. {
  63562. if (isOnDesktop())
  63563. {
  63564. Component::addToDesktop (getDesktopWindowStyleFlags());
  63565. toFront (true);
  63566. }
  63567. }
  63568. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63569. {
  63570. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63571. because this class needs to make sure its layout corresponds with settings like whether
  63572. it's got a native title bar or not.
  63573. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63574. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63575. method, then add or remove whatever flags are necessary from this value before returning it.
  63576. */
  63577. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63578. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63579. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63580. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63581. sendLookAndFeelChange();
  63582. }
  63583. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63584. {
  63585. if (c == 0)
  63586. c = TopLevelWindow::getActiveTopLevelWindow();
  63587. if (c == 0)
  63588. {
  63589. centreWithSize (width, height);
  63590. }
  63591. else
  63592. {
  63593. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63594. Rectangle<int> parentArea (c->getParentMonitorArea());
  63595. if (getParentComponent() != 0)
  63596. {
  63597. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63598. parentArea = getParentComponent()->getLocalBounds();
  63599. }
  63600. parentArea.reduce (12, 12);
  63601. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63602. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63603. width, height);
  63604. }
  63605. }
  63606. int TopLevelWindow::getNumTopLevelWindows() throw()
  63607. {
  63608. return TopLevelWindowManager::getInstance()->windows.size();
  63609. }
  63610. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63611. {
  63612. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63613. }
  63614. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63615. {
  63616. TopLevelWindow* best = 0;
  63617. int bestNumTWLParents = -1;
  63618. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63619. {
  63620. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63621. if (tlw->isActiveWindow())
  63622. {
  63623. int numTWLParents = 0;
  63624. const Component* c = tlw->getParentComponent();
  63625. while (c != 0)
  63626. {
  63627. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63628. ++numTWLParents;
  63629. c = c->getParentComponent();
  63630. }
  63631. if (bestNumTWLParents < numTWLParents)
  63632. {
  63633. best = tlw;
  63634. bestNumTWLParents = numTWLParents;
  63635. }
  63636. }
  63637. }
  63638. return best;
  63639. }
  63640. END_JUCE_NAMESPACE
  63641. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63642. /*** Start of inlined file: juce_MarkerList.cpp ***/
  63643. BEGIN_JUCE_NAMESPACE
  63644. MarkerList::MarkerList()
  63645. {
  63646. }
  63647. MarkerList::MarkerList (const MarkerList& other)
  63648. {
  63649. operator= (other);
  63650. }
  63651. MarkerList& MarkerList::operator= (const MarkerList& other)
  63652. {
  63653. if (other != *this)
  63654. {
  63655. markers.clear();
  63656. markers.addCopiesOf (other.markers);
  63657. markersHaveChanged();
  63658. }
  63659. return *this;
  63660. }
  63661. MarkerList::~MarkerList()
  63662. {
  63663. listeners.call (&MarkerList::Listener::markerListBeingDeleted, this);
  63664. }
  63665. bool MarkerList::operator== (const MarkerList& other) const throw()
  63666. {
  63667. if (other.markers.size() != markers.size())
  63668. return false;
  63669. for (int i = markers.size(); --i >= 0;)
  63670. {
  63671. const Marker* const m1 = markers.getUnchecked(i);
  63672. jassert (m1 != 0);
  63673. const Marker* const m2 = other.getMarker (m1->name);
  63674. if (m2 == 0 || *m1 != *m2)
  63675. return false;
  63676. }
  63677. return true;
  63678. }
  63679. bool MarkerList::operator!= (const MarkerList& other) const throw()
  63680. {
  63681. return ! operator== (other);
  63682. }
  63683. int MarkerList::getNumMarkers() const throw()
  63684. {
  63685. return markers.size();
  63686. }
  63687. const MarkerList::Marker* MarkerList::getMarker (const int index) const throw()
  63688. {
  63689. return markers [index];
  63690. }
  63691. const MarkerList::Marker* MarkerList::getMarker (const String& name) const throw()
  63692. {
  63693. for (int i = 0; i < markers.size(); ++i)
  63694. {
  63695. const Marker* const m = markers.getUnchecked(i);
  63696. if (m->name == name)
  63697. return m;
  63698. }
  63699. return 0;
  63700. }
  63701. void MarkerList::setMarker (const String& name, const RelativeCoordinate& position)
  63702. {
  63703. Marker* const m = const_cast <Marker*> (getMarker (name));
  63704. if (m != 0)
  63705. {
  63706. if (m->position != position)
  63707. {
  63708. m->position = position;
  63709. markersHaveChanged();
  63710. }
  63711. return;
  63712. }
  63713. markers.add (new Marker (name, position));
  63714. markersHaveChanged();
  63715. }
  63716. void MarkerList::removeMarker (const int index)
  63717. {
  63718. if (isPositiveAndBelow (index, markers.size()))
  63719. {
  63720. markers.remove (index);
  63721. markersHaveChanged();
  63722. }
  63723. }
  63724. void MarkerList::removeMarker (const String& name)
  63725. {
  63726. for (int i = 0; i < markers.size(); ++i)
  63727. {
  63728. const Marker* const m = markers.getUnchecked(i);
  63729. if (m->name == name)
  63730. {
  63731. markers.remove (i);
  63732. markersHaveChanged();
  63733. }
  63734. }
  63735. }
  63736. void MarkerList::markersHaveChanged()
  63737. {
  63738. listeners.call (&MarkerList::Listener::markersChanged, this);
  63739. }
  63740. void MarkerList::Listener::markerListBeingDeleted (MarkerList*)
  63741. {
  63742. }
  63743. void MarkerList::addListener (Listener* listener)
  63744. {
  63745. listeners.add (listener);
  63746. }
  63747. void MarkerList::removeListener (Listener* listener)
  63748. {
  63749. listeners.remove (listener);
  63750. }
  63751. MarkerList::Marker::Marker (const Marker& other)
  63752. : name (other.name), position (other.position)
  63753. {
  63754. }
  63755. MarkerList::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  63756. : name (name_), position (position_)
  63757. {
  63758. }
  63759. bool MarkerList::Marker::operator== (const Marker& other) const throw()
  63760. {
  63761. return name == other.name && position == other.position;
  63762. }
  63763. bool MarkerList::Marker::operator!= (const Marker& other) const throw()
  63764. {
  63765. return ! operator== (other);
  63766. }
  63767. const Identifier MarkerList::ValueTreeWrapper::markerTag ("Marker");
  63768. const Identifier MarkerList::ValueTreeWrapper::nameProperty ("name");
  63769. const Identifier MarkerList::ValueTreeWrapper::posProperty ("position");
  63770. MarkerList::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  63771. : state (state_)
  63772. {
  63773. }
  63774. int MarkerList::ValueTreeWrapper::getNumMarkers() const
  63775. {
  63776. return state.getNumChildren();
  63777. }
  63778. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (int index) const
  63779. {
  63780. return state.getChild (index);
  63781. }
  63782. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (const String& name) const
  63783. {
  63784. return state.getChildWithProperty (nameProperty, name);
  63785. }
  63786. bool MarkerList::ValueTreeWrapper::containsMarker (const ValueTree& marker) const
  63787. {
  63788. return marker.isAChildOf (state);
  63789. }
  63790. const MarkerList::Marker MarkerList::ValueTreeWrapper::getMarker (const ValueTree& marker) const
  63791. {
  63792. jassert (containsMarker (marker));
  63793. return MarkerList::Marker (marker [nameProperty], RelativeCoordinate (marker [posProperty].toString()));
  63794. }
  63795. void MarkerList::ValueTreeWrapper::setMarker (const MarkerList::Marker& m, UndoManager* undoManager)
  63796. {
  63797. ValueTree marker (state.getChildWithProperty (nameProperty, m.name));
  63798. if (marker.isValid())
  63799. {
  63800. marker.setProperty (posProperty, m.position.toString(), undoManager);
  63801. }
  63802. else
  63803. {
  63804. marker = ValueTree (markerTag);
  63805. marker.setProperty (nameProperty, m.name, 0);
  63806. marker.setProperty (posProperty, m.position.toString(), 0);
  63807. state.addChild (marker, -1, undoManager);
  63808. }
  63809. }
  63810. void MarkerList::ValueTreeWrapper::removeMarker (const ValueTree& marker, UndoManager* undoManager)
  63811. {
  63812. state.removeChild (marker, undoManager);
  63813. }
  63814. class MarkerListEvaluator : public Expression::EvaluationContext
  63815. {
  63816. public:
  63817. MarkerListEvaluator (const MarkerList& markerList_, Component* const parentComponent_)
  63818. : markerList (markerList_), parentComponent (parentComponent_)
  63819. {
  63820. }
  63821. const Expression getSymbolValue (const String& objectName, const String& member) const
  63822. {
  63823. if (member.isEmpty())
  63824. {
  63825. const MarkerList::Marker* const marker = markerList.getMarker (objectName);
  63826. if (marker != 0)
  63827. return Expression (marker->position.resolve (this));
  63828. }
  63829. else if (parentComponent != 0 && objectName == RelativeCoordinate::Strings::parent)
  63830. {
  63831. if (member == RelativeCoordinate::Strings::right) return Expression ((double) parentComponent->getWidth());
  63832. if (member == RelativeCoordinate::Strings::bottom) return Expression ((double) parentComponent->getHeight());
  63833. }
  63834. return Expression::EvaluationContext::getSymbolValue (objectName, member);
  63835. }
  63836. private:
  63837. const MarkerList& markerList;
  63838. Component* parentComponent;
  63839. JUCE_DECLARE_NON_COPYABLE (MarkerListEvaluator);
  63840. };
  63841. double MarkerList::getMarkerPosition (const Marker& marker, Component* const parentComponent) const
  63842. {
  63843. MarkerListEvaluator context (*this, parentComponent);
  63844. return marker.position.resolve (&context);
  63845. }
  63846. void MarkerList::ValueTreeWrapper::applyTo (MarkerList& markerList)
  63847. {
  63848. const int numMarkers = getNumMarkers();
  63849. StringArray updatedMarkers;
  63850. int i;
  63851. for (i = 0; i < numMarkers; ++i)
  63852. {
  63853. const ValueTree marker (state.getChild (i));
  63854. const String name (marker [nameProperty].toString());
  63855. markerList.setMarker (name, RelativeCoordinate (marker [posProperty].toString()));
  63856. updatedMarkers.add (name);
  63857. }
  63858. for (i = markerList.getNumMarkers(); --i >= 0;)
  63859. if (! updatedMarkers.contains (markerList.getMarker (i)->name))
  63860. markerList.removeMarker (i);
  63861. }
  63862. void MarkerList::ValueTreeWrapper::readFrom (const MarkerList& markerList, UndoManager* undoManager)
  63863. {
  63864. state.removeAllChildren (undoManager);
  63865. for (int i = 0; i < markerList.getNumMarkers(); ++i)
  63866. setMarker (*markerList.getMarker(i), undoManager);
  63867. }
  63868. END_JUCE_NAMESPACE
  63869. /*** End of inlined file: juce_MarkerList.cpp ***/
  63870. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  63871. BEGIN_JUCE_NAMESPACE
  63872. const String RelativeCoordinate::Strings::parent ("parent");
  63873. const String RelativeCoordinate::Strings::this_ ("this");
  63874. const String RelativeCoordinate::Strings::left ("left");
  63875. const String RelativeCoordinate::Strings::right ("right");
  63876. const String RelativeCoordinate::Strings::top ("top");
  63877. const String RelativeCoordinate::Strings::bottom ("bottom");
  63878. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  63879. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  63880. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  63881. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  63882. RelativeCoordinate::RelativeCoordinate()
  63883. {
  63884. }
  63885. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  63886. : term (term_)
  63887. {
  63888. }
  63889. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  63890. : term (other.term)
  63891. {
  63892. }
  63893. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  63894. {
  63895. term = other.term;
  63896. return *this;
  63897. }
  63898. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  63899. : term (absoluteDistanceFromOrigin)
  63900. {
  63901. }
  63902. RelativeCoordinate::RelativeCoordinate (const String& s)
  63903. {
  63904. try
  63905. {
  63906. term = Expression (s);
  63907. }
  63908. catch (...)
  63909. {}
  63910. }
  63911. RelativeCoordinate::~RelativeCoordinate()
  63912. {
  63913. }
  63914. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  63915. {
  63916. return term.toString() == other.term.toString();
  63917. }
  63918. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  63919. {
  63920. return ! operator== (other);
  63921. }
  63922. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  63923. {
  63924. try
  63925. {
  63926. if (context != 0)
  63927. return term.evaluate (*context);
  63928. else
  63929. return term.evaluate();
  63930. }
  63931. catch (...)
  63932. {}
  63933. return 0.0;
  63934. }
  63935. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  63936. {
  63937. try
  63938. {
  63939. if (context != 0)
  63940. term.evaluate (*context);
  63941. else
  63942. term.evaluate();
  63943. }
  63944. catch (...)
  63945. {
  63946. return true;
  63947. }
  63948. return false;
  63949. }
  63950. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  63951. {
  63952. try
  63953. {
  63954. if (context != 0)
  63955. {
  63956. term = term.adjustedToGiveNewResult (newPos, *context);
  63957. }
  63958. else
  63959. {
  63960. Expression::EvaluationContext defaultContext;
  63961. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  63962. }
  63963. }
  63964. catch (...)
  63965. {}
  63966. }
  63967. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  63968. {
  63969. try
  63970. {
  63971. return term.referencesSymbol (coordName, context);
  63972. }
  63973. catch (...)
  63974. {}
  63975. return false;
  63976. }
  63977. bool RelativeCoordinate::isDynamic() const
  63978. {
  63979. return term.usesAnySymbols();
  63980. }
  63981. const String RelativeCoordinate::toString() const
  63982. {
  63983. return term.toString();
  63984. }
  63985. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  63986. {
  63987. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  63988. if (term.referencesSymbol (oldName, 0))
  63989. term = term.withRenamedSymbol (oldName, newName);
  63990. }
  63991. END_JUCE_NAMESPACE
  63992. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  63993. /*** Start of inlined file: juce_RelativePoint.cpp ***/
  63994. BEGIN_JUCE_NAMESPACE
  63995. namespace RelativePointHelpers
  63996. {
  63997. void skipComma (const juce_wchar* const s, int& i)
  63998. {
  63999. while (CharacterFunctions::isWhitespace (s[i]))
  64000. ++i;
  64001. if (s[i] == ',')
  64002. ++i;
  64003. }
  64004. }
  64005. RelativePoint::RelativePoint()
  64006. {
  64007. }
  64008. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64009. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64010. {
  64011. }
  64012. RelativePoint::RelativePoint (const float x_, const float y_)
  64013. : x (x_), y (y_)
  64014. {
  64015. }
  64016. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64017. : x (x_), y (y_)
  64018. {
  64019. }
  64020. RelativePoint::RelativePoint (const String& s)
  64021. {
  64022. int i = 0;
  64023. x = RelativeCoordinate (Expression::parse (s, i));
  64024. RelativePointHelpers::skipComma (s, i);
  64025. y = RelativeCoordinate (Expression::parse (s, i));
  64026. }
  64027. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64028. {
  64029. return x == other.x && y == other.y;
  64030. }
  64031. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64032. {
  64033. return ! operator== (other);
  64034. }
  64035. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64036. {
  64037. return Point<float> ((float) x.resolve (context),
  64038. (float) y.resolve (context));
  64039. }
  64040. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64041. {
  64042. x.moveToAbsolute (newPos.getX(), context);
  64043. y.moveToAbsolute (newPos.getY(), context);
  64044. }
  64045. const String RelativePoint::toString() const
  64046. {
  64047. return x.toString() + ", " + y.toString();
  64048. }
  64049. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64050. {
  64051. x.renameSymbolIfUsed (oldName, newName);
  64052. y.renameSymbolIfUsed (oldName, newName);
  64053. }
  64054. bool RelativePoint::isDynamic() const
  64055. {
  64056. return x.isDynamic() || y.isDynamic();
  64057. }
  64058. END_JUCE_NAMESPACE
  64059. /*** End of inlined file: juce_RelativePoint.cpp ***/
  64060. /*** Start of inlined file: juce_RelativeRectangle.cpp ***/
  64061. BEGIN_JUCE_NAMESPACE
  64062. namespace RelativeRectangleHelpers
  64063. {
  64064. inline void skipComma (const juce_wchar* const s, int& i)
  64065. {
  64066. while (CharacterFunctions::isWhitespace (s[i]))
  64067. ++i;
  64068. if (s[i] == ',')
  64069. ++i;
  64070. }
  64071. bool dependsOnSymbolsOtherThanThis (const Expression& e)
  64072. {
  64073. if (e.getType() == Expression::symbolType)
  64074. {
  64075. String objectName, memberName;
  64076. e.getSymbolParts (objectName, memberName);
  64077. if (objectName != RelativeCoordinate::Strings::this_)
  64078. return true;
  64079. }
  64080. else
  64081. {
  64082. for (int i = e.getNumInputs(); --i >= 0;)
  64083. if (dependsOnSymbolsOtherThanThis (e.getInput(i)))
  64084. return true;
  64085. }
  64086. return false;
  64087. }
  64088. }
  64089. RelativeRectangle::RelativeRectangle()
  64090. {
  64091. }
  64092. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64093. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64094. : left (left_), right (right_), top (top_), bottom (bottom_)
  64095. {
  64096. }
  64097. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect)
  64098. : left (rect.getX()),
  64099. right (Expression::symbol (RelativeCoordinate::Strings::this_ + "." + RelativeCoordinate::Strings::left)
  64100. + Expression ((double) rect.getWidth())),
  64101. top (rect.getY()),
  64102. bottom (Expression::symbol (RelativeCoordinate::Strings::this_ + "." + RelativeCoordinate::Strings::top)
  64103. + Expression ((double) rect.getHeight()))
  64104. {
  64105. }
  64106. RelativeRectangle::RelativeRectangle (const String& s)
  64107. {
  64108. int i = 0;
  64109. left = RelativeCoordinate (Expression::parse (s, i));
  64110. RelativeRectangleHelpers::skipComma (s, i);
  64111. top = RelativeCoordinate (Expression::parse (s, i));
  64112. RelativeRectangleHelpers::skipComma (s, i);
  64113. right = RelativeCoordinate (Expression::parse (s, i));
  64114. RelativeRectangleHelpers::skipComma (s, i);
  64115. bottom = RelativeCoordinate (Expression::parse (s, i));
  64116. }
  64117. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64118. {
  64119. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64120. }
  64121. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64122. {
  64123. return ! operator== (other);
  64124. }
  64125. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64126. {
  64127. const double l = left.resolve (context);
  64128. const double r = right.resolve (context);
  64129. const double t = top.resolve (context);
  64130. const double b = bottom.resolve (context);
  64131. return Rectangle<float> ((float) l, (float) t, (float) jmax (0.0, r - l), (float) jmax (0.0, b - t));
  64132. }
  64133. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64134. {
  64135. left.moveToAbsolute (newPos.getX(), context);
  64136. right.moveToAbsolute (newPos.getRight(), context);
  64137. top.moveToAbsolute (newPos.getY(), context);
  64138. bottom.moveToAbsolute (newPos.getBottom(), context);
  64139. }
  64140. bool RelativeRectangle::isDynamic() const
  64141. {
  64142. using namespace RelativeRectangleHelpers;
  64143. return dependsOnSymbolsOtherThanThis (left.getExpression())
  64144. || dependsOnSymbolsOtherThanThis (right.getExpression())
  64145. || dependsOnSymbolsOtherThanThis (top.getExpression())
  64146. || dependsOnSymbolsOtherThanThis (bottom.getExpression());
  64147. }
  64148. const String RelativeRectangle::toString() const
  64149. {
  64150. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64151. }
  64152. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64153. {
  64154. left.renameSymbolIfUsed (oldName, newName);
  64155. right.renameSymbolIfUsed (oldName, newName);
  64156. top.renameSymbolIfUsed (oldName, newName);
  64157. bottom.renameSymbolIfUsed (oldName, newName);
  64158. }
  64159. class RelativeRectangleComponentPositioner : public RelativeCoordinatePositionerBase
  64160. {
  64161. public:
  64162. RelativeRectangleComponentPositioner (Component& component_, const RelativeRectangle& rectangle_)
  64163. : RelativeCoordinatePositionerBase (component_),
  64164. rectangle (rectangle_)
  64165. {
  64166. }
  64167. bool registerCoordinates()
  64168. {
  64169. bool ok = addCoordinate (rectangle.left);
  64170. ok = addCoordinate (rectangle.right) && ok;
  64171. ok = addCoordinate (rectangle.top) && ok;
  64172. ok = addCoordinate (rectangle.bottom) && ok;
  64173. return ok;
  64174. }
  64175. bool isUsingRectangle (const RelativeRectangle& other) const throw()
  64176. {
  64177. return rectangle == other;
  64178. }
  64179. void applyToComponentBounds()
  64180. {
  64181. for (int i = 4; --i >= 0;)
  64182. {
  64183. const Rectangle<int> newBounds (rectangle.resolve (this).getSmallestIntegerContainer());
  64184. if (newBounds == getComponent().getBounds())
  64185. return;
  64186. getComponent().setBounds (newBounds);
  64187. }
  64188. jassertfalse; // must be a recursive reference!
  64189. }
  64190. private:
  64191. const RelativeRectangle rectangle;
  64192. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeRectangleComponentPositioner);
  64193. };
  64194. // An expression context that can evaluate expressions using "this"
  64195. class TemporaryRectangleContext : public Expression::EvaluationContext
  64196. {
  64197. public:
  64198. TemporaryRectangleContext (const RelativeRectangle& rect_) : rect (rect_) {}
  64199. const Expression getSymbolValue (const String& objectName, const String& edge) const
  64200. {
  64201. if (objectName == RelativeCoordinate::Strings::this_)
  64202. {
  64203. if (edge == RelativeCoordinate::Strings::left) return rect.left.getExpression();
  64204. if (edge == RelativeCoordinate::Strings::right) return rect.right.getExpression();
  64205. if (edge == RelativeCoordinate::Strings::top) return rect.top.getExpression();
  64206. if (edge == RelativeCoordinate::Strings::bottom) return rect.bottom.getExpression();
  64207. }
  64208. return Expression::EvaluationContext::getSymbolValue (objectName, edge);
  64209. }
  64210. private:
  64211. const RelativeRectangle& rect;
  64212. JUCE_DECLARE_NON_COPYABLE (TemporaryRectangleContext);
  64213. };
  64214. void RelativeRectangle::applyToComponent (Component& component) const
  64215. {
  64216. if (isDynamic())
  64217. {
  64218. RelativeRectangleComponentPositioner* current = dynamic_cast <RelativeRectangleComponentPositioner*> (component.getPositioner());
  64219. if (current == 0 || ! current->isUsingRectangle (*this))
  64220. {
  64221. RelativeRectangleComponentPositioner* p = new RelativeRectangleComponentPositioner (component, *this);
  64222. component.setPositioner (p);
  64223. p->apply();
  64224. }
  64225. }
  64226. else
  64227. {
  64228. component.setPositioner (0);
  64229. TemporaryRectangleContext context (*this);
  64230. component.setBounds (resolve (&context).getSmallestIntegerContainer());
  64231. }
  64232. }
  64233. END_JUCE_NAMESPACE
  64234. /*** End of inlined file: juce_RelativeRectangle.cpp ***/
  64235. /*** Start of inlined file: juce_RelativePointPath.cpp ***/
  64236. BEGIN_JUCE_NAMESPACE
  64237. RelativePointPath::RelativePointPath()
  64238. : usesNonZeroWinding (true),
  64239. containsDynamicPoints (false)
  64240. {
  64241. }
  64242. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64243. : usesNonZeroWinding (true),
  64244. containsDynamicPoints (false)
  64245. {
  64246. for (int i = 0; i < other.elements.size(); ++i)
  64247. elements.add (other.elements.getUnchecked(i)->clone());
  64248. }
  64249. RelativePointPath::RelativePointPath (const Path& path)
  64250. : usesNonZeroWinding (path.isUsingNonZeroWinding()),
  64251. containsDynamicPoints (false)
  64252. {
  64253. for (Path::Iterator i (path); i.next();)
  64254. {
  64255. switch (i.elementType)
  64256. {
  64257. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64258. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64259. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64260. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64261. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64262. default: jassertfalse; break;
  64263. }
  64264. }
  64265. }
  64266. RelativePointPath::~RelativePointPath()
  64267. {
  64268. }
  64269. bool RelativePointPath::operator== (const RelativePointPath& other) const throw()
  64270. {
  64271. if (elements.size() != other.elements.size()
  64272. || usesNonZeroWinding != other.usesNonZeroWinding
  64273. || containsDynamicPoints != other.containsDynamicPoints)
  64274. return false;
  64275. for (int i = 0; i < elements.size(); ++i)
  64276. {
  64277. ElementBase* const e1 = elements.getUnchecked(i);
  64278. ElementBase* const e2 = other.elements.getUnchecked(i);
  64279. if (e1->type != e2->type)
  64280. return false;
  64281. int numPoints1, numPoints2;
  64282. const RelativePoint* const points1 = e1->getControlPoints (numPoints1);
  64283. const RelativePoint* const points2 = e2->getControlPoints (numPoints2);
  64284. jassert (numPoints1 == numPoints2);
  64285. for (int j = numPoints1; --j >= 0;)
  64286. if (points1[j] != points2[j])
  64287. return false;
  64288. }
  64289. return true;
  64290. }
  64291. bool RelativePointPath::operator!= (const RelativePointPath& other) const throw()
  64292. {
  64293. return ! operator== (other);
  64294. }
  64295. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64296. {
  64297. elements.swapWithArray (other.elements);
  64298. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64299. swapVariables (containsDynamicPoints, other.containsDynamicPoints);
  64300. }
  64301. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64302. {
  64303. for (int i = 0; i < elements.size(); ++i)
  64304. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64305. }
  64306. bool RelativePointPath::containsAnyDynamicPoints() const
  64307. {
  64308. return containsDynamicPoints;
  64309. }
  64310. void RelativePointPath::addElement (ElementBase* newElement)
  64311. {
  64312. if (newElement != 0)
  64313. {
  64314. elements.add (newElement);
  64315. containsDynamicPoints = containsDynamicPoints || newElement->isDynamic();
  64316. }
  64317. }
  64318. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64319. {
  64320. }
  64321. bool RelativePointPath::ElementBase::isDynamic()
  64322. {
  64323. int numPoints;
  64324. const RelativePoint* const points = getControlPoints (numPoints);
  64325. for (int i = numPoints; --i >= 0;)
  64326. if (points[i].isDynamic())
  64327. return true;
  64328. return false;
  64329. }
  64330. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64331. : ElementBase (startSubPathElement), startPos (pos)
  64332. {
  64333. }
  64334. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64335. {
  64336. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64337. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64338. return v;
  64339. }
  64340. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64341. {
  64342. path.startNewSubPath (startPos.resolve (coordFinder));
  64343. }
  64344. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64345. {
  64346. numPoints = 1;
  64347. return &startPos;
  64348. }
  64349. RelativePointPath::ElementBase* RelativePointPath::StartSubPath::clone() const
  64350. {
  64351. return new StartSubPath (startPos);
  64352. }
  64353. RelativePointPath::CloseSubPath::CloseSubPath()
  64354. : ElementBase (closeSubPathElement)
  64355. {
  64356. }
  64357. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64358. {
  64359. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64360. }
  64361. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64362. {
  64363. path.closeSubPath();
  64364. }
  64365. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64366. {
  64367. numPoints = 0;
  64368. return 0;
  64369. }
  64370. RelativePointPath::ElementBase* RelativePointPath::CloseSubPath::clone() const
  64371. {
  64372. return new CloseSubPath();
  64373. }
  64374. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64375. : ElementBase (lineToElement), endPoint (endPoint_)
  64376. {
  64377. }
  64378. const ValueTree RelativePointPath::LineTo::createTree() const
  64379. {
  64380. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64381. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64382. return v;
  64383. }
  64384. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64385. {
  64386. path.lineTo (endPoint.resolve (coordFinder));
  64387. }
  64388. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64389. {
  64390. numPoints = 1;
  64391. return &endPoint;
  64392. }
  64393. RelativePointPath::ElementBase* RelativePointPath::LineTo::clone() const
  64394. {
  64395. return new LineTo (endPoint);
  64396. }
  64397. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64398. : ElementBase (quadraticToElement)
  64399. {
  64400. controlPoints[0] = controlPoint;
  64401. controlPoints[1] = endPoint;
  64402. }
  64403. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64404. {
  64405. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64406. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64407. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64408. return v;
  64409. }
  64410. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64411. {
  64412. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64413. controlPoints[1].resolve (coordFinder));
  64414. }
  64415. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64416. {
  64417. numPoints = 2;
  64418. return controlPoints;
  64419. }
  64420. RelativePointPath::ElementBase* RelativePointPath::QuadraticTo::clone() const
  64421. {
  64422. return new QuadraticTo (controlPoints[0], controlPoints[1]);
  64423. }
  64424. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64425. : ElementBase (cubicToElement)
  64426. {
  64427. controlPoints[0] = controlPoint1;
  64428. controlPoints[1] = controlPoint2;
  64429. controlPoints[2] = endPoint;
  64430. }
  64431. const ValueTree RelativePointPath::CubicTo::createTree() const
  64432. {
  64433. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64434. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64435. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64436. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64437. return v;
  64438. }
  64439. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64440. {
  64441. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64442. controlPoints[1].resolve (coordFinder),
  64443. controlPoints[2].resolve (coordFinder));
  64444. }
  64445. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64446. {
  64447. numPoints = 3;
  64448. return controlPoints;
  64449. }
  64450. RelativePointPath::ElementBase* RelativePointPath::CubicTo::clone() const
  64451. {
  64452. return new CubicTo (controlPoints[0], controlPoints[1], controlPoints[2]);
  64453. }
  64454. END_JUCE_NAMESPACE
  64455. /*** End of inlined file: juce_RelativePointPath.cpp ***/
  64456. /*** Start of inlined file: juce_RelativeParallelogram.cpp ***/
  64457. BEGIN_JUCE_NAMESPACE
  64458. RelativeParallelogram::RelativeParallelogram()
  64459. {
  64460. }
  64461. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64462. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64463. {
  64464. }
  64465. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64466. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64467. {
  64468. }
  64469. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64470. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64471. {
  64472. }
  64473. RelativeParallelogram::~RelativeParallelogram()
  64474. {
  64475. }
  64476. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64477. {
  64478. points[0] = topLeft.resolve (coordFinder);
  64479. points[1] = topRight.resolve (coordFinder);
  64480. points[2] = bottomLeft.resolve (coordFinder);
  64481. }
  64482. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64483. {
  64484. resolveThreePoints (points, coordFinder);
  64485. points[3] = points[1] + (points[2] - points[0]);
  64486. }
  64487. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64488. {
  64489. Point<float> points[4];
  64490. resolveFourCorners (points, coordFinder);
  64491. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64492. }
  64493. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64494. {
  64495. Point<float> points[4];
  64496. resolveFourCorners (points, coordFinder);
  64497. path.startNewSubPath (points[0]);
  64498. path.lineTo (points[1]);
  64499. path.lineTo (points[3]);
  64500. path.lineTo (points[2]);
  64501. path.closeSubPath();
  64502. }
  64503. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64504. {
  64505. Point<float> corners[3];
  64506. resolveThreePoints (corners, coordFinder);
  64507. const Line<float> top (corners[0], corners[1]);
  64508. const Line<float> left (corners[0], corners[2]);
  64509. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64510. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64511. topRight.moveToAbsolute (newTopRight, coordFinder);
  64512. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64513. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64514. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64515. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64516. }
  64517. bool RelativeParallelogram::isDynamic() const
  64518. {
  64519. return topLeft.isDynamic() || topRight.isDynamic() || bottomLeft.isDynamic();
  64520. }
  64521. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64522. {
  64523. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64524. }
  64525. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64526. {
  64527. return ! operator== (other);
  64528. }
  64529. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64530. {
  64531. const Point<float> tr (corners[1] - corners[0]);
  64532. const Point<float> bl (corners[2] - corners[0]);
  64533. target -= corners[0];
  64534. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64535. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64536. }
  64537. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64538. {
  64539. return corners[0]
  64540. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64541. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64542. }
  64543. const Rectangle<float> RelativeParallelogram::getBoundingBox (const Point<float>* const p) throw()
  64544. {
  64545. const Point<float> points[] = { p[0], p[1], p[2], p[1] + (p[2] - p[0]) };
  64546. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64547. }
  64548. END_JUCE_NAMESPACE
  64549. /*** End of inlined file: juce_RelativeParallelogram.cpp ***/
  64550. /*** Start of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64551. BEGIN_JUCE_NAMESPACE
  64552. RelativeCoordinatePositionerBase::RelativeCoordinatePositionerBase (Component& component_)
  64553. : Component::Positioner (component_), registeredOk (false)
  64554. {
  64555. }
  64556. RelativeCoordinatePositionerBase::~RelativeCoordinatePositionerBase()
  64557. {
  64558. unregisterListeners();
  64559. }
  64560. const Expression RelativeCoordinatePositionerBase::getSymbolValue (const String& objectName, const String& member) const
  64561. {
  64562. jassert (objectName.isNotEmpty());
  64563. if (member.isNotEmpty())
  64564. {
  64565. const Component* comp = getSourceComponent (objectName);
  64566. if (comp == 0)
  64567. {
  64568. if (objectName == RelativeCoordinate::Strings::parent)
  64569. comp = getComponent().getParentComponent();
  64570. else if (objectName == RelativeCoordinate::Strings::this_ || objectName == getComponent().getComponentID())
  64571. comp = &getComponent();
  64572. }
  64573. if (comp != 0)
  64574. {
  64575. if (member == RelativeCoordinate::Strings::left) return xToExpression (comp, 0);
  64576. if (member == RelativeCoordinate::Strings::right) return xToExpression (comp, comp->getWidth());
  64577. if (member == RelativeCoordinate::Strings::top) return yToExpression (comp, 0);
  64578. if (member == RelativeCoordinate::Strings::bottom) return yToExpression (comp, comp->getHeight());
  64579. }
  64580. }
  64581. for (int i = sourceMarkerLists.size(); --i >= 0;)
  64582. {
  64583. MarkerList* const markerList = sourceMarkerLists.getUnchecked(i);
  64584. const MarkerList::Marker* const marker = markerList->getMarker (objectName);
  64585. if (marker != 0)
  64586. return Expression (markerList->getMarkerPosition (*marker, getComponent().getParentComponent()));
  64587. }
  64588. return Expression::EvaluationContext::getSymbolValue (objectName, member);
  64589. }
  64590. void RelativeCoordinatePositionerBase::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  64591. {
  64592. apply();
  64593. }
  64594. void RelativeCoordinatePositionerBase::componentParentHierarchyChanged (Component&)
  64595. {
  64596. apply();
  64597. }
  64598. void RelativeCoordinatePositionerBase::componentBeingDeleted (Component& component)
  64599. {
  64600. jassert (sourceComponents.contains (&component));
  64601. sourceComponents.removeValue (&component);
  64602. }
  64603. void RelativeCoordinatePositionerBase::markersChanged (MarkerList*)
  64604. {
  64605. apply();
  64606. }
  64607. void RelativeCoordinatePositionerBase::markerListBeingDeleted (MarkerList* markerList)
  64608. {
  64609. jassert (sourceMarkerLists.contains (markerList));
  64610. sourceMarkerLists.removeValue (markerList);
  64611. }
  64612. void RelativeCoordinatePositionerBase::apply()
  64613. {
  64614. if (! registeredOk)
  64615. {
  64616. unregisterListeners();
  64617. registeredOk = registerCoordinates();
  64618. }
  64619. applyToComponentBounds();
  64620. }
  64621. bool RelativeCoordinatePositionerBase::addCoordinate (const RelativeCoordinate& coord)
  64622. {
  64623. return registerListeners (coord.getExpression());
  64624. }
  64625. bool RelativeCoordinatePositionerBase::addPoint (const RelativePoint& point)
  64626. {
  64627. const bool ok = addCoordinate (point.x);
  64628. return addCoordinate (point.y) && ok;
  64629. }
  64630. bool RelativeCoordinatePositionerBase::registerListeners (const Expression& e)
  64631. {
  64632. bool ok = true;
  64633. if (e.getType() == Expression::symbolType)
  64634. {
  64635. String objectName, memberName;
  64636. e.getSymbolParts (objectName, memberName);
  64637. if (memberName.isNotEmpty())
  64638. ok = registerComponent (objectName) && ok;
  64639. else
  64640. ok = registerMarker (objectName) && ok;
  64641. }
  64642. else
  64643. {
  64644. for (int i = e.getNumInputs(); --i >= 0;)
  64645. ok = registerListeners (e.getInput (i)) && ok;
  64646. }
  64647. return ok;
  64648. }
  64649. bool RelativeCoordinatePositionerBase::registerComponent (const String& componentID)
  64650. {
  64651. Component* comp = findComponent (componentID);
  64652. if (comp == 0)
  64653. {
  64654. if (componentID == RelativeCoordinate::Strings::parent)
  64655. comp = getComponent().getParentComponent();
  64656. else if (componentID == RelativeCoordinate::Strings::this_ || componentID == getComponent().getComponentID())
  64657. comp = &getComponent();
  64658. }
  64659. if (comp != 0)
  64660. {
  64661. if (comp != &getComponent())
  64662. registerComponentListener (comp);
  64663. return true;
  64664. }
  64665. else
  64666. {
  64667. // The component we want doesn't exist, so watch the parent in case the hierarchy changes and it appears later..
  64668. Component* const parent = getComponent().getParentComponent();
  64669. if (parent != 0)
  64670. registerComponentListener (parent);
  64671. else
  64672. registerComponentListener (&getComponent());
  64673. return false;
  64674. }
  64675. }
  64676. bool RelativeCoordinatePositionerBase::registerMarker (const String markerName)
  64677. {
  64678. Component* const parent = getComponent().getParentComponent();
  64679. if (parent != 0)
  64680. {
  64681. MarkerList* list = parent->getMarkers (true);
  64682. if (list == 0 || list->getMarker (markerName) == 0)
  64683. list = parent->getMarkers (false);
  64684. if (list != 0 && list->getMarker (markerName) != 0)
  64685. {
  64686. registerMarkerListListener (list);
  64687. return true;
  64688. }
  64689. else
  64690. {
  64691. // The marker we want doesn't exist, so watch all lists in case they change and the marker appears later..
  64692. registerMarkerListListener (parent->getMarkers (true));
  64693. registerMarkerListListener (parent->getMarkers (false));
  64694. }
  64695. }
  64696. return false;
  64697. }
  64698. void RelativeCoordinatePositionerBase::registerComponentListener (Component* const comp)
  64699. {
  64700. if (comp != 0 && ! sourceComponents.contains (comp))
  64701. {
  64702. comp->addComponentListener (this);
  64703. sourceComponents.add (comp);
  64704. }
  64705. }
  64706. void RelativeCoordinatePositionerBase::registerMarkerListListener (MarkerList* const list)
  64707. {
  64708. if (list != 0 && ! sourceMarkerLists.contains (list))
  64709. {
  64710. list->addListener (this);
  64711. sourceMarkerLists.add (list);
  64712. }
  64713. }
  64714. void RelativeCoordinatePositionerBase::unregisterListeners()
  64715. {
  64716. int i;
  64717. for (i = sourceComponents.size(); --i >= 0;)
  64718. sourceComponents.getUnchecked(i)->removeComponentListener (this);
  64719. for (i = sourceMarkerLists.size(); --i >= 0;)
  64720. sourceMarkerLists.getUnchecked(i)->removeListener (this);
  64721. sourceComponents.clear();
  64722. sourceMarkerLists.clear();
  64723. }
  64724. Component* RelativeCoordinatePositionerBase::findComponent (const String& componentID) const
  64725. {
  64726. Component* const parent = getComponent().getParentComponent();
  64727. if (parent != 0)
  64728. {
  64729. for (int i = parent->getNumChildComponents(); --i >= 0;)
  64730. {
  64731. Component* const c = parent->getChildComponent(i);
  64732. if (c->getComponentID() == componentID)
  64733. return c;
  64734. }
  64735. }
  64736. return 0;
  64737. }
  64738. Component* RelativeCoordinatePositionerBase::getSourceComponent (const String& objectName) const
  64739. {
  64740. for (int i = sourceComponents.size(); --i >= 0;)
  64741. {
  64742. Component* const comp = sourceComponents.getUnchecked(i);
  64743. if (comp->getComponentID() == objectName)
  64744. return comp;
  64745. }
  64746. return 0;
  64747. }
  64748. const Expression RelativeCoordinatePositionerBase::xToExpression (const Component* const source, const int x) const
  64749. {
  64750. return Expression ((double) (getComponent().getLocalPoint (source, Point<int> (x, 0)).getX() + getComponent().getX()));
  64751. }
  64752. const Expression RelativeCoordinatePositionerBase::yToExpression (const Component* const source, const int y) const
  64753. {
  64754. return Expression ((double) (getComponent().getLocalPoint (source, Point<int> (0, y)).getY() + getComponent().getY()));
  64755. }
  64756. END_JUCE_NAMESPACE
  64757. /*** End of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64758. #endif
  64759. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64760. /*** Start of inlined file: juce_Colour.cpp ***/
  64761. BEGIN_JUCE_NAMESPACE
  64762. namespace ColourHelpers
  64763. {
  64764. uint8 floatAlphaToInt (const float alpha) throw()
  64765. {
  64766. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64767. }
  64768. void convertHSBtoRGB (float h, float s, float v,
  64769. uint8& r, uint8& g, uint8& b) throw()
  64770. {
  64771. v = jlimit (0.0f, 1.0f, v);
  64772. v *= 255.0f;
  64773. const uint8 intV = (uint8) roundToInt (v);
  64774. if (s <= 0)
  64775. {
  64776. r = intV;
  64777. g = intV;
  64778. b = intV;
  64779. }
  64780. else
  64781. {
  64782. s = jmin (1.0f, s);
  64783. h = jlimit (0.0f, 1.0f, h);
  64784. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64785. const float f = h - std::floor (h);
  64786. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64787. const float y = v * (1.0f - s * f);
  64788. const float z = v * (1.0f - (s * (1.0f - f)));
  64789. if (h < 1.0f)
  64790. {
  64791. r = intV;
  64792. g = (uint8) roundToInt (z);
  64793. b = x;
  64794. }
  64795. else if (h < 2.0f)
  64796. {
  64797. r = (uint8) roundToInt (y);
  64798. g = intV;
  64799. b = x;
  64800. }
  64801. else if (h < 3.0f)
  64802. {
  64803. r = x;
  64804. g = intV;
  64805. b = (uint8) roundToInt (z);
  64806. }
  64807. else if (h < 4.0f)
  64808. {
  64809. r = x;
  64810. g = (uint8) roundToInt (y);
  64811. b = intV;
  64812. }
  64813. else if (h < 5.0f)
  64814. {
  64815. r = (uint8) roundToInt (z);
  64816. g = x;
  64817. b = intV;
  64818. }
  64819. else if (h < 6.0f)
  64820. {
  64821. r = intV;
  64822. g = x;
  64823. b = (uint8) roundToInt (y);
  64824. }
  64825. else
  64826. {
  64827. r = 0;
  64828. g = 0;
  64829. b = 0;
  64830. }
  64831. }
  64832. }
  64833. }
  64834. Colour::Colour() throw()
  64835. : argb (0)
  64836. {
  64837. }
  64838. Colour::Colour (const Colour& other) throw()
  64839. : argb (other.argb)
  64840. {
  64841. }
  64842. Colour& Colour::operator= (const Colour& other) throw()
  64843. {
  64844. argb = other.argb;
  64845. return *this;
  64846. }
  64847. bool Colour::operator== (const Colour& other) const throw()
  64848. {
  64849. return argb.getARGB() == other.argb.getARGB();
  64850. }
  64851. bool Colour::operator!= (const Colour& other) const throw()
  64852. {
  64853. return argb.getARGB() != other.argb.getARGB();
  64854. }
  64855. Colour::Colour (const uint32 argb_) throw()
  64856. : argb (argb_)
  64857. {
  64858. }
  64859. Colour::Colour (const uint8 red,
  64860. const uint8 green,
  64861. const uint8 blue) throw()
  64862. {
  64863. argb.setARGB (0xff, red, green, blue);
  64864. }
  64865. const Colour Colour::fromRGB (const uint8 red,
  64866. const uint8 green,
  64867. const uint8 blue) throw()
  64868. {
  64869. return Colour (red, green, blue);
  64870. }
  64871. Colour::Colour (const uint8 red,
  64872. const uint8 green,
  64873. const uint8 blue,
  64874. const uint8 alpha) throw()
  64875. {
  64876. argb.setARGB (alpha, red, green, blue);
  64877. }
  64878. const Colour Colour::fromRGBA (const uint8 red,
  64879. const uint8 green,
  64880. const uint8 blue,
  64881. const uint8 alpha) throw()
  64882. {
  64883. return Colour (red, green, blue, alpha);
  64884. }
  64885. Colour::Colour (const uint8 red,
  64886. const uint8 green,
  64887. const uint8 blue,
  64888. const float alpha) throw()
  64889. {
  64890. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64891. }
  64892. const Colour Colour::fromRGBAFloat (const uint8 red,
  64893. const uint8 green,
  64894. const uint8 blue,
  64895. const float alpha) throw()
  64896. {
  64897. return Colour (red, green, blue, alpha);
  64898. }
  64899. Colour::Colour (const float hue,
  64900. const float saturation,
  64901. const float brightness,
  64902. const float alpha) throw()
  64903. {
  64904. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64905. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64906. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64907. }
  64908. const Colour Colour::fromHSV (const float hue,
  64909. const float saturation,
  64910. const float brightness,
  64911. const float alpha) throw()
  64912. {
  64913. return Colour (hue, saturation, brightness, alpha);
  64914. }
  64915. Colour::Colour (const float hue,
  64916. const float saturation,
  64917. const float brightness,
  64918. const uint8 alpha) throw()
  64919. {
  64920. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64921. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64922. argb.setARGB (alpha, r, g, b);
  64923. }
  64924. Colour::~Colour() throw()
  64925. {
  64926. }
  64927. const PixelARGB Colour::getPixelARGB() const throw()
  64928. {
  64929. PixelARGB p (argb);
  64930. p.premultiply();
  64931. return p;
  64932. }
  64933. uint32 Colour::getARGB() const throw()
  64934. {
  64935. return argb.getARGB();
  64936. }
  64937. bool Colour::isTransparent() const throw()
  64938. {
  64939. return getAlpha() == 0;
  64940. }
  64941. bool Colour::isOpaque() const throw()
  64942. {
  64943. return getAlpha() == 0xff;
  64944. }
  64945. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64946. {
  64947. PixelARGB newCol (argb);
  64948. newCol.setAlpha (newAlpha);
  64949. return Colour (newCol.getARGB());
  64950. }
  64951. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64952. {
  64953. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64954. PixelARGB newCol (argb);
  64955. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64956. return Colour (newCol.getARGB());
  64957. }
  64958. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64959. {
  64960. jassert (alphaMultiplier >= 0);
  64961. PixelARGB newCol (argb);
  64962. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64963. return Colour (newCol.getARGB());
  64964. }
  64965. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64966. {
  64967. const int destAlpha = getAlpha();
  64968. if (destAlpha > 0)
  64969. {
  64970. const int invA = 0xff - (int) src.getAlpha();
  64971. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64972. if (resA > 0)
  64973. {
  64974. const int da = (invA * destAlpha) / resA;
  64975. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64976. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64977. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64978. (uint8) resA);
  64979. }
  64980. return *this;
  64981. }
  64982. else
  64983. {
  64984. return src;
  64985. }
  64986. }
  64987. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64988. {
  64989. if (proportionOfOther <= 0)
  64990. return *this;
  64991. if (proportionOfOther >= 1.0f)
  64992. return other;
  64993. PixelARGB c1 (getPixelARGB());
  64994. const PixelARGB c2 (other.getPixelARGB());
  64995. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64996. c1.unpremultiply();
  64997. return Colour (c1.getARGB());
  64998. }
  64999. float Colour::getFloatRed() const throw()
  65000. {
  65001. return getRed() / 255.0f;
  65002. }
  65003. float Colour::getFloatGreen() const throw()
  65004. {
  65005. return getGreen() / 255.0f;
  65006. }
  65007. float Colour::getFloatBlue() const throw()
  65008. {
  65009. return getBlue() / 255.0f;
  65010. }
  65011. float Colour::getFloatAlpha() const throw()
  65012. {
  65013. return getAlpha() / 255.0f;
  65014. }
  65015. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65016. {
  65017. const int r = getRed();
  65018. const int g = getGreen();
  65019. const int b = getBlue();
  65020. const int hi = jmax (r, g, b);
  65021. const int lo = jmin (r, g, b);
  65022. if (hi != 0)
  65023. {
  65024. s = (hi - lo) / (float) hi;
  65025. if (s != 0)
  65026. {
  65027. const float invDiff = 1.0f / (hi - lo);
  65028. const float red = (hi - r) * invDiff;
  65029. const float green = (hi - g) * invDiff;
  65030. const float blue = (hi - b) * invDiff;
  65031. if (r == hi)
  65032. h = blue - green;
  65033. else if (g == hi)
  65034. h = 2.0f + red - blue;
  65035. else
  65036. h = 4.0f + green - red;
  65037. h *= 1.0f / 6.0f;
  65038. if (h < 0)
  65039. ++h;
  65040. }
  65041. else
  65042. {
  65043. h = 0;
  65044. }
  65045. }
  65046. else
  65047. {
  65048. s = 0;
  65049. h = 0;
  65050. }
  65051. v = hi / 255.0f;
  65052. }
  65053. float Colour::getHue() const throw()
  65054. {
  65055. float h, s, b;
  65056. getHSB (h, s, b);
  65057. return h;
  65058. }
  65059. const Colour Colour::withHue (const float hue) const throw()
  65060. {
  65061. float h, s, b;
  65062. getHSB (h, s, b);
  65063. return Colour (hue, s, b, getAlpha());
  65064. }
  65065. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65066. {
  65067. float h, s, b;
  65068. getHSB (h, s, b);
  65069. h += amountToRotate;
  65070. h -= std::floor (h);
  65071. return Colour (h, s, b, getAlpha());
  65072. }
  65073. float Colour::getSaturation() const throw()
  65074. {
  65075. float h, s, b;
  65076. getHSB (h, s, b);
  65077. return s;
  65078. }
  65079. const Colour Colour::withSaturation (const float saturation) const throw()
  65080. {
  65081. float h, s, b;
  65082. getHSB (h, s, b);
  65083. return Colour (h, saturation, b, getAlpha());
  65084. }
  65085. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65086. {
  65087. float h, s, b;
  65088. getHSB (h, s, b);
  65089. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65090. }
  65091. float Colour::getBrightness() const throw()
  65092. {
  65093. float h, s, b;
  65094. getHSB (h, s, b);
  65095. return b;
  65096. }
  65097. const Colour Colour::withBrightness (const float brightness) const throw()
  65098. {
  65099. float h, s, b;
  65100. getHSB (h, s, b);
  65101. return Colour (h, s, brightness, getAlpha());
  65102. }
  65103. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65104. {
  65105. float h, s, b;
  65106. getHSB (h, s, b);
  65107. b *= amount;
  65108. if (b > 1.0f)
  65109. b = 1.0f;
  65110. return Colour (h, s, b, getAlpha());
  65111. }
  65112. const Colour Colour::brighter (float amount) const throw()
  65113. {
  65114. amount = 1.0f / (1.0f + amount);
  65115. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65116. (uint8) (255 - (amount * (255 - getGreen()))),
  65117. (uint8) (255 - (amount * (255 - getBlue()))),
  65118. getAlpha());
  65119. }
  65120. const Colour Colour::darker (float amount) const throw()
  65121. {
  65122. amount = 1.0f / (1.0f + amount);
  65123. return Colour ((uint8) (amount * getRed()),
  65124. (uint8) (amount * getGreen()),
  65125. (uint8) (amount * getBlue()),
  65126. getAlpha());
  65127. }
  65128. const Colour Colour::greyLevel (const float brightness) throw()
  65129. {
  65130. const uint8 level
  65131. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65132. return Colour (level, level, level);
  65133. }
  65134. const Colour Colour::contrasting (const float amount) const throw()
  65135. {
  65136. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65137. ? Colours::black
  65138. : Colours::white).withAlpha (amount));
  65139. }
  65140. const Colour Colour::contrasting (const Colour& colour1,
  65141. const Colour& colour2) throw()
  65142. {
  65143. const float b1 = colour1.getBrightness();
  65144. const float b2 = colour2.getBrightness();
  65145. float best = 0.0f;
  65146. float bestDist = 0.0f;
  65147. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65148. {
  65149. const float d1 = std::abs (i - b1);
  65150. const float d2 = std::abs (i - b2);
  65151. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65152. if (dist > bestDist)
  65153. {
  65154. best = i;
  65155. bestDist = dist;
  65156. }
  65157. }
  65158. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65159. .withBrightness (best);
  65160. }
  65161. const String Colour::toString() const
  65162. {
  65163. return String::toHexString ((int) argb.getARGB());
  65164. }
  65165. const Colour Colour::fromString (const String& encodedColourString)
  65166. {
  65167. return Colour ((uint32) encodedColourString.getHexValue32());
  65168. }
  65169. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65170. {
  65171. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65172. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65173. .toUpperCase();
  65174. }
  65175. END_JUCE_NAMESPACE
  65176. /*** End of inlined file: juce_Colour.cpp ***/
  65177. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65178. BEGIN_JUCE_NAMESPACE
  65179. ColourGradient::ColourGradient() throw()
  65180. {
  65181. #if JUCE_DEBUG
  65182. point1.setX (987654.0f);
  65183. #endif
  65184. }
  65185. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65186. const Colour& colour2, const float x2_, const float y2_,
  65187. const bool isRadial_)
  65188. : point1 (x1_, y1_),
  65189. point2 (x2_, y2_),
  65190. isRadial (isRadial_)
  65191. {
  65192. colours.add (ColourPoint (0.0, colour1));
  65193. colours.add (ColourPoint (1.0, colour2));
  65194. }
  65195. ColourGradient::~ColourGradient()
  65196. {
  65197. }
  65198. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65199. {
  65200. return point1 == other.point1 && point2 == other.point2
  65201. && isRadial == other.isRadial
  65202. && colours == other.colours;
  65203. }
  65204. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65205. {
  65206. return ! operator== (other);
  65207. }
  65208. void ColourGradient::clearColours()
  65209. {
  65210. colours.clear();
  65211. }
  65212. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65213. {
  65214. // must be within the two end-points
  65215. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65216. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65217. int i;
  65218. for (i = 0; i < colours.size(); ++i)
  65219. if (colours.getReference(i).position > pos)
  65220. break;
  65221. colours.insert (i, ColourPoint (pos, colour));
  65222. return i;
  65223. }
  65224. void ColourGradient::removeColour (int index)
  65225. {
  65226. jassert (index > 0 && index < colours.size() - 1);
  65227. colours.remove (index);
  65228. }
  65229. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65230. {
  65231. for (int i = 0; i < colours.size(); ++i)
  65232. {
  65233. Colour& c = colours.getReference(i).colour;
  65234. c = c.withMultipliedAlpha (multiplier);
  65235. }
  65236. }
  65237. int ColourGradient::getNumColours() const throw()
  65238. {
  65239. return colours.size();
  65240. }
  65241. double ColourGradient::getColourPosition (const int index) const throw()
  65242. {
  65243. if (isPositiveAndBelow (index, colours.size()))
  65244. return colours.getReference (index).position;
  65245. return 0;
  65246. }
  65247. const Colour ColourGradient::getColour (const int index) const throw()
  65248. {
  65249. if (isPositiveAndBelow (index, colours.size()))
  65250. return colours.getReference (index).colour;
  65251. return Colour();
  65252. }
  65253. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65254. {
  65255. if (isPositiveAndBelow (index, colours.size()))
  65256. colours.getReference (index).colour = newColour;
  65257. }
  65258. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65259. {
  65260. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65261. if (position <= 0 || colours.size() <= 1)
  65262. return colours.getReference(0).colour;
  65263. int i = colours.size() - 1;
  65264. while (position < colours.getReference(i).position)
  65265. --i;
  65266. const ColourPoint& p1 = colours.getReference (i);
  65267. if (i >= colours.size() - 1)
  65268. return p1.colour;
  65269. const ColourPoint& p2 = colours.getReference (i + 1);
  65270. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65271. }
  65272. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65273. {
  65274. #if JUCE_DEBUG
  65275. // trying to use the object without setting its co-ordinates? Have a careful read of
  65276. // the comments for the constructors.
  65277. jassert (point1.getX() != 987654.0f);
  65278. #endif
  65279. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65280. 3 * (int) point1.transformedBy (transform)
  65281. .getDistanceFrom (point2.transformedBy (transform)));
  65282. lookupTable.malloc (numEntries);
  65283. if (colours.size() >= 2)
  65284. {
  65285. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65286. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65287. int index = 0;
  65288. for (int j = 1; j < colours.size(); ++j)
  65289. {
  65290. const ColourPoint& p = colours.getReference (j);
  65291. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65292. const PixelARGB pix2 (p.colour.getPixelARGB());
  65293. for (int i = 0; i < numToDo; ++i)
  65294. {
  65295. jassert (index >= 0 && index < numEntries);
  65296. lookupTable[index] = pix1;
  65297. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65298. ++index;
  65299. }
  65300. pix1 = pix2;
  65301. }
  65302. while (index < numEntries)
  65303. lookupTable [index++] = pix1;
  65304. }
  65305. else
  65306. {
  65307. jassertfalse; // no colours specified!
  65308. }
  65309. return numEntries;
  65310. }
  65311. bool ColourGradient::isOpaque() const throw()
  65312. {
  65313. for (int i = 0; i < colours.size(); ++i)
  65314. if (! colours.getReference(i).colour.isOpaque())
  65315. return false;
  65316. return true;
  65317. }
  65318. bool ColourGradient::isInvisible() const throw()
  65319. {
  65320. for (int i = 0; i < colours.size(); ++i)
  65321. if (! colours.getReference(i).colour.isTransparent())
  65322. return false;
  65323. return true;
  65324. }
  65325. END_JUCE_NAMESPACE
  65326. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65327. /*** Start of inlined file: juce_Colours.cpp ***/
  65328. BEGIN_JUCE_NAMESPACE
  65329. const Colour Colours::transparentBlack (0);
  65330. const Colour Colours::transparentWhite (0x00ffffff);
  65331. const Colour Colours::aliceblue (0xfff0f8ff);
  65332. const Colour Colours::antiquewhite (0xfffaebd7);
  65333. const Colour Colours::aqua (0xff00ffff);
  65334. const Colour Colours::aquamarine (0xff7fffd4);
  65335. const Colour Colours::azure (0xfff0ffff);
  65336. const Colour Colours::beige (0xfff5f5dc);
  65337. const Colour Colours::bisque (0xffffe4c4);
  65338. const Colour Colours::black (0xff000000);
  65339. const Colour Colours::blanchedalmond (0xffffebcd);
  65340. const Colour Colours::blue (0xff0000ff);
  65341. const Colour Colours::blueviolet (0xff8a2be2);
  65342. const Colour Colours::brown (0xffa52a2a);
  65343. const Colour Colours::burlywood (0xffdeb887);
  65344. const Colour Colours::cadetblue (0xff5f9ea0);
  65345. const Colour Colours::chartreuse (0xff7fff00);
  65346. const Colour Colours::chocolate (0xffd2691e);
  65347. const Colour Colours::coral (0xffff7f50);
  65348. const Colour Colours::cornflowerblue (0xff6495ed);
  65349. const Colour Colours::cornsilk (0xfffff8dc);
  65350. const Colour Colours::crimson (0xffdc143c);
  65351. const Colour Colours::cyan (0xff00ffff);
  65352. const Colour Colours::darkblue (0xff00008b);
  65353. const Colour Colours::darkcyan (0xff008b8b);
  65354. const Colour Colours::darkgoldenrod (0xffb8860b);
  65355. const Colour Colours::darkgrey (0xff555555);
  65356. const Colour Colours::darkgreen (0xff006400);
  65357. const Colour Colours::darkkhaki (0xffbdb76b);
  65358. const Colour Colours::darkmagenta (0xff8b008b);
  65359. const Colour Colours::darkolivegreen (0xff556b2f);
  65360. const Colour Colours::darkorange (0xffff8c00);
  65361. const Colour Colours::darkorchid (0xff9932cc);
  65362. const Colour Colours::darkred (0xff8b0000);
  65363. const Colour Colours::darksalmon (0xffe9967a);
  65364. const Colour Colours::darkseagreen (0xff8fbc8f);
  65365. const Colour Colours::darkslateblue (0xff483d8b);
  65366. const Colour Colours::darkslategrey (0xff2f4f4f);
  65367. const Colour Colours::darkturquoise (0xff00ced1);
  65368. const Colour Colours::darkviolet (0xff9400d3);
  65369. const Colour Colours::deeppink (0xffff1493);
  65370. const Colour Colours::deepskyblue (0xff00bfff);
  65371. const Colour Colours::dimgrey (0xff696969);
  65372. const Colour Colours::dodgerblue (0xff1e90ff);
  65373. const Colour Colours::firebrick (0xffb22222);
  65374. const Colour Colours::floralwhite (0xfffffaf0);
  65375. const Colour Colours::forestgreen (0xff228b22);
  65376. const Colour Colours::fuchsia (0xffff00ff);
  65377. const Colour Colours::gainsboro (0xffdcdcdc);
  65378. const Colour Colours::gold (0xffffd700);
  65379. const Colour Colours::goldenrod (0xffdaa520);
  65380. const Colour Colours::grey (0xff808080);
  65381. const Colour Colours::green (0xff008000);
  65382. const Colour Colours::greenyellow (0xffadff2f);
  65383. const Colour Colours::honeydew (0xfff0fff0);
  65384. const Colour Colours::hotpink (0xffff69b4);
  65385. const Colour Colours::indianred (0xffcd5c5c);
  65386. const Colour Colours::indigo (0xff4b0082);
  65387. const Colour Colours::ivory (0xfffffff0);
  65388. const Colour Colours::khaki (0xfff0e68c);
  65389. const Colour Colours::lavender (0xffe6e6fa);
  65390. const Colour Colours::lavenderblush (0xfffff0f5);
  65391. const Colour Colours::lemonchiffon (0xfffffacd);
  65392. const Colour Colours::lightblue (0xffadd8e6);
  65393. const Colour Colours::lightcoral (0xfff08080);
  65394. const Colour Colours::lightcyan (0xffe0ffff);
  65395. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65396. const Colour Colours::lightgreen (0xff90ee90);
  65397. const Colour Colours::lightgrey (0xffd3d3d3);
  65398. const Colour Colours::lightpink (0xffffb6c1);
  65399. const Colour Colours::lightsalmon (0xffffa07a);
  65400. const Colour Colours::lightseagreen (0xff20b2aa);
  65401. const Colour Colours::lightskyblue (0xff87cefa);
  65402. const Colour Colours::lightslategrey (0xff778899);
  65403. const Colour Colours::lightsteelblue (0xffb0c4de);
  65404. const Colour Colours::lightyellow (0xffffffe0);
  65405. const Colour Colours::lime (0xff00ff00);
  65406. const Colour Colours::limegreen (0xff32cd32);
  65407. const Colour Colours::linen (0xfffaf0e6);
  65408. const Colour Colours::magenta (0xffff00ff);
  65409. const Colour Colours::maroon (0xff800000);
  65410. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65411. const Colour Colours::mediumblue (0xff0000cd);
  65412. const Colour Colours::mediumorchid (0xffba55d3);
  65413. const Colour Colours::mediumpurple (0xff9370db);
  65414. const Colour Colours::mediumseagreen (0xff3cb371);
  65415. const Colour Colours::mediumslateblue (0xff7b68ee);
  65416. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65417. const Colour Colours::mediumturquoise (0xff48d1cc);
  65418. const Colour Colours::mediumvioletred (0xffc71585);
  65419. const Colour Colours::midnightblue (0xff191970);
  65420. const Colour Colours::mintcream (0xfff5fffa);
  65421. const Colour Colours::mistyrose (0xffffe4e1);
  65422. const Colour Colours::navajowhite (0xffffdead);
  65423. const Colour Colours::navy (0xff000080);
  65424. const Colour Colours::oldlace (0xfffdf5e6);
  65425. const Colour Colours::olive (0xff808000);
  65426. const Colour Colours::olivedrab (0xff6b8e23);
  65427. const Colour Colours::orange (0xffffa500);
  65428. const Colour Colours::orangered (0xffff4500);
  65429. const Colour Colours::orchid (0xffda70d6);
  65430. const Colour Colours::palegoldenrod (0xffeee8aa);
  65431. const Colour Colours::palegreen (0xff98fb98);
  65432. const Colour Colours::paleturquoise (0xffafeeee);
  65433. const Colour Colours::palevioletred (0xffdb7093);
  65434. const Colour Colours::papayawhip (0xffffefd5);
  65435. const Colour Colours::peachpuff (0xffffdab9);
  65436. const Colour Colours::peru (0xffcd853f);
  65437. const Colour Colours::pink (0xffffc0cb);
  65438. const Colour Colours::plum (0xffdda0dd);
  65439. const Colour Colours::powderblue (0xffb0e0e6);
  65440. const Colour Colours::purple (0xff800080);
  65441. const Colour Colours::red (0xffff0000);
  65442. const Colour Colours::rosybrown (0xffbc8f8f);
  65443. const Colour Colours::royalblue (0xff4169e1);
  65444. const Colour Colours::saddlebrown (0xff8b4513);
  65445. const Colour Colours::salmon (0xfffa8072);
  65446. const Colour Colours::sandybrown (0xfff4a460);
  65447. const Colour Colours::seagreen (0xff2e8b57);
  65448. const Colour Colours::seashell (0xfffff5ee);
  65449. const Colour Colours::sienna (0xffa0522d);
  65450. const Colour Colours::silver (0xffc0c0c0);
  65451. const Colour Colours::skyblue (0xff87ceeb);
  65452. const Colour Colours::slateblue (0xff6a5acd);
  65453. const Colour Colours::slategrey (0xff708090);
  65454. const Colour Colours::snow (0xfffffafa);
  65455. const Colour Colours::springgreen (0xff00ff7f);
  65456. const Colour Colours::steelblue (0xff4682b4);
  65457. const Colour Colours::tan (0xffd2b48c);
  65458. const Colour Colours::teal (0xff008080);
  65459. const Colour Colours::thistle (0xffd8bfd8);
  65460. const Colour Colours::tomato (0xffff6347);
  65461. const Colour Colours::turquoise (0xff40e0d0);
  65462. const Colour Colours::violet (0xffee82ee);
  65463. const Colour Colours::wheat (0xfff5deb3);
  65464. const Colour Colours::white (0xffffffff);
  65465. const Colour Colours::whitesmoke (0xfff5f5f5);
  65466. const Colour Colours::yellow (0xffffff00);
  65467. const Colour Colours::yellowgreen (0xff9acd32);
  65468. const Colour Colours::findColourForName (const String& colourName,
  65469. const Colour& defaultColour)
  65470. {
  65471. static const int presets[] =
  65472. {
  65473. // (first value is the string's hashcode, second is ARGB)
  65474. 0x05978fff, 0xff000000, /* black */
  65475. 0x06bdcc29, 0xffffffff, /* white */
  65476. 0x002e305a, 0xff0000ff, /* blue */
  65477. 0x00308adf, 0xff808080, /* grey */
  65478. 0x05e0cf03, 0xff008000, /* green */
  65479. 0x0001b891, 0xffff0000, /* red */
  65480. 0xd43c6474, 0xffffff00, /* yellow */
  65481. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65482. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65483. 0x002dcebc, 0xff00ffff, /* aqua */
  65484. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65485. 0x0590228f, 0xfff0ffff, /* azure */
  65486. 0x05947fe4, 0xfff5f5dc, /* beige */
  65487. 0xad388e35, 0xffffe4c4, /* bisque */
  65488. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65489. 0x39129959, 0xff8a2be2, /* blueviolet */
  65490. 0x059a8136, 0xffa52a2a, /* brown */
  65491. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65492. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65493. 0x6b748956, 0xff7fff00, /* chartreuse */
  65494. 0x2903623c, 0xffd2691e, /* chocolate */
  65495. 0x05a74431, 0xffff7f50, /* coral */
  65496. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65497. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65498. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65499. 0x002ed323, 0xff00ffff, /* cyan */
  65500. 0x67cc74d0, 0xff00008b, /* darkblue */
  65501. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65502. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65503. 0x67cecf55, 0xff555555, /* darkgrey */
  65504. 0x920b194d, 0xff006400, /* darkgreen */
  65505. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65506. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65507. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65508. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65509. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65510. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65511. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65512. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65513. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65514. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65515. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65516. 0xc8769375, 0xff9400d3, /* darkviolet */
  65517. 0x25832862, 0xffff1493, /* deeppink */
  65518. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65519. 0x634c8b67, 0xff696969, /* dimgrey */
  65520. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65521. 0xef19e3cb, 0xffb22222, /* firebrick */
  65522. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65523. 0xd086fd06, 0xff228b22, /* forestgreen */
  65524. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65525. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65526. 0x00308060, 0xffffd700, /* gold */
  65527. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65528. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65529. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65530. 0x41892743, 0xffff69b4, /* hotpink */
  65531. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65532. 0xb969fed2, 0xff4b0082, /* indigo */
  65533. 0x05fef6a9, 0xfffffff0, /* ivory */
  65534. 0x06149302, 0xfff0e68c, /* khaki */
  65535. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65536. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65537. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65538. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65539. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65540. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65541. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65542. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65543. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65544. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65545. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65546. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65547. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65548. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65549. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65550. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65551. 0x0032afd5, 0xff00ff00, /* lime */
  65552. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65553. 0x06234efa, 0xfffaf0e6, /* linen */
  65554. 0x316858a9, 0xffff00ff, /* magenta */
  65555. 0xbf8ca470, 0xff800000, /* maroon */
  65556. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65557. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65558. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65559. 0x07556b71, 0xff9370db, /* mediumpurple */
  65560. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65561. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65562. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65563. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65564. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65565. 0x168eb32a, 0xff191970, /* midnightblue */
  65566. 0x4306b960, 0xfff5fffa, /* mintcream */
  65567. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65568. 0xe97218a6, 0xffffdead, /* navajowhite */
  65569. 0x00337bb6, 0xff000080, /* navy */
  65570. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65571. 0x064ee1db, 0xff808000, /* olive */
  65572. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65573. 0xc3de262e, 0xffffa500, /* orange */
  65574. 0x58bebba3, 0xffff4500, /* orangered */
  65575. 0xc3def8a3, 0xffda70d6, /* orchid */
  65576. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65577. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65578. 0x74022737, 0xffafeeee, /* paleturquoise */
  65579. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65580. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65581. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65582. 0x003472f8, 0xffcd853f, /* peru */
  65583. 0x00348176, 0xffffc0cb, /* pink */
  65584. 0x00348d94, 0xffdda0dd, /* plum */
  65585. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65586. 0xc5c507bc, 0xff800080, /* purple */
  65587. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65588. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65589. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65590. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65591. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65592. 0x34636c14, 0xff2e8b57, /* seagreen */
  65593. 0x3507fb41, 0xfffff5ee, /* seashell */
  65594. 0xca348772, 0xffa0522d, /* sienna */
  65595. 0xca37d30d, 0xffc0c0c0, /* silver */
  65596. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65597. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65598. 0x44ab37f8, 0xff708090, /* slategrey */
  65599. 0x0035f183, 0xfffffafa, /* snow */
  65600. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65601. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65602. 0x0001bfa1, 0xffd2b48c, /* tan */
  65603. 0x0036425c, 0xff008080, /* teal */
  65604. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65605. 0xcc41600a, 0xffff6347, /* tomato */
  65606. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65607. 0xcf57947f, 0xffee82ee, /* violet */
  65608. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65609. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65610. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65611. };
  65612. const int hash = colourName.trim().toLowerCase().hashCode();
  65613. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65614. if (presets [i] == hash)
  65615. return Colour (presets [i + 1]);
  65616. return defaultColour;
  65617. }
  65618. END_JUCE_NAMESPACE
  65619. /*** End of inlined file: juce_Colours.cpp ***/
  65620. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65621. BEGIN_JUCE_NAMESPACE
  65622. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65623. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65624. const Path& path, const AffineTransform& transform)
  65625. : bounds (bounds_),
  65626. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65627. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65628. needToCheckEmptinesss (true)
  65629. {
  65630. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65631. int* t = table;
  65632. for (int i = bounds.getHeight(); --i >= 0;)
  65633. {
  65634. *t = 0;
  65635. t += lineStrideElements;
  65636. }
  65637. const int topLimit = bounds.getY() << 8;
  65638. const int heightLimit = bounds.getHeight() << 8;
  65639. const int leftLimit = bounds.getX() << 8;
  65640. const int rightLimit = bounds.getRight() << 8;
  65641. PathFlatteningIterator iter (path, transform);
  65642. while (iter.next())
  65643. {
  65644. int y1 = roundToInt (iter.y1 * 256.0f);
  65645. int y2 = roundToInt (iter.y2 * 256.0f);
  65646. if (y1 != y2)
  65647. {
  65648. y1 -= topLimit;
  65649. y2 -= topLimit;
  65650. const int startY = y1;
  65651. int direction = -1;
  65652. if (y1 > y2)
  65653. {
  65654. swapVariables (y1, y2);
  65655. direction = 1;
  65656. }
  65657. if (y1 < 0)
  65658. y1 = 0;
  65659. if (y2 > heightLimit)
  65660. y2 = heightLimit;
  65661. if (y1 < y2)
  65662. {
  65663. const double startX = 256.0f * iter.x1;
  65664. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65665. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65666. do
  65667. {
  65668. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65669. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65670. if (x < leftLimit)
  65671. x = leftLimit;
  65672. else if (x >= rightLimit)
  65673. x = rightLimit - 1;
  65674. addEdgePoint (x, y1 >> 8, direction * step);
  65675. y1 += step;
  65676. }
  65677. while (y1 < y2);
  65678. }
  65679. }
  65680. }
  65681. sanitiseLevels (path.isUsingNonZeroWinding());
  65682. }
  65683. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65684. : bounds (rectangleToAdd),
  65685. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65686. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65687. needToCheckEmptinesss (true)
  65688. {
  65689. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65690. table[0] = 0;
  65691. const int x1 = rectangleToAdd.getX() << 8;
  65692. const int x2 = rectangleToAdd.getRight() << 8;
  65693. int* t = table;
  65694. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65695. {
  65696. t[0] = 2;
  65697. t[1] = x1;
  65698. t[2] = 255;
  65699. t[3] = x2;
  65700. t[4] = 0;
  65701. t += lineStrideElements;
  65702. }
  65703. }
  65704. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65705. : bounds (rectanglesToAdd.getBounds()),
  65706. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65707. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65708. needToCheckEmptinesss (true)
  65709. {
  65710. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65711. int* t = table;
  65712. for (int i = bounds.getHeight(); --i >= 0;)
  65713. {
  65714. *t = 0;
  65715. t += lineStrideElements;
  65716. }
  65717. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65718. {
  65719. const Rectangle<int>* const r = iter.getRectangle();
  65720. const int x1 = r->getX() << 8;
  65721. const int x2 = r->getRight() << 8;
  65722. int y = r->getY() - bounds.getY();
  65723. for (int j = r->getHeight(); --j >= 0;)
  65724. {
  65725. addEdgePoint (x1, y, 255);
  65726. addEdgePoint (x2, y, -255);
  65727. ++y;
  65728. }
  65729. }
  65730. sanitiseLevels (true);
  65731. }
  65732. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65733. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65734. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65735. 2 + (int) rectangleToAdd.getWidth(),
  65736. 2 + (int) rectangleToAdd.getHeight())),
  65737. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65738. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65739. needToCheckEmptinesss (true)
  65740. {
  65741. jassert (! rectangleToAdd.isEmpty());
  65742. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65743. table[0] = 0;
  65744. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65745. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65746. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65747. jassert (y1 < 256);
  65748. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65749. if (x2 <= x1 || y2 <= y1)
  65750. {
  65751. bounds.setHeight (0);
  65752. return;
  65753. }
  65754. int lineY = 0;
  65755. int* t = table;
  65756. if ((y1 >> 8) == (y2 >> 8))
  65757. {
  65758. t[0] = 2;
  65759. t[1] = x1;
  65760. t[2] = y2 - y1;
  65761. t[3] = x2;
  65762. t[4] = 0;
  65763. ++lineY;
  65764. t += lineStrideElements;
  65765. }
  65766. else
  65767. {
  65768. t[0] = 2;
  65769. t[1] = x1;
  65770. t[2] = 255 - (y1 & 255);
  65771. t[3] = x2;
  65772. t[4] = 0;
  65773. ++lineY;
  65774. t += lineStrideElements;
  65775. while (lineY < (y2 >> 8))
  65776. {
  65777. t[0] = 2;
  65778. t[1] = x1;
  65779. t[2] = 255;
  65780. t[3] = x2;
  65781. t[4] = 0;
  65782. ++lineY;
  65783. t += lineStrideElements;
  65784. }
  65785. jassert (lineY < bounds.getHeight());
  65786. t[0] = 2;
  65787. t[1] = x1;
  65788. t[2] = y2 & 255;
  65789. t[3] = x2;
  65790. t[4] = 0;
  65791. ++lineY;
  65792. t += lineStrideElements;
  65793. }
  65794. while (lineY < bounds.getHeight())
  65795. {
  65796. t[0] = 0;
  65797. t += lineStrideElements;
  65798. ++lineY;
  65799. }
  65800. }
  65801. EdgeTable::EdgeTable (const EdgeTable& other)
  65802. {
  65803. operator= (other);
  65804. }
  65805. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65806. {
  65807. bounds = other.bounds;
  65808. maxEdgesPerLine = other.maxEdgesPerLine;
  65809. lineStrideElements = other.lineStrideElements;
  65810. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65811. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65812. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65813. return *this;
  65814. }
  65815. EdgeTable::~EdgeTable()
  65816. {
  65817. }
  65818. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65819. {
  65820. while (--numLines >= 0)
  65821. {
  65822. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65823. src += srcLineStride;
  65824. dest += destLineStride;
  65825. }
  65826. }
  65827. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65828. {
  65829. // Convert the table from relative windings to absolute levels..
  65830. int* lineStart = table;
  65831. for (int i = bounds.getHeight(); --i >= 0;)
  65832. {
  65833. int* line = lineStart;
  65834. lineStart += lineStrideElements;
  65835. int num = *line;
  65836. if (num == 0)
  65837. continue;
  65838. int level = 0;
  65839. if (useNonZeroWinding)
  65840. {
  65841. while (--num > 0)
  65842. {
  65843. line += 2;
  65844. level += *line;
  65845. int corrected = abs (level);
  65846. if (corrected >> 8)
  65847. corrected = 255;
  65848. *line = corrected;
  65849. }
  65850. }
  65851. else
  65852. {
  65853. while (--num > 0)
  65854. {
  65855. line += 2;
  65856. level += *line;
  65857. int corrected = abs (level);
  65858. if (corrected >> 8)
  65859. {
  65860. corrected &= 511;
  65861. if (corrected >> 8)
  65862. corrected = 511 - corrected;
  65863. }
  65864. *line = corrected;
  65865. }
  65866. }
  65867. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65868. }
  65869. }
  65870. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine)
  65871. {
  65872. if (newNumEdgesPerLine != maxEdgesPerLine)
  65873. {
  65874. maxEdgesPerLine = newNumEdgesPerLine;
  65875. jassert (bounds.getHeight() > 0);
  65876. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65877. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65878. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65879. table.swapWith (newTable);
  65880. lineStrideElements = newLineStrideElements;
  65881. }
  65882. }
  65883. void EdgeTable::optimiseTable()
  65884. {
  65885. int maxLineElements = 0;
  65886. for (int i = bounds.getHeight(); --i >= 0;)
  65887. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65888. remapTableForNumEdges (maxLineElements);
  65889. }
  65890. void EdgeTable::addEdgePoint (const int x, const int y, const int winding)
  65891. {
  65892. jassert (y >= 0 && y < bounds.getHeight());
  65893. int* line = table + lineStrideElements * y;
  65894. const int numPoints = line[0];
  65895. int n = numPoints << 1;
  65896. if (n > 0)
  65897. {
  65898. while (n > 0)
  65899. {
  65900. const int cx = line [n - 1];
  65901. if (cx <= x)
  65902. {
  65903. if (cx == x)
  65904. {
  65905. line [n] += winding;
  65906. return;
  65907. }
  65908. break;
  65909. }
  65910. n -= 2;
  65911. }
  65912. if (numPoints >= maxEdgesPerLine)
  65913. {
  65914. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65915. jassert (numPoints < maxEdgesPerLine);
  65916. line = table + lineStrideElements * y;
  65917. }
  65918. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65919. }
  65920. line [n + 1] = x;
  65921. line [n + 2] = winding;
  65922. line[0]++;
  65923. }
  65924. void EdgeTable::translate (float dx, const int dy) throw()
  65925. {
  65926. bounds.translate ((int) std::floor (dx), dy);
  65927. int* lineStart = table;
  65928. const int intDx = (int) (dx * 256.0f);
  65929. for (int i = bounds.getHeight(); --i >= 0;)
  65930. {
  65931. int* line = lineStart;
  65932. lineStart += lineStrideElements;
  65933. int num = *line++;
  65934. while (--num >= 0)
  65935. {
  65936. *line += intDx;
  65937. line += 2;
  65938. }
  65939. }
  65940. }
  65941. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine)
  65942. {
  65943. jassert (y >= 0 && y < bounds.getHeight());
  65944. int* dest = table + lineStrideElements * y;
  65945. if (dest[0] == 0)
  65946. return;
  65947. int otherNumPoints = *otherLine;
  65948. if (otherNumPoints == 0)
  65949. {
  65950. *dest = 0;
  65951. return;
  65952. }
  65953. const int right = bounds.getRight() << 8;
  65954. // optimise for the common case where our line lies entirely within a
  65955. // single pair of points, as happens when clipping to a simple rect.
  65956. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65957. {
  65958. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65959. return;
  65960. }
  65961. ++otherLine;
  65962. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65963. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  65964. memcpy (temp, dest, lineSizeBytes);
  65965. const int* src1 = temp;
  65966. int srcNum1 = *src1++;
  65967. int x1 = *src1++;
  65968. const int* src2 = otherLine;
  65969. int srcNum2 = otherNumPoints;
  65970. int x2 = *src2++;
  65971. int destIndex = 0, destTotal = 0;
  65972. int level1 = 0, level2 = 0;
  65973. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65974. while (srcNum1 > 0 && srcNum2 > 0)
  65975. {
  65976. int nextX;
  65977. if (x1 < x2)
  65978. {
  65979. nextX = x1;
  65980. level1 = *src1++;
  65981. x1 = *src1++;
  65982. --srcNum1;
  65983. }
  65984. else if (x1 == x2)
  65985. {
  65986. nextX = x1;
  65987. level1 = *src1++;
  65988. level2 = *src2++;
  65989. x1 = *src1++;
  65990. x2 = *src2++;
  65991. --srcNum1;
  65992. --srcNum2;
  65993. }
  65994. else
  65995. {
  65996. nextX = x2;
  65997. level2 = *src2++;
  65998. x2 = *src2++;
  65999. --srcNum2;
  66000. }
  66001. if (nextX > lastX)
  66002. {
  66003. if (nextX >= right)
  66004. break;
  66005. lastX = nextX;
  66006. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66007. jassert (isPositiveAndBelow (nextLevel, (int) 256));
  66008. if (nextLevel != lastLevel)
  66009. {
  66010. if (destTotal >= maxEdgesPerLine)
  66011. {
  66012. dest[0] = destTotal;
  66013. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66014. dest = table + lineStrideElements * y;
  66015. }
  66016. ++destTotal;
  66017. lastLevel = nextLevel;
  66018. dest[++destIndex] = nextX;
  66019. dest[++destIndex] = nextLevel;
  66020. }
  66021. }
  66022. }
  66023. if (lastLevel > 0)
  66024. {
  66025. if (destTotal >= maxEdgesPerLine)
  66026. {
  66027. dest[0] = destTotal;
  66028. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66029. dest = table + lineStrideElements * y;
  66030. }
  66031. ++destTotal;
  66032. dest[++destIndex] = right;
  66033. dest[++destIndex] = 0;
  66034. }
  66035. dest[0] = destTotal;
  66036. #if JUCE_DEBUG
  66037. int last = std::numeric_limits<int>::min();
  66038. for (int i = 0; i < dest[0]; ++i)
  66039. {
  66040. jassert (dest[i * 2 + 1] > last);
  66041. last = dest[i * 2 + 1];
  66042. }
  66043. jassert (dest [dest[0] * 2] == 0);
  66044. #endif
  66045. }
  66046. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66047. {
  66048. int* lastItem = dest + (dest[0] * 2 - 1);
  66049. if (x2 < lastItem[0])
  66050. {
  66051. if (x2 <= dest[1])
  66052. {
  66053. dest[0] = 0;
  66054. return;
  66055. }
  66056. while (x2 < lastItem[-2])
  66057. {
  66058. --(dest[0]);
  66059. lastItem -= 2;
  66060. }
  66061. lastItem[0] = x2;
  66062. lastItem[1] = 0;
  66063. }
  66064. if (x1 > dest[1])
  66065. {
  66066. while (lastItem[0] > x1)
  66067. lastItem -= 2;
  66068. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66069. if (itemsRemoved > 0)
  66070. {
  66071. dest[0] -= itemsRemoved;
  66072. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66073. }
  66074. dest[1] = x1;
  66075. }
  66076. }
  66077. void EdgeTable::clipToRectangle (const Rectangle<int>& r)
  66078. {
  66079. const Rectangle<int> clipped (r.getIntersection (bounds));
  66080. if (clipped.isEmpty())
  66081. {
  66082. needToCheckEmptinesss = false;
  66083. bounds.setHeight (0);
  66084. }
  66085. else
  66086. {
  66087. const int top = clipped.getY() - bounds.getY();
  66088. const int bottom = clipped.getBottom() - bounds.getY();
  66089. if (bottom < bounds.getHeight())
  66090. bounds.setHeight (bottom);
  66091. if (clipped.getRight() < bounds.getRight())
  66092. bounds.setRight (clipped.getRight());
  66093. for (int i = top; --i >= 0;)
  66094. table [lineStrideElements * i] = 0;
  66095. if (clipped.getX() > bounds.getX())
  66096. {
  66097. const int x1 = clipped.getX() << 8;
  66098. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66099. int* line = table + lineStrideElements * top;
  66100. for (int i = bottom - top; --i >= 0;)
  66101. {
  66102. if (line[0] != 0)
  66103. clipEdgeTableLineToRange (line, x1, x2);
  66104. line += lineStrideElements;
  66105. }
  66106. }
  66107. needToCheckEmptinesss = true;
  66108. }
  66109. }
  66110. void EdgeTable::excludeRectangle (const Rectangle<int>& r)
  66111. {
  66112. const Rectangle<int> clipped (r.getIntersection (bounds));
  66113. if (! clipped.isEmpty())
  66114. {
  66115. const int top = clipped.getY() - bounds.getY();
  66116. const int bottom = clipped.getBottom() - bounds.getY();
  66117. //XXX optimise here by shortening the table if it fills top or bottom
  66118. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66119. clipped.getX() << 8, 0,
  66120. clipped.getRight() << 8, 255,
  66121. std::numeric_limits<int>::max(), 0 };
  66122. for (int i = top; i < bottom; ++i)
  66123. intersectWithEdgeTableLine (i, rectLine);
  66124. needToCheckEmptinesss = true;
  66125. }
  66126. }
  66127. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66128. {
  66129. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66130. if (clipped.isEmpty())
  66131. {
  66132. needToCheckEmptinesss = false;
  66133. bounds.setHeight (0);
  66134. }
  66135. else
  66136. {
  66137. const int top = clipped.getY() - bounds.getY();
  66138. const int bottom = clipped.getBottom() - bounds.getY();
  66139. if (bottom < bounds.getHeight())
  66140. bounds.setHeight (bottom);
  66141. if (clipped.getRight() < bounds.getRight())
  66142. bounds.setRight (clipped.getRight());
  66143. int i = 0;
  66144. for (i = top; --i >= 0;)
  66145. table [lineStrideElements * i] = 0;
  66146. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66147. for (i = top; i < bottom; ++i)
  66148. {
  66149. intersectWithEdgeTableLine (i, otherLine);
  66150. otherLine += other.lineStrideElements;
  66151. }
  66152. needToCheckEmptinesss = true;
  66153. }
  66154. }
  66155. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels)
  66156. {
  66157. y -= bounds.getY();
  66158. if (y < 0 || y >= bounds.getHeight())
  66159. return;
  66160. needToCheckEmptinesss = true;
  66161. if (numPixels <= 0)
  66162. {
  66163. table [lineStrideElements * y] = 0;
  66164. return;
  66165. }
  66166. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66167. int destIndex = 0, lastLevel = 0;
  66168. while (--numPixels >= 0)
  66169. {
  66170. const int alpha = *mask;
  66171. mask += maskStride;
  66172. if (alpha != lastLevel)
  66173. {
  66174. tempLine[++destIndex] = (x << 8);
  66175. tempLine[++destIndex] = alpha;
  66176. lastLevel = alpha;
  66177. }
  66178. ++x;
  66179. }
  66180. if (lastLevel > 0)
  66181. {
  66182. tempLine[++destIndex] = (x << 8);
  66183. tempLine[++destIndex] = 0;
  66184. }
  66185. tempLine[0] = destIndex >> 1;
  66186. intersectWithEdgeTableLine (y, tempLine);
  66187. }
  66188. bool EdgeTable::isEmpty() throw()
  66189. {
  66190. if (needToCheckEmptinesss)
  66191. {
  66192. needToCheckEmptinesss = false;
  66193. int* t = table;
  66194. for (int i = bounds.getHeight(); --i >= 0;)
  66195. {
  66196. if (t[0] > 1)
  66197. return false;
  66198. t += lineStrideElements;
  66199. }
  66200. bounds.setHeight (0);
  66201. }
  66202. return bounds.getHeight() == 0;
  66203. }
  66204. END_JUCE_NAMESPACE
  66205. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66206. /*** Start of inlined file: juce_FillType.cpp ***/
  66207. BEGIN_JUCE_NAMESPACE
  66208. FillType::FillType() throw()
  66209. : colour (0xff000000), image (0)
  66210. {
  66211. }
  66212. FillType::FillType (const Colour& colour_) throw()
  66213. : colour (colour_), image (0)
  66214. {
  66215. }
  66216. FillType::FillType (const ColourGradient& gradient_)
  66217. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66218. {
  66219. }
  66220. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66221. : colour (0xff000000), image (image_), transform (transform_)
  66222. {
  66223. }
  66224. FillType::FillType (const FillType& other)
  66225. : colour (other.colour),
  66226. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66227. image (other.image), transform (other.transform)
  66228. {
  66229. }
  66230. FillType& FillType::operator= (const FillType& other)
  66231. {
  66232. if (this != &other)
  66233. {
  66234. colour = other.colour;
  66235. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66236. image = other.image;
  66237. transform = other.transform;
  66238. }
  66239. return *this;
  66240. }
  66241. FillType::~FillType() throw()
  66242. {
  66243. }
  66244. bool FillType::operator== (const FillType& other) const
  66245. {
  66246. return colour == other.colour && image == other.image
  66247. && transform == other.transform
  66248. && (gradient == other.gradient
  66249. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66250. }
  66251. bool FillType::operator!= (const FillType& other) const
  66252. {
  66253. return ! operator== (other);
  66254. }
  66255. void FillType::setColour (const Colour& newColour) throw()
  66256. {
  66257. gradient = 0;
  66258. image = Image::null;
  66259. colour = newColour;
  66260. }
  66261. void FillType::setGradient (const ColourGradient& newGradient)
  66262. {
  66263. if (gradient != 0)
  66264. {
  66265. *gradient = newGradient;
  66266. }
  66267. else
  66268. {
  66269. image = Image::null;
  66270. gradient = new ColourGradient (newGradient);
  66271. colour = Colours::black;
  66272. }
  66273. }
  66274. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66275. {
  66276. gradient = 0;
  66277. image = image_;
  66278. transform = transform_;
  66279. colour = Colours::black;
  66280. }
  66281. void FillType::setOpacity (const float newOpacity) throw()
  66282. {
  66283. colour = colour.withAlpha (newOpacity);
  66284. }
  66285. bool FillType::isInvisible() const throw()
  66286. {
  66287. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66288. }
  66289. END_JUCE_NAMESPACE
  66290. /*** End of inlined file: juce_FillType.cpp ***/
  66291. /*** Start of inlined file: juce_Graphics.cpp ***/
  66292. BEGIN_JUCE_NAMESPACE
  66293. namespace
  66294. {
  66295. template <typename Type>
  66296. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66297. {
  66298. const int maxVal = 0x3fffffff;
  66299. return (int) x >= -maxVal && (int) x <= maxVal
  66300. && (int) y >= -maxVal && (int) y <= maxVal
  66301. && (int) w >= -maxVal && (int) w <= maxVal
  66302. && (int) h >= -maxVal && (int) h <= maxVal;
  66303. }
  66304. }
  66305. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66306. {
  66307. }
  66308. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66309. {
  66310. }
  66311. Graphics::Graphics (const Image& imageToDrawOnto)
  66312. : context (imageToDrawOnto.createLowLevelContext()),
  66313. contextToDelete (context),
  66314. saveStatePending (false)
  66315. {
  66316. }
  66317. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66318. : context (internalContext),
  66319. saveStatePending (false)
  66320. {
  66321. }
  66322. Graphics::~Graphics()
  66323. {
  66324. }
  66325. void Graphics::resetToDefaultState()
  66326. {
  66327. saveStateIfPending();
  66328. context->setFill (FillType());
  66329. context->setFont (Font());
  66330. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66331. }
  66332. bool Graphics::isVectorDevice() const
  66333. {
  66334. return context->isVectorDevice();
  66335. }
  66336. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66337. {
  66338. saveStateIfPending();
  66339. return context->clipToRectangle (area);
  66340. }
  66341. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66342. {
  66343. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66344. }
  66345. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66346. {
  66347. saveStateIfPending();
  66348. return context->clipToRectangleList (clipRegion);
  66349. }
  66350. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66351. {
  66352. saveStateIfPending();
  66353. context->clipToPath (path, transform);
  66354. return ! context->isClipEmpty();
  66355. }
  66356. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66357. {
  66358. saveStateIfPending();
  66359. context->clipToImageAlpha (image, transform);
  66360. return ! context->isClipEmpty();
  66361. }
  66362. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66363. {
  66364. saveStateIfPending();
  66365. context->excludeClipRectangle (rectangleToExclude);
  66366. }
  66367. bool Graphics::isClipEmpty() const
  66368. {
  66369. return context->isClipEmpty();
  66370. }
  66371. const Rectangle<int> Graphics::getClipBounds() const
  66372. {
  66373. return context->getClipBounds();
  66374. }
  66375. void Graphics::saveState()
  66376. {
  66377. saveStateIfPending();
  66378. saveStatePending = true;
  66379. }
  66380. void Graphics::restoreState()
  66381. {
  66382. if (saveStatePending)
  66383. saveStatePending = false;
  66384. else
  66385. context->restoreState();
  66386. }
  66387. void Graphics::saveStateIfPending()
  66388. {
  66389. if (saveStatePending)
  66390. {
  66391. saveStatePending = false;
  66392. context->saveState();
  66393. }
  66394. }
  66395. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66396. {
  66397. saveStateIfPending();
  66398. context->setOrigin (newOriginX, newOriginY);
  66399. }
  66400. void Graphics::addTransform (const AffineTransform& transform)
  66401. {
  66402. saveStateIfPending();
  66403. context->addTransform (transform);
  66404. }
  66405. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66406. {
  66407. return context->clipRegionIntersects (area);
  66408. }
  66409. void Graphics::beginTransparencyLayer (float layerOpacity)
  66410. {
  66411. saveStateIfPending();
  66412. context->beginTransparencyLayer (layerOpacity);
  66413. }
  66414. void Graphics::endTransparencyLayer()
  66415. {
  66416. context->endTransparencyLayer();
  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, context->getScaleFactor());
  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. Graphics::ScopedSaveState::ScopedSaveState (Graphics& g)
  66858. : context (g)
  66859. {
  66860. context.saveState();
  66861. }
  66862. Graphics::ScopedSaveState::~ScopedSaveState()
  66863. {
  66864. context.restoreState();
  66865. }
  66866. END_JUCE_NAMESPACE
  66867. /*** End of inlined file: juce_Graphics.cpp ***/
  66868. /*** Start of inlined file: juce_Justification.cpp ***/
  66869. BEGIN_JUCE_NAMESPACE
  66870. Justification::Justification (const Justification& other) throw()
  66871. : flags (other.flags)
  66872. {
  66873. }
  66874. Justification& Justification::operator= (const Justification& other) throw()
  66875. {
  66876. flags = other.flags;
  66877. return *this;
  66878. }
  66879. int Justification::getOnlyVerticalFlags() const throw()
  66880. {
  66881. return flags & (top | bottom | verticallyCentred);
  66882. }
  66883. int Justification::getOnlyHorizontalFlags() const throw()
  66884. {
  66885. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66886. }
  66887. END_JUCE_NAMESPACE
  66888. /*** End of inlined file: juce_Justification.cpp ***/
  66889. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66890. BEGIN_JUCE_NAMESPACE
  66891. // this will throw an assertion if you try to draw something that's not
  66892. // possible in postscript
  66893. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66894. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66895. #define notPossibleInPostscriptAssert jassertfalse
  66896. #else
  66897. #define notPossibleInPostscriptAssert
  66898. #endif
  66899. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66900. const String& documentTitle,
  66901. const int totalWidth_,
  66902. const int totalHeight_)
  66903. : out (resultingPostScript),
  66904. totalWidth (totalWidth_),
  66905. totalHeight (totalHeight_),
  66906. needToClip (true)
  66907. {
  66908. stateStack.add (new SavedState());
  66909. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66910. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66911. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66912. "\n%%BoundingBox: 0 0 600 824"
  66913. "\n%%Pages: 0"
  66914. "\n%%Creator: Raw Material Software JUCE"
  66915. "\n%%Title: " << documentTitle <<
  66916. "\n%%CreationDate: none"
  66917. "\n%%LanguageLevel: 2"
  66918. "\n%%EndComments"
  66919. "\n%%BeginProlog"
  66920. "\n%%BeginResource: JRes"
  66921. "\n/bd {bind def} bind def"
  66922. "\n/c {setrgbcolor} bd"
  66923. "\n/m {moveto} bd"
  66924. "\n/l {lineto} bd"
  66925. "\n/rl {rlineto} bd"
  66926. "\n/ct {curveto} bd"
  66927. "\n/cp {closepath} bd"
  66928. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66929. "\n/doclip {initclip newpath} bd"
  66930. "\n/endclip {clip newpath} bd"
  66931. "\n%%EndResource"
  66932. "\n%%EndProlog"
  66933. "\n%%BeginSetup"
  66934. "\n%%EndSetup"
  66935. "\n%%Page: 1 1"
  66936. "\n%%BeginPageSetup"
  66937. "\n%%EndPageSetup\n\n"
  66938. << "40 800 translate\n"
  66939. << scale << ' ' << scale << " scale\n\n";
  66940. }
  66941. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66942. {
  66943. }
  66944. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66945. {
  66946. return true;
  66947. }
  66948. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66949. {
  66950. if (x != 0 || y != 0)
  66951. {
  66952. stateStack.getLast()->xOffset += x;
  66953. stateStack.getLast()->yOffset += y;
  66954. needToClip = true;
  66955. }
  66956. }
  66957. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  66958. {
  66959. //xxx
  66960. jassertfalse;
  66961. }
  66962. float LowLevelGraphicsPostScriptRenderer::getScaleFactor()
  66963. {
  66964. jassertfalse; //xxx
  66965. return 1.0f;
  66966. }
  66967. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66968. {
  66969. needToClip = true;
  66970. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66971. }
  66972. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66973. {
  66974. needToClip = true;
  66975. return stateStack.getLast()->clip.clipTo (clipRegion);
  66976. }
  66977. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66978. {
  66979. needToClip = true;
  66980. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66981. }
  66982. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66983. {
  66984. writeClip();
  66985. Path p (path);
  66986. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66987. writePath (p);
  66988. out << "clip\n";
  66989. }
  66990. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66991. {
  66992. needToClip = true;
  66993. jassertfalse; // xxx
  66994. }
  66995. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66996. {
  66997. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66998. }
  66999. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67000. {
  67001. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67002. -stateStack.getLast()->yOffset);
  67003. }
  67004. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67005. {
  67006. return stateStack.getLast()->clip.isEmpty();
  67007. }
  67008. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67009. : xOffset (0),
  67010. yOffset (0)
  67011. {
  67012. }
  67013. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67014. {
  67015. }
  67016. void LowLevelGraphicsPostScriptRenderer::saveState()
  67017. {
  67018. stateStack.add (new SavedState (*stateStack.getLast()));
  67019. }
  67020. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67021. {
  67022. jassert (stateStack.size() > 0);
  67023. if (stateStack.size() > 0)
  67024. stateStack.removeLast();
  67025. }
  67026. void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float)
  67027. {
  67028. }
  67029. void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer()
  67030. {
  67031. }
  67032. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67033. {
  67034. if (needToClip)
  67035. {
  67036. needToClip = false;
  67037. out << "doclip ";
  67038. int itemsOnLine = 0;
  67039. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67040. {
  67041. if (++itemsOnLine == 6)
  67042. {
  67043. itemsOnLine = 0;
  67044. out << '\n';
  67045. }
  67046. const Rectangle<int>& r = *i.getRectangle();
  67047. out << r.getX() << ' ' << -r.getY() << ' '
  67048. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67049. }
  67050. out << "endclip\n";
  67051. }
  67052. }
  67053. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67054. {
  67055. Colour c (Colours::white.overlaidWith (colour));
  67056. if (lastColour != c)
  67057. {
  67058. lastColour = c;
  67059. out << String (c.getFloatRed(), 3) << ' '
  67060. << String (c.getFloatGreen(), 3) << ' '
  67061. << String (c.getFloatBlue(), 3) << " c\n";
  67062. }
  67063. }
  67064. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67065. {
  67066. out << String (x, 2) << ' '
  67067. << String (-y, 2) << ' ';
  67068. }
  67069. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67070. {
  67071. out << "newpath ";
  67072. float lastX = 0.0f;
  67073. float lastY = 0.0f;
  67074. int itemsOnLine = 0;
  67075. Path::Iterator i (path);
  67076. while (i.next())
  67077. {
  67078. if (++itemsOnLine == 4)
  67079. {
  67080. itemsOnLine = 0;
  67081. out << '\n';
  67082. }
  67083. switch (i.elementType)
  67084. {
  67085. case Path::Iterator::startNewSubPath:
  67086. writeXY (i.x1, i.y1);
  67087. lastX = i.x1;
  67088. lastY = i.y1;
  67089. out << "m ";
  67090. break;
  67091. case Path::Iterator::lineTo:
  67092. writeXY (i.x1, i.y1);
  67093. lastX = i.x1;
  67094. lastY = i.y1;
  67095. out << "l ";
  67096. break;
  67097. case Path::Iterator::quadraticTo:
  67098. {
  67099. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67100. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67101. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67102. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67103. writeXY (cp1x, cp1y);
  67104. writeXY (cp2x, cp2y);
  67105. writeXY (i.x2, i.y2);
  67106. out << "ct ";
  67107. lastX = i.x2;
  67108. lastY = i.y2;
  67109. }
  67110. break;
  67111. case Path::Iterator::cubicTo:
  67112. writeXY (i.x1, i.y1);
  67113. writeXY (i.x2, i.y2);
  67114. writeXY (i.x3, i.y3);
  67115. out << "ct ";
  67116. lastX = i.x3;
  67117. lastY = i.y3;
  67118. break;
  67119. case Path::Iterator::closePath:
  67120. out << "cp ";
  67121. break;
  67122. default:
  67123. jassertfalse;
  67124. break;
  67125. }
  67126. }
  67127. out << '\n';
  67128. }
  67129. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67130. {
  67131. out << "[ "
  67132. << trans.mat00 << ' '
  67133. << trans.mat10 << ' '
  67134. << trans.mat01 << ' '
  67135. << trans.mat11 << ' '
  67136. << trans.mat02 << ' '
  67137. << trans.mat12 << " ] concat ";
  67138. }
  67139. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67140. {
  67141. stateStack.getLast()->fillType = fillType;
  67142. }
  67143. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67144. {
  67145. }
  67146. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67147. {
  67148. }
  67149. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67150. {
  67151. if (stateStack.getLast()->fillType.isColour())
  67152. {
  67153. writeClip();
  67154. writeColour (stateStack.getLast()->fillType.colour);
  67155. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67156. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67157. }
  67158. else
  67159. {
  67160. Path p;
  67161. p.addRectangle (r);
  67162. fillPath (p, AffineTransform::identity);
  67163. }
  67164. }
  67165. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67166. {
  67167. if (stateStack.getLast()->fillType.isColour())
  67168. {
  67169. writeClip();
  67170. Path p (path);
  67171. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67172. (float) stateStack.getLast()->yOffset));
  67173. writePath (p);
  67174. writeColour (stateStack.getLast()->fillType.colour);
  67175. out << "fill\n";
  67176. }
  67177. else if (stateStack.getLast()->fillType.isGradient())
  67178. {
  67179. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67180. // postscript can't do semi-transparent ones.
  67181. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67182. writeClip();
  67183. out << "gsave ";
  67184. {
  67185. Path p (path);
  67186. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67187. writePath (p);
  67188. out << "clip\n";
  67189. }
  67190. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67191. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67192. // time-being, this just fills it with the average colour..
  67193. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67194. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67195. out << "grestore\n";
  67196. }
  67197. }
  67198. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67199. const int sx, const int sy,
  67200. const int maxW, const int maxH) const
  67201. {
  67202. out << "{<\n";
  67203. const int w = jmin (maxW, im.getWidth());
  67204. const int h = jmin (maxH, im.getHeight());
  67205. int charsOnLine = 0;
  67206. const Image::BitmapData srcData (im, 0, 0, w, h);
  67207. Colour pixel;
  67208. for (int y = h; --y >= 0;)
  67209. {
  67210. for (int x = 0; x < w; ++x)
  67211. {
  67212. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67213. if (x >= sx && y >= sy)
  67214. {
  67215. if (im.isARGB())
  67216. {
  67217. PixelARGB p (*(const PixelARGB*) pixelData);
  67218. p.unpremultiply();
  67219. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67220. }
  67221. else if (im.isRGB())
  67222. {
  67223. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67224. }
  67225. else
  67226. {
  67227. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67228. }
  67229. }
  67230. else
  67231. {
  67232. pixel = Colours::transparentWhite;
  67233. }
  67234. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67235. out << String::toHexString (pixelValues, 3, 0);
  67236. charsOnLine += 3;
  67237. if (charsOnLine > 100)
  67238. {
  67239. out << '\n';
  67240. charsOnLine = 0;
  67241. }
  67242. }
  67243. }
  67244. out << "\n>}\n";
  67245. }
  67246. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67247. {
  67248. const int w = sourceImage.getWidth();
  67249. const int h = sourceImage.getHeight();
  67250. writeClip();
  67251. out << "gsave ";
  67252. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67253. .scaled (1.0f, -1.0f));
  67254. RectangleList imageClip;
  67255. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67256. out << "newpath ";
  67257. int itemsOnLine = 0;
  67258. for (RectangleList::Iterator i (imageClip); i.next();)
  67259. {
  67260. if (++itemsOnLine == 6)
  67261. {
  67262. out << '\n';
  67263. itemsOnLine = 0;
  67264. }
  67265. const Rectangle<int>& r = *i.getRectangle();
  67266. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67267. }
  67268. out << " clip newpath\n";
  67269. out << w << ' ' << h << " scale\n";
  67270. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67271. writeImage (sourceImage, 0, 0, w, h);
  67272. out << "false 3 colorimage grestore\n";
  67273. needToClip = true;
  67274. }
  67275. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67276. {
  67277. Path p;
  67278. p.addLineSegment (line, 1.0f);
  67279. fillPath (p, AffineTransform::identity);
  67280. }
  67281. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67282. {
  67283. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67284. }
  67285. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67286. {
  67287. drawLine (Line<float> (left, (float) y, right, (float) y));
  67288. }
  67289. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67290. {
  67291. stateStack.getLast()->font = newFont;
  67292. }
  67293. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67294. {
  67295. return stateStack.getLast()->font;
  67296. }
  67297. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67298. {
  67299. Path p;
  67300. Font& font = stateStack.getLast()->font;
  67301. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67302. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67303. }
  67304. END_JUCE_NAMESPACE
  67305. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67306. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67307. BEGIN_JUCE_NAMESPACE
  67308. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67309. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67310. #endif
  67311. #if JUCE_MSVC
  67312. #pragma warning (push)
  67313. #pragma warning (disable: 4127) // "expression is constant" warning
  67314. #if JUCE_DEBUG
  67315. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67316. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67317. #endif
  67318. #endif
  67319. namespace SoftwareRendererClasses
  67320. {
  67321. template <class PixelType, bool replaceExisting = false>
  67322. class SolidColourEdgeTableRenderer
  67323. {
  67324. public:
  67325. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67326. : data (data_),
  67327. sourceColour (colour)
  67328. {
  67329. if (sizeof (PixelType) == 3)
  67330. {
  67331. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67332. && sourceColour.getGreen() == sourceColour.getBlue();
  67333. filler[0].set (sourceColour);
  67334. filler[1].set (sourceColour);
  67335. filler[2].set (sourceColour);
  67336. filler[3].set (sourceColour);
  67337. }
  67338. }
  67339. forcedinline void setEdgeTableYPos (const int y) throw()
  67340. {
  67341. linePixels = (PixelType*) data.getLinePointer (y);
  67342. }
  67343. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67344. {
  67345. if (replaceExisting)
  67346. linePixels[x].set (sourceColour);
  67347. else
  67348. linePixels[x].blend (sourceColour, alphaLevel);
  67349. }
  67350. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67351. {
  67352. if (replaceExisting)
  67353. linePixels[x].set (sourceColour);
  67354. else
  67355. linePixels[x].blend (sourceColour);
  67356. }
  67357. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67358. {
  67359. PixelARGB p (sourceColour);
  67360. p.multiplyAlpha (alphaLevel);
  67361. PixelType* dest = linePixels + x;
  67362. if (replaceExisting || p.getAlpha() >= 0xff)
  67363. replaceLine (dest, p, width);
  67364. else
  67365. blendLine (dest, p, width);
  67366. }
  67367. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67368. {
  67369. PixelType* dest = linePixels + x;
  67370. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67371. replaceLine (dest, sourceColour, width);
  67372. else
  67373. blendLine (dest, sourceColour, width);
  67374. }
  67375. private:
  67376. const Image::BitmapData& data;
  67377. PixelType* linePixels;
  67378. PixelARGB sourceColour;
  67379. PixelRGB filler [4];
  67380. bool areRGBComponentsEqual;
  67381. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67382. {
  67383. do
  67384. {
  67385. dest->blend (colour);
  67386. ++dest;
  67387. } while (--width > 0);
  67388. }
  67389. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67390. {
  67391. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67392. {
  67393. memset (dest, colour.getRed(), width * 3);
  67394. }
  67395. else
  67396. {
  67397. if (width >> 5)
  67398. {
  67399. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67400. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67401. {
  67402. dest->set (colour);
  67403. ++dest;
  67404. --width;
  67405. }
  67406. while (width > 4)
  67407. {
  67408. int* d = reinterpret_cast<int*> (dest);
  67409. *d++ = intFiller[0];
  67410. *d++ = intFiller[1];
  67411. *d++ = intFiller[2];
  67412. dest = reinterpret_cast<PixelRGB*> (d);
  67413. width -= 4;
  67414. }
  67415. }
  67416. while (--width >= 0)
  67417. {
  67418. dest->set (colour);
  67419. ++dest;
  67420. }
  67421. }
  67422. }
  67423. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67424. {
  67425. memset (dest, colour.getAlpha(), width);
  67426. }
  67427. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67428. {
  67429. do
  67430. {
  67431. dest->set (colour);
  67432. ++dest;
  67433. } while (--width > 0);
  67434. }
  67435. JUCE_DECLARE_NON_COPYABLE (SolidColourEdgeTableRenderer);
  67436. };
  67437. class LinearGradientPixelGenerator
  67438. {
  67439. public:
  67440. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67441. : lookupTable (lookupTable_), numEntries (numEntries_)
  67442. {
  67443. jassert (numEntries_ >= 0);
  67444. Point<float> p1 (gradient.point1);
  67445. Point<float> p2 (gradient.point2);
  67446. if (! transform.isIdentity())
  67447. {
  67448. const Line<float> l (p2, p1);
  67449. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67450. p1.applyTransform (transform);
  67451. p2.applyTransform (transform);
  67452. p3.applyTransform (transform);
  67453. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67454. }
  67455. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67456. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67457. if (vertical)
  67458. {
  67459. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67460. start = roundToInt (p1.getY() * scale);
  67461. }
  67462. else if (horizontal)
  67463. {
  67464. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67465. start = roundToInt (p1.getX() * scale);
  67466. }
  67467. else
  67468. {
  67469. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67470. yTerm = p1.getY() - p1.getX() / grad;
  67471. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67472. grad *= scale;
  67473. }
  67474. }
  67475. forcedinline void setY (const int y) throw()
  67476. {
  67477. if (vertical)
  67478. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67479. else if (! horizontal)
  67480. start = roundToInt ((y - yTerm) * grad);
  67481. }
  67482. inline const PixelARGB getPixel (const int x) const throw()
  67483. {
  67484. return vertical ? linePix
  67485. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67486. }
  67487. private:
  67488. const PixelARGB* const lookupTable;
  67489. const int numEntries;
  67490. PixelARGB linePix;
  67491. int start, scale;
  67492. double grad, yTerm;
  67493. bool vertical, horizontal;
  67494. enum { numScaleBits = 12 };
  67495. JUCE_DECLARE_NON_COPYABLE (LinearGradientPixelGenerator);
  67496. };
  67497. class RadialGradientPixelGenerator
  67498. {
  67499. public:
  67500. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67501. const PixelARGB* const lookupTable_, const int numEntries_)
  67502. : lookupTable (lookupTable_),
  67503. numEntries (numEntries_),
  67504. gx1 (gradient.point1.getX()),
  67505. gy1 (gradient.point1.getY())
  67506. {
  67507. jassert (numEntries_ >= 0);
  67508. const Point<float> diff (gradient.point1 - gradient.point2);
  67509. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67510. invScale = numEntries / std::sqrt (maxDist);
  67511. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67512. }
  67513. forcedinline void setY (const int y) throw()
  67514. {
  67515. dy = y - gy1;
  67516. dy *= dy;
  67517. }
  67518. inline const PixelARGB getPixel (const int px) const throw()
  67519. {
  67520. double x = px - gx1;
  67521. x *= x;
  67522. x += dy;
  67523. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67524. }
  67525. protected:
  67526. const PixelARGB* const lookupTable;
  67527. const int numEntries;
  67528. const double gx1, gy1;
  67529. double maxDist, invScale, dy;
  67530. JUCE_DECLARE_NON_COPYABLE (RadialGradientPixelGenerator);
  67531. };
  67532. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67533. {
  67534. public:
  67535. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67536. const PixelARGB* const lookupTable_, const int numEntries_)
  67537. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67538. inverseTransform (transform.inverted())
  67539. {
  67540. tM10 = inverseTransform.mat10;
  67541. tM00 = inverseTransform.mat00;
  67542. }
  67543. forcedinline void setY (const int y) throw()
  67544. {
  67545. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67546. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67547. }
  67548. inline const PixelARGB getPixel (const int px) const throw()
  67549. {
  67550. double x = px;
  67551. const double y = tM10 * x + lineYM11;
  67552. x = tM00 * x + lineYM01;
  67553. x *= x;
  67554. x += y * y;
  67555. if (x >= maxDist)
  67556. return lookupTable [numEntries];
  67557. else
  67558. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67559. }
  67560. private:
  67561. double tM10, tM00, lineYM01, lineYM11;
  67562. const AffineTransform inverseTransform;
  67563. JUCE_DECLARE_NON_COPYABLE (TransformedRadialGradientPixelGenerator);
  67564. };
  67565. template <class PixelType, class GradientType>
  67566. class GradientEdgeTableRenderer : public GradientType
  67567. {
  67568. public:
  67569. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67570. const PixelARGB* const lookupTable_, const int numEntries_)
  67571. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67572. destData (destData_)
  67573. {
  67574. }
  67575. forcedinline void setEdgeTableYPos (const int y) throw()
  67576. {
  67577. linePixels = (PixelType*) destData.getLinePointer (y);
  67578. GradientType::setY (y);
  67579. }
  67580. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67581. {
  67582. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67583. }
  67584. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67585. {
  67586. linePixels[x].blend (GradientType::getPixel (x));
  67587. }
  67588. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67589. {
  67590. PixelType* dest = linePixels + x;
  67591. if (alphaLevel < 0xff)
  67592. {
  67593. do
  67594. {
  67595. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67596. } while (--width > 0);
  67597. }
  67598. else
  67599. {
  67600. do
  67601. {
  67602. (dest++)->blend (GradientType::getPixel (x++));
  67603. } while (--width > 0);
  67604. }
  67605. }
  67606. void handleEdgeTableLineFull (int x, int width) const throw()
  67607. {
  67608. PixelType* dest = linePixels + x;
  67609. do
  67610. {
  67611. (dest++)->blend (GradientType::getPixel (x++));
  67612. } while (--width > 0);
  67613. }
  67614. private:
  67615. const Image::BitmapData& destData;
  67616. PixelType* linePixels;
  67617. JUCE_DECLARE_NON_COPYABLE (GradientEdgeTableRenderer);
  67618. };
  67619. namespace RenderingHelpers
  67620. {
  67621. forcedinline int safeModulo (int n, const int divisor) throw()
  67622. {
  67623. jassert (divisor > 0);
  67624. n %= divisor;
  67625. return (n < 0) ? (n + divisor) : n;
  67626. }
  67627. }
  67628. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67629. class ImageFillEdgeTableRenderer
  67630. {
  67631. public:
  67632. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67633. const Image::BitmapData& srcData_,
  67634. const int extraAlpha_,
  67635. const int x, const int y)
  67636. : destData (destData_),
  67637. srcData (srcData_),
  67638. extraAlpha (extraAlpha_ + 1),
  67639. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  67640. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  67641. {
  67642. }
  67643. forcedinline void setEdgeTableYPos (int y) throw()
  67644. {
  67645. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67646. y -= yOffset;
  67647. if (repeatPattern)
  67648. {
  67649. jassert (y >= 0);
  67650. y %= srcData.height;
  67651. }
  67652. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67653. }
  67654. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67655. {
  67656. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67657. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67658. }
  67659. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67660. {
  67661. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67662. }
  67663. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67664. {
  67665. DestPixelType* dest = linePixels + x;
  67666. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67667. x -= xOffset;
  67668. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67669. if (alphaLevel < 0xfe)
  67670. {
  67671. do
  67672. {
  67673. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67674. } while (--width > 0);
  67675. }
  67676. else
  67677. {
  67678. if (repeatPattern)
  67679. {
  67680. do
  67681. {
  67682. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67683. } while (--width > 0);
  67684. }
  67685. else
  67686. {
  67687. copyRow (dest, sourceLineStart + x, width);
  67688. }
  67689. }
  67690. }
  67691. void handleEdgeTableLineFull (int x, int width) const throw()
  67692. {
  67693. DestPixelType* dest = linePixels + x;
  67694. x -= xOffset;
  67695. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67696. if (extraAlpha < 0xfe)
  67697. {
  67698. do
  67699. {
  67700. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67701. } while (--width > 0);
  67702. }
  67703. else
  67704. {
  67705. if (repeatPattern)
  67706. {
  67707. do
  67708. {
  67709. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67710. } while (--width > 0);
  67711. }
  67712. else
  67713. {
  67714. copyRow (dest, sourceLineStart + x, width);
  67715. }
  67716. }
  67717. }
  67718. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67719. {
  67720. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67721. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67722. uint8* mask = (uint8*) (s + x - xOffset);
  67723. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67724. mask += PixelARGB::indexA;
  67725. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67726. }
  67727. private:
  67728. const Image::BitmapData& destData;
  67729. const Image::BitmapData& srcData;
  67730. const int extraAlpha, xOffset, yOffset;
  67731. DestPixelType* linePixels;
  67732. SrcPixelType* sourceLineStart;
  67733. template <class PixelType1, class PixelType2>
  67734. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67735. {
  67736. do
  67737. {
  67738. dest++ ->blend (*src++);
  67739. } while (--width > 0);
  67740. }
  67741. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67742. {
  67743. memcpy (dest, src, width * sizeof (PixelRGB));
  67744. }
  67745. JUCE_DECLARE_NON_COPYABLE (ImageFillEdgeTableRenderer);
  67746. };
  67747. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67748. class TransformedImageFillEdgeTableRenderer
  67749. {
  67750. public:
  67751. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67752. const Image::BitmapData& srcData_,
  67753. const AffineTransform& transform,
  67754. const int extraAlpha_,
  67755. const bool betterQuality_)
  67756. : interpolator (transform,
  67757. betterQuality_ ? 0.5f : 0.0f,
  67758. betterQuality_ ? -128 : 0),
  67759. destData (destData_),
  67760. srcData (srcData_),
  67761. extraAlpha (extraAlpha_ + 1),
  67762. betterQuality (betterQuality_),
  67763. maxX (srcData_.width - 1),
  67764. maxY (srcData_.height - 1),
  67765. scratchSize (2048)
  67766. {
  67767. scratchBuffer.malloc (scratchSize);
  67768. }
  67769. forcedinline void setEdgeTableYPos (const int newY) throw()
  67770. {
  67771. y = newY;
  67772. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67773. }
  67774. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  67775. {
  67776. SrcPixelType p;
  67777. generate (&p, x, 1);
  67778. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  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.getData(), x, width);
  67826. et.clipLineToMask (x, y_,
  67827. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67828. sizeof (SrcPixelType), width);
  67829. }
  67830. private:
  67831. template <class PixelType>
  67832. void generate (PixelType* dest, const int x, int numPixels) throw()
  67833. {
  67834. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  67835. do
  67836. {
  67837. int hiResX, hiResY;
  67838. this->interpolator.next (hiResX, hiResY);
  67839. int loResX = hiResX >> 8;
  67840. int loResY = hiResY >> 8;
  67841. if (repeatPattern)
  67842. {
  67843. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  67844. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  67845. }
  67846. if (betterQuality)
  67847. {
  67848. if (isPositiveAndBelow (loResX, maxX))
  67849. {
  67850. if (isPositiveAndBelow (loResY, maxY))
  67851. {
  67852. // In the centre of the image..
  67853. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  67854. hiResX & 255, hiResY & 255);
  67855. ++dest;
  67856. continue;
  67857. }
  67858. else
  67859. {
  67860. // At a top or bottom edge..
  67861. if (! repeatPattern)
  67862. {
  67863. if (loResY < 0)
  67864. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255, hiResY & 255);
  67865. else
  67866. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255, 255 - (hiResY & 255));
  67867. ++dest;
  67868. continue;
  67869. }
  67870. }
  67871. }
  67872. else
  67873. {
  67874. if (isPositiveAndBelow (loResY, maxY))
  67875. {
  67876. // At a left or right hand edge..
  67877. if (! repeatPattern)
  67878. {
  67879. if (loResX < 0)
  67880. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255, hiResX & 255);
  67881. else
  67882. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255, 255 - (hiResX & 255));
  67883. ++dest;
  67884. continue;
  67885. }
  67886. }
  67887. }
  67888. }
  67889. if (! repeatPattern)
  67890. {
  67891. if (loResX < 0) loResX = 0;
  67892. if (loResY < 0) loResY = 0;
  67893. if (loResX > maxX) loResX = maxX;
  67894. if (loResY > maxY) loResY = maxY;
  67895. }
  67896. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  67897. ++dest;
  67898. } while (--numPixels > 0);
  67899. }
  67900. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67901. {
  67902. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67903. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67904. c[0] += weight * src[0];
  67905. c[1] += weight * src[1];
  67906. c[2] += weight * src[2];
  67907. c[3] += weight * src[3];
  67908. weight = subPixelX * (256 - subPixelY);
  67909. c[0] += weight * src[4];
  67910. c[1] += weight * src[5];
  67911. c[2] += weight * src[6];
  67912. c[3] += weight * src[7];
  67913. src += this->srcData.lineStride;
  67914. weight = (256 - subPixelX) * subPixelY;
  67915. c[0] += weight * src[0];
  67916. c[1] += weight * src[1];
  67917. c[2] += weight * src[2];
  67918. c[3] += weight * src[3];
  67919. weight = subPixelX * subPixelY;
  67920. c[0] += weight * src[4];
  67921. c[1] += weight * src[5];
  67922. c[2] += weight * src[6];
  67923. c[3] += weight * src[7];
  67924. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67925. (uint8) (c[PixelARGB::indexR] >> 16),
  67926. (uint8) (c[PixelARGB::indexG] >> 16),
  67927. (uint8) (c[PixelARGB::indexB] >> 16));
  67928. }
  67929. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67930. {
  67931. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67932. uint32 weight = (256 - subPixelX) * alpha;
  67933. c[0] += weight * src[0];
  67934. c[1] += weight * src[1];
  67935. c[2] += weight * src[2];
  67936. c[3] += weight * src[3];
  67937. weight = subPixelX * alpha;
  67938. c[0] += weight * src[4];
  67939. c[1] += weight * src[5];
  67940. c[2] += weight * src[6];
  67941. c[3] += weight * src[7];
  67942. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67943. (uint8) (c[PixelARGB::indexR] >> 16),
  67944. (uint8) (c[PixelARGB::indexG] >> 16),
  67945. (uint8) (c[PixelARGB::indexB] >> 16));
  67946. }
  67947. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67948. {
  67949. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67950. uint32 weight = (256 - subPixelY) * alpha;
  67951. c[0] += weight * src[0];
  67952. c[1] += weight * src[1];
  67953. c[2] += weight * src[2];
  67954. c[3] += weight * src[3];
  67955. src += this->srcData.lineStride;
  67956. weight = subPixelY * alpha;
  67957. c[0] += weight * src[0];
  67958. c[1] += weight * src[1];
  67959. c[2] += weight * src[2];
  67960. c[3] += weight * src[3];
  67961. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67962. (uint8) (c[PixelARGB::indexR] >> 16),
  67963. (uint8) (c[PixelARGB::indexG] >> 16),
  67964. (uint8) (c[PixelARGB::indexB] >> 16));
  67965. }
  67966. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67967. {
  67968. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67969. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67970. c[0] += weight * src[0];
  67971. c[1] += weight * src[1];
  67972. c[2] += weight * src[2];
  67973. weight = subPixelX * (256 - subPixelY);
  67974. c[0] += weight * src[3];
  67975. c[1] += weight * src[4];
  67976. c[2] += weight * src[5];
  67977. src += this->srcData.lineStride;
  67978. weight = (256 - subPixelX) * subPixelY;
  67979. c[0] += weight * src[0];
  67980. c[1] += weight * src[1];
  67981. c[2] += weight * src[2];
  67982. weight = subPixelX * subPixelY;
  67983. c[0] += weight * src[3];
  67984. c[1] += weight * src[4];
  67985. c[2] += weight * src[5];
  67986. dest->setARGB ((uint8) 255,
  67987. (uint8) (c[PixelRGB::indexR] >> 16),
  67988. (uint8) (c[PixelRGB::indexG] >> 16),
  67989. (uint8) (c[PixelRGB::indexB] >> 16));
  67990. }
  67991. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX, const int /*alpha*/) throw()
  67992. {
  67993. uint32 c[3] = { 128, 128, 128 };
  67994. uint32 weight = (256 - subPixelX);
  67995. c[0] += weight * src[0];
  67996. c[1] += weight * src[1];
  67997. c[2] += weight * src[2];
  67998. c[0] += subPixelX * src[3];
  67999. c[1] += subPixelX * src[4];
  68000. c[2] += subPixelX * src[5];
  68001. dest->setARGB ((uint8) 255,
  68002. (uint8) (c[PixelRGB::indexR] >> 8),
  68003. (uint8) (c[PixelRGB::indexG] >> 8),
  68004. (uint8) (c[PixelRGB::indexB] >> 8));
  68005. }
  68006. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY, const int /*alpha*/) throw()
  68007. {
  68008. uint32 c[3] = { 128, 128, 128 };
  68009. uint32 weight = (256 - subPixelY);
  68010. c[0] += weight * src[0];
  68011. c[1] += weight * src[1];
  68012. c[2] += weight * src[2];
  68013. src += this->srcData.lineStride;
  68014. c[0] += subPixelY * src[0];
  68015. c[1] += subPixelY * src[1];
  68016. c[2] += subPixelY * src[2];
  68017. dest->setARGB ((uint8) 255,
  68018. (uint8) (c[PixelRGB::indexR] >> 8),
  68019. (uint8) (c[PixelRGB::indexG] >> 8),
  68020. (uint8) (c[PixelRGB::indexB] >> 8));
  68021. }
  68022. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  68023. {
  68024. uint32 c = 256 * 128;
  68025. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  68026. c += src[1] * (subPixelX * (256 - subPixelY));
  68027. src += this->srcData.lineStride;
  68028. c += src[0] * ((256 - subPixelX) * subPixelY);
  68029. c += src[1] * (subPixelX * subPixelY);
  68030. *((uint8*) dest) = (uint8) (c >> 16);
  68031. }
  68032. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  68033. {
  68034. uint32 c = 256 * 128;
  68035. c += src[0] * (256 - subPixelX) * alpha;
  68036. c += src[1] * subPixelX * alpha;
  68037. *((uint8*) dest) = (uint8) (c >> 16);
  68038. }
  68039. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  68040. {
  68041. uint32 c = 256 * 128;
  68042. c += src[0] * (256 - subPixelY) * alpha;
  68043. src += this->srcData.lineStride;
  68044. c += src[0] * subPixelY * alpha;
  68045. *((uint8*) dest) = (uint8) (c >> 16);
  68046. }
  68047. class TransformedImageSpanInterpolator
  68048. {
  68049. public:
  68050. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  68051. : inverseTransform (transform.inverted()),
  68052. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  68053. {}
  68054. void setStartOfLine (float x, float y, const int numPixels) throw()
  68055. {
  68056. jassert (numPixels > 0);
  68057. x += pixelOffset;
  68058. y += pixelOffset;
  68059. float x1 = x, y1 = y;
  68060. x += numPixels;
  68061. inverseTransform.transformPoints (x1, y1, x, y);
  68062. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  68063. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  68064. }
  68065. void next (int& x, int& y) throw()
  68066. {
  68067. x = xBresenham.n;
  68068. xBresenham.stepToNext();
  68069. y = yBresenham.n;
  68070. yBresenham.stepToNext();
  68071. }
  68072. private:
  68073. class BresenhamInterpolator
  68074. {
  68075. public:
  68076. BresenhamInterpolator() throw() {}
  68077. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  68078. {
  68079. numSteps = numSteps_;
  68080. step = (n2 - n1) / numSteps;
  68081. remainder = modulo = (n2 - n1) % numSteps;
  68082. n = n1 + pixelOffsetInt;
  68083. if (modulo <= 0)
  68084. {
  68085. modulo += numSteps;
  68086. remainder += numSteps;
  68087. --step;
  68088. }
  68089. modulo -= numSteps;
  68090. }
  68091. forcedinline void stepToNext() throw()
  68092. {
  68093. modulo += remainder;
  68094. n += step;
  68095. if (modulo > 0)
  68096. {
  68097. modulo -= numSteps;
  68098. ++n;
  68099. }
  68100. }
  68101. int n;
  68102. private:
  68103. int numSteps, step, modulo, remainder;
  68104. };
  68105. const AffineTransform inverseTransform;
  68106. BresenhamInterpolator xBresenham, yBresenham;
  68107. const float pixelOffset;
  68108. const int pixelOffsetInt;
  68109. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator);
  68110. };
  68111. TransformedImageSpanInterpolator interpolator;
  68112. const Image::BitmapData& destData;
  68113. const Image::BitmapData& srcData;
  68114. const int extraAlpha;
  68115. const bool betterQuality;
  68116. const int maxX, maxY;
  68117. int y;
  68118. DestPixelType* linePixels;
  68119. HeapBlock <SrcPixelType> scratchBuffer;
  68120. int scratchSize;
  68121. JUCE_DECLARE_NON_COPYABLE (TransformedImageFillEdgeTableRenderer);
  68122. };
  68123. class ClipRegionBase : public ReferenceCountedObject
  68124. {
  68125. public:
  68126. ClipRegionBase() {}
  68127. virtual ~ClipRegionBase() {}
  68128. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68129. virtual const Ptr clone() const = 0;
  68130. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68131. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68132. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68133. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68134. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68135. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68136. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68137. virtual const Ptr translated (const Point<int>& delta) = 0;
  68138. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68139. virtual const Rectangle<int> getClipBounds() const = 0;
  68140. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68141. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68142. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68143. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68144. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68145. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68146. protected:
  68147. template <class Iterator>
  68148. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68149. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68150. {
  68151. switch (destData.pixelFormat)
  68152. {
  68153. case Image::ARGB:
  68154. switch (srcData.pixelFormat)
  68155. {
  68156. case Image::ARGB:
  68157. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68158. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68159. break;
  68160. case Image::RGB:
  68161. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68162. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68163. break;
  68164. default:
  68165. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68166. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68167. break;
  68168. }
  68169. break;
  68170. case Image::RGB:
  68171. switch (srcData.pixelFormat)
  68172. {
  68173. case Image::ARGB:
  68174. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68175. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68176. break;
  68177. case Image::RGB:
  68178. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68179. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68180. break;
  68181. default:
  68182. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68183. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68184. break;
  68185. }
  68186. break;
  68187. default:
  68188. switch (srcData.pixelFormat)
  68189. {
  68190. case Image::ARGB:
  68191. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68192. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68193. break;
  68194. case Image::RGB:
  68195. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68196. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68197. break;
  68198. default:
  68199. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68200. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68201. break;
  68202. }
  68203. break;
  68204. }
  68205. }
  68206. template <class Iterator>
  68207. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68208. {
  68209. switch (destData.pixelFormat)
  68210. {
  68211. case Image::ARGB:
  68212. switch (srcData.pixelFormat)
  68213. {
  68214. case Image::ARGB:
  68215. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68216. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68217. break;
  68218. case Image::RGB:
  68219. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68220. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68221. break;
  68222. default:
  68223. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68224. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68225. break;
  68226. }
  68227. break;
  68228. case Image::RGB:
  68229. switch (srcData.pixelFormat)
  68230. {
  68231. case Image::ARGB:
  68232. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68233. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68234. break;
  68235. case Image::RGB:
  68236. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68237. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68238. break;
  68239. default:
  68240. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68241. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68242. break;
  68243. }
  68244. break;
  68245. default:
  68246. switch (srcData.pixelFormat)
  68247. {
  68248. case Image::ARGB:
  68249. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68250. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68251. break;
  68252. case Image::RGB:
  68253. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68254. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68255. break;
  68256. default:
  68257. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68258. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68259. break;
  68260. }
  68261. break;
  68262. }
  68263. }
  68264. template <class Iterator, class DestPixelType>
  68265. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68266. {
  68267. jassert (destData.pixelStride == sizeof (DestPixelType));
  68268. if (replaceContents)
  68269. {
  68270. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68271. iter.iterate (r);
  68272. }
  68273. else
  68274. {
  68275. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68276. iter.iterate (r);
  68277. }
  68278. }
  68279. template <class Iterator, class DestPixelType>
  68280. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68281. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68282. {
  68283. jassert (destData.pixelStride == sizeof (DestPixelType));
  68284. if (g.isRadial)
  68285. {
  68286. if (isIdentity)
  68287. {
  68288. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68289. iter.iterate (renderer);
  68290. }
  68291. else
  68292. {
  68293. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68294. iter.iterate (renderer);
  68295. }
  68296. }
  68297. else
  68298. {
  68299. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68300. iter.iterate (renderer);
  68301. }
  68302. }
  68303. };
  68304. class ClipRegion_EdgeTable : public ClipRegionBase
  68305. {
  68306. public:
  68307. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68308. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68309. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68310. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68311. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68312. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68313. ~ClipRegion_EdgeTable() {}
  68314. const Ptr clone() const
  68315. {
  68316. return new ClipRegion_EdgeTable (*this);
  68317. }
  68318. const Ptr applyClipTo (const Ptr& target) const
  68319. {
  68320. return target->clipToEdgeTable (edgeTable);
  68321. }
  68322. const Ptr clipToRectangle (const Rectangle<int>& r)
  68323. {
  68324. edgeTable.clipToRectangle (r);
  68325. return edgeTable.isEmpty() ? 0 : this;
  68326. }
  68327. const Ptr clipToRectangleList (const RectangleList& r)
  68328. {
  68329. RectangleList inverse (edgeTable.getMaximumBounds());
  68330. if (inverse.subtract (r))
  68331. for (RectangleList::Iterator iter (inverse); iter.next();)
  68332. edgeTable.excludeRectangle (*iter.getRectangle());
  68333. return edgeTable.isEmpty() ? 0 : this;
  68334. }
  68335. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68336. {
  68337. edgeTable.excludeRectangle (r);
  68338. return edgeTable.isEmpty() ? 0 : this;
  68339. }
  68340. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68341. {
  68342. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68343. edgeTable.clipToEdgeTable (et);
  68344. return edgeTable.isEmpty() ? 0 : this;
  68345. }
  68346. const Ptr clipToEdgeTable (const EdgeTable& et)
  68347. {
  68348. edgeTable.clipToEdgeTable (et);
  68349. return edgeTable.isEmpty() ? 0 : this;
  68350. }
  68351. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68352. {
  68353. const Image::BitmapData srcData (image, false);
  68354. if (transform.isOnlyTranslation())
  68355. {
  68356. // If our translation doesn't involve any distortion, just use a simple blit..
  68357. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68358. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68359. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68360. {
  68361. const int imageX = ((tx + 128) >> 8);
  68362. const int imageY = ((ty + 128) >> 8);
  68363. if (image.getFormat() == Image::ARGB)
  68364. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68365. else
  68366. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68367. return edgeTable.isEmpty() ? 0 : this;
  68368. }
  68369. }
  68370. if (transform.isSingularity())
  68371. return 0;
  68372. {
  68373. Path p;
  68374. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68375. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68376. edgeTable.clipToEdgeTable (et2);
  68377. }
  68378. if (! edgeTable.isEmpty())
  68379. {
  68380. if (image.getFormat() == Image::ARGB)
  68381. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68382. else
  68383. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68384. }
  68385. return edgeTable.isEmpty() ? 0 : this;
  68386. }
  68387. const Ptr translated (const Point<int>& delta)
  68388. {
  68389. edgeTable.translate ((float) delta.getX(), delta.getY());
  68390. return edgeTable.isEmpty() ? 0 : this;
  68391. }
  68392. bool clipRegionIntersects (const Rectangle<int>& r) const
  68393. {
  68394. return edgeTable.getMaximumBounds().intersects (r);
  68395. }
  68396. const Rectangle<int> getClipBounds() const
  68397. {
  68398. return edgeTable.getMaximumBounds();
  68399. }
  68400. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68401. {
  68402. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68403. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68404. if (! clipped.isEmpty())
  68405. {
  68406. ClipRegion_EdgeTable et (clipped);
  68407. et.edgeTable.clipToEdgeTable (edgeTable);
  68408. et.fillAllWithColour (destData, colour, replaceContents);
  68409. }
  68410. }
  68411. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68412. {
  68413. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68414. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68415. if (! clipped.isEmpty())
  68416. {
  68417. ClipRegion_EdgeTable et (clipped);
  68418. et.edgeTable.clipToEdgeTable (edgeTable);
  68419. et.fillAllWithColour (destData, colour, false);
  68420. }
  68421. }
  68422. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68423. {
  68424. switch (destData.pixelFormat)
  68425. {
  68426. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68427. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68428. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68429. }
  68430. }
  68431. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68432. {
  68433. HeapBlock <PixelARGB> lookupTable;
  68434. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68435. jassert (numLookupEntries > 0);
  68436. switch (destData.pixelFormat)
  68437. {
  68438. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68439. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68440. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68441. }
  68442. }
  68443. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68444. {
  68445. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68446. }
  68447. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68448. {
  68449. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68450. }
  68451. EdgeTable edgeTable;
  68452. private:
  68453. template <class SrcPixelType>
  68454. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68455. {
  68456. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68457. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68458. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68459. edgeTable.getMaximumBounds().getWidth());
  68460. }
  68461. template <class SrcPixelType>
  68462. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68463. {
  68464. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68465. edgeTable.clipToRectangle (r);
  68466. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68467. for (int y = 0; y < r.getHeight(); ++y)
  68468. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68469. }
  68470. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68471. };
  68472. class ClipRegion_RectangleList : public ClipRegionBase
  68473. {
  68474. public:
  68475. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68476. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68477. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68478. ~ClipRegion_RectangleList() {}
  68479. const Ptr clone() const
  68480. {
  68481. return new ClipRegion_RectangleList (*this);
  68482. }
  68483. const Ptr applyClipTo (const Ptr& target) const
  68484. {
  68485. return target->clipToRectangleList (clip);
  68486. }
  68487. const Ptr clipToRectangle (const Rectangle<int>& r)
  68488. {
  68489. clip.clipTo (r);
  68490. return clip.isEmpty() ? 0 : this;
  68491. }
  68492. const Ptr clipToRectangleList (const RectangleList& r)
  68493. {
  68494. clip.clipTo (r);
  68495. return clip.isEmpty() ? 0 : this;
  68496. }
  68497. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68498. {
  68499. clip.subtract (r);
  68500. return clip.isEmpty() ? 0 : this;
  68501. }
  68502. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68503. {
  68504. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68505. }
  68506. const Ptr clipToEdgeTable (const EdgeTable& et)
  68507. {
  68508. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68509. }
  68510. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68511. {
  68512. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68513. }
  68514. const Ptr translated (const Point<int>& delta)
  68515. {
  68516. clip.offsetAll (delta.getX(), delta.getY());
  68517. return clip.isEmpty() ? 0 : this;
  68518. }
  68519. bool clipRegionIntersects (const Rectangle<int>& r) const
  68520. {
  68521. return clip.intersects (r);
  68522. }
  68523. const Rectangle<int> getClipBounds() const
  68524. {
  68525. return clip.getBounds();
  68526. }
  68527. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68528. {
  68529. SubRectangleIterator iter (clip, area);
  68530. switch (destData.pixelFormat)
  68531. {
  68532. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68533. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68534. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68535. }
  68536. }
  68537. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68538. {
  68539. SubRectangleIteratorFloat iter (clip, area);
  68540. switch (destData.pixelFormat)
  68541. {
  68542. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68543. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68544. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68545. }
  68546. }
  68547. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68548. {
  68549. switch (destData.pixelFormat)
  68550. {
  68551. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68552. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68553. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68554. }
  68555. }
  68556. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68557. {
  68558. HeapBlock <PixelARGB> lookupTable;
  68559. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68560. jassert (numLookupEntries > 0);
  68561. switch (destData.pixelFormat)
  68562. {
  68563. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68564. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68565. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68566. }
  68567. }
  68568. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68569. {
  68570. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68571. }
  68572. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68573. {
  68574. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68575. }
  68576. RectangleList clip;
  68577. template <class Renderer>
  68578. void iterate (Renderer& r) const throw()
  68579. {
  68580. RectangleList::Iterator iter (clip);
  68581. while (iter.next())
  68582. {
  68583. const Rectangle<int> rect (*iter.getRectangle());
  68584. const int x = rect.getX();
  68585. const int w = rect.getWidth();
  68586. jassert (w > 0);
  68587. const int bottom = rect.getBottom();
  68588. for (int y = rect.getY(); y < bottom; ++y)
  68589. {
  68590. r.setEdgeTableYPos (y);
  68591. r.handleEdgeTableLineFull (x, w);
  68592. }
  68593. }
  68594. }
  68595. private:
  68596. class SubRectangleIterator
  68597. {
  68598. public:
  68599. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68600. : clip (clip_), area (area_)
  68601. {
  68602. }
  68603. template <class Renderer>
  68604. void iterate (Renderer& r) const throw()
  68605. {
  68606. RectangleList::Iterator iter (clip);
  68607. while (iter.next())
  68608. {
  68609. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68610. if (! rect.isEmpty())
  68611. {
  68612. const int x = rect.getX();
  68613. const int w = rect.getWidth();
  68614. const int bottom = rect.getBottom();
  68615. for (int y = rect.getY(); y < bottom; ++y)
  68616. {
  68617. r.setEdgeTableYPos (y);
  68618. r.handleEdgeTableLineFull (x, w);
  68619. }
  68620. }
  68621. }
  68622. }
  68623. private:
  68624. const RectangleList& clip;
  68625. const Rectangle<int> area;
  68626. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator);
  68627. };
  68628. class SubRectangleIteratorFloat
  68629. {
  68630. public:
  68631. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68632. : clip (clip_), area (area_)
  68633. {
  68634. }
  68635. template <class Renderer>
  68636. void iterate (Renderer& r) const throw()
  68637. {
  68638. int left = roundToInt (area.getX() * 256.0f);
  68639. int top = roundToInt (area.getY() * 256.0f);
  68640. int right = roundToInt (area.getRight() * 256.0f);
  68641. int bottom = roundToInt (area.getBottom() * 256.0f);
  68642. int totalTop, totalLeft, totalBottom, totalRight;
  68643. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68644. if ((top >> 8) == (bottom >> 8))
  68645. {
  68646. topAlpha = bottom - top;
  68647. bottomAlpha = 0;
  68648. totalTop = top >> 8;
  68649. totalBottom = bottom = top = totalTop + 1;
  68650. }
  68651. else
  68652. {
  68653. if ((top & 255) == 0)
  68654. {
  68655. topAlpha = 0;
  68656. top = totalTop = (top >> 8);
  68657. }
  68658. else
  68659. {
  68660. topAlpha = 255 - (top & 255);
  68661. totalTop = (top >> 8);
  68662. top = totalTop + 1;
  68663. }
  68664. bottomAlpha = bottom & 255;
  68665. bottom >>= 8;
  68666. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68667. }
  68668. if ((left >> 8) == (right >> 8))
  68669. {
  68670. leftAlpha = right - left;
  68671. rightAlpha = 0;
  68672. totalLeft = (left >> 8);
  68673. totalRight = right = left = totalLeft + 1;
  68674. }
  68675. else
  68676. {
  68677. if ((left & 255) == 0)
  68678. {
  68679. leftAlpha = 0;
  68680. left = totalLeft = (left >> 8);
  68681. }
  68682. else
  68683. {
  68684. leftAlpha = 255 - (left & 255);
  68685. totalLeft = (left >> 8);
  68686. left = totalLeft + 1;
  68687. }
  68688. rightAlpha = right & 255;
  68689. right >>= 8;
  68690. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68691. }
  68692. RectangleList::Iterator iter (clip);
  68693. while (iter.next())
  68694. {
  68695. const int clipLeft = iter.getRectangle()->getX();
  68696. const int clipRight = iter.getRectangle()->getRight();
  68697. const int clipTop = iter.getRectangle()->getY();
  68698. const int clipBottom = iter.getRectangle()->getBottom();
  68699. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68700. {
  68701. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68702. {
  68703. if (topAlpha != 0 && totalTop >= clipTop)
  68704. {
  68705. r.setEdgeTableYPos (totalTop);
  68706. r.handleEdgeTablePixel (left, topAlpha);
  68707. }
  68708. const int endY = jmin (bottom, clipBottom);
  68709. for (int y = jmax (clipTop, top); y < endY; ++y)
  68710. {
  68711. r.setEdgeTableYPos (y);
  68712. r.handleEdgeTablePixelFull (left);
  68713. }
  68714. if (bottomAlpha != 0 && bottom < clipBottom)
  68715. {
  68716. r.setEdgeTableYPos (bottom);
  68717. r.handleEdgeTablePixel (left, bottomAlpha);
  68718. }
  68719. }
  68720. else
  68721. {
  68722. const int clippedLeft = jmax (left, clipLeft);
  68723. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68724. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68725. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68726. if (topAlpha != 0 && totalTop >= clipTop)
  68727. {
  68728. r.setEdgeTableYPos (totalTop);
  68729. if (doLeftAlpha)
  68730. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68731. if (clippedWidth > 0)
  68732. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68733. if (doRightAlpha)
  68734. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68735. }
  68736. const int endY = jmin (bottom, clipBottom);
  68737. for (int y = jmax (clipTop, top); y < endY; ++y)
  68738. {
  68739. r.setEdgeTableYPos (y);
  68740. if (doLeftAlpha)
  68741. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68742. if (clippedWidth > 0)
  68743. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68744. if (doRightAlpha)
  68745. r.handleEdgeTablePixel (right, rightAlpha);
  68746. }
  68747. if (bottomAlpha != 0 && bottom < clipBottom)
  68748. {
  68749. r.setEdgeTableYPos (bottom);
  68750. if (doLeftAlpha)
  68751. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68752. if (clippedWidth > 0)
  68753. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68754. if (doRightAlpha)
  68755. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68756. }
  68757. }
  68758. }
  68759. }
  68760. }
  68761. private:
  68762. const RectangleList& clip;
  68763. const Rectangle<float>& area;
  68764. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat);
  68765. };
  68766. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68767. };
  68768. }
  68769. class LowLevelGraphicsSoftwareRenderer::SavedState
  68770. {
  68771. public:
  68772. SavedState (const Image& image_, const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68773. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68774. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68775. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68776. {
  68777. }
  68778. SavedState (const Image& image_, const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68779. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68780. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68781. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68782. {
  68783. }
  68784. SavedState (const SavedState& other)
  68785. : image (other.image), clip (other.clip), complexTransform (other.complexTransform),
  68786. xOffset (other.xOffset), yOffset (other.yOffset), compositionAlpha (other.compositionAlpha),
  68787. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType),
  68788. interpolationQuality (other.interpolationQuality)
  68789. {
  68790. }
  68791. void setOrigin (const int x, const int y) throw()
  68792. {
  68793. if (isOnlyTranslated)
  68794. {
  68795. xOffset += x;
  68796. yOffset += y;
  68797. }
  68798. else
  68799. {
  68800. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  68801. }
  68802. }
  68803. void addTransform (const AffineTransform& t)
  68804. {
  68805. if ((! isOnlyTranslated)
  68806. || (! t.isOnlyTranslation())
  68807. || (int) (t.getTranslationX() * 256.0f) != 0
  68808. || (int) (t.getTranslationY() * 256.0f) != 0)
  68809. {
  68810. complexTransform = getTransformWith (t);
  68811. isOnlyTranslated = false;
  68812. }
  68813. else
  68814. {
  68815. xOffset += (int) t.getTranslationX();
  68816. yOffset += (int) t.getTranslationY();
  68817. }
  68818. }
  68819. float getScaleFactor() const
  68820. {
  68821. return isOnlyTranslated ? 1.0f : complexTransform.getScaleFactor();
  68822. }
  68823. bool clipToRectangle (const Rectangle<int>& r)
  68824. {
  68825. if (clip != 0)
  68826. {
  68827. if (isOnlyTranslated)
  68828. {
  68829. cloneClipIfMultiplyReferenced();
  68830. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68831. }
  68832. else
  68833. {
  68834. Path p;
  68835. p.addRectangle (r);
  68836. clipToPath (p, AffineTransform::identity);
  68837. }
  68838. }
  68839. return clip != 0;
  68840. }
  68841. bool clipToRectangleList (const RectangleList& r)
  68842. {
  68843. if (clip != 0)
  68844. {
  68845. if (isOnlyTranslated)
  68846. {
  68847. cloneClipIfMultiplyReferenced();
  68848. RectangleList offsetList (r);
  68849. offsetList.offsetAll (xOffset, yOffset);
  68850. clip = clip->clipToRectangleList (offsetList);
  68851. }
  68852. else
  68853. {
  68854. clipToPath (r.toPath(), AffineTransform::identity);
  68855. }
  68856. }
  68857. return clip != 0;
  68858. }
  68859. bool excludeClipRectangle (const Rectangle<int>& r)
  68860. {
  68861. if (clip != 0)
  68862. {
  68863. cloneClipIfMultiplyReferenced();
  68864. if (isOnlyTranslated)
  68865. {
  68866. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68867. }
  68868. else
  68869. {
  68870. Path p;
  68871. p.addRectangle (r.toFloat());
  68872. p.applyTransform (complexTransform);
  68873. p.addRectangle (clip->getClipBounds().toFloat());
  68874. p.setUsingNonZeroWinding (false);
  68875. clip = clip->clipToPath (p, AffineTransform::identity);
  68876. }
  68877. }
  68878. return clip != 0;
  68879. }
  68880. void clipToPath (const Path& p, const AffineTransform& transform)
  68881. {
  68882. if (clip != 0)
  68883. {
  68884. cloneClipIfMultiplyReferenced();
  68885. clip = clip->clipToPath (p, getTransformWith (transform));
  68886. }
  68887. }
  68888. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& t)
  68889. {
  68890. if (clip != 0)
  68891. {
  68892. if (sourceImage.hasAlphaChannel())
  68893. {
  68894. cloneClipIfMultiplyReferenced();
  68895. clip = clip->clipToImageAlpha (sourceImage, getTransformWith (t),
  68896. interpolationQuality != Graphics::lowResamplingQuality);
  68897. }
  68898. else
  68899. {
  68900. Path p;
  68901. p.addRectangle (sourceImage.getBounds());
  68902. clipToPath (p, t);
  68903. }
  68904. }
  68905. }
  68906. bool clipRegionIntersects (const Rectangle<int>& r) const
  68907. {
  68908. if (clip != 0)
  68909. {
  68910. if (isOnlyTranslated)
  68911. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68912. else
  68913. return getClipBounds().intersects (r);
  68914. }
  68915. return false;
  68916. }
  68917. const Rectangle<int> getUntransformedClipBounds() const
  68918. {
  68919. return clip != 0 ? clip->getClipBounds() : Rectangle<int>();
  68920. }
  68921. const Rectangle<int> getClipBounds() const
  68922. {
  68923. if (clip != 0)
  68924. {
  68925. if (isOnlyTranslated)
  68926. return clip->getClipBounds().translated (-xOffset, -yOffset);
  68927. else
  68928. return clip->getClipBounds().toFloat().transformed (complexTransform.inverted()).getSmallestIntegerContainer();
  68929. }
  68930. return Rectangle<int>();
  68931. }
  68932. SavedState* beginTransparencyLayer (float opacity)
  68933. {
  68934. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68935. SavedState* s = new SavedState (*this);
  68936. s->image = Image (Image::ARGB, layerBounds.getWidth(), layerBounds.getHeight(), true);
  68937. s->compositionAlpha = opacity;
  68938. if (s->isOnlyTranslated)
  68939. {
  68940. s->xOffset -= layerBounds.getX();
  68941. s->yOffset -= layerBounds.getY();
  68942. }
  68943. else
  68944. {
  68945. s->complexTransform = s->complexTransform.followedBy (AffineTransform::translation ((float) -layerBounds.getX(),
  68946. (float) -layerBounds.getY()));
  68947. }
  68948. s->cloneClipIfMultiplyReferenced();
  68949. s->clip = s->clip->translated (-layerBounds.getPosition());
  68950. return s;
  68951. }
  68952. void endTransparencyLayer (SavedState& layerState)
  68953. {
  68954. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68955. const ScopedPointer<LowLevelGraphicsContext> g (image.createLowLevelContext());
  68956. g->setOpacity (layerState.compositionAlpha);
  68957. g->drawImage (layerState.image, AffineTransform::translation ((float) layerBounds.getX(),
  68958. (float) layerBounds.getY()), false);
  68959. }
  68960. void fillRect (const Rectangle<int>& r, const bool replaceContents)
  68961. {
  68962. if (clip != 0)
  68963. {
  68964. if (isOnlyTranslated)
  68965. {
  68966. if (fillType.isColour())
  68967. {
  68968. Image::BitmapData destData (image, true);
  68969. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68970. }
  68971. else
  68972. {
  68973. const Rectangle<int> totalClip (clip->getClipBounds());
  68974. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68975. if (! clipped.isEmpty())
  68976. fillShape (new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68977. }
  68978. }
  68979. else
  68980. {
  68981. Path p;
  68982. p.addRectangle (r);
  68983. fillPath (p, AffineTransform::identity);
  68984. }
  68985. }
  68986. }
  68987. void fillRect (const Rectangle<float>& r)
  68988. {
  68989. if (clip != 0)
  68990. {
  68991. if (isOnlyTranslated)
  68992. {
  68993. if (fillType.isColour())
  68994. {
  68995. Image::BitmapData destData (image, true);
  68996. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68997. }
  68998. else
  68999. {
  69000. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  69001. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  69002. if (! clipped.isEmpty())
  69003. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  69004. }
  69005. }
  69006. else
  69007. {
  69008. Path p;
  69009. p.addRectangle (r);
  69010. fillPath (p, AffineTransform::identity);
  69011. }
  69012. }
  69013. }
  69014. void fillPath (const Path& path, const AffineTransform& transform)
  69015. {
  69016. if (clip != 0)
  69017. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  69018. }
  69019. void fillEdgeTable (const EdgeTable& edgeTable, const float x, const int y)
  69020. {
  69021. jassert (isOnlyTranslated);
  69022. if (clip != 0)
  69023. {
  69024. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  69025. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  69026. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  69027. fillShape (shapeToFill, false);
  69028. }
  69029. }
  69030. void fillShape (SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  69031. {
  69032. jassert (clip != 0);
  69033. shapeToFill = clip->applyClipTo (shapeToFill);
  69034. if (shapeToFill != 0)
  69035. {
  69036. Image::BitmapData destData (image, true);
  69037. if (fillType.isGradient())
  69038. {
  69039. jassert (! replaceContents); // that option is just for solid colours
  69040. ColourGradient g2 (*(fillType.gradient));
  69041. g2.multiplyOpacity (fillType.getOpacity());
  69042. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  69043. const bool isIdentity = transform.isOnlyTranslation();
  69044. if (isIdentity)
  69045. {
  69046. // If our translation doesn't involve any distortion, we can speed it up..
  69047. g2.point1.applyTransform (transform);
  69048. g2.point2.applyTransform (transform);
  69049. transform = AffineTransform::identity;
  69050. }
  69051. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  69052. }
  69053. else if (fillType.isTiledImage())
  69054. {
  69055. renderImage (fillType.image, fillType.transform, shapeToFill);
  69056. }
  69057. else
  69058. {
  69059. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  69060. }
  69061. }
  69062. }
  69063. void renderImage (const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  69064. {
  69065. const AffineTransform transform (getTransformWith (t));
  69066. const Image::BitmapData destData (image, true);
  69067. const Image::BitmapData srcData (sourceImage, false);
  69068. const int alpha = fillType.colour.getAlpha();
  69069. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  69070. if (transform.isOnlyTranslation())
  69071. {
  69072. // If our translation doesn't involve any distortion, just use a simple blit..
  69073. int tx = (int) (transform.getTranslationX() * 256.0f);
  69074. int ty = (int) (transform.getTranslationY() * 256.0f);
  69075. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  69076. {
  69077. tx = ((tx + 128) >> 8);
  69078. ty = ((ty + 128) >> 8);
  69079. if (tiledFillClipRegion != 0)
  69080. {
  69081. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  69082. }
  69083. else
  69084. {
  69085. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (image.getBounds())));
  69086. c = clip->applyClipTo (c);
  69087. if (c != 0)
  69088. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69089. }
  69090. return;
  69091. }
  69092. }
  69093. if (transform.isSingularity())
  69094. return;
  69095. if (tiledFillClipRegion != 0)
  69096. {
  69097. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69098. }
  69099. else
  69100. {
  69101. Path p;
  69102. p.addRectangle (sourceImage.getBounds());
  69103. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69104. c = c->clipToPath (p, transform);
  69105. if (c != 0)
  69106. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69107. }
  69108. }
  69109. Image image;
  69110. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69111. private:
  69112. AffineTransform complexTransform;
  69113. int xOffset, yOffset;
  69114. float compositionAlpha;
  69115. public:
  69116. bool isOnlyTranslated;
  69117. Font font;
  69118. FillType fillType;
  69119. Graphics::ResamplingQuality interpolationQuality;
  69120. private:
  69121. void cloneClipIfMultiplyReferenced()
  69122. {
  69123. if (clip->getReferenceCount() > 1)
  69124. clip = clip->clone();
  69125. }
  69126. const AffineTransform getTransform() const
  69127. {
  69128. if (isOnlyTranslated)
  69129. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  69130. return complexTransform;
  69131. }
  69132. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  69133. {
  69134. if (isOnlyTranslated)
  69135. return userTransform.translated ((float) xOffset, (float) yOffset);
  69136. return userTransform.followedBy (complexTransform);
  69137. }
  69138. SavedState& operator= (const SavedState&);
  69139. };
  69140. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69141. : image (image_),
  69142. currentState (new SavedState (image_, image_.getBounds(), 0, 0))
  69143. {
  69144. }
  69145. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69146. const RectangleList& initialClip)
  69147. : image (image_),
  69148. currentState (new SavedState (image_, initialClip, xOffset, yOffset))
  69149. {
  69150. }
  69151. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69152. {
  69153. }
  69154. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69155. {
  69156. return false;
  69157. }
  69158. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69159. {
  69160. currentState->setOrigin (x, y);
  69161. }
  69162. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  69163. {
  69164. currentState->addTransform (transform);
  69165. }
  69166. float LowLevelGraphicsSoftwareRenderer::getScaleFactor()
  69167. {
  69168. return currentState->getScaleFactor();
  69169. }
  69170. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69171. {
  69172. return currentState->clipToRectangle (r);
  69173. }
  69174. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69175. {
  69176. return currentState->clipToRectangleList (clipRegion);
  69177. }
  69178. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69179. {
  69180. currentState->excludeClipRectangle (r);
  69181. }
  69182. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69183. {
  69184. currentState->clipToPath (path, transform);
  69185. }
  69186. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69187. {
  69188. currentState->clipToImageAlpha (sourceImage, transform);
  69189. }
  69190. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69191. {
  69192. return currentState->clipRegionIntersects (r);
  69193. }
  69194. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69195. {
  69196. return currentState->getClipBounds();
  69197. }
  69198. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69199. {
  69200. return currentState->clip == 0;
  69201. }
  69202. void LowLevelGraphicsSoftwareRenderer::saveState()
  69203. {
  69204. stateStack.add (new SavedState (*currentState));
  69205. }
  69206. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69207. {
  69208. SavedState* const top = stateStack.getLast();
  69209. if (top != 0)
  69210. {
  69211. currentState = top;
  69212. stateStack.removeLast (1, false);
  69213. }
  69214. else
  69215. {
  69216. jassertfalse; // trying to pop with an empty stack!
  69217. }
  69218. }
  69219. void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
  69220. {
  69221. saveState();
  69222. currentState = currentState->beginTransparencyLayer (opacity);
  69223. }
  69224. void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
  69225. {
  69226. const ScopedPointer<SavedState> layer (currentState);
  69227. restoreState();
  69228. currentState->endTransparencyLayer (*layer);
  69229. }
  69230. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69231. {
  69232. currentState->fillType = fillType;
  69233. }
  69234. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69235. {
  69236. currentState->fillType.setOpacity (newOpacity);
  69237. }
  69238. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69239. {
  69240. currentState->interpolationQuality = quality;
  69241. }
  69242. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69243. {
  69244. currentState->fillRect (r, replaceExistingContents);
  69245. }
  69246. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69247. {
  69248. currentState->fillPath (path, transform);
  69249. }
  69250. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69251. {
  69252. currentState->renderImage (sourceImage, transform, fillEntireClipAsTiles ? currentState->clip : 0);
  69253. }
  69254. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69255. {
  69256. Path p;
  69257. p.addLineSegment (line, 1.0f);
  69258. fillPath (p, AffineTransform::identity);
  69259. }
  69260. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69261. {
  69262. if (bottom > top)
  69263. currentState->fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69264. }
  69265. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69266. {
  69267. if (right > left)
  69268. currentState->fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  69269. }
  69270. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69271. {
  69272. public:
  69273. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69274. void draw (SavedState& state, float x, const float y) const
  69275. {
  69276. if (snapToIntegerCoordinate)
  69277. x = std::floor (x + 0.5f);
  69278. if (edgeTable != 0)
  69279. state.fillEdgeTable (*edgeTable, x, roundToInt (y));
  69280. }
  69281. void generate (const Font& newFont, const int glyphNumber)
  69282. {
  69283. font = newFont;
  69284. snapToIntegerCoordinate = newFont.getTypeface()->isHinted();
  69285. glyph = glyphNumber;
  69286. edgeTable = 0;
  69287. Path glyphPath;
  69288. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69289. if (! glyphPath.isEmpty())
  69290. {
  69291. const float fontHeight = font.getHeight();
  69292. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69293. #if JUCE_MAC || JUCE_IOS
  69294. .translated (0.0f, -0.5f)
  69295. #endif
  69296. );
  69297. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69298. glyphPath, transform);
  69299. }
  69300. }
  69301. Font font;
  69302. int glyph, lastAccessCount;
  69303. bool snapToIntegerCoordinate;
  69304. private:
  69305. ScopedPointer <EdgeTable> edgeTable;
  69306. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyph);
  69307. };
  69308. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69309. {
  69310. public:
  69311. GlyphCache()
  69312. : accessCounter (0), hits (0), misses (0)
  69313. {
  69314. addNewGlyphSlots (120);
  69315. }
  69316. ~GlyphCache()
  69317. {
  69318. clearSingletonInstance();
  69319. }
  69320. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69321. void drawGlyph (SavedState& state, const Font& font, const int glyphNumber, float x, float y)
  69322. {
  69323. ++accessCounter;
  69324. int oldestCounter = std::numeric_limits<int>::max();
  69325. CachedGlyph* oldest = 0;
  69326. for (int i = glyphs.size(); --i >= 0;)
  69327. {
  69328. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69329. if (glyph->glyph == glyphNumber && glyph->font == font)
  69330. {
  69331. ++hits;
  69332. glyph->lastAccessCount = accessCounter;
  69333. glyph->draw (state, x, y);
  69334. return;
  69335. }
  69336. if (glyph->lastAccessCount <= oldestCounter)
  69337. {
  69338. oldestCounter = glyph->lastAccessCount;
  69339. oldest = glyph;
  69340. }
  69341. }
  69342. if (hits + ++misses > (glyphs.size() << 4))
  69343. {
  69344. if (misses * 2 > hits)
  69345. addNewGlyphSlots (32);
  69346. hits = misses = 0;
  69347. oldest = glyphs.getLast();
  69348. }
  69349. jassert (oldest != 0);
  69350. oldest->lastAccessCount = accessCounter;
  69351. oldest->generate (font, glyphNumber);
  69352. oldest->draw (state, x, y);
  69353. }
  69354. private:
  69355. friend class OwnedArray <CachedGlyph>;
  69356. OwnedArray <CachedGlyph> glyphs;
  69357. int accessCounter, hits, misses;
  69358. void addNewGlyphSlots (int num)
  69359. {
  69360. while (--num >= 0)
  69361. glyphs.add (new CachedGlyph());
  69362. }
  69363. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache);
  69364. };
  69365. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69366. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69367. {
  69368. currentState->font = newFont;
  69369. }
  69370. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69371. {
  69372. return currentState->font;
  69373. }
  69374. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69375. {
  69376. Font& f = currentState->font;
  69377. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69378. {
  69379. GlyphCache::getInstance()->drawGlyph (*currentState, f, glyphNumber,
  69380. transform.getTranslationX(),
  69381. transform.getTranslationY());
  69382. }
  69383. else
  69384. {
  69385. Path p;
  69386. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69387. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69388. }
  69389. }
  69390. #if JUCE_MSVC
  69391. #pragma warning (pop)
  69392. #if JUCE_DEBUG
  69393. #pragma optimize ("", on) // resets optimisations to the project defaults
  69394. #endif
  69395. #endif
  69396. END_JUCE_NAMESPACE
  69397. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69398. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69399. BEGIN_JUCE_NAMESPACE
  69400. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69401. : flags (other.flags)
  69402. {
  69403. }
  69404. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69405. {
  69406. flags = other.flags;
  69407. return *this;
  69408. }
  69409. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69410. const double dx, const double dy, const double dw, const double dh) const throw()
  69411. {
  69412. if (w == 0 || h == 0)
  69413. return;
  69414. if ((flags & stretchToFit) != 0)
  69415. {
  69416. x = dx;
  69417. y = dy;
  69418. w = dw;
  69419. h = dh;
  69420. }
  69421. else
  69422. {
  69423. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69424. : jmin (dw / w, dh / h);
  69425. if ((flags & onlyReduceInSize) != 0)
  69426. scale = jmin (scale, 1.0);
  69427. if ((flags & onlyIncreaseInSize) != 0)
  69428. scale = jmax (scale, 1.0);
  69429. w *= scale;
  69430. h *= scale;
  69431. if ((flags & xLeft) != 0)
  69432. x = dx;
  69433. else if ((flags & xRight) != 0)
  69434. x = dx + dw - w;
  69435. else
  69436. x = dx + (dw - w) * 0.5;
  69437. if ((flags & yTop) != 0)
  69438. y = dy;
  69439. else if ((flags & yBottom) != 0)
  69440. y = dy + dh - h;
  69441. else
  69442. y = dy + (dh - h) * 0.5;
  69443. }
  69444. }
  69445. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69446. {
  69447. if (source.isEmpty())
  69448. return AffineTransform::identity;
  69449. float newX = destination.getX();
  69450. float newY = destination.getY();
  69451. float scaleX = destination.getWidth() / source.getWidth();
  69452. float scaleY = destination.getHeight() / source.getHeight();
  69453. if ((flags & stretchToFit) == 0)
  69454. {
  69455. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69456. : jmin (scaleX, scaleY);
  69457. if ((flags & onlyReduceInSize) != 0)
  69458. scaleX = jmin (scaleX, 1.0f);
  69459. if ((flags & onlyIncreaseInSize) != 0)
  69460. scaleX = jmax (scaleX, 1.0f);
  69461. scaleY = scaleX;
  69462. if ((flags & xRight) != 0)
  69463. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69464. else if ((flags & xLeft) == 0)
  69465. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69466. if ((flags & yBottom) != 0)
  69467. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69468. else if ((flags & yTop) == 0)
  69469. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69470. }
  69471. return AffineTransform::translation (-source.getX(), -source.getY())
  69472. .scaled (scaleX, scaleY)
  69473. .translated (newX, newY);
  69474. }
  69475. END_JUCE_NAMESPACE
  69476. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69477. /*** Start of inlined file: juce_Drawable.cpp ***/
  69478. BEGIN_JUCE_NAMESPACE
  69479. Drawable::Drawable()
  69480. {
  69481. setInterceptsMouseClicks (false, false);
  69482. setPaintingIsUnclipped (true);
  69483. }
  69484. Drawable::~Drawable()
  69485. {
  69486. }
  69487. void Drawable::draw (Graphics& g, float opacity, const AffineTransform& transform) const
  69488. {
  69489. const_cast <Drawable*> (this)->nonConstDraw (g, opacity, transform);
  69490. }
  69491. void Drawable::nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform)
  69492. {
  69493. Graphics::ScopedSaveState ss (g);
  69494. const float oldOpacity = getAlpha();
  69495. setAlpha (opacity);
  69496. g.addTransform (AffineTransform::translation ((float) -originRelativeToComponent.getX(),
  69497. (float) -originRelativeToComponent.getY())
  69498. .followedBy (getTransform())
  69499. .followedBy (transform));
  69500. if (! g.isClipEmpty())
  69501. paintEntireComponent (g, false);
  69502. setAlpha (oldOpacity);
  69503. }
  69504. void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
  69505. {
  69506. draw (g, opacity, AffineTransform::translation (x, y));
  69507. }
  69508. void Drawable::drawWithin (Graphics& g, const Rectangle<float>& destArea, const RectanglePlacement& placement, float opacity) const
  69509. {
  69510. draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
  69511. }
  69512. DrawableComposite* Drawable::getParent() const
  69513. {
  69514. return dynamic_cast <DrawableComposite*> (getParentComponent());
  69515. }
  69516. void Drawable::transformContextToCorrectOrigin (Graphics& g)
  69517. {
  69518. g.setOrigin (originRelativeToComponent.getX(),
  69519. originRelativeToComponent.getY());
  69520. }
  69521. void Drawable::parentHierarchyChanged()
  69522. {
  69523. setBoundsToEnclose (getDrawableBounds());
  69524. }
  69525. void Drawable::setBoundsToEnclose (const Rectangle<float>& area)
  69526. {
  69527. Drawable* const parent = getParent();
  69528. Point<int> parentOrigin;
  69529. if (parent != 0)
  69530. parentOrigin = parent->originRelativeToComponent;
  69531. const Rectangle<int> newBounds (area.getSmallestIntegerContainer() + parentOrigin);
  69532. originRelativeToComponent = parentOrigin - newBounds.getPosition();
  69533. setBounds (newBounds);
  69534. }
  69535. void Drawable::setOriginWithOriginalSize (const Point<float>& originWithinParent)
  69536. {
  69537. setTransform (AffineTransform::translation (originWithinParent.getX(), originWithinParent.getY()));
  69538. }
  69539. void Drawable::setTransformToFit (const Rectangle<float>& area, const RectanglePlacement& placement)
  69540. {
  69541. if (! area.isEmpty())
  69542. setTransform (placement.getTransformToFit (getDrawableBounds(), area));
  69543. }
  69544. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69545. {
  69546. Drawable* result = 0;
  69547. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69548. if (image.isValid())
  69549. {
  69550. DrawableImage* const di = new DrawableImage();
  69551. di->setImage (image);
  69552. result = di;
  69553. }
  69554. else
  69555. {
  69556. const String asString (String::createStringFromData (data, (int) numBytes));
  69557. XmlDocument doc (asString);
  69558. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69559. if (outer != 0 && outer->hasTagName ("svg"))
  69560. {
  69561. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69562. if (svg != 0)
  69563. result = Drawable::createFromSVG (*svg);
  69564. }
  69565. }
  69566. return result;
  69567. }
  69568. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69569. {
  69570. MemoryOutputStream mo;
  69571. mo.writeFromInputStream (dataSource, -1);
  69572. return createFromImageData (mo.getData(), mo.getDataSize());
  69573. }
  69574. Drawable* Drawable::createFromImageFile (const File& file)
  69575. {
  69576. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69577. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69578. }
  69579. template <class DrawableClass>
  69580. class DrawableTypeHandler : public ComponentBuilder::TypeHandler
  69581. {
  69582. public:
  69583. DrawableTypeHandler()
  69584. : ComponentBuilder::TypeHandler (DrawableClass::valueTreeType)
  69585. {
  69586. }
  69587. Component* addNewComponentFromState (const ValueTree& state, Component* parent)
  69588. {
  69589. DrawableClass* const d = new DrawableClass();
  69590. if (parent != 0)
  69591. parent->addAndMakeVisible (d);
  69592. updateComponentFromState (d, state);
  69593. return d;
  69594. }
  69595. void updateComponentFromState (Component* component, const ValueTree& state)
  69596. {
  69597. DrawableClass* const d = dynamic_cast <DrawableClass*> (component);
  69598. jassert (d != 0);
  69599. d->refreshFromValueTree (state, *this->getBuilder());
  69600. }
  69601. };
  69602. void Drawable::registerDrawableTypeHandlers (ComponentBuilder& builder)
  69603. {
  69604. builder.registerTypeHandler (new DrawableTypeHandler <DrawablePath>());
  69605. builder.registerTypeHandler (new DrawableTypeHandler <DrawableComposite>());
  69606. builder.registerTypeHandler (new DrawableTypeHandler <DrawableRectangle>());
  69607. builder.registerTypeHandler (new DrawableTypeHandler <DrawableImage>());
  69608. builder.registerTypeHandler (new DrawableTypeHandler <DrawableText>());
  69609. }
  69610. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider)
  69611. {
  69612. ComponentBuilder builder (tree);
  69613. builder.setImageProvider (imageProvider);
  69614. registerDrawableTypeHandlers (builder);
  69615. ScopedPointer<Component> comp (builder.createComponent());
  69616. Drawable* const d = dynamic_cast<Drawable*> (static_cast <Component*> (comp));
  69617. if (d != 0)
  69618. comp.release();
  69619. return d;
  69620. }
  69621. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69622. : state (state_)
  69623. {
  69624. }
  69625. const String Drawable::ValueTreeWrapperBase::getID() const
  69626. {
  69627. return state [ComponentBuilder::idProperty];
  69628. }
  69629. void Drawable::ValueTreeWrapperBase::setID (const String& newID)
  69630. {
  69631. if (newID.isEmpty())
  69632. state.removeProperty (ComponentBuilder::idProperty, 0);
  69633. else
  69634. state.setProperty (ComponentBuilder::idProperty, newID, 0);
  69635. }
  69636. END_JUCE_NAMESPACE
  69637. /*** End of inlined file: juce_Drawable.cpp ***/
  69638. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69639. BEGIN_JUCE_NAMESPACE
  69640. DrawableShape::DrawableShape()
  69641. : strokeType (0.0f),
  69642. mainFill (Colours::black),
  69643. strokeFill (Colours::black)
  69644. {
  69645. }
  69646. DrawableShape::DrawableShape (const DrawableShape& other)
  69647. : strokeType (other.strokeType),
  69648. mainFill (other.mainFill),
  69649. strokeFill (other.strokeFill)
  69650. {
  69651. }
  69652. DrawableShape::~DrawableShape()
  69653. {
  69654. }
  69655. class DrawableShape::RelativePositioner : public RelativeCoordinatePositionerBase
  69656. {
  69657. public:
  69658. RelativePositioner (DrawableShape& component_, const DrawableShape::RelativeFillType& fill_, bool isMainFill_)
  69659. : RelativeCoordinatePositionerBase (component_),
  69660. owner (component_),
  69661. fill (fill_),
  69662. isMainFill (isMainFill_)
  69663. {
  69664. }
  69665. bool registerCoordinates()
  69666. {
  69667. bool ok = addPoint (fill.gradientPoint1);
  69668. ok = addPoint (fill.gradientPoint2) && ok;
  69669. return addPoint (fill.gradientPoint3) && ok;
  69670. }
  69671. void applyToComponentBounds()
  69672. {
  69673. if (isMainFill ? owner.mainFill.recalculateCoords (this)
  69674. : owner.strokeFill.recalculateCoords (this))
  69675. owner.repaint();
  69676. }
  69677. private:
  69678. DrawableShape& owner;
  69679. const DrawableShape::RelativeFillType fill;
  69680. const bool isMainFill;
  69681. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  69682. };
  69683. void DrawableShape::setFill (const FillType& newFill)
  69684. {
  69685. setFill (RelativeFillType (newFill));
  69686. }
  69687. void DrawableShape::setStrokeFill (const FillType& newFill)
  69688. {
  69689. setStrokeFill (RelativeFillType (newFill));
  69690. }
  69691. void DrawableShape::setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  69692. ScopedPointer<RelativeCoordinatePositionerBase>& positioner)
  69693. {
  69694. if (fill != newFill)
  69695. {
  69696. fill = newFill;
  69697. positioner = 0;
  69698. if (fill.isDynamic())
  69699. {
  69700. positioner = new RelativePositioner (*this, fill, true);
  69701. positioner->apply();
  69702. }
  69703. else
  69704. {
  69705. fill.recalculateCoords (0);
  69706. }
  69707. repaint();
  69708. }
  69709. }
  69710. void DrawableShape::setFill (const RelativeFillType& newFill)
  69711. {
  69712. setFillInternal (mainFill, newFill, mainFillPositioner);
  69713. }
  69714. void DrawableShape::setStrokeFill (const RelativeFillType& newFill)
  69715. {
  69716. setFillInternal (strokeFill, newFill, strokeFillPositioner);
  69717. }
  69718. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69719. {
  69720. if (strokeType != newStrokeType)
  69721. {
  69722. strokeType = newStrokeType;
  69723. strokeChanged();
  69724. }
  69725. }
  69726. void DrawableShape::setStrokeThickness (const float newThickness)
  69727. {
  69728. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69729. }
  69730. bool DrawableShape::isStrokeVisible() const throw()
  69731. {
  69732. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.fill.isInvisible();
  69733. }
  69734. void DrawableShape::refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider* imageProvider)
  69735. {
  69736. setFill (newState.getFill (FillAndStrokeState::fill, imageProvider));
  69737. setStrokeFill (newState.getFill (FillAndStrokeState::stroke, imageProvider));
  69738. }
  69739. void DrawableShape::writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69740. {
  69741. state.setFill (FillAndStrokeState::fill, mainFill, imageProvider, undoManager);
  69742. state.setFill (FillAndStrokeState::stroke, strokeFill, imageProvider, undoManager);
  69743. state.setStrokeType (strokeType, undoManager);
  69744. }
  69745. void DrawableShape::paint (Graphics& g)
  69746. {
  69747. transformContextToCorrectOrigin (g);
  69748. g.setFillType (mainFill.fill);
  69749. g.fillPath (path);
  69750. if (isStrokeVisible())
  69751. {
  69752. g.setFillType (strokeFill.fill);
  69753. g.fillPath (strokePath);
  69754. }
  69755. }
  69756. void DrawableShape::pathChanged()
  69757. {
  69758. strokeChanged();
  69759. }
  69760. void DrawableShape::strokeChanged()
  69761. {
  69762. strokePath.clear();
  69763. strokeType.createStrokedPath (strokePath, path, AffineTransform::identity, 4.0f);
  69764. setBoundsToEnclose (getDrawableBounds());
  69765. repaint();
  69766. }
  69767. const Rectangle<float> DrawableShape::getDrawableBounds() const
  69768. {
  69769. if (isStrokeVisible())
  69770. return strokePath.getBounds();
  69771. else
  69772. return path.getBounds();
  69773. }
  69774. bool DrawableShape::hitTest (int x, int y) const
  69775. {
  69776. const float globalX = (float) (x - originRelativeToComponent.getX());
  69777. const float globalY = (float) (y - originRelativeToComponent.getY());
  69778. return path.contains (globalX, globalY)
  69779. || (isStrokeVisible() && strokePath.contains (globalX, globalY));
  69780. }
  69781. DrawableShape::RelativeFillType::RelativeFillType()
  69782. {
  69783. }
  69784. DrawableShape::RelativeFillType::RelativeFillType (const FillType& fill_)
  69785. : fill (fill_)
  69786. {
  69787. if (fill.isGradient())
  69788. {
  69789. const ColourGradient& g = *fill.gradient;
  69790. gradientPoint1 = g.point1.transformedBy (fill.transform);
  69791. gradientPoint2 = g.point2.transformedBy (fill.transform);
  69792. gradientPoint3 = Point<float> (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69793. g.point1.getY() + g.point1.getX() - g.point2.getX())
  69794. .transformedBy (fill.transform);
  69795. fill.transform = AffineTransform::identity;
  69796. }
  69797. }
  69798. DrawableShape::RelativeFillType::RelativeFillType (const RelativeFillType& other)
  69799. : fill (other.fill),
  69800. gradientPoint1 (other.gradientPoint1),
  69801. gradientPoint2 (other.gradientPoint2),
  69802. gradientPoint3 (other.gradientPoint3)
  69803. {
  69804. }
  69805. DrawableShape::RelativeFillType& DrawableShape::RelativeFillType::operator= (const RelativeFillType& other)
  69806. {
  69807. fill = other.fill;
  69808. gradientPoint1 = other.gradientPoint1;
  69809. gradientPoint2 = other.gradientPoint2;
  69810. gradientPoint3 = other.gradientPoint3;
  69811. return *this;
  69812. }
  69813. bool DrawableShape::RelativeFillType::operator== (const RelativeFillType& other) const
  69814. {
  69815. return fill == other.fill
  69816. && ((! fill.isGradient())
  69817. || (gradientPoint1 == other.gradientPoint1
  69818. && gradientPoint2 == other.gradientPoint2
  69819. && gradientPoint3 == other.gradientPoint3));
  69820. }
  69821. bool DrawableShape::RelativeFillType::operator!= (const RelativeFillType& other) const
  69822. {
  69823. return ! operator== (other);
  69824. }
  69825. bool DrawableShape::RelativeFillType::recalculateCoords (Expression::EvaluationContext* context)
  69826. {
  69827. if (fill.isGradient())
  69828. {
  69829. const Point<float> g1 (gradientPoint1.resolve (context));
  69830. const Point<float> g2 (gradientPoint2.resolve (context));
  69831. AffineTransform t;
  69832. ColourGradient& g = *fill.gradient;
  69833. if (g.isRadial)
  69834. {
  69835. const Point<float> g3 (gradientPoint3.resolve (context));
  69836. const Point<float> g3Source (g1.getX() + g2.getY() - g1.getY(),
  69837. g1.getY() + g1.getX() - g2.getX());
  69838. t = AffineTransform::fromTargetPoints (g1.getX(), g1.getY(), g1.getX(), g1.getY(),
  69839. g2.getX(), g2.getY(), g2.getX(), g2.getY(),
  69840. g3Source.getX(), g3Source.getY(), g3.getX(), g3.getY());
  69841. }
  69842. if (g.point1 != g1 || g.point2 != g2 || fill.transform != t)
  69843. {
  69844. g.point1 = g1;
  69845. g.point2 = g2;
  69846. fill.transform = t;
  69847. return true;
  69848. }
  69849. }
  69850. return false;
  69851. }
  69852. bool DrawableShape::RelativeFillType::isDynamic() const
  69853. {
  69854. return gradientPoint1.isDynamic() || gradientPoint2.isDynamic() || gradientPoint3.isDynamic();
  69855. }
  69856. void DrawableShape::RelativeFillType::writeTo (ValueTree& v, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69857. {
  69858. if (fill.isColour())
  69859. {
  69860. v.setProperty (FillAndStrokeState::type, "solid", undoManager);
  69861. v.setProperty (FillAndStrokeState::colour, String::toHexString ((int) fill.colour.getARGB()), undoManager);
  69862. }
  69863. else if (fill.isGradient())
  69864. {
  69865. v.setProperty (FillAndStrokeState::type, "gradient", undoManager);
  69866. v.setProperty (FillAndStrokeState::gradientPoint1, gradientPoint1.toString(), undoManager);
  69867. v.setProperty (FillAndStrokeState::gradientPoint2, gradientPoint2.toString(), undoManager);
  69868. v.setProperty (FillAndStrokeState::gradientPoint3, gradientPoint3.toString(), undoManager);
  69869. const ColourGradient& cg = *fill.gradient;
  69870. v.setProperty (FillAndStrokeState::radial, cg.isRadial, undoManager);
  69871. String s;
  69872. for (int i = 0; i < cg.getNumColours(); ++i)
  69873. s << ' ' << cg.getColourPosition (i)
  69874. << ' ' << String::toHexString ((int) cg.getColour(i).getARGB());
  69875. v.setProperty (FillAndStrokeState::colours, s.trimStart(), undoManager);
  69876. }
  69877. else if (fill.isTiledImage())
  69878. {
  69879. v.setProperty (FillAndStrokeState::type, "image", undoManager);
  69880. if (imageProvider != 0)
  69881. v.setProperty (FillAndStrokeState::imageId, imageProvider->getIdentifierForImage (fill.image), undoManager);
  69882. if (fill.getOpacity() < 1.0f)
  69883. v.setProperty (FillAndStrokeState::imageOpacity, fill.getOpacity(), undoManager);
  69884. else
  69885. v.removeProperty (FillAndStrokeState::imageOpacity, undoManager);
  69886. }
  69887. else
  69888. {
  69889. jassertfalse;
  69890. }
  69891. }
  69892. bool DrawableShape::RelativeFillType::readFrom (const ValueTree& v, ComponentBuilder::ImageProvider* imageProvider)
  69893. {
  69894. const String newType (v [FillAndStrokeState::type].toString());
  69895. if (newType == "solid")
  69896. {
  69897. const String colourString (v [FillAndStrokeState::colour].toString());
  69898. fill.setColour (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69899. : (uint32) colourString.getHexValue32()));
  69900. return true;
  69901. }
  69902. else if (newType == "gradient")
  69903. {
  69904. ColourGradient g;
  69905. g.isRadial = v [FillAndStrokeState::radial];
  69906. StringArray colourSteps;
  69907. colourSteps.addTokens (v [FillAndStrokeState::colours].toString(), false);
  69908. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69909. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69910. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69911. fill.setGradient (g);
  69912. gradientPoint1 = RelativePoint (v [FillAndStrokeState::gradientPoint1]);
  69913. gradientPoint2 = RelativePoint (v [FillAndStrokeState::gradientPoint2]);
  69914. gradientPoint3 = RelativePoint (v [FillAndStrokeState::gradientPoint3]);
  69915. return true;
  69916. }
  69917. else if (newType == "image")
  69918. {
  69919. Image im;
  69920. if (imageProvider != 0)
  69921. im = imageProvider->getImageForIdentifier (v [FillAndStrokeState::imageId]);
  69922. fill.setTiledImage (im, AffineTransform::identity);
  69923. fill.setOpacity ((float) v.getProperty (FillAndStrokeState::imageOpacity, 1.0f));
  69924. return true;
  69925. }
  69926. jassertfalse;
  69927. return false;
  69928. }
  69929. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69930. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69931. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69932. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69933. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69934. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69935. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69936. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69937. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69938. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69939. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69940. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69941. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69942. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69943. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69944. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69945. : Drawable::ValueTreeWrapperBase (state_)
  69946. {
  69947. }
  69948. const DrawableShape::RelativeFillType DrawableShape::FillAndStrokeState::getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider* imageProvider) const
  69949. {
  69950. DrawableShape::RelativeFillType f;
  69951. f.readFrom (state.getChildWithName (fillOrStrokeType), imageProvider);
  69952. return f;
  69953. }
  69954. ValueTree DrawableShape::FillAndStrokeState::getFillState (const Identifier& fillOrStrokeType)
  69955. {
  69956. ValueTree v (state.getChildWithName (fillOrStrokeType));
  69957. if (v.isValid())
  69958. return v;
  69959. setFill (fillOrStrokeType, FillType (Colours::black), 0, 0);
  69960. return getFillState (fillOrStrokeType);
  69961. }
  69962. void DrawableShape::FillAndStrokeState::setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  69963. ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager)
  69964. {
  69965. ValueTree v (state.getOrCreateChildWithName (fillOrStrokeType, undoManager));
  69966. newFill.writeTo (v, imageProvider, undoManager);
  69967. }
  69968. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69969. {
  69970. const String jointStyleString (state [jointStyle].toString());
  69971. const String capStyleString (state [capStyle].toString());
  69972. return PathStrokeType (state [strokeWidth],
  69973. jointStyleString == "curved" ? PathStrokeType::curved
  69974. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69975. : PathStrokeType::mitered),
  69976. capStyleString == "square" ? PathStrokeType::square
  69977. : (capStyleString == "round" ? PathStrokeType::rounded
  69978. : PathStrokeType::butt));
  69979. }
  69980. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69981. {
  69982. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69983. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69984. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69985. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69986. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69987. }
  69988. END_JUCE_NAMESPACE
  69989. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69990. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69991. BEGIN_JUCE_NAMESPACE
  69992. DrawableComposite::DrawableComposite()
  69993. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f)),
  69994. updateBoundsReentrant (false)
  69995. {
  69996. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69997. RelativeCoordinate (100.0),
  69998. RelativeCoordinate (0.0),
  69999. RelativeCoordinate (100.0)));
  70000. }
  70001. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  70002. : bounds (other.bounds),
  70003. markersX (other.markersX),
  70004. markersY (other.markersY),
  70005. updateBoundsReentrant (false)
  70006. {
  70007. for (int i = 0; i < other.getNumChildComponents(); ++i)
  70008. {
  70009. const Drawable* const d = dynamic_cast <const Drawable*> (other.getChildComponent(i));
  70010. if (d != 0)
  70011. addAndMakeVisible (d->createCopy());
  70012. }
  70013. }
  70014. DrawableComposite::~DrawableComposite()
  70015. {
  70016. deleteAllChildren();
  70017. }
  70018. Drawable* DrawableComposite::createCopy() const
  70019. {
  70020. return new DrawableComposite (*this);
  70021. }
  70022. const Rectangle<float> DrawableComposite::getDrawableBounds() const
  70023. {
  70024. Rectangle<float> r;
  70025. for (int i = getNumChildComponents(); --i >= 0;)
  70026. {
  70027. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70028. if (d != 0)
  70029. r = r.getUnion (d->isTransformed() ? d->getDrawableBounds().transformed (d->getTransform())
  70030. : d->getDrawableBounds());
  70031. }
  70032. return r;
  70033. }
  70034. MarkerList* DrawableComposite::getMarkers (bool xAxis)
  70035. {
  70036. return xAxis ? &markersX : &markersY;
  70037. }
  70038. const RelativeRectangle DrawableComposite::getContentArea() const
  70039. {
  70040. jassert (markersX.getNumMarkers() >= 2 && markersX.getMarker (0)->name == contentLeftMarkerName && markersX.getMarker (1)->name == contentRightMarkerName);
  70041. jassert (markersY.getNumMarkers() >= 2 && markersY.getMarker (0)->name == contentTopMarkerName && markersY.getMarker (1)->name == contentBottomMarkerName);
  70042. return RelativeRectangle (markersX.getMarker(0)->position, markersX.getMarker(1)->position,
  70043. markersY.getMarker(0)->position, markersY.getMarker(1)->position);
  70044. }
  70045. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  70046. {
  70047. markersX.setMarker (contentLeftMarkerName, newArea.left);
  70048. markersX.setMarker (contentRightMarkerName, newArea.right);
  70049. markersY.setMarker (contentTopMarkerName, newArea.top);
  70050. markersY.setMarker (contentBottomMarkerName, newArea.bottom);
  70051. }
  70052. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBounds)
  70053. {
  70054. if (bounds != newBounds)
  70055. {
  70056. bounds = newBounds;
  70057. if (bounds.isDynamic())
  70058. {
  70059. Drawable::Positioner<DrawableComposite>* const p = new Drawable::Positioner<DrawableComposite> (*this);
  70060. setPositioner (p);
  70061. p->apply();
  70062. }
  70063. else
  70064. {
  70065. setPositioner (0);
  70066. recalculateCoordinates (0);
  70067. }
  70068. }
  70069. }
  70070. void DrawableComposite::resetBoundingBoxToContentArea()
  70071. {
  70072. const RelativeRectangle content (getContentArea());
  70073. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70074. RelativePoint (content.right, content.top),
  70075. RelativePoint (content.left, content.bottom)));
  70076. }
  70077. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  70078. {
  70079. const Rectangle<float> activeArea (getDrawableBounds());
  70080. setContentArea (RelativeRectangle (RelativeCoordinate (activeArea.getX()),
  70081. RelativeCoordinate (activeArea.getRight()),
  70082. RelativeCoordinate (activeArea.getY()),
  70083. RelativeCoordinate (activeArea.getBottom())));
  70084. resetBoundingBoxToContentArea();
  70085. }
  70086. bool DrawableComposite::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70087. {
  70088. bool ok = positioner.addPoint (bounds.topLeft);
  70089. ok = positioner.addPoint (bounds.topRight) && ok;
  70090. return positioner.addPoint (bounds.bottomLeft) && ok;
  70091. }
  70092. void DrawableComposite::recalculateCoordinates (Expression::EvaluationContext* context)
  70093. {
  70094. Point<float> resolved[3];
  70095. bounds.resolveThreePoints (resolved, context);
  70096. const Rectangle<float> content (getContentArea().resolve (context));
  70097. AffineTransform t (AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  70098. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  70099. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY()));
  70100. if (t.isSingularity())
  70101. t = AffineTransform::identity;
  70102. setTransform (t);
  70103. }
  70104. void DrawableComposite::parentHierarchyChanged()
  70105. {
  70106. DrawableComposite* parent = getParent();
  70107. if (parent != 0)
  70108. originRelativeToComponent = parent->originRelativeToComponent - getPosition();
  70109. }
  70110. void DrawableComposite::childBoundsChanged (Component*)
  70111. {
  70112. updateBoundsToFitChildren();
  70113. }
  70114. void DrawableComposite::childrenChanged()
  70115. {
  70116. updateBoundsToFitChildren();
  70117. }
  70118. struct RentrancyCheckSetter
  70119. {
  70120. RentrancyCheckSetter (bool& b_) : b (b_) { b_ = true; }
  70121. ~RentrancyCheckSetter() { b = false; }
  70122. private:
  70123. bool& b;
  70124. JUCE_DECLARE_NON_COPYABLE (RentrancyCheckSetter);
  70125. };
  70126. void DrawableComposite::updateBoundsToFitChildren()
  70127. {
  70128. if (! updateBoundsReentrant)
  70129. {
  70130. const RentrancyCheckSetter checkSetter (updateBoundsReentrant);
  70131. Rectangle<int> childArea;
  70132. for (int i = getNumChildComponents(); --i >= 0;)
  70133. childArea = childArea.getUnion (getChildComponent(i)->getBoundsInParent());
  70134. const Point<int> delta (childArea.getPosition());
  70135. childArea += getPosition();
  70136. if (childArea != getBounds())
  70137. {
  70138. if (! delta.isOrigin())
  70139. {
  70140. originRelativeToComponent -= delta;
  70141. for (int i = getNumChildComponents(); --i >= 0;)
  70142. {
  70143. Component* const c = getChildComponent(i);
  70144. if (c != 0)
  70145. c->setBounds (c->getBounds() - delta);
  70146. }
  70147. }
  70148. setBounds (childArea);
  70149. }
  70150. }
  70151. }
  70152. const char* const DrawableComposite::contentLeftMarkerName = "left";
  70153. const char* const DrawableComposite::contentRightMarkerName = "right";
  70154. const char* const DrawableComposite::contentTopMarkerName = "top";
  70155. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  70156. const Identifier DrawableComposite::valueTreeType ("Group");
  70157. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  70158. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  70159. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70160. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  70161. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  70162. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  70163. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70164. : ValueTreeWrapperBase (state_)
  70165. {
  70166. jassert (state.hasType (valueTreeType));
  70167. }
  70168. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70169. {
  70170. return state.getChildWithName (childGroupTag);
  70171. }
  70172. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70173. {
  70174. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70175. }
  70176. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70177. {
  70178. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70179. state.getProperty (topRight, "100, 0"),
  70180. state.getProperty (bottomLeft, "0, 100"));
  70181. }
  70182. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70183. {
  70184. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70185. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70186. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70187. }
  70188. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70189. {
  70190. const RelativeRectangle content (getContentArea());
  70191. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70192. RelativePoint (content.right, content.top),
  70193. RelativePoint (content.left, content.bottom)), undoManager);
  70194. }
  70195. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70196. {
  70197. MarkerList::ValueTreeWrapper markersX (getMarkerList (true));
  70198. MarkerList::ValueTreeWrapper markersY (getMarkerList (false));
  70199. return RelativeRectangle (markersX.getMarker (markersX.getMarkerState (0)).position,
  70200. markersX.getMarker (markersX.getMarkerState (1)).position,
  70201. markersY.getMarker (markersY.getMarkerState (0)).position,
  70202. markersY.getMarker (markersY.getMarkerState (1)).position);
  70203. }
  70204. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70205. {
  70206. MarkerList::ValueTreeWrapper markersX (getMarkerListCreating (true, 0));
  70207. MarkerList::ValueTreeWrapper markersY (getMarkerListCreating (false, 0));
  70208. markersX.setMarker (MarkerList::Marker (contentLeftMarkerName, newArea.left), undoManager);
  70209. markersX.setMarker (MarkerList::Marker (contentRightMarkerName, newArea.right), undoManager);
  70210. markersY.setMarker (MarkerList::Marker (contentTopMarkerName, newArea.top), undoManager);
  70211. markersY.setMarker (MarkerList::Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70212. }
  70213. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70214. {
  70215. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70216. }
  70217. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70218. {
  70219. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70220. }
  70221. void DrawableComposite::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70222. {
  70223. const ValueTreeWrapper wrapper (tree);
  70224. setComponentID (wrapper.getID());
  70225. wrapper.getMarkerList (true).applyTo (markersX);
  70226. wrapper.getMarkerList (false).applyTo (markersY);
  70227. setBoundingBox (wrapper.getBoundingBox());
  70228. builder.updateChildComponents (*this, wrapper.getChildList());
  70229. }
  70230. const ValueTree DrawableComposite::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70231. {
  70232. ValueTree tree (valueTreeType);
  70233. ValueTreeWrapper v (tree);
  70234. v.setID (getComponentID());
  70235. v.setBoundingBox (bounds, 0);
  70236. ValueTree childList (v.getChildListCreating (0));
  70237. for (int i = getNumChildComponents(); --i >= 0;)
  70238. {
  70239. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70240. jassert (d != 0); // You can't save a mix of Drawables and normal components!
  70241. childList.addChild (d->createValueTree (imageProvider), -1, 0);
  70242. }
  70243. v.getMarkerListCreating (true, 0).readFrom (markersX, 0);
  70244. v.getMarkerListCreating (false, 0).readFrom (markersY, 0);
  70245. return tree;
  70246. }
  70247. END_JUCE_NAMESPACE
  70248. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70249. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70250. BEGIN_JUCE_NAMESPACE
  70251. DrawableImage::DrawableImage()
  70252. : image (0),
  70253. opacity (1.0f),
  70254. overlayColour (0x00000000)
  70255. {
  70256. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70257. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70258. }
  70259. DrawableImage::DrawableImage (const DrawableImage& other)
  70260. : image (other.image),
  70261. opacity (other.opacity),
  70262. overlayColour (other.overlayColour),
  70263. bounds (other.bounds)
  70264. {
  70265. }
  70266. DrawableImage::~DrawableImage()
  70267. {
  70268. }
  70269. void DrawableImage::setImage (const Image& imageToUse)
  70270. {
  70271. image = imageToUse;
  70272. setBounds (imageToUse.getBounds());
  70273. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70274. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70275. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70276. recalculateCoordinates (0);
  70277. repaint();
  70278. }
  70279. void DrawableImage::setOpacity (const float newOpacity)
  70280. {
  70281. opacity = newOpacity;
  70282. }
  70283. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70284. {
  70285. overlayColour = newOverlayColour;
  70286. }
  70287. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70288. {
  70289. if (bounds != newBounds)
  70290. {
  70291. bounds = newBounds;
  70292. if (bounds.isDynamic())
  70293. {
  70294. Drawable::Positioner<DrawableImage>* const p = new Drawable::Positioner<DrawableImage> (*this);
  70295. setPositioner (p);
  70296. p->apply();
  70297. }
  70298. else
  70299. {
  70300. setPositioner (0);
  70301. recalculateCoordinates (0);
  70302. }
  70303. }
  70304. }
  70305. bool DrawableImage::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70306. {
  70307. bool ok = positioner.addPoint (bounds.topLeft);
  70308. ok = positioner.addPoint (bounds.topRight) && ok;
  70309. return positioner.addPoint (bounds.bottomLeft) && ok;
  70310. }
  70311. void DrawableImage::recalculateCoordinates (Expression::EvaluationContext* context)
  70312. {
  70313. if (image.isValid())
  70314. {
  70315. Point<float> resolved[3];
  70316. bounds.resolveThreePoints (resolved, context);
  70317. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70318. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70319. AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70320. tr.getX(), tr.getY(),
  70321. bl.getX(), bl.getY()));
  70322. if (t.isSingularity())
  70323. t = AffineTransform::identity;
  70324. setTransform (t);
  70325. }
  70326. }
  70327. void DrawableImage::paint (Graphics& g)
  70328. {
  70329. if (image.isValid())
  70330. {
  70331. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70332. {
  70333. g.setOpacity (opacity);
  70334. g.drawImageAt (image, 0, 0, false);
  70335. }
  70336. if (! overlayColour.isTransparent())
  70337. {
  70338. g.setColour (overlayColour.withMultipliedAlpha (opacity));
  70339. g.drawImageAt (image, 0, 0, true);
  70340. }
  70341. }
  70342. }
  70343. const Rectangle<float> DrawableImage::getDrawableBounds() const
  70344. {
  70345. return image.getBounds().toFloat();
  70346. }
  70347. bool DrawableImage::hitTest (int x, int y) const
  70348. {
  70349. return (! image.isNull())
  70350. && image.getPixelAt (x, y).getAlpha() >= 127;
  70351. }
  70352. Drawable* DrawableImage::createCopy() const
  70353. {
  70354. return new DrawableImage (*this);
  70355. }
  70356. const Identifier DrawableImage::valueTreeType ("Image");
  70357. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70358. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70359. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70360. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70361. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70362. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70363. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70364. : ValueTreeWrapperBase (state_)
  70365. {
  70366. jassert (state.hasType (valueTreeType));
  70367. }
  70368. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70369. {
  70370. return state [image];
  70371. }
  70372. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70373. {
  70374. return state.getPropertyAsValue (image, undoManager);
  70375. }
  70376. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70377. {
  70378. state.setProperty (image, newIdentifier, undoManager);
  70379. }
  70380. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70381. {
  70382. return (float) state.getProperty (opacity, 1.0);
  70383. }
  70384. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70385. {
  70386. if (! state.hasProperty (opacity))
  70387. state.setProperty (opacity, 1.0, undoManager);
  70388. return state.getPropertyAsValue (opacity, undoManager);
  70389. }
  70390. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70391. {
  70392. state.setProperty (opacity, newOpacity, undoManager);
  70393. }
  70394. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70395. {
  70396. return Colour (state [overlay].toString().getHexValue32());
  70397. }
  70398. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70399. {
  70400. if (newColour.isTransparent())
  70401. state.removeProperty (overlay, undoManager);
  70402. else
  70403. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70404. }
  70405. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70406. {
  70407. return state.getPropertyAsValue (overlay, undoManager);
  70408. }
  70409. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70410. {
  70411. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70412. state.getProperty (topRight, "100, 0"),
  70413. state.getProperty (bottomLeft, "0, 100"));
  70414. }
  70415. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70416. {
  70417. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70418. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70419. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70420. }
  70421. void DrawableImage::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70422. {
  70423. const ValueTreeWrapper controller (tree);
  70424. setComponentID (controller.getID());
  70425. const float newOpacity = controller.getOpacity();
  70426. const Colour newOverlayColour (controller.getOverlayColour());
  70427. Image newImage;
  70428. const var imageIdentifier (controller.getImageIdentifier());
  70429. jassert (builder.getImageProvider() != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70430. if (builder.getImageProvider() != 0)
  70431. newImage = builder.getImageProvider()->getImageForIdentifier (imageIdentifier);
  70432. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70433. if (bounds != newBounds || newOpacity != opacity
  70434. || overlayColour != newOverlayColour || image != newImage)
  70435. {
  70436. repaint();
  70437. opacity = newOpacity;
  70438. overlayColour = newOverlayColour;
  70439. if (image != newImage)
  70440. setImage (newImage);
  70441. setBoundingBox (newBounds);
  70442. }
  70443. }
  70444. const ValueTree DrawableImage::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70445. {
  70446. ValueTree tree (valueTreeType);
  70447. ValueTreeWrapper v (tree);
  70448. v.setID (getComponentID());
  70449. v.setOpacity (opacity, 0);
  70450. v.setOverlayColour (overlayColour, 0);
  70451. v.setBoundingBox (bounds, 0);
  70452. if (image.isValid())
  70453. {
  70454. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70455. if (imageProvider != 0)
  70456. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70457. }
  70458. return tree;
  70459. }
  70460. END_JUCE_NAMESPACE
  70461. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70462. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70463. BEGIN_JUCE_NAMESPACE
  70464. DrawablePath::DrawablePath()
  70465. {
  70466. }
  70467. DrawablePath::DrawablePath (const DrawablePath& other)
  70468. : DrawableShape (other)
  70469. {
  70470. if (other.relativePath != 0)
  70471. setPath (*other.relativePath);
  70472. else
  70473. setPath (other.path);
  70474. }
  70475. DrawablePath::~DrawablePath()
  70476. {
  70477. }
  70478. Drawable* DrawablePath::createCopy() const
  70479. {
  70480. return new DrawablePath (*this);
  70481. }
  70482. void DrawablePath::setPath (const Path& newPath)
  70483. {
  70484. path = newPath;
  70485. pathChanged();
  70486. }
  70487. const Path& DrawablePath::getPath() const
  70488. {
  70489. return path;
  70490. }
  70491. const Path& DrawablePath::getStrokePath() const
  70492. {
  70493. return strokePath;
  70494. }
  70495. void DrawablePath::applyRelativePath (const RelativePointPath& newRelativePath, Expression::EvaluationContext* context)
  70496. {
  70497. Path newPath;
  70498. newRelativePath.createPath (newPath, context);
  70499. if (path != newPath)
  70500. {
  70501. path.swapWithPath (newPath);
  70502. pathChanged();
  70503. }
  70504. }
  70505. class DrawablePath::RelativePositioner : public RelativeCoordinatePositionerBase
  70506. {
  70507. public:
  70508. RelativePositioner (DrawablePath& component_)
  70509. : RelativeCoordinatePositionerBase (component_),
  70510. owner (component_)
  70511. {
  70512. }
  70513. bool registerCoordinates()
  70514. {
  70515. bool ok = true;
  70516. jassert (owner.relativePath != 0);
  70517. const RelativePointPath& path = *owner.relativePath;
  70518. for (int i = 0; i < path.elements.size(); ++i)
  70519. {
  70520. RelativePointPath::ElementBase* const e = path.elements.getUnchecked(i);
  70521. int numPoints;
  70522. RelativePoint* const points = e->getControlPoints (numPoints);
  70523. for (int j = numPoints; --j >= 0;)
  70524. ok = addPoint (points[j]) && ok;
  70525. }
  70526. return ok;
  70527. }
  70528. void applyToComponentBounds()
  70529. {
  70530. jassert (owner.relativePath != 0);
  70531. owner.applyRelativePath (*owner.relativePath, this);
  70532. }
  70533. private:
  70534. DrawablePath& owner;
  70535. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  70536. };
  70537. void DrawablePath::setPath (const RelativePointPath& newRelativePath)
  70538. {
  70539. if (newRelativePath.containsAnyDynamicPoints())
  70540. {
  70541. if (relativePath == 0 || newRelativePath != *relativePath)
  70542. {
  70543. relativePath = new RelativePointPath (newRelativePath);
  70544. RelativePositioner* const p = new RelativePositioner (*this);
  70545. setPositioner (p);
  70546. p->apply();
  70547. }
  70548. }
  70549. else
  70550. {
  70551. relativePath = 0;
  70552. applyRelativePath (newRelativePath, 0);
  70553. }
  70554. }
  70555. const Identifier DrawablePath::valueTreeType ("Path");
  70556. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70557. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70558. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70559. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70560. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70561. : FillAndStrokeState (state_)
  70562. {
  70563. jassert (state.hasType (valueTreeType));
  70564. }
  70565. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70566. {
  70567. return state.getOrCreateChildWithName (path, 0);
  70568. }
  70569. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70570. {
  70571. return state [nonZeroWinding];
  70572. }
  70573. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70574. {
  70575. state.setProperty (nonZeroWinding, b, undoManager);
  70576. }
  70577. void DrawablePath::ValueTreeWrapper::readFrom (const RelativePointPath& relativePath, UndoManager* undoManager)
  70578. {
  70579. setUsesNonZeroWinding (relativePath.usesNonZeroWinding, undoManager);
  70580. ValueTree pathTree (getPathState());
  70581. pathTree.removeAllChildren (undoManager);
  70582. for (int i = 0; i < relativePath.elements.size(); ++i)
  70583. pathTree.addChild (relativePath.elements.getUnchecked(i)->createTree(), -1, undoManager);
  70584. }
  70585. void DrawablePath::ValueTreeWrapper::writeTo (RelativePointPath& relativePath) const
  70586. {
  70587. relativePath.usesNonZeroWinding = usesNonZeroWinding();
  70588. RelativePoint points[3];
  70589. const ValueTree pathTree (state.getChildWithName (path));
  70590. const int num = pathTree.getNumChildren();
  70591. for (int i = 0; i < num; ++i)
  70592. {
  70593. const Element e (pathTree.getChild(i));
  70594. const int numCps = e.getNumControlPoints();
  70595. for (int j = 0; j < numCps; ++j)
  70596. points[j] = e.getControlPoint (j);
  70597. const Identifier type (e.getType());
  70598. RelativePointPath::ElementBase* newElement = 0;
  70599. if (type == Element::startSubPathElement) newElement = new RelativePointPath::StartSubPath (points[0]);
  70600. else if (type == Element::closeSubPathElement) newElement = new RelativePointPath::CloseSubPath();
  70601. else if (type == Element::lineToElement) newElement = new RelativePointPath::LineTo (points[0]);
  70602. else if (type == Element::quadraticToElement) newElement = new RelativePointPath::QuadraticTo (points[0], points[1]);
  70603. else if (type == Element::cubicToElement) newElement = new RelativePointPath::CubicTo (points[0], points[1], points[2]);
  70604. else jassertfalse;
  70605. relativePath.addElement (newElement);
  70606. }
  70607. }
  70608. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70609. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70610. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70611. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70612. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70613. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70614. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70615. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70616. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70617. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70618. : state (state_)
  70619. {
  70620. }
  70621. DrawablePath::ValueTreeWrapper::Element::~Element()
  70622. {
  70623. }
  70624. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70625. {
  70626. return ValueTreeWrapper (state.getParent().getParent());
  70627. }
  70628. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70629. {
  70630. return Element (state.getSibling (-1));
  70631. }
  70632. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70633. {
  70634. const Identifier i (state.getType());
  70635. if (i == startSubPathElement || i == lineToElement) return 1;
  70636. if (i == quadraticToElement) return 2;
  70637. if (i == cubicToElement) return 3;
  70638. return 0;
  70639. }
  70640. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70641. {
  70642. jassert (index >= 0 && index < getNumControlPoints());
  70643. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70644. }
  70645. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70646. {
  70647. jassert (index >= 0 && index < getNumControlPoints());
  70648. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70649. }
  70650. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70651. {
  70652. jassert (index >= 0 && index < getNumControlPoints());
  70653. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70654. }
  70655. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70656. {
  70657. const Identifier i (state.getType());
  70658. if (i == startSubPathElement)
  70659. return getControlPoint (0);
  70660. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70661. return getPreviousElement().getEndPoint();
  70662. }
  70663. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70664. {
  70665. const Identifier i (state.getType());
  70666. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70667. if (i == quadraticToElement) return getControlPoint (1);
  70668. if (i == cubicToElement) return getControlPoint (2);
  70669. jassert (i == closeSubPathElement);
  70670. return RelativePoint();
  70671. }
  70672. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* context) const
  70673. {
  70674. const Identifier i (state.getType());
  70675. if (i == lineToElement || i == closeSubPathElement)
  70676. return getEndPoint().resolve (context).getDistanceFrom (getStartPoint().resolve (context));
  70677. if (i == cubicToElement)
  70678. {
  70679. Path p;
  70680. p.startNewSubPath (getStartPoint().resolve (context));
  70681. p.cubicTo (getControlPoint (0).resolve (context), getControlPoint (1).resolve (context), getControlPoint (2).resolve (context));
  70682. return p.getLength();
  70683. }
  70684. if (i == quadraticToElement)
  70685. {
  70686. Path p;
  70687. p.startNewSubPath (getStartPoint().resolve (context));
  70688. p.quadraticTo (getControlPoint (0).resolve (context), getControlPoint (1).resolve (context));
  70689. return p.getLength();
  70690. }
  70691. jassert (i == startSubPathElement);
  70692. return 0;
  70693. }
  70694. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70695. {
  70696. return state [mode].toString();
  70697. }
  70698. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70699. {
  70700. if (state.hasType (cubicToElement))
  70701. state.setProperty (mode, newMode, undoManager);
  70702. }
  70703. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70704. {
  70705. const Identifier i (state.getType());
  70706. if (i == quadraticToElement || i == cubicToElement)
  70707. {
  70708. ValueTree newState (lineToElement);
  70709. Element e (newState);
  70710. e.setControlPoint (0, getEndPoint(), undoManager);
  70711. state = newState;
  70712. }
  70713. }
  70714. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* context, UndoManager* undoManager)
  70715. {
  70716. const Identifier i (state.getType());
  70717. if (i == lineToElement || i == quadraticToElement)
  70718. {
  70719. ValueTree newState (cubicToElement);
  70720. Element e (newState);
  70721. const RelativePoint start (getStartPoint());
  70722. const RelativePoint end (getEndPoint());
  70723. const Point<float> startResolved (start.resolve (context));
  70724. const Point<float> endResolved (end.resolve (context));
  70725. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70726. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70727. e.setControlPoint (2, end, undoManager);
  70728. state = newState;
  70729. }
  70730. }
  70731. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70732. {
  70733. const Identifier i (state.getType());
  70734. if (i != startSubPathElement)
  70735. {
  70736. ValueTree newState (startSubPathElement);
  70737. Element e (newState);
  70738. e.setControlPoint (0, getEndPoint(), undoManager);
  70739. state = newState;
  70740. }
  70741. }
  70742. namespace DrawablePathHelpers
  70743. {
  70744. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70745. {
  70746. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70747. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70748. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70749. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70750. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70751. return newCp1 + (newCp2 - newCp1) * proportion;
  70752. }
  70753. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70754. {
  70755. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70756. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70757. return mid1 + (mid2 - mid1) * proportion;
  70758. }
  70759. }
  70760. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* context) const
  70761. {
  70762. using namespace DrawablePathHelpers;
  70763. const Identifier type (state.getType());
  70764. float bestProp = 0;
  70765. if (type == cubicToElement)
  70766. {
  70767. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70768. const Point<float> points[] = { rp1.resolve (context), rp2.resolve (context), rp3.resolve (context), rp4.resolve (context) };
  70769. float bestDistance = std::numeric_limits<float>::max();
  70770. for (int i = 110; --i >= 0;)
  70771. {
  70772. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70773. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70774. const float distance = centre.getDistanceFrom (targetPoint);
  70775. if (distance < bestDistance)
  70776. {
  70777. bestProp = prop;
  70778. bestDistance = distance;
  70779. }
  70780. }
  70781. }
  70782. else if (type == quadraticToElement)
  70783. {
  70784. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70785. const Point<float> points[] = { rp1.resolve (context), rp2.resolve (context), rp3.resolve (context) };
  70786. float bestDistance = std::numeric_limits<float>::max();
  70787. for (int i = 110; --i >= 0;)
  70788. {
  70789. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70790. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70791. const float distance = centre.getDistanceFrom (targetPoint);
  70792. if (distance < bestDistance)
  70793. {
  70794. bestProp = prop;
  70795. bestDistance = distance;
  70796. }
  70797. }
  70798. }
  70799. else if (type == lineToElement)
  70800. {
  70801. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70802. const Line<float> line (rp1.resolve (context), rp2.resolve (context));
  70803. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70804. }
  70805. return bestProp;
  70806. }
  70807. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* context, UndoManager* undoManager)
  70808. {
  70809. ValueTree newTree;
  70810. const Identifier type (state.getType());
  70811. if (type == cubicToElement)
  70812. {
  70813. float bestProp = findProportionAlongLine (targetPoint, context);
  70814. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70815. const Point<float> points[] = { rp1.resolve (context), rp2.resolve (context), rp3.resolve (context), rp4.resolve (context) };
  70816. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70817. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70818. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70819. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70820. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70821. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70822. setControlPoint (0, mid1, undoManager);
  70823. setControlPoint (1, newCp1, undoManager);
  70824. setControlPoint (2, newCentre, undoManager);
  70825. setModeOfEndPoint (roundedMode, undoManager);
  70826. Element newElement (newTree = ValueTree (cubicToElement));
  70827. newElement.setControlPoint (0, newCp2, 0);
  70828. newElement.setControlPoint (1, mid3, 0);
  70829. newElement.setControlPoint (2, rp4, 0);
  70830. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70831. }
  70832. else if (type == quadraticToElement)
  70833. {
  70834. float bestProp = findProportionAlongLine (targetPoint, context);
  70835. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70836. const Point<float> points[] = { rp1.resolve (context), rp2.resolve (context), rp3.resolve (context) };
  70837. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70838. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70839. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70840. setControlPoint (0, mid1, undoManager);
  70841. setControlPoint (1, newCentre, undoManager);
  70842. setModeOfEndPoint (roundedMode, undoManager);
  70843. Element newElement (newTree = ValueTree (quadraticToElement));
  70844. newElement.setControlPoint (0, mid2, 0);
  70845. newElement.setControlPoint (1, rp3, 0);
  70846. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70847. }
  70848. else if (type == lineToElement)
  70849. {
  70850. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70851. const Line<float> line (rp1.resolve (context), rp2.resolve (context));
  70852. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70853. setControlPoint (0, newPoint, undoManager);
  70854. Element newElement (newTree = ValueTree (lineToElement));
  70855. newElement.setControlPoint (0, rp2, 0);
  70856. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70857. }
  70858. else if (type == closeSubPathElement)
  70859. {
  70860. }
  70861. return newTree;
  70862. }
  70863. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70864. {
  70865. state.getParent().removeChild (state, undoManager);
  70866. }
  70867. void DrawablePath::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70868. {
  70869. ValueTreeWrapper v (tree);
  70870. setComponentID (v.getID());
  70871. refreshFillTypes (v, builder.getImageProvider());
  70872. setStrokeType (v.getStrokeType());
  70873. RelativePointPath newRelativePath;
  70874. v.writeTo (newRelativePath);
  70875. setPath (newRelativePath);
  70876. }
  70877. const ValueTree DrawablePath::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70878. {
  70879. ValueTree tree (valueTreeType);
  70880. ValueTreeWrapper v (tree);
  70881. v.setID (getComponentID());
  70882. writeTo (v, imageProvider, 0);
  70883. if (relativePath != 0)
  70884. v.readFrom (*relativePath, 0);
  70885. else
  70886. v.readFrom (RelativePointPath (path), 0);
  70887. return tree;
  70888. }
  70889. END_JUCE_NAMESPACE
  70890. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70891. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70892. BEGIN_JUCE_NAMESPACE
  70893. DrawableRectangle::DrawableRectangle()
  70894. {
  70895. }
  70896. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70897. : DrawableShape (other),
  70898. bounds (other.bounds),
  70899. cornerSize (other.cornerSize)
  70900. {
  70901. }
  70902. DrawableRectangle::~DrawableRectangle()
  70903. {
  70904. }
  70905. Drawable* DrawableRectangle::createCopy() const
  70906. {
  70907. return new DrawableRectangle (*this);
  70908. }
  70909. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70910. {
  70911. if (bounds != newBounds)
  70912. {
  70913. bounds = newBounds;
  70914. rebuildPath();
  70915. }
  70916. }
  70917. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  70918. {
  70919. if (cornerSize != newSize)
  70920. {
  70921. cornerSize = newSize;
  70922. rebuildPath();
  70923. }
  70924. }
  70925. void DrawableRectangle::rebuildPath()
  70926. {
  70927. if (bounds.isDynamic() || cornerSize.isDynamic())
  70928. {
  70929. Drawable::Positioner<DrawableRectangle>* const p = new Drawable::Positioner<DrawableRectangle> (*this);
  70930. setPositioner (p);
  70931. p->apply();
  70932. }
  70933. else
  70934. {
  70935. setPositioner (0);
  70936. recalculateCoordinates (0);
  70937. }
  70938. }
  70939. bool DrawableRectangle::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70940. {
  70941. bool ok = positioner.addPoint (bounds.topLeft);
  70942. ok = positioner.addPoint (bounds.topRight) && ok;
  70943. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  70944. return positioner.addPoint (cornerSize) && ok;
  70945. }
  70946. void DrawableRectangle::recalculateCoordinates (Expression::EvaluationContext* context)
  70947. {
  70948. Point<float> points[3];
  70949. bounds.resolveThreePoints (points, context);
  70950. const float cornerSizeX = (float) cornerSize.x.resolve (context);
  70951. const float cornerSizeY = (float) cornerSize.y.resolve (context);
  70952. const float w = Line<float> (points[0], points[1]).getLength();
  70953. const float h = Line<float> (points[0], points[2]).getLength();
  70954. Path newPath;
  70955. if (cornerSizeX > 0 && cornerSizeY > 0)
  70956. newPath.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  70957. else
  70958. newPath.addRectangle (0, 0, w, h);
  70959. newPath.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70960. w, 0, points[1].getX(), points[1].getY(),
  70961. 0, h, points[2].getX(), points[2].getY()));
  70962. if (path != newPath)
  70963. {
  70964. path.swapWithPath (newPath);
  70965. pathChanged();
  70966. }
  70967. }
  70968. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  70969. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  70970. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  70971. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70972. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  70973. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70974. : FillAndStrokeState (state_)
  70975. {
  70976. jassert (state.hasType (valueTreeType));
  70977. }
  70978. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  70979. {
  70980. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70981. state.getProperty (topRight, "100, 0"),
  70982. state.getProperty (bottomLeft, "0, 100"));
  70983. }
  70984. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70985. {
  70986. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70987. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70988. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70989. }
  70990. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  70991. {
  70992. state.setProperty (cornerSize, newSize.toString(), undoManager);
  70993. }
  70994. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  70995. {
  70996. return RelativePoint (state [cornerSize]);
  70997. }
  70998. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  70999. {
  71000. return state.getPropertyAsValue (cornerSize, undoManager);
  71001. }
  71002. void DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  71003. {
  71004. ValueTreeWrapper v (tree);
  71005. setComponentID (v.getID());
  71006. refreshFillTypes (v, builder.getImageProvider());
  71007. setStrokeType (v.getStrokeType());
  71008. setRectangle (v.getRectangle());
  71009. setCornerSize (v.getCornerSize());
  71010. }
  71011. const ValueTree DrawableRectangle::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  71012. {
  71013. ValueTree tree (valueTreeType);
  71014. ValueTreeWrapper v (tree);
  71015. v.setID (getComponentID());
  71016. writeTo (v, imageProvider, 0);
  71017. v.setRectangle (bounds, 0);
  71018. v.setCornerSize (cornerSize, 0);
  71019. return tree;
  71020. }
  71021. END_JUCE_NAMESPACE
  71022. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  71023. /*** Start of inlined file: juce_DrawableText.cpp ***/
  71024. BEGIN_JUCE_NAMESPACE
  71025. DrawableText::DrawableText()
  71026. : colour (Colours::black),
  71027. justification (Justification::centredLeft)
  71028. {
  71029. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  71030. RelativePoint (50.0f, 0.0f),
  71031. RelativePoint (0.0f, 20.0f)));
  71032. setFont (Font (15.0f), true);
  71033. }
  71034. DrawableText::DrawableText (const DrawableText& other)
  71035. : bounds (other.bounds),
  71036. fontSizeControlPoint (other.fontSizeControlPoint),
  71037. font (other.font),
  71038. text (other.text),
  71039. colour (other.colour),
  71040. justification (other.justification)
  71041. {
  71042. }
  71043. DrawableText::~DrawableText()
  71044. {
  71045. }
  71046. void DrawableText::setText (const String& newText)
  71047. {
  71048. if (text != newText)
  71049. {
  71050. text = newText;
  71051. refreshBounds();
  71052. }
  71053. }
  71054. void DrawableText::setColour (const Colour& newColour)
  71055. {
  71056. if (colour != newColour)
  71057. {
  71058. colour = newColour;
  71059. repaint();
  71060. }
  71061. }
  71062. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  71063. {
  71064. if (font != newFont)
  71065. {
  71066. font = newFont;
  71067. if (applySizeAndScale)
  71068. {
  71069. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (resolvedPoints,
  71070. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  71071. }
  71072. refreshBounds();
  71073. }
  71074. }
  71075. void DrawableText::setJustification (const Justification& newJustification)
  71076. {
  71077. justification = newJustification;
  71078. repaint();
  71079. }
  71080. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  71081. {
  71082. if (bounds != newBounds)
  71083. {
  71084. bounds = newBounds;
  71085. refreshBounds();
  71086. }
  71087. }
  71088. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  71089. {
  71090. if (fontSizeControlPoint != newPoint)
  71091. {
  71092. fontSizeControlPoint = newPoint;
  71093. refreshBounds();
  71094. }
  71095. }
  71096. void DrawableText::refreshBounds()
  71097. {
  71098. if (bounds.isDynamic() || fontSizeControlPoint.isDynamic())
  71099. {
  71100. Drawable::Positioner<DrawableText>* const p = new Drawable::Positioner<DrawableText> (*this);
  71101. setPositioner (p);
  71102. p->apply();
  71103. }
  71104. else
  71105. {
  71106. setPositioner (0);
  71107. recalculateCoordinates (0);
  71108. }
  71109. }
  71110. bool DrawableText::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  71111. {
  71112. bool ok = positioner.addPoint (bounds.topLeft);
  71113. ok = positioner.addPoint (bounds.topRight) && ok;
  71114. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  71115. return positioner.addPoint (fontSizeControlPoint) && ok;
  71116. }
  71117. void DrawableText::recalculateCoordinates (Expression::EvaluationContext* context)
  71118. {
  71119. bounds.resolveThreePoints (resolvedPoints, context);
  71120. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  71121. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  71122. const Point<float> fontCoords (RelativeParallelogram::getInternalCoordForPoint (resolvedPoints, fontSizeControlPoint.resolve (context)));
  71123. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  71124. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  71125. scaledFont = font;
  71126. scaledFont.setHeight (fontHeight);
  71127. scaledFont.setHorizontalScale (fontWidth / fontHeight);
  71128. setBoundsToEnclose (getDrawableBounds());
  71129. repaint();
  71130. }
  71131. const AffineTransform DrawableText::getArrangementAndTransform (GlyphArrangement& glyphs) const
  71132. {
  71133. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  71134. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  71135. glyphs.addFittedText (scaledFont, text, 0, 0, w, h, justification, 0x100000);
  71136. return AffineTransform::fromTargetPoints (0, 0, resolvedPoints[0].getX(), resolvedPoints[0].getY(),
  71137. w, 0, resolvedPoints[1].getX(), resolvedPoints[1].getY(),
  71138. 0, h, resolvedPoints[2].getX(), resolvedPoints[2].getY());
  71139. }
  71140. void DrawableText::paint (Graphics& g)
  71141. {
  71142. transformContextToCorrectOrigin (g);
  71143. g.setColour (colour);
  71144. GlyphArrangement ga;
  71145. const AffineTransform transform (getArrangementAndTransform (ga));
  71146. ga.draw (g, transform);
  71147. }
  71148. const Rectangle<float> DrawableText::getDrawableBounds() const
  71149. {
  71150. return RelativeParallelogram::getBoundingBox (resolvedPoints);
  71151. }
  71152. Drawable* DrawableText::createCopy() const
  71153. {
  71154. return new DrawableText (*this);
  71155. }
  71156. const Identifier DrawableText::valueTreeType ("Text");
  71157. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71158. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71159. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71160. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71161. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71162. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71163. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71164. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71165. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71166. : ValueTreeWrapperBase (state_)
  71167. {
  71168. jassert (state.hasType (valueTreeType));
  71169. }
  71170. const String DrawableText::ValueTreeWrapper::getText() const
  71171. {
  71172. return state [text].toString();
  71173. }
  71174. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71175. {
  71176. state.setProperty (text, newText, undoManager);
  71177. }
  71178. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71179. {
  71180. return state.getPropertyAsValue (text, undoManager);
  71181. }
  71182. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71183. {
  71184. return Colour::fromString (state [colour].toString());
  71185. }
  71186. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71187. {
  71188. state.setProperty (colour, newColour.toString(), undoManager);
  71189. }
  71190. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71191. {
  71192. return Justification ((int) state [justification]);
  71193. }
  71194. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71195. {
  71196. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71197. }
  71198. const Font DrawableText::ValueTreeWrapper::getFont() const
  71199. {
  71200. return Font::fromString (state [font]);
  71201. }
  71202. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71203. {
  71204. state.setProperty (font, newFont.toString(), undoManager);
  71205. }
  71206. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71207. {
  71208. return state.getPropertyAsValue (font, undoManager);
  71209. }
  71210. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71211. {
  71212. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71213. }
  71214. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71215. {
  71216. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71217. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71218. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71219. }
  71220. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71221. {
  71222. return state [fontSizeAnchor].toString();
  71223. }
  71224. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71225. {
  71226. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71227. }
  71228. void DrawableText::refreshFromValueTree (const ValueTree& tree, ComponentBuilder&)
  71229. {
  71230. ValueTreeWrapper v (tree);
  71231. setComponentID (v.getID());
  71232. const RelativeParallelogram newBounds (v.getBoundingBox());
  71233. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71234. const Colour newColour (v.getColour());
  71235. const Justification newJustification (v.getJustification());
  71236. const String newText (v.getText());
  71237. const Font newFont (v.getFont());
  71238. if (text != newText || font != newFont || justification != newJustification
  71239. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71240. {
  71241. setBoundingBox (newBounds);
  71242. setFontSizeControlPoint (newFontPoint);
  71243. setColour (newColour);
  71244. setFont (newFont, false);
  71245. setJustification (newJustification);
  71246. setText (newText);
  71247. }
  71248. }
  71249. const ValueTree DrawableText::createValueTree (ComponentBuilder::ImageProvider*) const
  71250. {
  71251. ValueTree tree (valueTreeType);
  71252. ValueTreeWrapper v (tree);
  71253. v.setID (getComponentID());
  71254. v.setText (text, 0);
  71255. v.setFont (font, 0);
  71256. v.setJustification (justification, 0);
  71257. v.setColour (colour, 0);
  71258. v.setBoundingBox (bounds, 0);
  71259. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71260. return tree;
  71261. }
  71262. END_JUCE_NAMESPACE
  71263. /*** End of inlined file: juce_DrawableText.cpp ***/
  71264. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71265. BEGIN_JUCE_NAMESPACE
  71266. class SVGState
  71267. {
  71268. public:
  71269. SVGState (const XmlElement* const topLevel)
  71270. : topLevelXml (topLevel),
  71271. elementX (0), elementY (0),
  71272. width (512), height (512),
  71273. viewBoxW (0), viewBoxH (0)
  71274. {
  71275. }
  71276. ~SVGState()
  71277. {
  71278. }
  71279. Drawable* parseSVGElement (const XmlElement& xml)
  71280. {
  71281. if (! xml.hasTagName ("svg"))
  71282. return 0;
  71283. DrawableComposite* const drawable = new DrawableComposite();
  71284. drawable->setName (xml.getStringAttribute ("id"));
  71285. SVGState newState (*this);
  71286. if (xml.hasAttribute ("transform"))
  71287. newState.addTransform (xml);
  71288. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71289. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71290. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71291. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71292. if (xml.hasAttribute ("viewBox"))
  71293. {
  71294. const String viewParams (xml.getStringAttribute ("viewBox"));
  71295. int i = 0;
  71296. float vx, vy, vw, vh;
  71297. if (parseCoords (viewParams, vx, vy, i, true)
  71298. && parseCoords (viewParams, vw, vh, i, true)
  71299. && vw > 0
  71300. && vh > 0)
  71301. {
  71302. newState.viewBoxW = vw;
  71303. newState.viewBoxH = vh;
  71304. int placementFlags = 0;
  71305. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71306. if (aspect.containsIgnoreCase ("none"))
  71307. {
  71308. placementFlags = RectanglePlacement::stretchToFit;
  71309. }
  71310. else
  71311. {
  71312. if (aspect.containsIgnoreCase ("slice"))
  71313. placementFlags |= RectanglePlacement::fillDestination;
  71314. if (aspect.containsIgnoreCase ("xMin"))
  71315. placementFlags |= RectanglePlacement::xLeft;
  71316. else if (aspect.containsIgnoreCase ("xMax"))
  71317. placementFlags |= RectanglePlacement::xRight;
  71318. else
  71319. placementFlags |= RectanglePlacement::xMid;
  71320. if (aspect.containsIgnoreCase ("yMin"))
  71321. placementFlags |= RectanglePlacement::yTop;
  71322. else if (aspect.containsIgnoreCase ("yMax"))
  71323. placementFlags |= RectanglePlacement::yBottom;
  71324. else
  71325. placementFlags |= RectanglePlacement::yMid;
  71326. }
  71327. const RectanglePlacement placement (placementFlags);
  71328. newState.transform
  71329. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71330. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71331. .followedBy (newState.transform);
  71332. }
  71333. }
  71334. else
  71335. {
  71336. if (viewBoxW == 0)
  71337. newState.viewBoxW = newState.width;
  71338. if (viewBoxH == 0)
  71339. newState.viewBoxH = newState.height;
  71340. }
  71341. newState.parseSubElements (xml, drawable);
  71342. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71343. return drawable;
  71344. }
  71345. private:
  71346. const XmlElement* const topLevelXml;
  71347. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71348. AffineTransform transform;
  71349. String cssStyleText;
  71350. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71351. {
  71352. forEachXmlChildElement (xml, e)
  71353. {
  71354. Drawable* d = 0;
  71355. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71356. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71357. else if (e->hasTagName ("path")) d = parsePath (*e);
  71358. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71359. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71360. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71361. else if (e->hasTagName ("line")) d = parseLine (*e);
  71362. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71363. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71364. else if (e->hasTagName ("text")) d = parseText (*e);
  71365. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71366. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71367. parentDrawable->addAndMakeVisible (d);
  71368. }
  71369. }
  71370. DrawableComposite* parseSwitch (const XmlElement& xml)
  71371. {
  71372. const XmlElement* const group = xml.getChildByName ("g");
  71373. if (group != 0)
  71374. return parseGroupElement (*group);
  71375. return 0;
  71376. }
  71377. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71378. {
  71379. DrawableComposite* const drawable = new DrawableComposite();
  71380. drawable->setName (xml.getStringAttribute ("id"));
  71381. if (xml.hasAttribute ("transform"))
  71382. {
  71383. SVGState newState (*this);
  71384. newState.addTransform (xml);
  71385. newState.parseSubElements (xml, drawable);
  71386. }
  71387. else
  71388. {
  71389. parseSubElements (xml, drawable);
  71390. }
  71391. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71392. return drawable;
  71393. }
  71394. Drawable* parsePath (const XmlElement& xml) const
  71395. {
  71396. const String d (xml.getStringAttribute ("d").trimStart());
  71397. Path path;
  71398. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71399. path.setUsingNonZeroWinding (false);
  71400. int index = 0;
  71401. float lastX = 0, lastY = 0;
  71402. float lastX2 = 0, lastY2 = 0;
  71403. juce_wchar lastCommandChar = 0;
  71404. bool isRelative = true;
  71405. bool carryOn = true;
  71406. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71407. while (d[index] != 0)
  71408. {
  71409. float x, y, x2, y2, x3, y3;
  71410. if (validCommandChars.containsChar (d[index]))
  71411. {
  71412. lastCommandChar = d [index++];
  71413. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71414. }
  71415. switch (lastCommandChar)
  71416. {
  71417. case 'M':
  71418. case 'm':
  71419. case 'L':
  71420. case 'l':
  71421. if (parseCoords (d, x, y, index, false))
  71422. {
  71423. if (isRelative)
  71424. {
  71425. x += lastX;
  71426. y += lastY;
  71427. }
  71428. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71429. {
  71430. path.startNewSubPath (x, y);
  71431. lastCommandChar = 'l';
  71432. }
  71433. else
  71434. path.lineTo (x, y);
  71435. lastX2 = lastX;
  71436. lastY2 = lastY;
  71437. lastX = x;
  71438. lastY = y;
  71439. }
  71440. else
  71441. {
  71442. ++index;
  71443. }
  71444. break;
  71445. case 'H':
  71446. case 'h':
  71447. if (parseCoord (d, x, index, false, true))
  71448. {
  71449. if (isRelative)
  71450. x += lastX;
  71451. path.lineTo (x, lastY);
  71452. lastX2 = lastX;
  71453. lastX = x;
  71454. }
  71455. else
  71456. {
  71457. ++index;
  71458. }
  71459. break;
  71460. case 'V':
  71461. case 'v':
  71462. if (parseCoord (d, y, index, false, false))
  71463. {
  71464. if (isRelative)
  71465. y += lastY;
  71466. path.lineTo (lastX, y);
  71467. lastY2 = lastY;
  71468. lastY = y;
  71469. }
  71470. else
  71471. {
  71472. ++index;
  71473. }
  71474. break;
  71475. case 'C':
  71476. case 'c':
  71477. if (parseCoords (d, x, y, index, false)
  71478. && parseCoords (d, x2, y2, index, false)
  71479. && parseCoords (d, x3, y3, index, false))
  71480. {
  71481. if (isRelative)
  71482. {
  71483. x += lastX;
  71484. y += lastY;
  71485. x2 += lastX;
  71486. y2 += lastY;
  71487. x3 += lastX;
  71488. y3 += lastY;
  71489. }
  71490. path.cubicTo (x, y, x2, y2, x3, y3);
  71491. lastX2 = x2;
  71492. lastY2 = y2;
  71493. lastX = x3;
  71494. lastY = y3;
  71495. }
  71496. else
  71497. {
  71498. ++index;
  71499. }
  71500. break;
  71501. case 'S':
  71502. case 's':
  71503. if (parseCoords (d, x, y, index, false)
  71504. && parseCoords (d, x3, y3, index, false))
  71505. {
  71506. if (isRelative)
  71507. {
  71508. x += lastX;
  71509. y += lastY;
  71510. x3 += lastX;
  71511. y3 += lastY;
  71512. }
  71513. x2 = lastX + (lastX - lastX2);
  71514. y2 = lastY + (lastY - lastY2);
  71515. path.cubicTo (x2, y2, x, y, x3, y3);
  71516. lastX2 = x;
  71517. lastY2 = y;
  71518. lastX = x3;
  71519. lastY = y3;
  71520. }
  71521. else
  71522. {
  71523. ++index;
  71524. }
  71525. break;
  71526. case 'Q':
  71527. case 'q':
  71528. if (parseCoords (d, x, y, index, false)
  71529. && parseCoords (d, x2, y2, index, false))
  71530. {
  71531. if (isRelative)
  71532. {
  71533. x += lastX;
  71534. y += lastY;
  71535. x2 += lastX;
  71536. y2 += lastY;
  71537. }
  71538. path.quadraticTo (x, y, x2, y2);
  71539. lastX2 = x;
  71540. lastY2 = y;
  71541. lastX = x2;
  71542. lastY = y2;
  71543. }
  71544. else
  71545. {
  71546. ++index;
  71547. }
  71548. break;
  71549. case 'T':
  71550. case 't':
  71551. if (parseCoords (d, x, y, index, false))
  71552. {
  71553. if (isRelative)
  71554. {
  71555. x += lastX;
  71556. y += lastY;
  71557. }
  71558. x2 = lastX + (lastX - lastX2);
  71559. y2 = lastY + (lastY - lastY2);
  71560. path.quadraticTo (x2, y2, x, y);
  71561. lastX2 = x2;
  71562. lastY2 = y2;
  71563. lastX = x;
  71564. lastY = y;
  71565. }
  71566. else
  71567. {
  71568. ++index;
  71569. }
  71570. break;
  71571. case 'A':
  71572. case 'a':
  71573. if (parseCoords (d, x, y, index, false))
  71574. {
  71575. String num;
  71576. if (parseNextNumber (d, num, index, false))
  71577. {
  71578. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71579. if (parseNextNumber (d, num, index, false))
  71580. {
  71581. const bool largeArc = num.getIntValue() != 0;
  71582. if (parseNextNumber (d, num, index, false))
  71583. {
  71584. const bool sweep = num.getIntValue() != 0;
  71585. if (parseCoords (d, x2, y2, index, false))
  71586. {
  71587. if (isRelative)
  71588. {
  71589. x2 += lastX;
  71590. y2 += lastY;
  71591. }
  71592. if (lastX != x2 || lastY != y2)
  71593. {
  71594. double centreX, centreY, startAngle, deltaAngle;
  71595. double rx = x, ry = y;
  71596. endpointToCentreParameters (lastX, lastY, x2, y2,
  71597. angle, largeArc, sweep,
  71598. rx, ry, centreX, centreY,
  71599. startAngle, deltaAngle);
  71600. path.addCentredArc ((float) centreX, (float) centreY,
  71601. (float) rx, (float) ry,
  71602. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71603. false);
  71604. path.lineTo (x2, y2);
  71605. }
  71606. lastX2 = lastX;
  71607. lastY2 = lastY;
  71608. lastX = x2;
  71609. lastY = y2;
  71610. }
  71611. }
  71612. }
  71613. }
  71614. }
  71615. else
  71616. {
  71617. ++index;
  71618. }
  71619. break;
  71620. case 'Z':
  71621. case 'z':
  71622. path.closeSubPath();
  71623. while (CharacterFunctions::isWhitespace (d [index]))
  71624. ++index;
  71625. break;
  71626. default:
  71627. carryOn = false;
  71628. break;
  71629. }
  71630. if (! carryOn)
  71631. break;
  71632. }
  71633. return parseShape (xml, path);
  71634. }
  71635. Drawable* parseRect (const XmlElement& xml) const
  71636. {
  71637. Path rect;
  71638. const bool hasRX = xml.hasAttribute ("rx");
  71639. const bool hasRY = xml.hasAttribute ("ry");
  71640. if (hasRX || hasRY)
  71641. {
  71642. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71643. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71644. if (! hasRX)
  71645. rx = ry;
  71646. else if (! hasRY)
  71647. ry = rx;
  71648. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71649. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71650. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71651. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71652. rx, ry);
  71653. }
  71654. else
  71655. {
  71656. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71657. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71658. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71659. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71660. }
  71661. return parseShape (xml, rect);
  71662. }
  71663. Drawable* parseCircle (const XmlElement& xml) const
  71664. {
  71665. Path circle;
  71666. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71667. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71668. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71669. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71670. return parseShape (xml, circle);
  71671. }
  71672. Drawable* parseEllipse (const XmlElement& xml) const
  71673. {
  71674. Path ellipse;
  71675. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71676. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71677. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71678. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71679. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71680. return parseShape (xml, ellipse);
  71681. }
  71682. Drawable* parseLine (const XmlElement& xml) const
  71683. {
  71684. Path line;
  71685. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71686. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71687. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71688. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71689. line.startNewSubPath (x1, y1);
  71690. line.lineTo (x2, y2);
  71691. return parseShape (xml, line);
  71692. }
  71693. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71694. {
  71695. const String points (xml.getStringAttribute ("points"));
  71696. Path path;
  71697. int index = 0;
  71698. float x, y;
  71699. if (parseCoords (points, x, y, index, true))
  71700. {
  71701. float firstX = x;
  71702. float firstY = y;
  71703. float lastX = 0, lastY = 0;
  71704. path.startNewSubPath (x, y);
  71705. while (parseCoords (points, x, y, index, true))
  71706. {
  71707. lastX = x;
  71708. lastY = y;
  71709. path.lineTo (x, y);
  71710. }
  71711. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71712. path.closeSubPath();
  71713. }
  71714. return parseShape (xml, path);
  71715. }
  71716. Drawable* parseShape (const XmlElement& xml, Path& path,
  71717. const bool shouldParseTransform = true) const
  71718. {
  71719. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71720. {
  71721. SVGState newState (*this);
  71722. newState.addTransform (xml);
  71723. return newState.parseShape (xml, path, false);
  71724. }
  71725. DrawablePath* dp = new DrawablePath();
  71726. dp->setName (xml.getStringAttribute ("id"));
  71727. dp->setFill (Colours::transparentBlack);
  71728. path.applyTransform (transform);
  71729. dp->setPath (path);
  71730. Path::Iterator iter (path);
  71731. bool containsClosedSubPath = false;
  71732. while (iter.next())
  71733. {
  71734. if (iter.elementType == Path::Iterator::closePath)
  71735. {
  71736. containsClosedSubPath = true;
  71737. break;
  71738. }
  71739. }
  71740. dp->setFill (getPathFillType (path,
  71741. getStyleAttribute (&xml, "fill"),
  71742. getStyleAttribute (&xml, "fill-opacity"),
  71743. getStyleAttribute (&xml, "opacity"),
  71744. containsClosedSubPath ? Colours::black
  71745. : Colours::transparentBlack));
  71746. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71747. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71748. {
  71749. dp->setStrokeFill (getPathFillType (path, strokeType,
  71750. getStyleAttribute (&xml, "stroke-opacity"),
  71751. getStyleAttribute (&xml, "opacity"),
  71752. Colours::transparentBlack));
  71753. dp->setStrokeType (getStrokeFor (&xml));
  71754. }
  71755. return dp;
  71756. }
  71757. const XmlElement* findLinkedElement (const XmlElement* e) const
  71758. {
  71759. const String id (e->getStringAttribute ("xlink:href"));
  71760. if (! id.startsWithChar ('#'))
  71761. return 0;
  71762. return findElementForId (topLevelXml, id.substring (1));
  71763. }
  71764. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71765. {
  71766. if (fillXml == 0)
  71767. return;
  71768. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71769. {
  71770. int index = 0;
  71771. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71772. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71773. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71774. double offset = e->getDoubleAttribute ("offset");
  71775. if (e->getStringAttribute ("offset").containsChar ('%'))
  71776. offset *= 0.01;
  71777. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71778. }
  71779. }
  71780. const FillType getPathFillType (const Path& path,
  71781. const String& fill,
  71782. const String& fillOpacity,
  71783. const String& overallOpacity,
  71784. const Colour& defaultColour) const
  71785. {
  71786. float opacity = 1.0f;
  71787. if (overallOpacity.isNotEmpty())
  71788. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71789. if (fillOpacity.isNotEmpty())
  71790. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71791. if (fill.startsWithIgnoreCase ("url"))
  71792. {
  71793. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71794. .upToLastOccurrenceOf (")", false, false).trim());
  71795. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71796. if (fillXml != 0
  71797. && (fillXml->hasTagName ("linearGradient")
  71798. || fillXml->hasTagName ("radialGradient")))
  71799. {
  71800. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71801. ColourGradient gradient;
  71802. addGradientStopsIn (gradient, inheritedFrom);
  71803. addGradientStopsIn (gradient, fillXml);
  71804. if (gradient.getNumColours() > 0)
  71805. {
  71806. gradient.addColour (0.0, gradient.getColour (0));
  71807. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71808. }
  71809. else
  71810. {
  71811. gradient.addColour (0.0, Colours::black);
  71812. gradient.addColour (1.0, Colours::black);
  71813. }
  71814. if (overallOpacity.isNotEmpty())
  71815. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71816. jassert (gradient.getNumColours() > 0);
  71817. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71818. float gradientWidth = viewBoxW;
  71819. float gradientHeight = viewBoxH;
  71820. float dx = 0.0f;
  71821. float dy = 0.0f;
  71822. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71823. if (! userSpace)
  71824. {
  71825. const Rectangle<float> bounds (path.getBounds());
  71826. dx = bounds.getX();
  71827. dy = bounds.getY();
  71828. gradientWidth = bounds.getWidth();
  71829. gradientHeight = bounds.getHeight();
  71830. }
  71831. if (gradient.isRadial)
  71832. {
  71833. if (userSpace)
  71834. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71835. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71836. else
  71837. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71838. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71839. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71840. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71841. //xxx (the fx, fy focal point isn't handled properly here..)
  71842. }
  71843. else
  71844. {
  71845. if (userSpace)
  71846. {
  71847. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71848. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71849. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71850. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71851. }
  71852. else
  71853. {
  71854. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71855. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71856. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71857. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71858. }
  71859. if (gradient.point1 == gradient.point2)
  71860. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71861. }
  71862. FillType type (gradient);
  71863. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71864. .followedBy (transform);
  71865. return type;
  71866. }
  71867. }
  71868. if (fill.equalsIgnoreCase ("none"))
  71869. return Colours::transparentBlack;
  71870. int i = 0;
  71871. const Colour colour (parseColour (fill, i, defaultColour));
  71872. return colour.withMultipliedAlpha (opacity);
  71873. }
  71874. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71875. {
  71876. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71877. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71878. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71879. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71880. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71881. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71882. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71883. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71884. if (join.equalsIgnoreCase ("round"))
  71885. joinStyle = PathStrokeType::curved;
  71886. else if (join.equalsIgnoreCase ("bevel"))
  71887. joinStyle = PathStrokeType::beveled;
  71888. if (cap.equalsIgnoreCase ("round"))
  71889. capStyle = PathStrokeType::rounded;
  71890. else if (cap.equalsIgnoreCase ("square"))
  71891. capStyle = PathStrokeType::square;
  71892. float ox = 0.0f, oy = 0.0f;
  71893. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71894. transform.transformPoints (ox, oy, x, y);
  71895. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  71896. joinStyle, capStyle);
  71897. }
  71898. Drawable* parseText (const XmlElement& xml)
  71899. {
  71900. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71901. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71902. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71903. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71904. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71905. //xxx not done text yet!
  71906. forEachXmlChildElement (xml, e)
  71907. {
  71908. if (e->isTextElement())
  71909. {
  71910. const String text (e->getText());
  71911. Path path;
  71912. Drawable* s = parseShape (*e, path);
  71913. delete s; // xxx not finished!
  71914. }
  71915. else if (e->hasTagName ("tspan"))
  71916. {
  71917. Drawable* s = parseText (*e);
  71918. delete s; // xxx not finished!
  71919. }
  71920. }
  71921. return 0;
  71922. }
  71923. void addTransform (const XmlElement& xml)
  71924. {
  71925. transform = parseTransform (xml.getStringAttribute ("transform"))
  71926. .followedBy (transform);
  71927. }
  71928. bool parseCoord (const String& s, float& value, int& index,
  71929. const bool allowUnits, const bool isX) const
  71930. {
  71931. String number;
  71932. if (! parseNextNumber (s, number, index, allowUnits))
  71933. {
  71934. value = 0;
  71935. return false;
  71936. }
  71937. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71938. return true;
  71939. }
  71940. bool parseCoords (const String& s, float& x, float& y,
  71941. int& index, const bool allowUnits) const
  71942. {
  71943. return parseCoord (s, x, index, allowUnits, true)
  71944. && parseCoord (s, y, index, allowUnits, false);
  71945. }
  71946. float getCoordLength (const String& s, const float sizeForProportions) const
  71947. {
  71948. float n = s.getFloatValue();
  71949. const int len = s.length();
  71950. if (len > 2)
  71951. {
  71952. const float dpi = 96.0f;
  71953. const juce_wchar n1 = s [len - 2];
  71954. const juce_wchar n2 = s [len - 1];
  71955. if (n1 == 'i' && n2 == 'n')
  71956. n *= dpi;
  71957. else if (n1 == 'm' && n2 == 'm')
  71958. n *= dpi / 25.4f;
  71959. else if (n1 == 'c' && n2 == 'm')
  71960. n *= dpi / 2.54f;
  71961. else if (n1 == 'p' && n2 == 'c')
  71962. n *= 15.0f;
  71963. else if (n2 == '%')
  71964. n *= 0.01f * sizeForProportions;
  71965. }
  71966. return n;
  71967. }
  71968. void getCoordList (Array <float>& coords, const String& list,
  71969. const bool allowUnits, const bool isX) const
  71970. {
  71971. int index = 0;
  71972. float value;
  71973. while (parseCoord (list, value, index, allowUnits, isX))
  71974. coords.add (value);
  71975. }
  71976. void parseCSSStyle (const XmlElement& xml)
  71977. {
  71978. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71979. }
  71980. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71981. const String& defaultValue = String::empty) const
  71982. {
  71983. if (xml->hasAttribute (attributeName))
  71984. return xml->getStringAttribute (attributeName, defaultValue);
  71985. const String styleAtt (xml->getStringAttribute ("style"));
  71986. if (styleAtt.isNotEmpty())
  71987. {
  71988. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71989. if (value.isNotEmpty())
  71990. return value;
  71991. }
  71992. else if (xml->hasAttribute ("class"))
  71993. {
  71994. const String className ("." + xml->getStringAttribute ("class"));
  71995. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71996. if (index < 0)
  71997. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71998. if (index >= 0)
  71999. {
  72000. const int openBracket = cssStyleText.indexOfChar (index, '{');
  72001. if (openBracket > index)
  72002. {
  72003. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  72004. if (closeBracket > openBracket)
  72005. {
  72006. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  72007. if (value.isNotEmpty())
  72008. return value;
  72009. }
  72010. }
  72011. }
  72012. }
  72013. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72014. if (xml != 0)
  72015. return getStyleAttribute (xml, attributeName, defaultValue);
  72016. return defaultValue;
  72017. }
  72018. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  72019. {
  72020. if (xml->hasAttribute (attributeName))
  72021. return xml->getStringAttribute (attributeName);
  72022. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72023. if (xml != 0)
  72024. return getInheritedAttribute (xml, attributeName);
  72025. return String::empty;
  72026. }
  72027. static bool isIdentifierChar (const juce_wchar c)
  72028. {
  72029. return CharacterFunctions::isLetter (c) || c == '-';
  72030. }
  72031. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  72032. {
  72033. int i = 0;
  72034. for (;;)
  72035. {
  72036. i = list.indexOf (i, attributeName);
  72037. if (i < 0)
  72038. break;
  72039. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  72040. && ! isIdentifierChar (list [i + attributeName.length()]))
  72041. {
  72042. i = list.indexOfChar (i, ':');
  72043. if (i < 0)
  72044. break;
  72045. int end = list.indexOfChar (i, ';');
  72046. if (end < 0)
  72047. end = 0x7ffff;
  72048. return list.substring (i + 1, end).trim();
  72049. }
  72050. ++i;
  72051. }
  72052. return defaultValue;
  72053. }
  72054. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  72055. {
  72056. const juce_wchar* const s = source;
  72057. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72058. ++index;
  72059. int start = index;
  72060. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  72061. ++index;
  72062. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  72063. ++index;
  72064. if ((s[index] == 'e' || s[index] == 'E')
  72065. && (CharacterFunctions::isDigit (s[index + 1])
  72066. || s[index + 1] == '-'
  72067. || s[index + 1] == '+'))
  72068. {
  72069. index += 2;
  72070. while (CharacterFunctions::isDigit (s[index]))
  72071. ++index;
  72072. }
  72073. if (allowUnits)
  72074. {
  72075. while (CharacterFunctions::isLetter (s[index]))
  72076. ++index;
  72077. }
  72078. if (index == start)
  72079. return false;
  72080. value = String (s + start, index - start);
  72081. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72082. ++index;
  72083. return true;
  72084. }
  72085. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  72086. {
  72087. if (s [index] == '#')
  72088. {
  72089. uint32 hex [6];
  72090. zeromem (hex, sizeof (hex));
  72091. int numChars = 0;
  72092. for (int i = 6; --i >= 0;)
  72093. {
  72094. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  72095. if (hexValue >= 0)
  72096. hex [numChars++] = hexValue;
  72097. else
  72098. break;
  72099. }
  72100. if (numChars <= 3)
  72101. return Colour ((uint8) (hex [0] * 0x11),
  72102. (uint8) (hex [1] * 0x11),
  72103. (uint8) (hex [2] * 0x11));
  72104. else
  72105. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  72106. (uint8) ((hex [2] << 4) + hex [3]),
  72107. (uint8) ((hex [4] << 4) + hex [5]));
  72108. }
  72109. else if (s [index] == 'r'
  72110. && s [index + 1] == 'g'
  72111. && s [index + 2] == 'b')
  72112. {
  72113. const int openBracket = s.indexOfChar (index, '(');
  72114. const int closeBracket = s.indexOfChar (openBracket, ')');
  72115. if (openBracket >= 3 && closeBracket > openBracket)
  72116. {
  72117. index = closeBracket;
  72118. StringArray tokens;
  72119. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  72120. tokens.trim();
  72121. tokens.removeEmptyStrings();
  72122. if (tokens[0].containsChar ('%'))
  72123. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  72124. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  72125. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  72126. else
  72127. return Colour ((uint8) tokens[0].getIntValue(),
  72128. (uint8) tokens[1].getIntValue(),
  72129. (uint8) tokens[2].getIntValue());
  72130. }
  72131. }
  72132. return Colours::findColourForName (s, defaultColour);
  72133. }
  72134. static const AffineTransform parseTransform (String t)
  72135. {
  72136. AffineTransform result;
  72137. while (t.isNotEmpty())
  72138. {
  72139. StringArray tokens;
  72140. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72141. .upToFirstOccurrenceOf (")", false, false),
  72142. ", ", String::empty);
  72143. tokens.removeEmptyStrings (true);
  72144. float numbers [6];
  72145. for (int i = 0; i < 6; ++i)
  72146. numbers[i] = tokens[i].getFloatValue();
  72147. AffineTransform trans;
  72148. if (t.startsWithIgnoreCase ("matrix"))
  72149. {
  72150. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72151. numbers[1], numbers[3], numbers[5]);
  72152. }
  72153. else if (t.startsWithIgnoreCase ("translate"))
  72154. {
  72155. jassert (tokens.size() == 2);
  72156. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72157. }
  72158. else if (t.startsWithIgnoreCase ("scale"))
  72159. {
  72160. if (tokens.size() == 1)
  72161. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72162. else
  72163. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72164. }
  72165. else if (t.startsWithIgnoreCase ("rotate"))
  72166. {
  72167. if (tokens.size() != 3)
  72168. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72169. else
  72170. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72171. numbers[1], numbers[2]);
  72172. }
  72173. else if (t.startsWithIgnoreCase ("skewX"))
  72174. {
  72175. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72176. 0.0f, 1.0f, 0.0f);
  72177. }
  72178. else if (t.startsWithIgnoreCase ("skewY"))
  72179. {
  72180. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72181. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72182. }
  72183. result = trans.followedBy (result);
  72184. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72185. }
  72186. return result;
  72187. }
  72188. static void endpointToCentreParameters (const double x1, const double y1,
  72189. const double x2, const double y2,
  72190. const double angle,
  72191. const bool largeArc, const bool sweep,
  72192. double& rx, double& ry,
  72193. double& centreX, double& centreY,
  72194. double& startAngle, double& deltaAngle)
  72195. {
  72196. const double midX = (x1 - x2) * 0.5;
  72197. const double midY = (y1 - y2) * 0.5;
  72198. const double cosAngle = cos (angle);
  72199. const double sinAngle = sin (angle);
  72200. const double xp = cosAngle * midX + sinAngle * midY;
  72201. const double yp = cosAngle * midY - sinAngle * midX;
  72202. const double xp2 = xp * xp;
  72203. const double yp2 = yp * yp;
  72204. double rx2 = rx * rx;
  72205. double ry2 = ry * ry;
  72206. const double s = (xp2 / rx2) + (yp2 / ry2);
  72207. double c;
  72208. if (s <= 1.0)
  72209. {
  72210. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72211. / (( rx2 * yp2) + (ry2 * xp2))));
  72212. if (largeArc == sweep)
  72213. c = -c;
  72214. }
  72215. else
  72216. {
  72217. const double s2 = std::sqrt (s);
  72218. rx *= s2;
  72219. ry *= s2;
  72220. rx2 = rx * rx;
  72221. ry2 = ry * ry;
  72222. c = 0;
  72223. }
  72224. const double cpx = ((rx * yp) / ry) * c;
  72225. const double cpy = ((-ry * xp) / rx) * c;
  72226. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72227. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72228. const double ux = (xp - cpx) / rx;
  72229. const double uy = (yp - cpy) / ry;
  72230. const double vx = (-xp - cpx) / rx;
  72231. const double vy = (-yp - cpy) / ry;
  72232. const double length = juce_hypot (ux, uy);
  72233. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72234. if (uy < 0)
  72235. startAngle = -startAngle;
  72236. startAngle += double_Pi * 0.5;
  72237. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72238. / (length * juce_hypot (vx, vy))));
  72239. if ((ux * vy) - (uy * vx) < 0)
  72240. deltaAngle = -deltaAngle;
  72241. if (sweep)
  72242. {
  72243. if (deltaAngle < 0)
  72244. deltaAngle += double_Pi * 2.0;
  72245. }
  72246. else
  72247. {
  72248. if (deltaAngle > 0)
  72249. deltaAngle -= double_Pi * 2.0;
  72250. }
  72251. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72252. }
  72253. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72254. {
  72255. forEachXmlChildElement (*parent, e)
  72256. {
  72257. if (e->compareAttribute ("id", id))
  72258. return e;
  72259. const XmlElement* const found = findElementForId (e, id);
  72260. if (found != 0)
  72261. return found;
  72262. }
  72263. return 0;
  72264. }
  72265. SVGState& operator= (const SVGState&);
  72266. };
  72267. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72268. {
  72269. SVGState state (&svgDocument);
  72270. return state.parseSVGElement (svgDocument);
  72271. }
  72272. END_JUCE_NAMESPACE
  72273. /*** End of inlined file: juce_SVGParser.cpp ***/
  72274. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72275. BEGIN_JUCE_NAMESPACE
  72276. #if JUCE_MSVC && JUCE_DEBUG
  72277. #pragma optimize ("t", on)
  72278. #endif
  72279. DropShadowEffect::DropShadowEffect()
  72280. : offsetX (0),
  72281. offsetY (0),
  72282. radius (4),
  72283. opacity (0.6f)
  72284. {
  72285. }
  72286. DropShadowEffect::~DropShadowEffect()
  72287. {
  72288. }
  72289. void DropShadowEffect::setShadowProperties (const float newRadius,
  72290. const float newOpacity,
  72291. const int newShadowOffsetX,
  72292. const int newShadowOffsetY)
  72293. {
  72294. radius = jmax (1.1f, newRadius);
  72295. offsetX = newShadowOffsetX;
  72296. offsetY = newShadowOffsetY;
  72297. opacity = newOpacity;
  72298. }
  72299. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72300. {
  72301. const int w = image.getWidth();
  72302. const int h = image.getHeight();
  72303. Image shadowImage (Image::SingleChannel, w, h, false);
  72304. const Image::BitmapData srcData (image, false);
  72305. const Image::BitmapData destData (shadowImage, true);
  72306. const int filter = roundToInt (63.0f / radius);
  72307. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72308. for (int x = w; --x >= 0;)
  72309. {
  72310. int shadowAlpha = 0;
  72311. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72312. uint8* shadowPix = destData.data + x;
  72313. for (int y = h; --y >= 0;)
  72314. {
  72315. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72316. *shadowPix = (uint8) shadowAlpha;
  72317. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72318. shadowPix += destData.lineStride;
  72319. }
  72320. }
  72321. for (int y = h; --y >= 0;)
  72322. {
  72323. int shadowAlpha = 0;
  72324. uint8* shadowPix = destData.getLinePointer (y);
  72325. for (int x = w; --x >= 0;)
  72326. {
  72327. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72328. *shadowPix++ = (uint8) shadowAlpha;
  72329. }
  72330. }
  72331. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72332. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72333. g.setOpacity (alpha);
  72334. g.drawImageAt (image, 0, 0);
  72335. }
  72336. #if JUCE_MSVC && JUCE_DEBUG
  72337. #pragma optimize ("", on) // resets optimisations to the project defaults
  72338. #endif
  72339. END_JUCE_NAMESPACE
  72340. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72341. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72342. BEGIN_JUCE_NAMESPACE
  72343. GlowEffect::GlowEffect()
  72344. : radius (2.0f),
  72345. colour (Colours::white)
  72346. {
  72347. }
  72348. GlowEffect::~GlowEffect()
  72349. {
  72350. }
  72351. void GlowEffect::setGlowProperties (const float newRadius,
  72352. const Colour& newColour)
  72353. {
  72354. radius = newRadius;
  72355. colour = newColour;
  72356. }
  72357. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72358. {
  72359. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72360. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72361. blurKernel.createGaussianBlur (radius);
  72362. blurKernel.rescaleAllValues (radius);
  72363. blurKernel.applyToImage (temp, image, image.getBounds());
  72364. g.setColour (colour.withMultipliedAlpha (alpha));
  72365. g.drawImageAt (temp, 0, 0, true);
  72366. g.setOpacity (alpha);
  72367. g.drawImageAt (image, 0, 0, false);
  72368. }
  72369. END_JUCE_NAMESPACE
  72370. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72371. /*** Start of inlined file: juce_Font.cpp ***/
  72372. BEGIN_JUCE_NAMESPACE
  72373. namespace FontValues
  72374. {
  72375. float limitFontHeight (const float height) throw()
  72376. {
  72377. return jlimit (0.1f, 10000.0f, height);
  72378. }
  72379. const float defaultFontHeight = 14.0f;
  72380. String fallbackFont;
  72381. }
  72382. class TypefaceCache : public DeletedAtShutdown
  72383. {
  72384. public:
  72385. TypefaceCache()
  72386. : counter (0)
  72387. {
  72388. setSize (10);
  72389. }
  72390. ~TypefaceCache()
  72391. {
  72392. clearSingletonInstance();
  72393. }
  72394. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72395. void setSize (const int numToCache)
  72396. {
  72397. faces.clear();
  72398. faces.insertMultiple (-1, CachedFace(), numToCache);
  72399. }
  72400. const Typeface::Ptr findTypefaceFor (const Font& font)
  72401. {
  72402. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72403. const String faceName (font.getTypefaceName());
  72404. int i;
  72405. for (i = faces.size(); --i >= 0;)
  72406. {
  72407. CachedFace& face = faces.getReference(i);
  72408. if (face.flags == flags
  72409. && face.typefaceName == faceName
  72410. && face.typeface->isSuitableForFont (font))
  72411. {
  72412. face.lastUsageCount = ++counter;
  72413. return face.typeface;
  72414. }
  72415. }
  72416. int replaceIndex = 0;
  72417. int bestLastUsageCount = std::numeric_limits<int>::max();
  72418. for (i = faces.size(); --i >= 0;)
  72419. {
  72420. const int lu = faces.getReference(i).lastUsageCount;
  72421. if (bestLastUsageCount > lu)
  72422. {
  72423. bestLastUsageCount = lu;
  72424. replaceIndex = i;
  72425. }
  72426. }
  72427. CachedFace& face = faces.getReference (replaceIndex);
  72428. face.typefaceName = faceName;
  72429. face.flags = flags;
  72430. face.lastUsageCount = ++counter;
  72431. face.typeface = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72432. jassert (face.typeface != 0); // the look and feel must return a typeface!
  72433. if (defaultFace == 0 && font == Font())
  72434. defaultFace = face.typeface;
  72435. return face.typeface;
  72436. }
  72437. const Typeface::Ptr getDefaultTypeface() const throw()
  72438. {
  72439. return defaultFace;
  72440. }
  72441. private:
  72442. struct CachedFace
  72443. {
  72444. CachedFace() throw()
  72445. : lastUsageCount (0), flags (-1)
  72446. {
  72447. }
  72448. // Although it seems a bit wacky to store the name here, it's because it may be a
  72449. // placeholder rather than a real one, e.g. "<Sans-Serif>" vs the actual typeface name.
  72450. // Since the typeface itself doesn't know that it may have this alias, the name under
  72451. // which it was fetched needs to be stored separately.
  72452. String typefaceName;
  72453. int lastUsageCount, flags;
  72454. Typeface::Ptr typeface;
  72455. };
  72456. Array <CachedFace> faces;
  72457. Typeface::Ptr defaultFace;
  72458. int counter;
  72459. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache);
  72460. };
  72461. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72462. void Typeface::setTypefaceCacheSize (int numFontsToCache)
  72463. {
  72464. TypefaceCache::getInstance()->setSize (numFontsToCache);
  72465. }
  72466. Font::SharedFontInternal::SharedFontInternal (const float height_, const int styleFlags_) throw()
  72467. : typefaceName (Font::getDefaultSansSerifFontName()),
  72468. height (height_),
  72469. horizontalScale (1.0f),
  72470. kerning (0),
  72471. ascent (0),
  72472. styleFlags (styleFlags_),
  72473. typeface (TypefaceCache::getInstance()->getDefaultTypeface())
  72474. {
  72475. }
  72476. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const int styleFlags_) throw()
  72477. : typefaceName (typefaceName_),
  72478. height (height_),
  72479. horizontalScale (1.0f),
  72480. kerning (0),
  72481. ascent (0),
  72482. styleFlags (styleFlags_),
  72483. typeface (0)
  72484. {
  72485. }
  72486. Font::SharedFontInternal::SharedFontInternal (const Typeface::Ptr& typeface_) throw()
  72487. : typefaceName (typeface_->getName()),
  72488. height (FontValues::defaultFontHeight),
  72489. horizontalScale (1.0f),
  72490. kerning (0),
  72491. ascent (0),
  72492. styleFlags (Font::plain),
  72493. typeface (typeface_)
  72494. {
  72495. }
  72496. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72497. : typefaceName (other.typefaceName),
  72498. height (other.height),
  72499. horizontalScale (other.horizontalScale),
  72500. kerning (other.kerning),
  72501. ascent (other.ascent),
  72502. styleFlags (other.styleFlags),
  72503. typeface (other.typeface)
  72504. {
  72505. }
  72506. bool Font::SharedFontInternal::operator== (const SharedFontInternal& other) const throw()
  72507. {
  72508. return height == other.height
  72509. && styleFlags == other.styleFlags
  72510. && horizontalScale == other.horizontalScale
  72511. && kerning == other.kerning
  72512. && typefaceName == other.typefaceName;
  72513. }
  72514. Font::Font()
  72515. : font (new SharedFontInternal (FontValues::defaultFontHeight, Font::plain))
  72516. {
  72517. }
  72518. Font::Font (const float fontHeight, const int styleFlags_)
  72519. : font (new SharedFontInternal (FontValues::limitFontHeight (fontHeight), styleFlags_))
  72520. {
  72521. }
  72522. Font::Font (const String& typefaceName_, const float fontHeight, const int styleFlags_)
  72523. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight), styleFlags_))
  72524. {
  72525. }
  72526. Font::Font (const Typeface::Ptr& typeface)
  72527. : font (new SharedFontInternal (typeface))
  72528. {
  72529. }
  72530. Font::Font (const Font& other) throw()
  72531. : font (other.font)
  72532. {
  72533. }
  72534. Font& Font::operator= (const Font& other) throw()
  72535. {
  72536. font = other.font;
  72537. return *this;
  72538. }
  72539. Font::~Font() throw()
  72540. {
  72541. }
  72542. bool Font::operator== (const Font& other) const throw()
  72543. {
  72544. return font == other.font
  72545. || *font == *other.font;
  72546. }
  72547. bool Font::operator!= (const Font& other) const throw()
  72548. {
  72549. return ! operator== (other);
  72550. }
  72551. void Font::dupeInternalIfShared()
  72552. {
  72553. if (font->getReferenceCount() > 1)
  72554. font = new SharedFontInternal (*font);
  72555. }
  72556. const String Font::getDefaultSansSerifFontName()
  72557. {
  72558. static const String name ("<Sans-Serif>");
  72559. return name;
  72560. }
  72561. const String Font::getDefaultSerifFontName()
  72562. {
  72563. static const String name ("<Serif>");
  72564. return name;
  72565. }
  72566. const String Font::getDefaultMonospacedFontName()
  72567. {
  72568. static const String name ("<Monospaced>");
  72569. return name;
  72570. }
  72571. void Font::setTypefaceName (const String& faceName)
  72572. {
  72573. if (faceName != font->typefaceName)
  72574. {
  72575. dupeInternalIfShared();
  72576. font->typefaceName = faceName;
  72577. font->typeface = 0;
  72578. font->ascent = 0;
  72579. }
  72580. }
  72581. const String Font::getFallbackFontName()
  72582. {
  72583. return FontValues::fallbackFont;
  72584. }
  72585. void Font::setFallbackFontName (const String& name)
  72586. {
  72587. FontValues::fallbackFont = name;
  72588. }
  72589. void Font::setHeight (float newHeight)
  72590. {
  72591. newHeight = FontValues::limitFontHeight (newHeight);
  72592. if (font->height != newHeight)
  72593. {
  72594. dupeInternalIfShared();
  72595. font->height = newHeight;
  72596. }
  72597. }
  72598. void Font::setHeightWithoutChangingWidth (float newHeight)
  72599. {
  72600. newHeight = FontValues::limitFontHeight (newHeight);
  72601. if (font->height != newHeight)
  72602. {
  72603. dupeInternalIfShared();
  72604. font->horizontalScale *= (font->height / newHeight);
  72605. font->height = newHeight;
  72606. }
  72607. }
  72608. void Font::setStyleFlags (const int newFlags)
  72609. {
  72610. if (font->styleFlags != newFlags)
  72611. {
  72612. dupeInternalIfShared();
  72613. font->styleFlags = newFlags;
  72614. font->typeface = 0;
  72615. font->ascent = 0;
  72616. }
  72617. }
  72618. void Font::setSizeAndStyle (float newHeight,
  72619. const int newStyleFlags,
  72620. const float newHorizontalScale,
  72621. const float newKerningAmount)
  72622. {
  72623. newHeight = FontValues::limitFontHeight (newHeight);
  72624. if (font->height != newHeight
  72625. || font->horizontalScale != newHorizontalScale
  72626. || font->kerning != newKerningAmount)
  72627. {
  72628. dupeInternalIfShared();
  72629. font->height = newHeight;
  72630. font->horizontalScale = newHorizontalScale;
  72631. font->kerning = newKerningAmount;
  72632. }
  72633. setStyleFlags (newStyleFlags);
  72634. }
  72635. void Font::setHorizontalScale (const float scaleFactor)
  72636. {
  72637. dupeInternalIfShared();
  72638. font->horizontalScale = scaleFactor;
  72639. }
  72640. void Font::setExtraKerningFactor (const float extraKerning)
  72641. {
  72642. dupeInternalIfShared();
  72643. font->kerning = extraKerning;
  72644. }
  72645. void Font::setBold (const bool shouldBeBold)
  72646. {
  72647. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72648. : (font->styleFlags & ~bold));
  72649. }
  72650. const Font Font::boldened() const
  72651. {
  72652. Font f (*this);
  72653. f.setBold (true);
  72654. return f;
  72655. }
  72656. bool Font::isBold() const throw()
  72657. {
  72658. return (font->styleFlags & bold) != 0;
  72659. }
  72660. void Font::setItalic (const bool shouldBeItalic)
  72661. {
  72662. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72663. : (font->styleFlags & ~italic));
  72664. }
  72665. const Font Font::italicised() const
  72666. {
  72667. Font f (*this);
  72668. f.setItalic (true);
  72669. return f;
  72670. }
  72671. bool Font::isItalic() const throw()
  72672. {
  72673. return (font->styleFlags & italic) != 0;
  72674. }
  72675. void Font::setUnderline (const bool shouldBeUnderlined)
  72676. {
  72677. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72678. : (font->styleFlags & ~underlined));
  72679. }
  72680. bool Font::isUnderlined() const throw()
  72681. {
  72682. return (font->styleFlags & underlined) != 0;
  72683. }
  72684. float Font::getAscent() const
  72685. {
  72686. if (font->ascent == 0)
  72687. font->ascent = getTypeface()->getAscent();
  72688. return font->height * font->ascent;
  72689. }
  72690. float Font::getDescent() const
  72691. {
  72692. return font->height - getAscent();
  72693. }
  72694. int Font::getStringWidth (const String& text) const
  72695. {
  72696. return roundToInt (getStringWidthFloat (text));
  72697. }
  72698. float Font::getStringWidthFloat (const String& text) const
  72699. {
  72700. float w = getTypeface()->getStringWidth (text);
  72701. if (font->kerning != 0)
  72702. w += font->kerning * text.length();
  72703. return w * font->height * font->horizontalScale;
  72704. }
  72705. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72706. {
  72707. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72708. const float scale = font->height * font->horizontalScale;
  72709. const int num = xOffsets.size();
  72710. if (num > 0)
  72711. {
  72712. float* const x = &(xOffsets.getReference(0));
  72713. if (font->kerning != 0)
  72714. {
  72715. for (int i = 0; i < num; ++i)
  72716. x[i] = (x[i] + i * font->kerning) * scale;
  72717. }
  72718. else
  72719. {
  72720. for (int i = 0; i < num; ++i)
  72721. x[i] *= scale;
  72722. }
  72723. }
  72724. }
  72725. void Font::findFonts (Array<Font>& destArray)
  72726. {
  72727. const StringArray names (findAllTypefaceNames());
  72728. for (int i = 0; i < names.size(); ++i)
  72729. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72730. }
  72731. const String Font::toString() const
  72732. {
  72733. String s (getTypefaceName());
  72734. if (s == getDefaultSansSerifFontName())
  72735. s = String::empty;
  72736. else
  72737. s += "; ";
  72738. s += String (getHeight(), 1);
  72739. if (isBold())
  72740. s += " bold";
  72741. if (isItalic())
  72742. s += " italic";
  72743. return s;
  72744. }
  72745. const Font Font::fromString (const String& fontDescription)
  72746. {
  72747. String name;
  72748. const int separator = fontDescription.indexOfChar (';');
  72749. if (separator > 0)
  72750. name = fontDescription.substring (0, separator).trim();
  72751. if (name.isEmpty())
  72752. name = getDefaultSansSerifFontName();
  72753. String sizeAndStyle (fontDescription.substring (separator + 1));
  72754. float height = sizeAndStyle.getFloatValue();
  72755. if (height <= 0)
  72756. height = 10.0f;
  72757. int flags = Font::plain;
  72758. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72759. flags |= Font::bold;
  72760. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72761. flags |= Font::italic;
  72762. return Font (name, height, flags);
  72763. }
  72764. Typeface* Font::getTypeface() const
  72765. {
  72766. if (font->typeface == 0)
  72767. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72768. return font->typeface;
  72769. }
  72770. END_JUCE_NAMESPACE
  72771. /*** End of inlined file: juce_Font.cpp ***/
  72772. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72773. BEGIN_JUCE_NAMESPACE
  72774. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72775. const juce_wchar character_, const int glyph_)
  72776. : x (x_),
  72777. y (y_),
  72778. w (w_),
  72779. font (font_),
  72780. character (character_),
  72781. glyph (glyph_)
  72782. {
  72783. }
  72784. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72785. : x (other.x),
  72786. y (other.y),
  72787. w (other.w),
  72788. font (other.font),
  72789. character (other.character),
  72790. glyph (other.glyph)
  72791. {
  72792. }
  72793. void PositionedGlyph::draw (const Graphics& g) const
  72794. {
  72795. if (! isWhitespace())
  72796. {
  72797. g.getInternalContext()->setFont (font);
  72798. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72799. }
  72800. }
  72801. void PositionedGlyph::draw (const Graphics& g,
  72802. const AffineTransform& transform) const
  72803. {
  72804. if (! isWhitespace())
  72805. {
  72806. g.getInternalContext()->setFont (font);
  72807. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72808. .followedBy (transform));
  72809. }
  72810. }
  72811. void PositionedGlyph::createPath (Path& path) const
  72812. {
  72813. if (! isWhitespace())
  72814. {
  72815. Typeface* const t = font.getTypeface();
  72816. if (t != 0)
  72817. {
  72818. Path p;
  72819. t->getOutlineForGlyph (glyph, p);
  72820. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72821. .translated (x, y));
  72822. }
  72823. }
  72824. }
  72825. bool PositionedGlyph::hitTest (float px, float py) const
  72826. {
  72827. if (getBounds().contains (px, py) && ! isWhitespace())
  72828. {
  72829. Typeface* const t = font.getTypeface();
  72830. if (t != 0)
  72831. {
  72832. Path p;
  72833. t->getOutlineForGlyph (glyph, p);
  72834. AffineTransform::translation (-x, -y)
  72835. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72836. .transformPoint (px, py);
  72837. return p.contains (px, py);
  72838. }
  72839. }
  72840. return false;
  72841. }
  72842. void PositionedGlyph::moveBy (const float deltaX,
  72843. const float deltaY)
  72844. {
  72845. x += deltaX;
  72846. y += deltaY;
  72847. }
  72848. GlyphArrangement::GlyphArrangement()
  72849. {
  72850. glyphs.ensureStorageAllocated (128);
  72851. }
  72852. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72853. {
  72854. addGlyphArrangement (other);
  72855. }
  72856. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72857. {
  72858. if (this != &other)
  72859. {
  72860. clear();
  72861. addGlyphArrangement (other);
  72862. }
  72863. return *this;
  72864. }
  72865. GlyphArrangement::~GlyphArrangement()
  72866. {
  72867. }
  72868. void GlyphArrangement::clear()
  72869. {
  72870. glyphs.clear();
  72871. }
  72872. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72873. {
  72874. jassert (isPositiveAndBelow (index, glyphs.size()));
  72875. return *glyphs [index];
  72876. }
  72877. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72878. {
  72879. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72880. glyphs.addCopiesOf (other.glyphs);
  72881. }
  72882. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72883. {
  72884. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72885. }
  72886. void GlyphArrangement::addLineOfText (const Font& font,
  72887. const String& text,
  72888. const float xOffset,
  72889. const float yOffset)
  72890. {
  72891. addCurtailedLineOfText (font, text,
  72892. xOffset, yOffset,
  72893. 1.0e10f, false);
  72894. }
  72895. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72896. const String& text,
  72897. float xOffset,
  72898. const float yOffset,
  72899. const float maxWidthPixels,
  72900. const bool useEllipsis)
  72901. {
  72902. if (text.isNotEmpty())
  72903. {
  72904. Array <int> newGlyphs;
  72905. Array <float> xOffsets;
  72906. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72907. const int textLen = newGlyphs.size();
  72908. const juce_wchar* const unicodeText = text;
  72909. for (int i = 0; i < textLen; ++i)
  72910. {
  72911. const float thisX = xOffsets.getUnchecked (i);
  72912. const float nextX = xOffsets.getUnchecked (i + 1);
  72913. if (nextX > maxWidthPixels + 1.0f)
  72914. {
  72915. // curtail the string if it's too wide..
  72916. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72917. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72918. break;
  72919. }
  72920. else
  72921. {
  72922. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72923. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72924. }
  72925. }
  72926. }
  72927. }
  72928. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72929. const int startIndex, int endIndex)
  72930. {
  72931. int numDeleted = 0;
  72932. if (glyphs.size() > 0)
  72933. {
  72934. Array<int> dotGlyphs;
  72935. Array<float> dotXs;
  72936. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72937. const float dx = dotXs[1];
  72938. float xOffset = 0.0f, yOffset = 0.0f;
  72939. while (endIndex > startIndex)
  72940. {
  72941. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72942. xOffset = pg->x;
  72943. yOffset = pg->y;
  72944. glyphs.remove (endIndex);
  72945. ++numDeleted;
  72946. if (xOffset + dx * 3 <= maxXPos)
  72947. break;
  72948. }
  72949. for (int i = 3; --i >= 0;)
  72950. {
  72951. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72952. font, '.', dotGlyphs.getFirst()));
  72953. --numDeleted;
  72954. xOffset += dx;
  72955. if (xOffset > maxXPos)
  72956. break;
  72957. }
  72958. }
  72959. return numDeleted;
  72960. }
  72961. void GlyphArrangement::addJustifiedText (const Font& font,
  72962. const String& text,
  72963. float x, float y,
  72964. const float maxLineWidth,
  72965. const Justification& horizontalLayout)
  72966. {
  72967. int lineStartIndex = glyphs.size();
  72968. addLineOfText (font, text, x, y);
  72969. const float originalY = y;
  72970. while (lineStartIndex < glyphs.size())
  72971. {
  72972. int i = lineStartIndex;
  72973. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72974. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72975. ++i;
  72976. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72977. int lastWordBreakIndex = -1;
  72978. while (i < glyphs.size())
  72979. {
  72980. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72981. const juce_wchar c = pg->getCharacter();
  72982. if (c == '\r' || c == '\n')
  72983. {
  72984. ++i;
  72985. if (c == '\r' && i < glyphs.size()
  72986. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72987. ++i;
  72988. break;
  72989. }
  72990. else if (pg->isWhitespace())
  72991. {
  72992. lastWordBreakIndex = i + 1;
  72993. }
  72994. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72995. {
  72996. if (lastWordBreakIndex >= 0)
  72997. i = lastWordBreakIndex;
  72998. break;
  72999. }
  73000. ++i;
  73001. }
  73002. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  73003. float currentLineEndX = currentLineStartX;
  73004. for (int j = i; --j >= lineStartIndex;)
  73005. {
  73006. if (! glyphs.getUnchecked (j)->isWhitespace())
  73007. {
  73008. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  73009. break;
  73010. }
  73011. }
  73012. float deltaX = 0.0f;
  73013. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  73014. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  73015. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  73016. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  73017. else if (horizontalLayout.testFlags (Justification::right))
  73018. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  73019. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  73020. x + deltaX - currentLineStartX, y - originalY);
  73021. lineStartIndex = i;
  73022. y += font.getHeight();
  73023. }
  73024. }
  73025. void GlyphArrangement::addFittedText (const Font& f,
  73026. const String& text,
  73027. const float x, const float y,
  73028. const float width, const float height,
  73029. const Justification& layout,
  73030. int maximumLines,
  73031. const float minimumHorizontalScale)
  73032. {
  73033. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  73034. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  73035. if (text.containsAnyOf ("\r\n"))
  73036. {
  73037. GlyphArrangement ga;
  73038. ga.addJustifiedText (f, text, x, y, width, layout);
  73039. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  73040. float dy = y - bb.getY();
  73041. if (layout.testFlags (Justification::verticallyCentred))
  73042. dy += (height - bb.getHeight()) * 0.5f;
  73043. else if (layout.testFlags (Justification::bottom))
  73044. dy += height - bb.getHeight();
  73045. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  73046. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  73047. for (int i = 0; i < ga.glyphs.size(); ++i)
  73048. glyphs.add (ga.glyphs.getUnchecked (i));
  73049. ga.glyphs.clear (false);
  73050. return;
  73051. }
  73052. int startIndex = glyphs.size();
  73053. addLineOfText (f, text.trim(), x, y);
  73054. if (glyphs.size() > startIndex)
  73055. {
  73056. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73057. - glyphs.getUnchecked (startIndex)->getLeft();
  73058. if (lineWidth <= 0)
  73059. return;
  73060. if (lineWidth * minimumHorizontalScale < width)
  73061. {
  73062. if (lineWidth > width)
  73063. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  73064. width / lineWidth);
  73065. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  73066. x, y, width, height, layout);
  73067. }
  73068. else if (maximumLines <= 1)
  73069. {
  73070. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  73071. x, y, width, height, f, layout, minimumHorizontalScale);
  73072. }
  73073. else
  73074. {
  73075. Font font (f);
  73076. String txt (text.trim());
  73077. const int length = txt.length();
  73078. const int originalStartIndex = startIndex;
  73079. int numLines = 1;
  73080. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  73081. maximumLines = 1;
  73082. maximumLines = jmin (maximumLines, length);
  73083. while (numLines < maximumLines)
  73084. {
  73085. ++numLines;
  73086. const float newFontHeight = height / (float) numLines;
  73087. if (newFontHeight < font.getHeight())
  73088. {
  73089. font.setHeight (jmax (8.0f, newFontHeight));
  73090. removeRangeOfGlyphs (startIndex, -1);
  73091. addLineOfText (font, txt, x, y);
  73092. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73093. - glyphs.getUnchecked (startIndex)->getLeft();
  73094. }
  73095. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  73096. break;
  73097. }
  73098. if (numLines < 1)
  73099. numLines = 1;
  73100. float lineY = y;
  73101. float widthPerLine = lineWidth / numLines;
  73102. int lastLineStartIndex = 0;
  73103. for (int line = 0; line < numLines; ++line)
  73104. {
  73105. int i = startIndex;
  73106. lastLineStartIndex = i;
  73107. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  73108. if (line == numLines - 1)
  73109. {
  73110. widthPerLine = width;
  73111. i = glyphs.size();
  73112. }
  73113. else
  73114. {
  73115. while (i < glyphs.size())
  73116. {
  73117. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  73118. if (lineWidth > widthPerLine)
  73119. {
  73120. // got to a point where the line's too long, so skip forward to find a
  73121. // good place to break it..
  73122. const int searchStartIndex = i;
  73123. while (i < glyphs.size())
  73124. {
  73125. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  73126. {
  73127. if (glyphs.getUnchecked (i)->isWhitespace()
  73128. || glyphs.getUnchecked (i)->getCharacter() == '-')
  73129. {
  73130. ++i;
  73131. break;
  73132. }
  73133. }
  73134. else
  73135. {
  73136. // can't find a suitable break, so try looking backwards..
  73137. i = searchStartIndex;
  73138. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73139. {
  73140. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73141. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73142. {
  73143. i -= back - 1;
  73144. break;
  73145. }
  73146. }
  73147. break;
  73148. }
  73149. ++i;
  73150. }
  73151. break;
  73152. }
  73153. ++i;
  73154. }
  73155. int wsStart = i;
  73156. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73157. --wsStart;
  73158. int wsEnd = i;
  73159. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73160. ++wsEnd;
  73161. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73162. i = jmax (wsStart, startIndex + 1);
  73163. }
  73164. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73165. x, lineY, width, font.getHeight(), font,
  73166. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73167. minimumHorizontalScale);
  73168. startIndex = i;
  73169. lineY += font.getHeight();
  73170. if (startIndex >= glyphs.size())
  73171. break;
  73172. }
  73173. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73174. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73175. }
  73176. }
  73177. }
  73178. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73179. const float dx, const float dy)
  73180. {
  73181. jassert (startIndex >= 0);
  73182. if (dx != 0.0f || dy != 0.0f)
  73183. {
  73184. if (num < 0 || startIndex + num > glyphs.size())
  73185. num = glyphs.size() - startIndex;
  73186. while (--num >= 0)
  73187. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73188. }
  73189. }
  73190. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73191. const Justification& justification, float minimumHorizontalScale)
  73192. {
  73193. int numDeleted = 0;
  73194. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73195. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73196. if (lineWidth > w)
  73197. {
  73198. if (minimumHorizontalScale < 1.0f)
  73199. {
  73200. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73201. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73202. }
  73203. if (lineWidth > w)
  73204. {
  73205. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73206. numGlyphs -= numDeleted;
  73207. }
  73208. }
  73209. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73210. return numDeleted;
  73211. }
  73212. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73213. const float horizontalScaleFactor)
  73214. {
  73215. jassert (startIndex >= 0);
  73216. if (num < 0 || startIndex + num > glyphs.size())
  73217. num = glyphs.size() - startIndex;
  73218. if (num > 0)
  73219. {
  73220. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73221. while (--num >= 0)
  73222. {
  73223. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73224. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73225. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73226. pg->w *= horizontalScaleFactor;
  73227. }
  73228. }
  73229. }
  73230. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73231. {
  73232. jassert (startIndex >= 0);
  73233. if (num < 0 || startIndex + num > glyphs.size())
  73234. num = glyphs.size() - startIndex;
  73235. Rectangle<float> result;
  73236. while (--num >= 0)
  73237. {
  73238. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73239. if (includeWhitespace || ! pg->isWhitespace())
  73240. result = result.getUnion (pg->getBounds());
  73241. }
  73242. return result;
  73243. }
  73244. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73245. const float x, const float y, const float width, const float height,
  73246. const Justification& justification)
  73247. {
  73248. jassert (num >= 0 && startIndex >= 0);
  73249. if (glyphs.size() > 0 && num > 0)
  73250. {
  73251. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73252. | Justification::horizontallyCentred)));
  73253. float deltaX = 0.0f;
  73254. if (justification.testFlags (Justification::horizontallyJustified))
  73255. deltaX = x - bb.getX();
  73256. else if (justification.testFlags (Justification::horizontallyCentred))
  73257. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73258. else if (justification.testFlags (Justification::right))
  73259. deltaX = (x + width) - bb.getRight();
  73260. else
  73261. deltaX = x - bb.getX();
  73262. float deltaY = 0.0f;
  73263. if (justification.testFlags (Justification::top))
  73264. deltaY = y - bb.getY();
  73265. else if (justification.testFlags (Justification::bottom))
  73266. deltaY = (y + height) - bb.getBottom();
  73267. else
  73268. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73269. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73270. if (justification.testFlags (Justification::horizontallyJustified))
  73271. {
  73272. int lineStart = 0;
  73273. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73274. int i;
  73275. for (i = 0; i < num; ++i)
  73276. {
  73277. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73278. if (glyphY != baseY)
  73279. {
  73280. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73281. lineStart = i;
  73282. baseY = glyphY;
  73283. }
  73284. }
  73285. if (i > lineStart)
  73286. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73287. }
  73288. }
  73289. }
  73290. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73291. {
  73292. if (start + num < glyphs.size()
  73293. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73294. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73295. {
  73296. int numSpaces = 0;
  73297. int spacesAtEnd = 0;
  73298. for (int i = 0; i < num; ++i)
  73299. {
  73300. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73301. {
  73302. ++spacesAtEnd;
  73303. ++numSpaces;
  73304. }
  73305. else
  73306. {
  73307. spacesAtEnd = 0;
  73308. }
  73309. }
  73310. numSpaces -= spacesAtEnd;
  73311. if (numSpaces > 0)
  73312. {
  73313. const float startX = glyphs.getUnchecked (start)->getLeft();
  73314. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73315. const float extraPaddingBetweenWords
  73316. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73317. float deltaX = 0.0f;
  73318. for (int i = 0; i < num; ++i)
  73319. {
  73320. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73321. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73322. deltaX += extraPaddingBetweenWords;
  73323. }
  73324. }
  73325. }
  73326. }
  73327. void GlyphArrangement::draw (const Graphics& g) const
  73328. {
  73329. for (int i = 0; i < glyphs.size(); ++i)
  73330. {
  73331. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73332. if (pg->font.isUnderlined())
  73333. {
  73334. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73335. float nextX = pg->x + pg->w;
  73336. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73337. nextX = glyphs.getUnchecked (i + 1)->x;
  73338. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73339. nextX - pg->x, lineThickness);
  73340. }
  73341. pg->draw (g);
  73342. }
  73343. }
  73344. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73345. {
  73346. for (int i = 0; i < glyphs.size(); ++i)
  73347. {
  73348. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73349. if (pg->font.isUnderlined())
  73350. {
  73351. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73352. float nextX = pg->x + pg->w;
  73353. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73354. nextX = glyphs.getUnchecked (i + 1)->x;
  73355. Path p;
  73356. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73357. nextX, pg->y + lineThickness * 2.0f),
  73358. lineThickness);
  73359. g.fillPath (p, transform);
  73360. }
  73361. pg->draw (g, transform);
  73362. }
  73363. }
  73364. void GlyphArrangement::createPath (Path& path) const
  73365. {
  73366. for (int i = 0; i < glyphs.size(); ++i)
  73367. glyphs.getUnchecked (i)->createPath (path);
  73368. }
  73369. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73370. {
  73371. for (int i = 0; i < glyphs.size(); ++i)
  73372. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73373. return i;
  73374. return -1;
  73375. }
  73376. END_JUCE_NAMESPACE
  73377. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73378. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73379. BEGIN_JUCE_NAMESPACE
  73380. class TextLayout::Token
  73381. {
  73382. public:
  73383. Token (const String& t,
  73384. const Font& f,
  73385. const bool isWhitespace_)
  73386. : text (t),
  73387. font (f),
  73388. x(0),
  73389. y(0),
  73390. isWhitespace (isWhitespace_)
  73391. {
  73392. w = font.getStringWidth (t);
  73393. h = roundToInt (f.getHeight());
  73394. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73395. }
  73396. Token (const Token& other)
  73397. : text (other.text),
  73398. font (other.font),
  73399. x (other.x),
  73400. y (other.y),
  73401. w (other.w),
  73402. h (other.h),
  73403. line (other.line),
  73404. lineHeight (other.lineHeight),
  73405. isWhitespace (other.isWhitespace),
  73406. isNewLine (other.isNewLine)
  73407. {
  73408. }
  73409. void draw (Graphics& g,
  73410. const int xOffset,
  73411. const int yOffset)
  73412. {
  73413. if (! isWhitespace)
  73414. {
  73415. g.setFont (font);
  73416. g.drawSingleLineText (text.trimEnd(),
  73417. xOffset + x,
  73418. yOffset + y + (lineHeight - h)
  73419. + roundToInt (font.getAscent()));
  73420. }
  73421. }
  73422. String text;
  73423. Font font;
  73424. int x, y, w, h;
  73425. int line, lineHeight;
  73426. bool isWhitespace, isNewLine;
  73427. private:
  73428. JUCE_LEAK_DETECTOR (Token);
  73429. };
  73430. TextLayout::TextLayout()
  73431. : totalLines (0)
  73432. {
  73433. tokens.ensureStorageAllocated (64);
  73434. }
  73435. TextLayout::TextLayout (const String& text, const Font& font)
  73436. : totalLines (0)
  73437. {
  73438. tokens.ensureStorageAllocated (64);
  73439. appendText (text, font);
  73440. }
  73441. TextLayout::TextLayout (const TextLayout& other)
  73442. : totalLines (0)
  73443. {
  73444. *this = other;
  73445. }
  73446. TextLayout& TextLayout::operator= (const TextLayout& other)
  73447. {
  73448. if (this != &other)
  73449. {
  73450. clear();
  73451. totalLines = other.totalLines;
  73452. tokens.addCopiesOf (other.tokens);
  73453. }
  73454. return *this;
  73455. }
  73456. TextLayout::~TextLayout()
  73457. {
  73458. clear();
  73459. }
  73460. void TextLayout::clear()
  73461. {
  73462. tokens.clear();
  73463. totalLines = 0;
  73464. }
  73465. bool TextLayout::isEmpty() const
  73466. {
  73467. return tokens.size() == 0;
  73468. }
  73469. void TextLayout::appendText (const String& text, const Font& font)
  73470. {
  73471. const juce_wchar* t = text;
  73472. String currentString;
  73473. int lastCharType = 0;
  73474. for (;;)
  73475. {
  73476. const juce_wchar c = *t++;
  73477. if (c == 0)
  73478. break;
  73479. int charType;
  73480. if (c == '\r' || c == '\n')
  73481. {
  73482. charType = 0;
  73483. }
  73484. else if (CharacterFunctions::isWhitespace (c))
  73485. {
  73486. charType = 2;
  73487. }
  73488. else
  73489. {
  73490. charType = 1;
  73491. }
  73492. if (charType == 0 || charType != lastCharType)
  73493. {
  73494. if (currentString.isNotEmpty())
  73495. {
  73496. tokens.add (new Token (currentString, font,
  73497. lastCharType == 2 || lastCharType == 0));
  73498. }
  73499. currentString = String::charToString (c);
  73500. if (c == '\r' && *t == '\n')
  73501. currentString += *t++;
  73502. }
  73503. else
  73504. {
  73505. currentString += c;
  73506. }
  73507. lastCharType = charType;
  73508. }
  73509. if (currentString.isNotEmpty())
  73510. tokens.add (new Token (currentString, font, lastCharType == 2));
  73511. }
  73512. void TextLayout::setText (const String& text, const Font& font)
  73513. {
  73514. clear();
  73515. appendText (text, font);
  73516. }
  73517. void TextLayout::layout (int maxWidth,
  73518. const Justification& justification,
  73519. const bool attemptToBalanceLineLengths)
  73520. {
  73521. if (attemptToBalanceLineLengths)
  73522. {
  73523. const int originalW = maxWidth;
  73524. int bestWidth = maxWidth;
  73525. float bestLineProportion = 0.0f;
  73526. while (maxWidth > originalW / 2)
  73527. {
  73528. layout (maxWidth, justification, false);
  73529. if (getNumLines() <= 1)
  73530. return;
  73531. const int lastLineW = getLineWidth (getNumLines() - 1);
  73532. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73533. const float prop = lastLineW / (float) lastButOneLineW;
  73534. if (prop > 0.9f)
  73535. return;
  73536. if (prop > bestLineProportion)
  73537. {
  73538. bestLineProportion = prop;
  73539. bestWidth = maxWidth;
  73540. }
  73541. maxWidth -= 10;
  73542. }
  73543. layout (bestWidth, justification, false);
  73544. }
  73545. else
  73546. {
  73547. int x = 0;
  73548. int y = 0;
  73549. int h = 0;
  73550. totalLines = 0;
  73551. int i;
  73552. for (i = 0; i < tokens.size(); ++i)
  73553. {
  73554. Token* const t = tokens.getUnchecked(i);
  73555. t->x = x;
  73556. t->y = y;
  73557. t->line = totalLines;
  73558. x += t->w;
  73559. h = jmax (h, t->h);
  73560. const Token* nextTok = tokens [i + 1];
  73561. if (nextTok == 0)
  73562. break;
  73563. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73564. {
  73565. // finished a line, so go back and update the heights of the things on it
  73566. for (int j = i; j >= 0; --j)
  73567. {
  73568. Token* const tok = tokens.getUnchecked(j);
  73569. if (tok->line == totalLines)
  73570. tok->lineHeight = h;
  73571. else
  73572. break;
  73573. }
  73574. x = 0;
  73575. y += h;
  73576. h = 0;
  73577. ++totalLines;
  73578. }
  73579. }
  73580. // finished a line, so go back and update the heights of the things on it
  73581. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73582. {
  73583. Token* const t = tokens.getUnchecked(j);
  73584. if (t->line == totalLines)
  73585. t->lineHeight = h;
  73586. else
  73587. break;
  73588. }
  73589. ++totalLines;
  73590. if (! justification.testFlags (Justification::left))
  73591. {
  73592. int totalW = getWidth();
  73593. for (i = totalLines; --i >= 0;)
  73594. {
  73595. const int lineW = getLineWidth (i);
  73596. int dx = 0;
  73597. if (justification.testFlags (Justification::horizontallyCentred))
  73598. dx = (totalW - lineW) / 2;
  73599. else if (justification.testFlags (Justification::right))
  73600. dx = totalW - lineW;
  73601. for (int j = tokens.size(); --j >= 0;)
  73602. {
  73603. Token* const t = tokens.getUnchecked(j);
  73604. if (t->line == i)
  73605. t->x += dx;
  73606. }
  73607. }
  73608. }
  73609. }
  73610. }
  73611. int TextLayout::getLineWidth (const int lineNumber) const
  73612. {
  73613. int maxW = 0;
  73614. for (int i = tokens.size(); --i >= 0;)
  73615. {
  73616. const Token* const t = tokens.getUnchecked(i);
  73617. if (t->line == lineNumber && ! t->isWhitespace)
  73618. maxW = jmax (maxW, t->x + t->w);
  73619. }
  73620. return maxW;
  73621. }
  73622. int TextLayout::getWidth() const
  73623. {
  73624. int maxW = 0;
  73625. for (int i = tokens.size(); --i >= 0;)
  73626. {
  73627. const Token* const t = tokens.getUnchecked(i);
  73628. if (! t->isWhitespace)
  73629. maxW = jmax (maxW, t->x + t->w);
  73630. }
  73631. return maxW;
  73632. }
  73633. int TextLayout::getHeight() const
  73634. {
  73635. int maxH = 0;
  73636. for (int i = tokens.size(); --i >= 0;)
  73637. {
  73638. const Token* const t = tokens.getUnchecked(i);
  73639. if (! t->isWhitespace)
  73640. maxH = jmax (maxH, t->y + t->h);
  73641. }
  73642. return maxH;
  73643. }
  73644. void TextLayout::draw (Graphics& g,
  73645. const int xOffset,
  73646. const int yOffset) const
  73647. {
  73648. for (int i = tokens.size(); --i >= 0;)
  73649. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73650. }
  73651. void TextLayout::drawWithin (Graphics& g,
  73652. int x, int y, int w, int h,
  73653. const Justification& justification) const
  73654. {
  73655. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73656. x, y, w, h);
  73657. draw (g, x, y);
  73658. }
  73659. END_JUCE_NAMESPACE
  73660. /*** End of inlined file: juce_TextLayout.cpp ***/
  73661. /*** Start of inlined file: juce_Typeface.cpp ***/
  73662. BEGIN_JUCE_NAMESPACE
  73663. Typeface::Typeface (const String& name_) throw()
  73664. : name (name_), isFallbackFont (false)
  73665. {
  73666. }
  73667. Typeface::~Typeface()
  73668. {
  73669. }
  73670. const Typeface::Ptr Typeface::getFallbackTypeface()
  73671. {
  73672. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73673. Typeface* t = fallbackFont.getTypeface();
  73674. t->isFallbackFont = true;
  73675. return t;
  73676. }
  73677. class CustomTypeface::GlyphInfo
  73678. {
  73679. public:
  73680. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73681. : character (character_), path (path_), width (width_)
  73682. {
  73683. }
  73684. struct KerningPair
  73685. {
  73686. juce_wchar character2;
  73687. float kerningAmount;
  73688. };
  73689. void addKerningPair (const juce_wchar subsequentCharacter,
  73690. const float extraKerningAmount) throw()
  73691. {
  73692. KerningPair kp;
  73693. kp.character2 = subsequentCharacter;
  73694. kp.kerningAmount = extraKerningAmount;
  73695. kerningPairs.add (kp);
  73696. }
  73697. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73698. {
  73699. if (subsequentCharacter != 0)
  73700. {
  73701. for (int i = kerningPairs.size(); --i >= 0;)
  73702. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73703. return width + kerningPairs.getReference(i).kerningAmount;
  73704. }
  73705. return width;
  73706. }
  73707. const juce_wchar character;
  73708. const Path path;
  73709. float width;
  73710. Array <KerningPair> kerningPairs;
  73711. private:
  73712. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphInfo);
  73713. };
  73714. CustomTypeface::CustomTypeface()
  73715. : Typeface (String::empty)
  73716. {
  73717. clear();
  73718. }
  73719. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73720. : Typeface (String::empty)
  73721. {
  73722. clear();
  73723. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73724. BufferedInputStream in (gzin, 32768);
  73725. name = in.readString();
  73726. isBold = in.readBool();
  73727. isItalic = in.readBool();
  73728. ascent = in.readFloat();
  73729. defaultCharacter = (juce_wchar) in.readShort();
  73730. int i, numChars = in.readInt();
  73731. for (i = 0; i < numChars; ++i)
  73732. {
  73733. const juce_wchar c = (juce_wchar) in.readShort();
  73734. const float width = in.readFloat();
  73735. Path p;
  73736. p.loadPathFromStream (in);
  73737. addGlyph (c, p, width);
  73738. }
  73739. const int numKerningPairs = in.readInt();
  73740. for (i = 0; i < numKerningPairs; ++i)
  73741. {
  73742. const juce_wchar char1 = (juce_wchar) in.readShort();
  73743. const juce_wchar char2 = (juce_wchar) in.readShort();
  73744. addKerningPair (char1, char2, in.readFloat());
  73745. }
  73746. }
  73747. CustomTypeface::~CustomTypeface()
  73748. {
  73749. }
  73750. void CustomTypeface::clear()
  73751. {
  73752. defaultCharacter = 0;
  73753. ascent = 1.0f;
  73754. isBold = isItalic = false;
  73755. zeromem (lookupTable, sizeof (lookupTable));
  73756. glyphs.clear();
  73757. }
  73758. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73759. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73760. {
  73761. name = name_;
  73762. defaultCharacter = defaultCharacter_;
  73763. ascent = ascent_;
  73764. isBold = isBold_;
  73765. isItalic = isItalic_;
  73766. }
  73767. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73768. {
  73769. // Check that you're not trying to add the same character twice..
  73770. jassert (findGlyph (character, false) == 0);
  73771. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)))
  73772. lookupTable [character] = (short) glyphs.size();
  73773. glyphs.add (new GlyphInfo (character, path, width));
  73774. }
  73775. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73776. {
  73777. if (extraAmount != 0)
  73778. {
  73779. GlyphInfo* const g = findGlyph (char1, true);
  73780. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73781. if (g != 0)
  73782. g->addKerningPair (char2, extraAmount);
  73783. }
  73784. }
  73785. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73786. {
  73787. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)) && lookupTable [character] > 0)
  73788. return glyphs [(int) lookupTable [(int) character]];
  73789. for (int i = 0; i < glyphs.size(); ++i)
  73790. {
  73791. GlyphInfo* const g = glyphs.getUnchecked(i);
  73792. if (g->character == character)
  73793. return g;
  73794. }
  73795. if (loadIfNeeded && loadGlyphIfPossible (character))
  73796. return findGlyph (character, false);
  73797. return 0;
  73798. }
  73799. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73800. {
  73801. GlyphInfo* glyph = findGlyph (character, true);
  73802. if (glyph == 0)
  73803. {
  73804. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73805. glyph = findGlyph (L' ', true);
  73806. if (glyph == 0)
  73807. {
  73808. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73809. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73810. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73811. {
  73812. Path path;
  73813. fallbackTypeface->getOutlineForGlyph (character, path);
  73814. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  73815. }
  73816. if (glyph == 0)
  73817. glyph = findGlyph (defaultCharacter, true);
  73818. }
  73819. }
  73820. return glyph;
  73821. }
  73822. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73823. {
  73824. return false;
  73825. }
  73826. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73827. {
  73828. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73829. for (int i = 0; i < numCharacters; ++i)
  73830. {
  73831. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73832. Array <int> glyphIndexes;
  73833. Array <float> offsets;
  73834. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73835. const int glyphIndex = glyphIndexes.getFirst();
  73836. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73837. {
  73838. const float glyphWidth = offsets[1];
  73839. Path p;
  73840. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73841. addGlyph (c, p, glyphWidth);
  73842. for (int j = glyphs.size() - 1; --j >= 0;)
  73843. {
  73844. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73845. glyphIndexes.clearQuick();
  73846. offsets.clearQuick();
  73847. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73848. if (offsets.size() > 1)
  73849. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73850. }
  73851. }
  73852. }
  73853. }
  73854. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73855. {
  73856. GZIPCompressorOutputStream out (&outputStream);
  73857. out.writeString (name);
  73858. out.writeBool (isBold);
  73859. out.writeBool (isItalic);
  73860. out.writeFloat (ascent);
  73861. out.writeShort ((short) (unsigned short) defaultCharacter);
  73862. out.writeInt (glyphs.size());
  73863. int i, numKerningPairs = 0;
  73864. for (i = 0; i < glyphs.size(); ++i)
  73865. {
  73866. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73867. out.writeShort ((short) (unsigned short) g->character);
  73868. out.writeFloat (g->width);
  73869. g->path.writePathToStream (out);
  73870. numKerningPairs += g->kerningPairs.size();
  73871. }
  73872. out.writeInt (numKerningPairs);
  73873. for (i = 0; i < glyphs.size(); ++i)
  73874. {
  73875. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73876. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73877. {
  73878. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73879. out.writeShort ((short) (unsigned short) g->character);
  73880. out.writeShort ((short) (unsigned short) p.character2);
  73881. out.writeFloat (p.kerningAmount);
  73882. }
  73883. }
  73884. return true;
  73885. }
  73886. float CustomTypeface::getAscent() const
  73887. {
  73888. return ascent;
  73889. }
  73890. float CustomTypeface::getDescent() const
  73891. {
  73892. return 1.0f - ascent;
  73893. }
  73894. float CustomTypeface::getStringWidth (const String& text)
  73895. {
  73896. float x = 0;
  73897. const juce_wchar* t = text;
  73898. while (*t != 0)
  73899. {
  73900. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73901. if (glyph == 0 && ! isFallbackFont)
  73902. {
  73903. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73904. if (fallbackTypeface != 0)
  73905. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  73906. }
  73907. if (glyph != 0)
  73908. x += glyph->getHorizontalSpacing (*t);
  73909. }
  73910. return x;
  73911. }
  73912. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73913. {
  73914. xOffsets.add (0);
  73915. float x = 0;
  73916. const juce_wchar* t = text;
  73917. while (*t != 0)
  73918. {
  73919. const juce_wchar c = *t++;
  73920. const GlyphInfo* const glyph = findGlyph (c, true);
  73921. if (glyph == 0 && ! isFallbackFont)
  73922. {
  73923. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73924. if (fallbackTypeface != 0)
  73925. {
  73926. Array <int> subGlyphs;
  73927. Array <float> subOffsets;
  73928. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  73929. if (subGlyphs.size() > 0)
  73930. {
  73931. resultGlyphs.add (subGlyphs.getFirst());
  73932. x += subOffsets[1];
  73933. xOffsets.add (x);
  73934. }
  73935. }
  73936. }
  73937. if (glyph != 0)
  73938. {
  73939. x += glyph->getHorizontalSpacing (*t);
  73940. resultGlyphs.add ((int) glyph->character);
  73941. xOffsets.add (x);
  73942. }
  73943. }
  73944. }
  73945. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73946. {
  73947. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  73948. if (glyph == 0 && ! isFallbackFont)
  73949. {
  73950. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73951. if (fallbackTypeface != 0)
  73952. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  73953. }
  73954. if (glyph != 0)
  73955. {
  73956. path = glyph->path;
  73957. return true;
  73958. }
  73959. return false;
  73960. }
  73961. END_JUCE_NAMESPACE
  73962. /*** End of inlined file: juce_Typeface.cpp ***/
  73963. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73964. BEGIN_JUCE_NAMESPACE
  73965. AffineTransform::AffineTransform() throw()
  73966. : mat00 (1.0f), mat01 (0), mat02 (0),
  73967. mat10 (0), mat11 (1.0f), mat12 (0)
  73968. {
  73969. }
  73970. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73971. : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
  73972. mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
  73973. {
  73974. }
  73975. AffineTransform::AffineTransform (const float mat00_, const float mat01_, const float mat02_,
  73976. const float mat10_, const float mat11_, const float mat12_) throw()
  73977. : mat00 (mat00_), mat01 (mat01_), mat02 (mat02_),
  73978. mat10 (mat10_), mat11 (mat11_), mat12 (mat12_)
  73979. {
  73980. }
  73981. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73982. {
  73983. mat00 = other.mat00;
  73984. mat01 = other.mat01;
  73985. mat02 = other.mat02;
  73986. mat10 = other.mat10;
  73987. mat11 = other.mat11;
  73988. mat12 = other.mat12;
  73989. return *this;
  73990. }
  73991. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73992. {
  73993. return mat00 == other.mat00
  73994. && mat01 == other.mat01
  73995. && mat02 == other.mat02
  73996. && mat10 == other.mat10
  73997. && mat11 == other.mat11
  73998. && mat12 == other.mat12;
  73999. }
  74000. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  74001. {
  74002. return ! operator== (other);
  74003. }
  74004. bool AffineTransform::isIdentity() const throw()
  74005. {
  74006. return (mat01 == 0)
  74007. && (mat02 == 0)
  74008. && (mat10 == 0)
  74009. && (mat12 == 0)
  74010. && (mat00 == 1.0f)
  74011. && (mat11 == 1.0f);
  74012. }
  74013. const AffineTransform AffineTransform::identity;
  74014. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  74015. {
  74016. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  74017. other.mat00 * mat01 + other.mat01 * mat11,
  74018. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  74019. other.mat10 * mat00 + other.mat11 * mat10,
  74020. other.mat10 * mat01 + other.mat11 * mat11,
  74021. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  74022. }
  74023. const AffineTransform AffineTransform::translated (const float dx, const float dy) const throw()
  74024. {
  74025. return AffineTransform (mat00, mat01, mat02 + dx,
  74026. mat10, mat11, mat12 + dy);
  74027. }
  74028. const AffineTransform AffineTransform::translation (const float dx, const float dy) throw()
  74029. {
  74030. return AffineTransform (1.0f, 0, dx,
  74031. 0, 1.0f, dy);
  74032. }
  74033. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  74034. {
  74035. const float cosRad = std::cos (rad);
  74036. const float sinRad = std::sin (rad);
  74037. return AffineTransform (cosRad * mat00 + -sinRad * mat10,
  74038. cosRad * mat01 + -sinRad * mat11,
  74039. cosRad * mat02 + -sinRad * mat12,
  74040. sinRad * mat00 + cosRad * mat10,
  74041. sinRad * mat01 + cosRad * mat11,
  74042. sinRad * mat02 + cosRad * mat12);
  74043. }
  74044. const AffineTransform AffineTransform::rotation (const float rad) throw()
  74045. {
  74046. const float cosRad = std::cos (rad);
  74047. const float sinRad = std::sin (rad);
  74048. return AffineTransform (cosRad, -sinRad, 0,
  74049. sinRad, cosRad, 0);
  74050. }
  74051. const AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) throw()
  74052. {
  74053. const float cosRad = std::cos (rad);
  74054. const float sinRad = std::sin (rad);
  74055. return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
  74056. sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
  74057. }
  74058. const AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const throw()
  74059. {
  74060. return followedBy (rotation (angle, pivotX, pivotY));
  74061. }
  74062. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const throw()
  74063. {
  74064. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  74065. factorY * mat10, factorY * mat11, factorY * mat12);
  74066. }
  74067. const AffineTransform AffineTransform::scale (const float factorX, const float factorY) throw()
  74068. {
  74069. return AffineTransform (factorX, 0, 0,
  74070. 0, factorY, 0);
  74071. }
  74072. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
  74073. const float pivotX, const float pivotY) const throw()
  74074. {
  74075. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
  74076. factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
  74077. }
  74078. const AffineTransform AffineTransform::scale (const float factorX, const float factorY,
  74079. const float pivotX, const float pivotY) throw()
  74080. {
  74081. return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
  74082. 0, factorY, pivotY * (1.0f - factorY));
  74083. }
  74084. const AffineTransform AffineTransform::shear (float shearX, float shearY) throw()
  74085. {
  74086. return AffineTransform (1.0f, shearX, 0,
  74087. shearY, 1.0f, 0);
  74088. }
  74089. const AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const throw()
  74090. {
  74091. return AffineTransform (mat00 + shearX * mat10,
  74092. mat01 + shearX * mat11,
  74093. mat02 + shearX * mat12,
  74094. shearY * mat00 + mat10,
  74095. shearY * mat01 + mat11,
  74096. shearY * mat02 + mat12);
  74097. }
  74098. const AffineTransform AffineTransform::inverted() const throw()
  74099. {
  74100. double determinant = (mat00 * mat11 - mat10 * mat01);
  74101. if (determinant != 0.0)
  74102. {
  74103. determinant = 1.0 / determinant;
  74104. const float dst00 = (float) (mat11 * determinant);
  74105. const float dst10 = (float) (-mat10 * determinant);
  74106. const float dst01 = (float) (-mat01 * determinant);
  74107. const float dst11 = (float) (mat00 * determinant);
  74108. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  74109. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  74110. }
  74111. else
  74112. {
  74113. // singularity..
  74114. return *this;
  74115. }
  74116. }
  74117. bool AffineTransform::isSingularity() const throw()
  74118. {
  74119. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  74120. }
  74121. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  74122. const float x10, const float y10,
  74123. const float x01, const float y01) throw()
  74124. {
  74125. return AffineTransform (x10 - x00, x01 - x00, x00,
  74126. y10 - y00, y01 - y00, y00);
  74127. }
  74128. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  74129. const float sx2, const float sy2, const float tx2, const float ty2,
  74130. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  74131. {
  74132. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  74133. .inverted()
  74134. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  74135. }
  74136. bool AffineTransform::isOnlyTranslation() const throw()
  74137. {
  74138. return (mat01 == 0)
  74139. && (mat10 == 0)
  74140. && (mat00 == 1.0f)
  74141. && (mat11 == 1.0f);
  74142. }
  74143. float AffineTransform::getScaleFactor() const throw()
  74144. {
  74145. return juce_hypot (mat00 + mat01, mat10 + mat11);
  74146. }
  74147. END_JUCE_NAMESPACE
  74148. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74149. /*** Start of inlined file: juce_BorderSize.cpp ***/
  74150. BEGIN_JUCE_NAMESPACE
  74151. BorderSize::BorderSize() throw()
  74152. : top (0),
  74153. left (0),
  74154. bottom (0),
  74155. right (0)
  74156. {
  74157. }
  74158. BorderSize::BorderSize (const BorderSize& other) throw()
  74159. : top (other.top),
  74160. left (other.left),
  74161. bottom (other.bottom),
  74162. right (other.right)
  74163. {
  74164. }
  74165. BorderSize::BorderSize (const int topGap,
  74166. const int leftGap,
  74167. const int bottomGap,
  74168. const int rightGap) throw()
  74169. : top (topGap),
  74170. left (leftGap),
  74171. bottom (bottomGap),
  74172. right (rightGap)
  74173. {
  74174. }
  74175. BorderSize::BorderSize (const int allGaps) throw()
  74176. : top (allGaps),
  74177. left (allGaps),
  74178. bottom (allGaps),
  74179. right (allGaps)
  74180. {
  74181. }
  74182. BorderSize::~BorderSize() throw()
  74183. {
  74184. }
  74185. void BorderSize::setTop (const int newTopGap) throw()
  74186. {
  74187. top = newTopGap;
  74188. }
  74189. void BorderSize::setLeft (const int newLeftGap) throw()
  74190. {
  74191. left = newLeftGap;
  74192. }
  74193. void BorderSize::setBottom (const int newBottomGap) throw()
  74194. {
  74195. bottom = newBottomGap;
  74196. }
  74197. void BorderSize::setRight (const int newRightGap) throw()
  74198. {
  74199. right = newRightGap;
  74200. }
  74201. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  74202. {
  74203. return Rectangle<int> (r.getX() + left,
  74204. r.getY() + top,
  74205. r.getWidth() - (left + right),
  74206. r.getHeight() - (top + bottom));
  74207. }
  74208. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  74209. {
  74210. r.setBounds (r.getX() + left,
  74211. r.getY() + top,
  74212. r.getWidth() - (left + right),
  74213. r.getHeight() - (top + bottom));
  74214. }
  74215. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  74216. {
  74217. return Rectangle<int> (r.getX() - left,
  74218. r.getY() - top,
  74219. r.getWidth() + (left + right),
  74220. r.getHeight() + (top + bottom));
  74221. }
  74222. void BorderSize::addTo (Rectangle<int>& r) const throw()
  74223. {
  74224. r.setBounds (r.getX() - left,
  74225. r.getY() - top,
  74226. r.getWidth() + (left + right),
  74227. r.getHeight() + (top + bottom));
  74228. }
  74229. bool BorderSize::operator== (const BorderSize& other) const throw()
  74230. {
  74231. return top == other.top
  74232. && left == other.left
  74233. && bottom == other.bottom
  74234. && right == other.right;
  74235. }
  74236. bool BorderSize::operator!= (const BorderSize& other) const throw()
  74237. {
  74238. return ! operator== (other);
  74239. }
  74240. END_JUCE_NAMESPACE
  74241. /*** End of inlined file: juce_BorderSize.cpp ***/
  74242. /*** Start of inlined file: juce_Path.cpp ***/
  74243. BEGIN_JUCE_NAMESPACE
  74244. // tests that some co-ords aren't NaNs
  74245. #define CHECK_COORDS_ARE_VALID(x, y) \
  74246. jassert (x == x && y == y);
  74247. namespace PathHelpers
  74248. {
  74249. const float ellipseAngularIncrement = 0.05f;
  74250. const String nextToken (const juce_wchar*& t)
  74251. {
  74252. while (CharacterFunctions::isWhitespace (*t))
  74253. ++t;
  74254. const juce_wchar* const start = t;
  74255. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74256. ++t;
  74257. return String (start, (int) (t - start));
  74258. }
  74259. inline double lengthOf (float x1, float y1, float x2, float y2) throw()
  74260. {
  74261. return juce_hypot ((double) (x1 - x2), (double) (y1 - y2));
  74262. }
  74263. }
  74264. const float Path::lineMarker = 100001.0f;
  74265. const float Path::moveMarker = 100002.0f;
  74266. const float Path::quadMarker = 100003.0f;
  74267. const float Path::cubicMarker = 100004.0f;
  74268. const float Path::closeSubPathMarker = 100005.0f;
  74269. Path::Path()
  74270. : numElements (0),
  74271. pathXMin (0),
  74272. pathXMax (0),
  74273. pathYMin (0),
  74274. pathYMax (0),
  74275. useNonZeroWinding (true)
  74276. {
  74277. }
  74278. Path::~Path()
  74279. {
  74280. }
  74281. Path::Path (const Path& other)
  74282. : numElements (other.numElements),
  74283. pathXMin (other.pathXMin),
  74284. pathXMax (other.pathXMax),
  74285. pathYMin (other.pathYMin),
  74286. pathYMax (other.pathYMax),
  74287. useNonZeroWinding (other.useNonZeroWinding)
  74288. {
  74289. if (numElements > 0)
  74290. {
  74291. data.setAllocatedSize ((int) numElements);
  74292. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74293. }
  74294. }
  74295. Path& Path::operator= (const Path& other)
  74296. {
  74297. if (this != &other)
  74298. {
  74299. data.ensureAllocatedSize ((int) other.numElements);
  74300. numElements = other.numElements;
  74301. pathXMin = other.pathXMin;
  74302. pathXMax = other.pathXMax;
  74303. pathYMin = other.pathYMin;
  74304. pathYMax = other.pathYMax;
  74305. useNonZeroWinding = other.useNonZeroWinding;
  74306. if (numElements > 0)
  74307. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74308. }
  74309. return *this;
  74310. }
  74311. bool Path::operator== (const Path& other) const throw()
  74312. {
  74313. return ! operator!= (other);
  74314. }
  74315. bool Path::operator!= (const Path& other) const throw()
  74316. {
  74317. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74318. return true;
  74319. for (size_t i = 0; i < numElements; ++i)
  74320. if (data.elements[i] != other.data.elements[i])
  74321. return true;
  74322. return false;
  74323. }
  74324. void Path::clear() throw()
  74325. {
  74326. numElements = 0;
  74327. pathXMin = 0;
  74328. pathYMin = 0;
  74329. pathYMax = 0;
  74330. pathXMax = 0;
  74331. }
  74332. void Path::swapWithPath (Path& other) throw()
  74333. {
  74334. data.swapWith (other.data);
  74335. swapVariables <size_t> (numElements, other.numElements);
  74336. swapVariables <float> (pathXMin, other.pathXMin);
  74337. swapVariables <float> (pathXMax, other.pathXMax);
  74338. swapVariables <float> (pathYMin, other.pathYMin);
  74339. swapVariables <float> (pathYMax, other.pathYMax);
  74340. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74341. }
  74342. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74343. {
  74344. useNonZeroWinding = isNonZero;
  74345. }
  74346. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74347. const bool preserveProportions) throw()
  74348. {
  74349. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74350. }
  74351. bool Path::isEmpty() const throw()
  74352. {
  74353. size_t i = 0;
  74354. while (i < numElements)
  74355. {
  74356. const float type = data.elements [i++];
  74357. if (type == moveMarker)
  74358. {
  74359. i += 2;
  74360. }
  74361. else if (type == lineMarker
  74362. || type == quadMarker
  74363. || type == cubicMarker)
  74364. {
  74365. return false;
  74366. }
  74367. }
  74368. return true;
  74369. }
  74370. const Rectangle<float> Path::getBounds() const throw()
  74371. {
  74372. return Rectangle<float> (pathXMin, pathYMin,
  74373. pathXMax - pathXMin,
  74374. pathYMax - pathYMin);
  74375. }
  74376. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74377. {
  74378. return getBounds().transformed (transform);
  74379. }
  74380. void Path::startNewSubPath (const float x, const float y)
  74381. {
  74382. CHECK_COORDS_ARE_VALID (x, y);
  74383. if (numElements == 0)
  74384. {
  74385. pathXMin = pathXMax = x;
  74386. pathYMin = pathYMax = y;
  74387. }
  74388. else
  74389. {
  74390. pathXMin = jmin (pathXMin, x);
  74391. pathXMax = jmax (pathXMax, x);
  74392. pathYMin = jmin (pathYMin, y);
  74393. pathYMax = jmax (pathYMax, y);
  74394. }
  74395. data.ensureAllocatedSize ((int) numElements + 3);
  74396. data.elements [numElements++] = moveMarker;
  74397. data.elements [numElements++] = x;
  74398. data.elements [numElements++] = y;
  74399. }
  74400. void Path::startNewSubPath (const Point<float>& start)
  74401. {
  74402. startNewSubPath (start.getX(), start.getY());
  74403. }
  74404. void Path::lineTo (const float x, const float y)
  74405. {
  74406. CHECK_COORDS_ARE_VALID (x, y);
  74407. if (numElements == 0)
  74408. startNewSubPath (0, 0);
  74409. data.ensureAllocatedSize ((int) numElements + 3);
  74410. data.elements [numElements++] = lineMarker;
  74411. data.elements [numElements++] = x;
  74412. data.elements [numElements++] = y;
  74413. pathXMin = jmin (pathXMin, x);
  74414. pathXMax = jmax (pathXMax, x);
  74415. pathYMin = jmin (pathYMin, y);
  74416. pathYMax = jmax (pathYMax, y);
  74417. }
  74418. void Path::lineTo (const Point<float>& end)
  74419. {
  74420. lineTo (end.getX(), end.getY());
  74421. }
  74422. void Path::quadraticTo (const float x1, const float y1,
  74423. const float x2, const float y2)
  74424. {
  74425. CHECK_COORDS_ARE_VALID (x1, y1);
  74426. CHECK_COORDS_ARE_VALID (x2, y2);
  74427. if (numElements == 0)
  74428. startNewSubPath (0, 0);
  74429. data.ensureAllocatedSize ((int) numElements + 5);
  74430. data.elements [numElements++] = quadMarker;
  74431. data.elements [numElements++] = x1;
  74432. data.elements [numElements++] = y1;
  74433. data.elements [numElements++] = x2;
  74434. data.elements [numElements++] = y2;
  74435. pathXMin = jmin (pathXMin, x1, x2);
  74436. pathXMax = jmax (pathXMax, x1, x2);
  74437. pathYMin = jmin (pathYMin, y1, y2);
  74438. pathYMax = jmax (pathYMax, y1, y2);
  74439. }
  74440. void Path::quadraticTo (const Point<float>& controlPoint,
  74441. const Point<float>& endPoint)
  74442. {
  74443. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74444. endPoint.getX(), endPoint.getY());
  74445. }
  74446. void Path::cubicTo (const float x1, const float y1,
  74447. const float x2, const float y2,
  74448. const float x3, const float y3)
  74449. {
  74450. CHECK_COORDS_ARE_VALID (x1, y1);
  74451. CHECK_COORDS_ARE_VALID (x2, y2);
  74452. CHECK_COORDS_ARE_VALID (x3, y3);
  74453. if (numElements == 0)
  74454. startNewSubPath (0, 0);
  74455. data.ensureAllocatedSize ((int) numElements + 7);
  74456. data.elements [numElements++] = cubicMarker;
  74457. data.elements [numElements++] = x1;
  74458. data.elements [numElements++] = y1;
  74459. data.elements [numElements++] = x2;
  74460. data.elements [numElements++] = y2;
  74461. data.elements [numElements++] = x3;
  74462. data.elements [numElements++] = y3;
  74463. pathXMin = jmin (pathXMin, x1, x2, x3);
  74464. pathXMax = jmax (pathXMax, x1, x2, x3);
  74465. pathYMin = jmin (pathYMin, y1, y2, y3);
  74466. pathYMax = jmax (pathYMax, y1, y2, y3);
  74467. }
  74468. void Path::cubicTo (const Point<float>& controlPoint1,
  74469. const Point<float>& controlPoint2,
  74470. const Point<float>& endPoint)
  74471. {
  74472. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74473. controlPoint2.getX(), controlPoint2.getY(),
  74474. endPoint.getX(), endPoint.getY());
  74475. }
  74476. void Path::closeSubPath()
  74477. {
  74478. if (numElements > 0
  74479. && data.elements [numElements - 1] != closeSubPathMarker)
  74480. {
  74481. data.ensureAllocatedSize ((int) numElements + 1);
  74482. data.elements [numElements++] = closeSubPathMarker;
  74483. }
  74484. }
  74485. const Point<float> Path::getCurrentPosition() const
  74486. {
  74487. size_t i = numElements - 1;
  74488. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74489. {
  74490. while (i >= 0)
  74491. {
  74492. if (data.elements[i] == moveMarker)
  74493. {
  74494. i += 2;
  74495. break;
  74496. }
  74497. --i;
  74498. }
  74499. }
  74500. if (i > 0)
  74501. return Point<float> (data.elements [i - 1], data.elements [i]);
  74502. return Point<float>();
  74503. }
  74504. void Path::addRectangle (const float x, const float y,
  74505. const float w, const float h)
  74506. {
  74507. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74508. if (w < 0)
  74509. swapVariables (x1, x2);
  74510. if (h < 0)
  74511. swapVariables (y1, y2);
  74512. data.ensureAllocatedSize ((int) numElements + 13);
  74513. if (numElements == 0)
  74514. {
  74515. pathXMin = x1;
  74516. pathXMax = x2;
  74517. pathYMin = y1;
  74518. pathYMax = y2;
  74519. }
  74520. else
  74521. {
  74522. pathXMin = jmin (pathXMin, x1);
  74523. pathXMax = jmax (pathXMax, x2);
  74524. pathYMin = jmin (pathYMin, y1);
  74525. pathYMax = jmax (pathYMax, y2);
  74526. }
  74527. data.elements [numElements++] = moveMarker;
  74528. data.elements [numElements++] = x1;
  74529. data.elements [numElements++] = y2;
  74530. data.elements [numElements++] = lineMarker;
  74531. data.elements [numElements++] = x1;
  74532. data.elements [numElements++] = y1;
  74533. data.elements [numElements++] = lineMarker;
  74534. data.elements [numElements++] = x2;
  74535. data.elements [numElements++] = y1;
  74536. data.elements [numElements++] = lineMarker;
  74537. data.elements [numElements++] = x2;
  74538. data.elements [numElements++] = y2;
  74539. data.elements [numElements++] = closeSubPathMarker;
  74540. }
  74541. void Path::addRoundedRectangle (const float x, const float y,
  74542. const float w, const float h,
  74543. float csx,
  74544. float csy)
  74545. {
  74546. csx = jmin (csx, w * 0.5f);
  74547. csy = jmin (csy, h * 0.5f);
  74548. const float cs45x = csx * 0.45f;
  74549. const float cs45y = csy * 0.45f;
  74550. const float x2 = x + w;
  74551. const float y2 = y + h;
  74552. startNewSubPath (x + csx, y);
  74553. lineTo (x2 - csx, y);
  74554. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74555. lineTo (x2, y2 - csy);
  74556. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74557. lineTo (x + csx, y2);
  74558. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74559. lineTo (x, y + csy);
  74560. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74561. closeSubPath();
  74562. }
  74563. void Path::addRoundedRectangle (const float x, const float y,
  74564. const float w, const float h,
  74565. float cs)
  74566. {
  74567. addRoundedRectangle (x, y, w, h, cs, cs);
  74568. }
  74569. void Path::addTriangle (const float x1, const float y1,
  74570. const float x2, const float y2,
  74571. const float x3, const float y3)
  74572. {
  74573. startNewSubPath (x1, y1);
  74574. lineTo (x2, y2);
  74575. lineTo (x3, y3);
  74576. closeSubPath();
  74577. }
  74578. void Path::addQuadrilateral (const float x1, const float y1,
  74579. const float x2, const float y2,
  74580. const float x3, const float y3,
  74581. const float x4, const float y4)
  74582. {
  74583. startNewSubPath (x1, y1);
  74584. lineTo (x2, y2);
  74585. lineTo (x3, y3);
  74586. lineTo (x4, y4);
  74587. closeSubPath();
  74588. }
  74589. void Path::addEllipse (const float x, const float y,
  74590. const float w, const float h)
  74591. {
  74592. const float hw = w * 0.5f;
  74593. const float hw55 = hw * 0.55f;
  74594. const float hh = h * 0.5f;
  74595. const float hh55 = hh * 0.55f;
  74596. const float cx = x + hw;
  74597. const float cy = y + hh;
  74598. startNewSubPath (cx, cy - hh);
  74599. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74600. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74601. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74602. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74603. closeSubPath();
  74604. }
  74605. void Path::addArc (const float x, const float y,
  74606. const float w, const float h,
  74607. const float fromRadians,
  74608. const float toRadians,
  74609. const bool startAsNewSubPath)
  74610. {
  74611. const float radiusX = w / 2.0f;
  74612. const float radiusY = h / 2.0f;
  74613. addCentredArc (x + radiusX,
  74614. y + radiusY,
  74615. radiusX, radiusY,
  74616. 0.0f,
  74617. fromRadians, toRadians,
  74618. startAsNewSubPath);
  74619. }
  74620. void Path::addCentredArc (const float centreX, const float centreY,
  74621. const float radiusX, const float radiusY,
  74622. const float rotationOfEllipse,
  74623. const float fromRadians,
  74624. const float toRadians,
  74625. const bool startAsNewSubPath)
  74626. {
  74627. if (radiusX > 0.0f && radiusY > 0.0f)
  74628. {
  74629. const Point<float> centre (centreX, centreY);
  74630. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74631. float angle = fromRadians;
  74632. if (startAsNewSubPath)
  74633. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74634. if (fromRadians < toRadians)
  74635. {
  74636. if (startAsNewSubPath)
  74637. angle += PathHelpers::ellipseAngularIncrement;
  74638. while (angle < toRadians)
  74639. {
  74640. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74641. angle += PathHelpers::ellipseAngularIncrement;
  74642. }
  74643. }
  74644. else
  74645. {
  74646. if (startAsNewSubPath)
  74647. angle -= PathHelpers::ellipseAngularIncrement;
  74648. while (angle > toRadians)
  74649. {
  74650. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74651. angle -= PathHelpers::ellipseAngularIncrement;
  74652. }
  74653. }
  74654. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74655. }
  74656. }
  74657. void Path::addPieSegment (const float x, const float y,
  74658. const float width, const float height,
  74659. const float fromRadians,
  74660. const float toRadians,
  74661. const float innerCircleProportionalSize)
  74662. {
  74663. float radiusX = width * 0.5f;
  74664. float radiusY = height * 0.5f;
  74665. const Point<float> centre (x + radiusX, y + radiusY);
  74666. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74667. addArc (x, y, width, height, fromRadians, toRadians);
  74668. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74669. {
  74670. closeSubPath();
  74671. if (innerCircleProportionalSize > 0)
  74672. {
  74673. radiusX *= innerCircleProportionalSize;
  74674. radiusY *= innerCircleProportionalSize;
  74675. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74676. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74677. }
  74678. }
  74679. else
  74680. {
  74681. if (innerCircleProportionalSize > 0)
  74682. {
  74683. radiusX *= innerCircleProportionalSize;
  74684. radiusY *= innerCircleProportionalSize;
  74685. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74686. }
  74687. else
  74688. {
  74689. lineTo (centre);
  74690. }
  74691. }
  74692. closeSubPath();
  74693. }
  74694. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74695. {
  74696. const Line<float> reversed (line.reversed());
  74697. lineThickness *= 0.5f;
  74698. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74699. lineTo (line.getPointAlongLine (0, -lineThickness));
  74700. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74701. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74702. closeSubPath();
  74703. }
  74704. void Path::addArrow (const Line<float>& line, float lineThickness,
  74705. float arrowheadWidth, float arrowheadLength)
  74706. {
  74707. const Line<float> reversed (line.reversed());
  74708. lineThickness *= 0.5f;
  74709. arrowheadWidth *= 0.5f;
  74710. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74711. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74712. lineTo (line.getPointAlongLine (0, -lineThickness));
  74713. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74714. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74715. lineTo (line.getEnd());
  74716. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74717. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74718. closeSubPath();
  74719. }
  74720. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74721. const float radius, const float startAngle)
  74722. {
  74723. jassert (numberOfSides > 1); // this would be silly.
  74724. if (numberOfSides > 1)
  74725. {
  74726. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74727. for (int i = 0; i < numberOfSides; ++i)
  74728. {
  74729. const float angle = startAngle + i * angleBetweenPoints;
  74730. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74731. if (i == 0)
  74732. startNewSubPath (p);
  74733. else
  74734. lineTo (p);
  74735. }
  74736. closeSubPath();
  74737. }
  74738. }
  74739. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74740. const float innerRadius, const float outerRadius, const float startAngle)
  74741. {
  74742. jassert (numberOfPoints > 1); // this would be silly.
  74743. if (numberOfPoints > 1)
  74744. {
  74745. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74746. for (int i = 0; i < numberOfPoints; ++i)
  74747. {
  74748. const float angle = startAngle + i * angleBetweenPoints;
  74749. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74750. if (i == 0)
  74751. startNewSubPath (p);
  74752. else
  74753. lineTo (p);
  74754. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74755. }
  74756. closeSubPath();
  74757. }
  74758. }
  74759. void Path::addBubble (float x, float y,
  74760. float w, float h,
  74761. float cs,
  74762. float tipX,
  74763. float tipY,
  74764. int whichSide,
  74765. float arrowPos,
  74766. float arrowWidth)
  74767. {
  74768. if (w > 1.0f && h > 1.0f)
  74769. {
  74770. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74771. const float cs2 = 2.0f * cs;
  74772. startNewSubPath (x + cs, y);
  74773. if (whichSide == 0)
  74774. {
  74775. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74776. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74777. lineTo (arrowX1, y);
  74778. lineTo (tipX, tipY);
  74779. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74780. }
  74781. lineTo (x + w - cs, y);
  74782. if (cs > 0.0f)
  74783. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74784. if (whichSide == 3)
  74785. {
  74786. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74787. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74788. lineTo (x + w, arrowY1);
  74789. lineTo (tipX, tipY);
  74790. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74791. }
  74792. lineTo (x + w, y + h - cs);
  74793. if (cs > 0.0f)
  74794. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74795. if (whichSide == 2)
  74796. {
  74797. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74798. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74799. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74800. lineTo (tipX, tipY);
  74801. lineTo (arrowX1, y + h);
  74802. }
  74803. lineTo (x + cs, y + h);
  74804. if (cs > 0.0f)
  74805. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74806. if (whichSide == 1)
  74807. {
  74808. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74809. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74810. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74811. lineTo (tipX, tipY);
  74812. lineTo (x, arrowY1);
  74813. }
  74814. lineTo (x, y + cs);
  74815. if (cs > 0.0f)
  74816. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74817. closeSubPath();
  74818. }
  74819. }
  74820. void Path::addPath (const Path& other)
  74821. {
  74822. size_t i = 0;
  74823. while (i < other.numElements)
  74824. {
  74825. const float type = other.data.elements [i++];
  74826. if (type == moveMarker)
  74827. {
  74828. startNewSubPath (other.data.elements [i],
  74829. other.data.elements [i + 1]);
  74830. i += 2;
  74831. }
  74832. else if (type == lineMarker)
  74833. {
  74834. lineTo (other.data.elements [i],
  74835. other.data.elements [i + 1]);
  74836. i += 2;
  74837. }
  74838. else if (type == quadMarker)
  74839. {
  74840. quadraticTo (other.data.elements [i],
  74841. other.data.elements [i + 1],
  74842. other.data.elements [i + 2],
  74843. other.data.elements [i + 3]);
  74844. i += 4;
  74845. }
  74846. else if (type == cubicMarker)
  74847. {
  74848. cubicTo (other.data.elements [i],
  74849. other.data.elements [i + 1],
  74850. other.data.elements [i + 2],
  74851. other.data.elements [i + 3],
  74852. other.data.elements [i + 4],
  74853. other.data.elements [i + 5]);
  74854. i += 6;
  74855. }
  74856. else if (type == closeSubPathMarker)
  74857. {
  74858. closeSubPath();
  74859. }
  74860. else
  74861. {
  74862. // something's gone wrong with the element list!
  74863. jassertfalse;
  74864. }
  74865. }
  74866. }
  74867. void Path::addPath (const Path& other,
  74868. const AffineTransform& transformToApply)
  74869. {
  74870. size_t i = 0;
  74871. while (i < other.numElements)
  74872. {
  74873. const float type = other.data.elements [i++];
  74874. if (type == closeSubPathMarker)
  74875. {
  74876. closeSubPath();
  74877. }
  74878. else
  74879. {
  74880. float x = other.data.elements [i++];
  74881. float y = other.data.elements [i++];
  74882. transformToApply.transformPoint (x, y);
  74883. if (type == moveMarker)
  74884. {
  74885. startNewSubPath (x, y);
  74886. }
  74887. else if (type == lineMarker)
  74888. {
  74889. lineTo (x, y);
  74890. }
  74891. else if (type == quadMarker)
  74892. {
  74893. float x2 = other.data.elements [i++];
  74894. float y2 = other.data.elements [i++];
  74895. transformToApply.transformPoint (x2, y2);
  74896. quadraticTo (x, y, x2, y2);
  74897. }
  74898. else if (type == cubicMarker)
  74899. {
  74900. float x2 = other.data.elements [i++];
  74901. float y2 = other.data.elements [i++];
  74902. float x3 = other.data.elements [i++];
  74903. float y3 = other.data.elements [i++];
  74904. transformToApply.transformPoints (x2, y2, x3, y3);
  74905. cubicTo (x, y, x2, y2, x3, y3);
  74906. }
  74907. else
  74908. {
  74909. // something's gone wrong with the element list!
  74910. jassertfalse;
  74911. }
  74912. }
  74913. }
  74914. }
  74915. void Path::applyTransform (const AffineTransform& transform) throw()
  74916. {
  74917. size_t i = 0;
  74918. pathYMin = pathXMin = 0;
  74919. pathYMax = pathXMax = 0;
  74920. bool setMaxMin = false;
  74921. while (i < numElements)
  74922. {
  74923. const float type = data.elements [i++];
  74924. if (type == moveMarker)
  74925. {
  74926. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74927. if (setMaxMin)
  74928. {
  74929. pathXMin = jmin (pathXMin, data.elements [i]);
  74930. pathXMax = jmax (pathXMax, data.elements [i]);
  74931. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74932. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74933. }
  74934. else
  74935. {
  74936. pathXMin = pathXMax = data.elements [i];
  74937. pathYMin = pathYMax = data.elements [i + 1];
  74938. setMaxMin = true;
  74939. }
  74940. i += 2;
  74941. }
  74942. else if (type == lineMarker)
  74943. {
  74944. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74945. pathXMin = jmin (pathXMin, data.elements [i]);
  74946. pathXMax = jmax (pathXMax, data.elements [i]);
  74947. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74948. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74949. i += 2;
  74950. }
  74951. else if (type == quadMarker)
  74952. {
  74953. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74954. data.elements [i + 2], data.elements [i + 3]);
  74955. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74956. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74957. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74958. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74959. i += 4;
  74960. }
  74961. else if (type == cubicMarker)
  74962. {
  74963. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74964. data.elements [i + 2], data.elements [i + 3],
  74965. data.elements [i + 4], data.elements [i + 5]);
  74966. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74967. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74968. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74969. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74970. i += 6;
  74971. }
  74972. }
  74973. }
  74974. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74975. const float w, const float h,
  74976. const bool preserveProportions,
  74977. const Justification& justification) const
  74978. {
  74979. Rectangle<float> bounds (getBounds());
  74980. if (preserveProportions)
  74981. {
  74982. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74983. return AffineTransform::identity;
  74984. float newW, newH;
  74985. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74986. if (srcRatio > h / w)
  74987. {
  74988. newW = h / srcRatio;
  74989. newH = h;
  74990. }
  74991. else
  74992. {
  74993. newW = w;
  74994. newH = w * srcRatio;
  74995. }
  74996. float newXCentre = x;
  74997. float newYCentre = y;
  74998. if (justification.testFlags (Justification::left))
  74999. newXCentre += newW * 0.5f;
  75000. else if (justification.testFlags (Justification::right))
  75001. newXCentre += w - newW * 0.5f;
  75002. else
  75003. newXCentre += w * 0.5f;
  75004. if (justification.testFlags (Justification::top))
  75005. newYCentre += newH * 0.5f;
  75006. else if (justification.testFlags (Justification::bottom))
  75007. newYCentre += h - newH * 0.5f;
  75008. else
  75009. newYCentre += h * 0.5f;
  75010. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  75011. bounds.getHeight() * -0.5f - bounds.getY())
  75012. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  75013. .translated (newXCentre, newYCentre);
  75014. }
  75015. else
  75016. {
  75017. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  75018. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  75019. .translated (x, y);
  75020. }
  75021. }
  75022. bool Path::contains (const float x, const float y, const float tolerance) const
  75023. {
  75024. if (x <= pathXMin || x >= pathXMax
  75025. || y <= pathYMin || y >= pathYMax)
  75026. return false;
  75027. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  75028. int positiveCrossings = 0;
  75029. int negativeCrossings = 0;
  75030. while (i.next())
  75031. {
  75032. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  75033. {
  75034. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  75035. if (intersectX <= x)
  75036. {
  75037. if (i.y1 < i.y2)
  75038. ++positiveCrossings;
  75039. else
  75040. ++negativeCrossings;
  75041. }
  75042. }
  75043. }
  75044. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  75045. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  75046. }
  75047. bool Path::contains (const Point<float>& point, const float tolerance) const
  75048. {
  75049. return contains (point.getX(), point.getY(), tolerance);
  75050. }
  75051. bool Path::intersectsLine (const Line<float>& line, const float tolerance)
  75052. {
  75053. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  75054. Point<float> intersection;
  75055. while (i.next())
  75056. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75057. return true;
  75058. return false;
  75059. }
  75060. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  75061. {
  75062. Line<float> result (line);
  75063. const bool startInside = contains (line.getStart());
  75064. const bool endInside = contains (line.getEnd());
  75065. if (startInside == endInside)
  75066. {
  75067. if (keepSectionOutsidePath == startInside)
  75068. result = Line<float>();
  75069. }
  75070. else
  75071. {
  75072. PathFlatteningIterator i (*this, AffineTransform::identity);
  75073. Point<float> intersection;
  75074. while (i.next())
  75075. {
  75076. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75077. {
  75078. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  75079. result.setStart (intersection);
  75080. else
  75081. result.setEnd (intersection);
  75082. }
  75083. }
  75084. }
  75085. return result;
  75086. }
  75087. float Path::getLength (const AffineTransform& transform) const
  75088. {
  75089. float length = 0;
  75090. PathFlatteningIterator i (*this, transform);
  75091. while (i.next())
  75092. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  75093. return length;
  75094. }
  75095. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  75096. {
  75097. PathFlatteningIterator i (*this, transform);
  75098. while (i.next())
  75099. {
  75100. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75101. const float lineLength = line.getLength();
  75102. if (distanceFromStart <= lineLength)
  75103. return line.getPointAlongLine (distanceFromStart);
  75104. distanceFromStart -= lineLength;
  75105. }
  75106. return Point<float> (i.x2, i.y2);
  75107. }
  75108. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  75109. const AffineTransform& transform) const
  75110. {
  75111. PathFlatteningIterator i (*this, transform);
  75112. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  75113. float length = 0;
  75114. Point<float> pointOnLine;
  75115. while (i.next())
  75116. {
  75117. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75118. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  75119. if (distance < bestDistance)
  75120. {
  75121. bestDistance = distance;
  75122. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  75123. pointOnPath = pointOnLine;
  75124. }
  75125. length += line.getLength();
  75126. }
  75127. return bestPosition;
  75128. }
  75129. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  75130. {
  75131. if (cornerRadius <= 0.01f)
  75132. return *this;
  75133. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  75134. size_t n = 0;
  75135. bool lastWasLine = false, firstWasLine = false;
  75136. Path p;
  75137. while (n < numElements)
  75138. {
  75139. const float type = data.elements [n++];
  75140. if (type == moveMarker)
  75141. {
  75142. indexOfPathStart = p.numElements;
  75143. indexOfPathStartThis = n - 1;
  75144. const float x = data.elements [n++];
  75145. const float y = data.elements [n++];
  75146. p.startNewSubPath (x, y);
  75147. lastWasLine = false;
  75148. firstWasLine = (data.elements [n] == lineMarker);
  75149. }
  75150. else if (type == lineMarker || type == closeSubPathMarker)
  75151. {
  75152. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  75153. if (type == lineMarker)
  75154. {
  75155. endX = data.elements [n++];
  75156. endY = data.elements [n++];
  75157. if (n > 8)
  75158. {
  75159. startX = data.elements [n - 8];
  75160. startY = data.elements [n - 7];
  75161. joinX = data.elements [n - 5];
  75162. joinY = data.elements [n - 4];
  75163. }
  75164. }
  75165. else
  75166. {
  75167. endX = data.elements [indexOfPathStartThis + 1];
  75168. endY = data.elements [indexOfPathStartThis + 2];
  75169. if (n > 6)
  75170. {
  75171. startX = data.elements [n - 6];
  75172. startY = data.elements [n - 5];
  75173. joinX = data.elements [n - 3];
  75174. joinY = data.elements [n - 2];
  75175. }
  75176. }
  75177. if (lastWasLine)
  75178. {
  75179. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  75180. if (len1 > 0)
  75181. {
  75182. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75183. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75184. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75185. }
  75186. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  75187. if (len2 > 0)
  75188. {
  75189. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75190. p.quadraticTo (joinX, joinY,
  75191. (float) (joinX + (endX - joinX) * propNeeded),
  75192. (float) (joinY + (endY - joinY) * propNeeded));
  75193. }
  75194. p.lineTo (endX, endY);
  75195. }
  75196. else if (type == lineMarker)
  75197. {
  75198. p.lineTo (endX, endY);
  75199. lastWasLine = true;
  75200. }
  75201. if (type == closeSubPathMarker)
  75202. {
  75203. if (firstWasLine)
  75204. {
  75205. startX = data.elements [n - 3];
  75206. startY = data.elements [n - 2];
  75207. joinX = endX;
  75208. joinY = endY;
  75209. endX = data.elements [indexOfPathStartThis + 4];
  75210. endY = data.elements [indexOfPathStartThis + 5];
  75211. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  75212. if (len1 > 0)
  75213. {
  75214. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75215. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75216. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75217. }
  75218. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  75219. if (len2 > 0)
  75220. {
  75221. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75222. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75223. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75224. p.quadraticTo (joinX, joinY, endX, endY);
  75225. p.data.elements [indexOfPathStart + 1] = endX;
  75226. p.data.elements [indexOfPathStart + 2] = endY;
  75227. }
  75228. }
  75229. p.closeSubPath();
  75230. }
  75231. }
  75232. else if (type == quadMarker)
  75233. {
  75234. lastWasLine = false;
  75235. const float x1 = data.elements [n++];
  75236. const float y1 = data.elements [n++];
  75237. const float x2 = data.elements [n++];
  75238. const float y2 = data.elements [n++];
  75239. p.quadraticTo (x1, y1, x2, y2);
  75240. }
  75241. else if (type == cubicMarker)
  75242. {
  75243. lastWasLine = false;
  75244. const float x1 = data.elements [n++];
  75245. const float y1 = data.elements [n++];
  75246. const float x2 = data.elements [n++];
  75247. const float y2 = data.elements [n++];
  75248. const float x3 = data.elements [n++];
  75249. const float y3 = data.elements [n++];
  75250. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75251. }
  75252. }
  75253. return p;
  75254. }
  75255. void Path::loadPathFromStream (InputStream& source)
  75256. {
  75257. while (! source.isExhausted())
  75258. {
  75259. switch (source.readByte())
  75260. {
  75261. case 'm':
  75262. {
  75263. const float x = source.readFloat();
  75264. const float y = source.readFloat();
  75265. startNewSubPath (x, y);
  75266. break;
  75267. }
  75268. case 'l':
  75269. {
  75270. const float x = source.readFloat();
  75271. const float y = source.readFloat();
  75272. lineTo (x, y);
  75273. break;
  75274. }
  75275. case 'q':
  75276. {
  75277. const float x1 = source.readFloat();
  75278. const float y1 = source.readFloat();
  75279. const float x2 = source.readFloat();
  75280. const float y2 = source.readFloat();
  75281. quadraticTo (x1, y1, x2, y2);
  75282. break;
  75283. }
  75284. case 'b':
  75285. {
  75286. const float x1 = source.readFloat();
  75287. const float y1 = source.readFloat();
  75288. const float x2 = source.readFloat();
  75289. const float y2 = source.readFloat();
  75290. const float x3 = source.readFloat();
  75291. const float y3 = source.readFloat();
  75292. cubicTo (x1, y1, x2, y2, x3, y3);
  75293. break;
  75294. }
  75295. case 'c':
  75296. closeSubPath();
  75297. break;
  75298. case 'n':
  75299. useNonZeroWinding = true;
  75300. break;
  75301. case 'z':
  75302. useNonZeroWinding = false;
  75303. break;
  75304. case 'e':
  75305. return; // end of path marker
  75306. default:
  75307. jassertfalse; // illegal char in the stream
  75308. break;
  75309. }
  75310. }
  75311. }
  75312. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75313. {
  75314. MemoryInputStream in (pathData, numberOfBytes, false);
  75315. loadPathFromStream (in);
  75316. }
  75317. void Path::writePathToStream (OutputStream& dest) const
  75318. {
  75319. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75320. size_t i = 0;
  75321. while (i < numElements)
  75322. {
  75323. const float type = data.elements [i++];
  75324. if (type == moveMarker)
  75325. {
  75326. dest.writeByte ('m');
  75327. dest.writeFloat (data.elements [i++]);
  75328. dest.writeFloat (data.elements [i++]);
  75329. }
  75330. else if (type == lineMarker)
  75331. {
  75332. dest.writeByte ('l');
  75333. dest.writeFloat (data.elements [i++]);
  75334. dest.writeFloat (data.elements [i++]);
  75335. }
  75336. else if (type == quadMarker)
  75337. {
  75338. dest.writeByte ('q');
  75339. dest.writeFloat (data.elements [i++]);
  75340. dest.writeFloat (data.elements [i++]);
  75341. dest.writeFloat (data.elements [i++]);
  75342. dest.writeFloat (data.elements [i++]);
  75343. }
  75344. else if (type == cubicMarker)
  75345. {
  75346. dest.writeByte ('b');
  75347. dest.writeFloat (data.elements [i++]);
  75348. dest.writeFloat (data.elements [i++]);
  75349. dest.writeFloat (data.elements [i++]);
  75350. dest.writeFloat (data.elements [i++]);
  75351. dest.writeFloat (data.elements [i++]);
  75352. dest.writeFloat (data.elements [i++]);
  75353. }
  75354. else if (type == closeSubPathMarker)
  75355. {
  75356. dest.writeByte ('c');
  75357. }
  75358. }
  75359. dest.writeByte ('e'); // marks the end-of-path
  75360. }
  75361. const String Path::toString() const
  75362. {
  75363. MemoryOutputStream s (2048);
  75364. if (! useNonZeroWinding)
  75365. s << 'a';
  75366. size_t i = 0;
  75367. float lastMarker = 0.0f;
  75368. while (i < numElements)
  75369. {
  75370. const float marker = data.elements [i++];
  75371. char markerChar = 0;
  75372. int numCoords = 0;
  75373. if (marker == moveMarker)
  75374. {
  75375. markerChar = 'm';
  75376. numCoords = 2;
  75377. }
  75378. else if (marker == lineMarker)
  75379. {
  75380. markerChar = 'l';
  75381. numCoords = 2;
  75382. }
  75383. else if (marker == quadMarker)
  75384. {
  75385. markerChar = 'q';
  75386. numCoords = 4;
  75387. }
  75388. else if (marker == cubicMarker)
  75389. {
  75390. markerChar = 'c';
  75391. numCoords = 6;
  75392. }
  75393. else
  75394. {
  75395. jassert (marker == closeSubPathMarker);
  75396. markerChar = 'z';
  75397. }
  75398. if (marker != lastMarker)
  75399. {
  75400. if (s.getDataSize() != 0)
  75401. s << ' ';
  75402. s << markerChar;
  75403. lastMarker = marker;
  75404. }
  75405. while (--numCoords >= 0 && i < numElements)
  75406. {
  75407. String coord (data.elements [i++], 3);
  75408. while (coord.endsWithChar ('0') && coord != "0")
  75409. coord = coord.dropLastCharacters (1);
  75410. if (coord.endsWithChar ('.'))
  75411. coord = coord.dropLastCharacters (1);
  75412. if (s.getDataSize() != 0)
  75413. s << ' ';
  75414. s << coord;
  75415. }
  75416. }
  75417. return s.toUTF8();
  75418. }
  75419. void Path::restoreFromString (const String& stringVersion)
  75420. {
  75421. clear();
  75422. setUsingNonZeroWinding (true);
  75423. const juce_wchar* t = stringVersion;
  75424. juce_wchar marker = 'm';
  75425. int numValues = 2;
  75426. float values [6];
  75427. for (;;)
  75428. {
  75429. const String token (PathHelpers::nextToken (t));
  75430. const juce_wchar firstChar = token[0];
  75431. int startNum = 0;
  75432. if (firstChar == 0)
  75433. break;
  75434. if (firstChar == 'm' || firstChar == 'l')
  75435. {
  75436. marker = firstChar;
  75437. numValues = 2;
  75438. }
  75439. else if (firstChar == 'q')
  75440. {
  75441. marker = firstChar;
  75442. numValues = 4;
  75443. }
  75444. else if (firstChar == 'c')
  75445. {
  75446. marker = firstChar;
  75447. numValues = 6;
  75448. }
  75449. else if (firstChar == 'z')
  75450. {
  75451. marker = firstChar;
  75452. numValues = 0;
  75453. }
  75454. else if (firstChar == 'a')
  75455. {
  75456. setUsingNonZeroWinding (false);
  75457. continue;
  75458. }
  75459. else
  75460. {
  75461. ++startNum;
  75462. values [0] = token.getFloatValue();
  75463. }
  75464. for (int i = startNum; i < numValues; ++i)
  75465. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75466. switch (marker)
  75467. {
  75468. case 'm': startNewSubPath (values[0], values[1]); break;
  75469. case 'l': lineTo (values[0], values[1]); break;
  75470. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75471. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75472. case 'z': closeSubPath(); break;
  75473. default: jassertfalse; break; // illegal string format?
  75474. }
  75475. }
  75476. }
  75477. Path::Iterator::Iterator (const Path& path_)
  75478. : path (path_),
  75479. index (0)
  75480. {
  75481. }
  75482. Path::Iterator::~Iterator()
  75483. {
  75484. }
  75485. bool Path::Iterator::next()
  75486. {
  75487. const float* const elements = path.data.elements;
  75488. if (index < path.numElements)
  75489. {
  75490. const float type = elements [index++];
  75491. if (type == moveMarker)
  75492. {
  75493. elementType = startNewSubPath;
  75494. x1 = elements [index++];
  75495. y1 = elements [index++];
  75496. }
  75497. else if (type == lineMarker)
  75498. {
  75499. elementType = lineTo;
  75500. x1 = elements [index++];
  75501. y1 = elements [index++];
  75502. }
  75503. else if (type == quadMarker)
  75504. {
  75505. elementType = quadraticTo;
  75506. x1 = elements [index++];
  75507. y1 = elements [index++];
  75508. x2 = elements [index++];
  75509. y2 = elements [index++];
  75510. }
  75511. else if (type == cubicMarker)
  75512. {
  75513. elementType = cubicTo;
  75514. x1 = elements [index++];
  75515. y1 = elements [index++];
  75516. x2 = elements [index++];
  75517. y2 = elements [index++];
  75518. x3 = elements [index++];
  75519. y3 = elements [index++];
  75520. }
  75521. else if (type == closeSubPathMarker)
  75522. {
  75523. elementType = closePath;
  75524. }
  75525. return true;
  75526. }
  75527. return false;
  75528. }
  75529. END_JUCE_NAMESPACE
  75530. /*** End of inlined file: juce_Path.cpp ***/
  75531. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75532. BEGIN_JUCE_NAMESPACE
  75533. #if JUCE_MSVC && JUCE_DEBUG
  75534. #pragma optimize ("t", on)
  75535. #endif
  75536. const float PathFlatteningIterator::defaultTolerance = 0.6f;
  75537. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75538. const AffineTransform& transform_,
  75539. const float tolerance)
  75540. : x2 (0),
  75541. y2 (0),
  75542. closesSubPath (false),
  75543. subPathIndex (-1),
  75544. path (path_),
  75545. transform (transform_),
  75546. points (path_.data.elements),
  75547. toleranceSquared (tolerance * tolerance),
  75548. subPathCloseX (0),
  75549. subPathCloseY (0),
  75550. isIdentityTransform (transform_.isIdentity()),
  75551. stackBase (32),
  75552. index (0),
  75553. stackSize (32)
  75554. {
  75555. stackPos = stackBase;
  75556. }
  75557. PathFlatteningIterator::~PathFlatteningIterator()
  75558. {
  75559. }
  75560. bool PathFlatteningIterator::next()
  75561. {
  75562. x1 = x2;
  75563. y1 = y2;
  75564. float x3 = 0;
  75565. float y3 = 0;
  75566. float x4 = 0;
  75567. float y4 = 0;
  75568. float type;
  75569. for (;;)
  75570. {
  75571. if (stackPos == stackBase)
  75572. {
  75573. if (index >= path.numElements)
  75574. {
  75575. return false;
  75576. }
  75577. else
  75578. {
  75579. type = points [index++];
  75580. if (type != Path::closeSubPathMarker)
  75581. {
  75582. x2 = points [index++];
  75583. y2 = points [index++];
  75584. if (type == Path::quadMarker)
  75585. {
  75586. x3 = points [index++];
  75587. y3 = points [index++];
  75588. if (! isIdentityTransform)
  75589. transform.transformPoints (x2, y2, x3, y3);
  75590. }
  75591. else if (type == Path::cubicMarker)
  75592. {
  75593. x3 = points [index++];
  75594. y3 = points [index++];
  75595. x4 = points [index++];
  75596. y4 = points [index++];
  75597. if (! isIdentityTransform)
  75598. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75599. }
  75600. else
  75601. {
  75602. if (! isIdentityTransform)
  75603. transform.transformPoint (x2, y2);
  75604. }
  75605. }
  75606. }
  75607. }
  75608. else
  75609. {
  75610. type = *--stackPos;
  75611. if (type != Path::closeSubPathMarker)
  75612. {
  75613. x2 = *--stackPos;
  75614. y2 = *--stackPos;
  75615. if (type == Path::quadMarker)
  75616. {
  75617. x3 = *--stackPos;
  75618. y3 = *--stackPos;
  75619. }
  75620. else if (type == Path::cubicMarker)
  75621. {
  75622. x3 = *--stackPos;
  75623. y3 = *--stackPos;
  75624. x4 = *--stackPos;
  75625. y4 = *--stackPos;
  75626. }
  75627. }
  75628. }
  75629. if (type == Path::lineMarker)
  75630. {
  75631. ++subPathIndex;
  75632. closesSubPath = (stackPos == stackBase)
  75633. && (index < path.numElements)
  75634. && (points [index] == Path::closeSubPathMarker)
  75635. && x2 == subPathCloseX
  75636. && y2 == subPathCloseY;
  75637. return true;
  75638. }
  75639. else if (type == Path::quadMarker)
  75640. {
  75641. const size_t offset = (size_t) (stackPos - stackBase);
  75642. if (offset >= stackSize - 10)
  75643. {
  75644. stackSize <<= 1;
  75645. stackBase.realloc (stackSize);
  75646. stackPos = stackBase + offset;
  75647. }
  75648. const float m1x = (x1 + x2) * 0.5f;
  75649. const float m1y = (y1 + y2) * 0.5f;
  75650. const float m2x = (x2 + x3) * 0.5f;
  75651. const float m2y = (y2 + y3) * 0.5f;
  75652. const float m3x = (m1x + m2x) * 0.5f;
  75653. const float m3y = (m1y + m2y) * 0.5f;
  75654. const float errorX = m3x - x2;
  75655. const float errorY = m3y - y2;
  75656. if (errorX * errorX + errorY * errorY > toleranceSquared)
  75657. {
  75658. *stackPos++ = y3;
  75659. *stackPos++ = x3;
  75660. *stackPos++ = m2y;
  75661. *stackPos++ = m2x;
  75662. *stackPos++ = Path::quadMarker;
  75663. *stackPos++ = m3y;
  75664. *stackPos++ = m3x;
  75665. *stackPos++ = m1y;
  75666. *stackPos++ = m1x;
  75667. *stackPos++ = Path::quadMarker;
  75668. }
  75669. else
  75670. {
  75671. *stackPos++ = y3;
  75672. *stackPos++ = x3;
  75673. *stackPos++ = Path::lineMarker;
  75674. *stackPos++ = m3y;
  75675. *stackPos++ = m3x;
  75676. *stackPos++ = Path::lineMarker;
  75677. }
  75678. jassert (stackPos < stackBase + stackSize);
  75679. }
  75680. else if (type == Path::cubicMarker)
  75681. {
  75682. const size_t offset = (size_t) (stackPos - stackBase);
  75683. if (offset >= stackSize - 16)
  75684. {
  75685. stackSize <<= 1;
  75686. stackBase.realloc (stackSize);
  75687. stackPos = stackBase + offset;
  75688. }
  75689. const float m1x = (x1 + x2) * 0.5f;
  75690. const float m1y = (y1 + y2) * 0.5f;
  75691. const float m2x = (x3 + x2) * 0.5f;
  75692. const float m2y = (y3 + y2) * 0.5f;
  75693. const float m3x = (x3 + x4) * 0.5f;
  75694. const float m3y = (y3 + y4) * 0.5f;
  75695. const float m4x = (m1x + m2x) * 0.5f;
  75696. const float m4y = (m1y + m2y) * 0.5f;
  75697. const float m5x = (m3x + m2x) * 0.5f;
  75698. const float m5y = (m3y + m2y) * 0.5f;
  75699. const float error1X = m4x - x2;
  75700. const float error1Y = m4y - y2;
  75701. const float error2X = m5x - x3;
  75702. const float error2Y = m5y - y3;
  75703. if (error1X * error1X + error1Y * error1Y > toleranceSquared
  75704. || error2X * error2X + error2Y * error2Y > toleranceSquared)
  75705. {
  75706. *stackPos++ = y4;
  75707. *stackPos++ = x4;
  75708. *stackPos++ = m3y;
  75709. *stackPos++ = m3x;
  75710. *stackPos++ = m5y;
  75711. *stackPos++ = m5x;
  75712. *stackPos++ = Path::cubicMarker;
  75713. *stackPos++ = (m4y + m5y) * 0.5f;
  75714. *stackPos++ = (m4x + m5x) * 0.5f;
  75715. *stackPos++ = m4y;
  75716. *stackPos++ = m4x;
  75717. *stackPos++ = m1y;
  75718. *stackPos++ = m1x;
  75719. *stackPos++ = Path::cubicMarker;
  75720. }
  75721. else
  75722. {
  75723. *stackPos++ = y4;
  75724. *stackPos++ = x4;
  75725. *stackPos++ = Path::lineMarker;
  75726. *stackPos++ = m5y;
  75727. *stackPos++ = m5x;
  75728. *stackPos++ = Path::lineMarker;
  75729. *stackPos++ = m4y;
  75730. *stackPos++ = m4x;
  75731. *stackPos++ = Path::lineMarker;
  75732. }
  75733. }
  75734. else if (type == Path::closeSubPathMarker)
  75735. {
  75736. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75737. {
  75738. x1 = x2;
  75739. y1 = y2;
  75740. x2 = subPathCloseX;
  75741. y2 = subPathCloseY;
  75742. closesSubPath = true;
  75743. return true;
  75744. }
  75745. }
  75746. else
  75747. {
  75748. jassert (type == Path::moveMarker);
  75749. subPathIndex = -1;
  75750. subPathCloseX = x1 = x2;
  75751. subPathCloseY = y1 = y2;
  75752. }
  75753. }
  75754. }
  75755. #if JUCE_MSVC && JUCE_DEBUG
  75756. #pragma optimize ("", on) // resets optimisations to the project defaults
  75757. #endif
  75758. END_JUCE_NAMESPACE
  75759. /*** End of inlined file: juce_PathIterator.cpp ***/
  75760. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75761. BEGIN_JUCE_NAMESPACE
  75762. PathStrokeType::PathStrokeType (const float strokeThickness,
  75763. const JointStyle jointStyle_,
  75764. const EndCapStyle endStyle_) throw()
  75765. : thickness (strokeThickness),
  75766. jointStyle (jointStyle_),
  75767. endStyle (endStyle_)
  75768. {
  75769. }
  75770. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75771. : thickness (other.thickness),
  75772. jointStyle (other.jointStyle),
  75773. endStyle (other.endStyle)
  75774. {
  75775. }
  75776. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75777. {
  75778. thickness = other.thickness;
  75779. jointStyle = other.jointStyle;
  75780. endStyle = other.endStyle;
  75781. return *this;
  75782. }
  75783. PathStrokeType::~PathStrokeType() throw()
  75784. {
  75785. }
  75786. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75787. {
  75788. return thickness == other.thickness
  75789. && jointStyle == other.jointStyle
  75790. && endStyle == other.endStyle;
  75791. }
  75792. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75793. {
  75794. return ! operator== (other);
  75795. }
  75796. namespace PathStrokeHelpers
  75797. {
  75798. bool lineIntersection (const float x1, const float y1,
  75799. const float x2, const float y2,
  75800. const float x3, const float y3,
  75801. const float x4, const float y4,
  75802. float& intersectionX,
  75803. float& intersectionY,
  75804. float& distanceBeyondLine1EndSquared) throw()
  75805. {
  75806. if (x2 != x3 || y2 != y3)
  75807. {
  75808. const float dx1 = x2 - x1;
  75809. const float dy1 = y2 - y1;
  75810. const float dx2 = x4 - x3;
  75811. const float dy2 = y4 - y3;
  75812. const float divisor = dx1 * dy2 - dx2 * dy1;
  75813. if (divisor == 0)
  75814. {
  75815. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75816. {
  75817. if (dy1 == 0 && dy2 != 0)
  75818. {
  75819. const float along = (y1 - y3) / dy2;
  75820. intersectionX = x3 + along * dx2;
  75821. intersectionY = y1;
  75822. distanceBeyondLine1EndSquared = intersectionX - x2;
  75823. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75824. if ((x2 > x1) == (intersectionX < x2))
  75825. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75826. return along >= 0 && along <= 1.0f;
  75827. }
  75828. else if (dy2 == 0 && dy1 != 0)
  75829. {
  75830. const float along = (y3 - y1) / dy1;
  75831. intersectionX = x1 + along * dx1;
  75832. intersectionY = y3;
  75833. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75834. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75835. if (along < 1.0f)
  75836. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75837. return along >= 0 && along <= 1.0f;
  75838. }
  75839. else if (dx1 == 0 && dx2 != 0)
  75840. {
  75841. const float along = (x1 - x3) / dx2;
  75842. intersectionX = x1;
  75843. intersectionY = y3 + along * dy2;
  75844. distanceBeyondLine1EndSquared = intersectionY - y2;
  75845. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75846. if ((y2 > y1) == (intersectionY < y2))
  75847. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75848. return along >= 0 && along <= 1.0f;
  75849. }
  75850. else if (dx2 == 0 && dx1 != 0)
  75851. {
  75852. const float along = (x3 - x1) / dx1;
  75853. intersectionX = x3;
  75854. intersectionY = y1 + along * dy1;
  75855. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75856. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75857. if (along < 1.0f)
  75858. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75859. return along >= 0 && along <= 1.0f;
  75860. }
  75861. }
  75862. intersectionX = 0.5f * (x2 + x3);
  75863. intersectionY = 0.5f * (y2 + y3);
  75864. distanceBeyondLine1EndSquared = 0.0f;
  75865. return false;
  75866. }
  75867. else
  75868. {
  75869. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75870. intersectionX = x1 + along1 * dx1;
  75871. intersectionY = y1 + along1 * dy1;
  75872. if (along1 >= 0 && along1 <= 1.0f)
  75873. {
  75874. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75875. if (along2 >= 0 && along2 <= divisor)
  75876. {
  75877. distanceBeyondLine1EndSquared = 0.0f;
  75878. return true;
  75879. }
  75880. }
  75881. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75882. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75883. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75884. if (along1 < 1.0f)
  75885. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75886. return false;
  75887. }
  75888. }
  75889. intersectionX = x2;
  75890. intersectionY = y2;
  75891. distanceBeyondLine1EndSquared = 0.0f;
  75892. return true;
  75893. }
  75894. void addEdgeAndJoint (Path& destPath,
  75895. const PathStrokeType::JointStyle style,
  75896. const float maxMiterExtensionSquared, const float width,
  75897. const float x1, const float y1,
  75898. const float x2, const float y2,
  75899. const float x3, const float y3,
  75900. const float x4, const float y4,
  75901. const float midX, const float midY)
  75902. {
  75903. if (style == PathStrokeType::beveled
  75904. || (x3 == x4 && y3 == y4)
  75905. || (x1 == x2 && y1 == y2))
  75906. {
  75907. destPath.lineTo (x2, y2);
  75908. destPath.lineTo (x3, y3);
  75909. }
  75910. else
  75911. {
  75912. float jx, jy, distanceBeyondLine1EndSquared;
  75913. // if they intersect, use this point..
  75914. if (lineIntersection (x1, y1, x2, y2,
  75915. x3, y3, x4, y4,
  75916. jx, jy, distanceBeyondLine1EndSquared))
  75917. {
  75918. destPath.lineTo (jx, jy);
  75919. }
  75920. else
  75921. {
  75922. if (style == PathStrokeType::mitered)
  75923. {
  75924. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75925. && distanceBeyondLine1EndSquared > 0.0f)
  75926. {
  75927. destPath.lineTo (jx, jy);
  75928. }
  75929. else
  75930. {
  75931. // the end sticks out too far, so just use a blunt joint
  75932. destPath.lineTo (x2, y2);
  75933. destPath.lineTo (x3, y3);
  75934. }
  75935. }
  75936. else
  75937. {
  75938. // curved joints
  75939. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75940. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75941. const float angleIncrement = 0.1f;
  75942. destPath.lineTo (x2, y2);
  75943. if (std::abs (angle1 - angle2) > angleIncrement)
  75944. {
  75945. if (angle2 > angle1 + float_Pi
  75946. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75947. {
  75948. if (angle2 > angle1)
  75949. angle2 -= float_Pi * 2.0f;
  75950. jassert (angle1 <= angle2 + float_Pi);
  75951. angle1 -= angleIncrement;
  75952. while (angle1 > angle2)
  75953. {
  75954. destPath.lineTo (midX + width * std::sin (angle1),
  75955. midY + width * std::cos (angle1));
  75956. angle1 -= angleIncrement;
  75957. }
  75958. }
  75959. else
  75960. {
  75961. if (angle1 > angle2)
  75962. angle1 -= float_Pi * 2.0f;
  75963. jassert (angle1 >= angle2 - float_Pi);
  75964. angle1 += angleIncrement;
  75965. while (angle1 < angle2)
  75966. {
  75967. destPath.lineTo (midX + width * std::sin (angle1),
  75968. midY + width * std::cos (angle1));
  75969. angle1 += angleIncrement;
  75970. }
  75971. }
  75972. }
  75973. destPath.lineTo (x3, y3);
  75974. }
  75975. }
  75976. }
  75977. }
  75978. void addLineEnd (Path& destPath,
  75979. const PathStrokeType::EndCapStyle style,
  75980. const float x1, const float y1,
  75981. const float x2, const float y2,
  75982. const float width)
  75983. {
  75984. if (style == PathStrokeType::butt)
  75985. {
  75986. destPath.lineTo (x2, y2);
  75987. }
  75988. else
  75989. {
  75990. float offx1, offy1, offx2, offy2;
  75991. float dx = x2 - x1;
  75992. float dy = y2 - y1;
  75993. const float len = juce_hypot (dx, dy);
  75994. if (len == 0)
  75995. {
  75996. offx1 = offx2 = x1;
  75997. offy1 = offy2 = y1;
  75998. }
  75999. else
  76000. {
  76001. const float offset = width / len;
  76002. dx *= offset;
  76003. dy *= offset;
  76004. offx1 = x1 + dy;
  76005. offy1 = y1 - dx;
  76006. offx2 = x2 + dy;
  76007. offy2 = y2 - dx;
  76008. }
  76009. if (style == PathStrokeType::square)
  76010. {
  76011. // sqaure ends
  76012. destPath.lineTo (offx1, offy1);
  76013. destPath.lineTo (offx2, offy2);
  76014. destPath.lineTo (x2, y2);
  76015. }
  76016. else
  76017. {
  76018. // rounded ends
  76019. const float midx = (offx1 + offx2) * 0.5f;
  76020. const float midy = (offy1 + offy2) * 0.5f;
  76021. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  76022. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  76023. midx, midy);
  76024. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  76025. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  76026. x2, y2);
  76027. }
  76028. }
  76029. }
  76030. struct Arrowhead
  76031. {
  76032. float startWidth, startLength;
  76033. float endWidth, endLength;
  76034. };
  76035. void addArrowhead (Path& destPath,
  76036. const float x1, const float y1,
  76037. const float x2, const float y2,
  76038. const float tipX, const float tipY,
  76039. const float width,
  76040. const float arrowheadWidth)
  76041. {
  76042. Line<float> line (x1, y1, x2, y2);
  76043. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  76044. destPath.lineTo (tipX, tipY);
  76045. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  76046. destPath.lineTo (x2, y2);
  76047. }
  76048. struct LineSection
  76049. {
  76050. float x1, y1, x2, y2; // original line
  76051. float lx1, ly1, lx2, ly2; // the left-hand stroke
  76052. float rx1, ry1, rx2, ry2; // the right-hand stroke
  76053. };
  76054. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  76055. {
  76056. while (amountAtEnd > 0 && subPath.size() > 0)
  76057. {
  76058. LineSection& l = subPath.getReference (subPath.size() - 1);
  76059. float dx = l.rx2 - l.rx1;
  76060. float dy = l.ry2 - l.ry1;
  76061. const float len = juce_hypot (dx, dy);
  76062. if (len <= amountAtEnd && subPath.size() > 1)
  76063. {
  76064. LineSection& prev = subPath.getReference (subPath.size() - 2);
  76065. prev.x2 = l.x2;
  76066. prev.y2 = l.y2;
  76067. subPath.removeLast();
  76068. amountAtEnd -= len;
  76069. }
  76070. else
  76071. {
  76072. const float prop = jmin (0.9999f, amountAtEnd / len);
  76073. dx *= prop;
  76074. dy *= prop;
  76075. l.rx1 += dx;
  76076. l.ry1 += dy;
  76077. l.lx2 += dx;
  76078. l.ly2 += dy;
  76079. break;
  76080. }
  76081. }
  76082. while (amountAtStart > 0 && subPath.size() > 0)
  76083. {
  76084. LineSection& l = subPath.getReference (0);
  76085. float dx = l.rx2 - l.rx1;
  76086. float dy = l.ry2 - l.ry1;
  76087. const float len = juce_hypot (dx, dy);
  76088. if (len <= amountAtStart && subPath.size() > 1)
  76089. {
  76090. LineSection& next = subPath.getReference (1);
  76091. next.x1 = l.x1;
  76092. next.y1 = l.y1;
  76093. subPath.remove (0);
  76094. amountAtStart -= len;
  76095. }
  76096. else
  76097. {
  76098. const float prop = jmin (0.9999f, amountAtStart / len);
  76099. dx *= prop;
  76100. dy *= prop;
  76101. l.rx2 -= dx;
  76102. l.ry2 -= dy;
  76103. l.lx1 -= dx;
  76104. l.ly1 -= dy;
  76105. break;
  76106. }
  76107. }
  76108. }
  76109. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  76110. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  76111. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  76112. const Arrowhead* const arrowhead)
  76113. {
  76114. jassert (subPath.size() > 0);
  76115. if (arrowhead != 0)
  76116. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  76117. const LineSection& firstLine = subPath.getReference (0);
  76118. float lastX1 = firstLine.lx1;
  76119. float lastY1 = firstLine.ly1;
  76120. float lastX2 = firstLine.lx2;
  76121. float lastY2 = firstLine.ly2;
  76122. if (isClosed)
  76123. {
  76124. destPath.startNewSubPath (lastX1, lastY1);
  76125. }
  76126. else
  76127. {
  76128. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  76129. if (arrowhead != 0)
  76130. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  76131. width, arrowhead->startWidth);
  76132. else
  76133. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  76134. }
  76135. int i;
  76136. for (i = 1; i < subPath.size(); ++i)
  76137. {
  76138. const LineSection& l = subPath.getReference (i);
  76139. addEdgeAndJoint (destPath, jointStyle,
  76140. maxMiterExtensionSquared, width,
  76141. lastX1, lastY1, lastX2, lastY2,
  76142. l.lx1, l.ly1, l.lx2, l.ly2,
  76143. l.x1, l.y1);
  76144. lastX1 = l.lx1;
  76145. lastY1 = l.ly1;
  76146. lastX2 = l.lx2;
  76147. lastY2 = l.ly2;
  76148. }
  76149. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  76150. if (isClosed)
  76151. {
  76152. const LineSection& l = subPath.getReference (0);
  76153. addEdgeAndJoint (destPath, jointStyle,
  76154. maxMiterExtensionSquared, width,
  76155. lastX1, lastY1, lastX2, lastY2,
  76156. l.lx1, l.ly1, l.lx2, l.ly2,
  76157. l.x1, l.y1);
  76158. destPath.closeSubPath();
  76159. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  76160. }
  76161. else
  76162. {
  76163. destPath.lineTo (lastX2, lastY2);
  76164. if (arrowhead != 0)
  76165. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  76166. width, arrowhead->endWidth);
  76167. else
  76168. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  76169. }
  76170. lastX1 = lastLine.rx1;
  76171. lastY1 = lastLine.ry1;
  76172. lastX2 = lastLine.rx2;
  76173. lastY2 = lastLine.ry2;
  76174. for (i = subPath.size() - 1; --i >= 0;)
  76175. {
  76176. const LineSection& l = subPath.getReference (i);
  76177. addEdgeAndJoint (destPath, jointStyle,
  76178. maxMiterExtensionSquared, width,
  76179. lastX1, lastY1, lastX2, lastY2,
  76180. l.rx1, l.ry1, l.rx2, l.ry2,
  76181. l.x2, l.y2);
  76182. lastX1 = l.rx1;
  76183. lastY1 = l.ry1;
  76184. lastX2 = l.rx2;
  76185. lastY2 = l.ry2;
  76186. }
  76187. if (isClosed)
  76188. {
  76189. addEdgeAndJoint (destPath, jointStyle,
  76190. maxMiterExtensionSquared, width,
  76191. lastX1, lastY1, lastX2, lastY2,
  76192. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  76193. lastLine.x2, lastLine.y2);
  76194. }
  76195. else
  76196. {
  76197. // do the last line
  76198. destPath.lineTo (lastX2, lastY2);
  76199. }
  76200. destPath.closeSubPath();
  76201. }
  76202. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  76203. const PathStrokeType::EndCapStyle endStyle,
  76204. Path& destPath, const Path& source,
  76205. const AffineTransform& transform,
  76206. const float extraAccuracy, const Arrowhead* const arrowhead)
  76207. {
  76208. jassert (extraAccuracy > 0);
  76209. if (thickness <= 0)
  76210. {
  76211. destPath.clear();
  76212. return;
  76213. }
  76214. const Path* sourcePath = &source;
  76215. Path temp;
  76216. if (sourcePath == &destPath)
  76217. {
  76218. destPath.swapWithPath (temp);
  76219. sourcePath = &temp;
  76220. }
  76221. else
  76222. {
  76223. destPath.clear();
  76224. }
  76225. destPath.setUsingNonZeroWinding (true);
  76226. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76227. const float width = 0.5f * thickness;
  76228. // Iterate the path, creating a list of the
  76229. // left/right-hand lines along either side of it...
  76230. PathFlatteningIterator it (*sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76231. Array <LineSection> subPath;
  76232. subPath.ensureStorageAllocated (512);
  76233. LineSection l;
  76234. l.x1 = 0;
  76235. l.y1 = 0;
  76236. const float minSegmentLength = 0.0001f;
  76237. while (it.next())
  76238. {
  76239. if (it.subPathIndex == 0)
  76240. {
  76241. if (subPath.size() > 0)
  76242. {
  76243. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76244. subPath.clearQuick();
  76245. }
  76246. l.x1 = it.x1;
  76247. l.y1 = it.y1;
  76248. }
  76249. l.x2 = it.x2;
  76250. l.y2 = it.y2;
  76251. float dx = l.x2 - l.x1;
  76252. float dy = l.y2 - l.y1;
  76253. const float hypotSquared = dx*dx + dy*dy;
  76254. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76255. {
  76256. const float len = std::sqrt (hypotSquared);
  76257. if (len == 0)
  76258. {
  76259. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76260. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76261. }
  76262. else
  76263. {
  76264. const float offset = width / len;
  76265. dx *= offset;
  76266. dy *= offset;
  76267. l.rx2 = l.x1 - dy;
  76268. l.ry2 = l.y1 + dx;
  76269. l.lx1 = l.x1 + dy;
  76270. l.ly1 = l.y1 - dx;
  76271. l.lx2 = l.x2 + dy;
  76272. l.ly2 = l.y2 - dx;
  76273. l.rx1 = l.x2 - dy;
  76274. l.ry1 = l.y2 + dx;
  76275. }
  76276. subPath.add (l);
  76277. if (it.closesSubPath)
  76278. {
  76279. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76280. subPath.clearQuick();
  76281. }
  76282. else
  76283. {
  76284. l.x1 = it.x2;
  76285. l.y1 = it.y2;
  76286. }
  76287. }
  76288. }
  76289. if (subPath.size() > 0)
  76290. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76291. }
  76292. }
  76293. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76294. const AffineTransform& transform, const float extraAccuracy) const
  76295. {
  76296. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76297. transform, extraAccuracy, 0);
  76298. }
  76299. void PathStrokeType::createDashedStroke (Path& destPath,
  76300. const Path& sourcePath,
  76301. const float* dashLengths,
  76302. int numDashLengths,
  76303. const AffineTransform& transform,
  76304. const float extraAccuracy) const
  76305. {
  76306. jassert (extraAccuracy > 0);
  76307. if (thickness <= 0)
  76308. return;
  76309. // this should really be an even number..
  76310. jassert ((numDashLengths & 1) == 0);
  76311. Path newDestPath;
  76312. PathFlatteningIterator it (sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76313. bool first = true;
  76314. int dashNum = 0;
  76315. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76316. float dx = 0.0f, dy = 0.0f;
  76317. for (;;)
  76318. {
  76319. const bool isSolid = ((dashNum & 1) == 0);
  76320. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76321. jassert (dashLen > 0); // must be a positive increment!
  76322. if (dashLen <= 0)
  76323. break;
  76324. pos += dashLen;
  76325. while (pos > lineEndPos)
  76326. {
  76327. if (! it.next())
  76328. {
  76329. if (isSolid && ! first)
  76330. newDestPath.lineTo (it.x2, it.y2);
  76331. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76332. return;
  76333. }
  76334. if (isSolid && ! first)
  76335. newDestPath.lineTo (it.x1, it.y1);
  76336. else
  76337. newDestPath.startNewSubPath (it.x1, it.y1);
  76338. dx = it.x2 - it.x1;
  76339. dy = it.y2 - it.y1;
  76340. lineLen = juce_hypot (dx, dy);
  76341. lineEndPos += lineLen;
  76342. first = it.closesSubPath;
  76343. }
  76344. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76345. if (isSolid)
  76346. newDestPath.lineTo (it.x1 + dx * alpha,
  76347. it.y1 + dy * alpha);
  76348. else
  76349. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76350. it.y1 + dy * alpha);
  76351. }
  76352. }
  76353. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76354. const Path& sourcePath,
  76355. const float arrowheadStartWidth, const float arrowheadStartLength,
  76356. const float arrowheadEndWidth, const float arrowheadEndLength,
  76357. const AffineTransform& transform,
  76358. const float extraAccuracy) const
  76359. {
  76360. PathStrokeHelpers::Arrowhead head;
  76361. head.startWidth = arrowheadStartWidth;
  76362. head.startLength = arrowheadStartLength;
  76363. head.endWidth = arrowheadEndWidth;
  76364. head.endLength = arrowheadEndLength;
  76365. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76366. destPath, sourcePath, transform, extraAccuracy, &head);
  76367. }
  76368. END_JUCE_NAMESPACE
  76369. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76370. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76371. BEGIN_JUCE_NAMESPACE
  76372. PositionedRectangle::PositionedRectangle() throw()
  76373. : x (0.0),
  76374. y (0.0),
  76375. w (0.0),
  76376. h (0.0),
  76377. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76378. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76379. wMode (absoluteSize),
  76380. hMode (absoluteSize)
  76381. {
  76382. }
  76383. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76384. : x (other.x),
  76385. y (other.y),
  76386. w (other.w),
  76387. h (other.h),
  76388. xMode (other.xMode),
  76389. yMode (other.yMode),
  76390. wMode (other.wMode),
  76391. hMode (other.hMode)
  76392. {
  76393. }
  76394. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76395. {
  76396. x = other.x;
  76397. y = other.y;
  76398. w = other.w;
  76399. h = other.h;
  76400. xMode = other.xMode;
  76401. yMode = other.yMode;
  76402. wMode = other.wMode;
  76403. hMode = other.hMode;
  76404. return *this;
  76405. }
  76406. PositionedRectangle::~PositionedRectangle() throw()
  76407. {
  76408. }
  76409. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76410. {
  76411. return x == other.x
  76412. && y == other.y
  76413. && w == other.w
  76414. && h == other.h
  76415. && xMode == other.xMode
  76416. && yMode == other.yMode
  76417. && wMode == other.wMode
  76418. && hMode == other.hMode;
  76419. }
  76420. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76421. {
  76422. return ! operator== (other);
  76423. }
  76424. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76425. {
  76426. StringArray tokens;
  76427. tokens.addTokens (stringVersion, false);
  76428. decodePosString (tokens [0], xMode, x);
  76429. decodePosString (tokens [1], yMode, y);
  76430. decodeSizeString (tokens [2], wMode, w);
  76431. decodeSizeString (tokens [3], hMode, h);
  76432. }
  76433. const String PositionedRectangle::toString() const throw()
  76434. {
  76435. String s;
  76436. s.preallocateStorage (12);
  76437. addPosDescription (s, xMode, x);
  76438. s << ' ';
  76439. addPosDescription (s, yMode, y);
  76440. s << ' ';
  76441. addSizeDescription (s, wMode, w);
  76442. s << ' ';
  76443. addSizeDescription (s, hMode, h);
  76444. return s;
  76445. }
  76446. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76447. {
  76448. jassert (! target.isEmpty());
  76449. double x_, y_, w_, h_;
  76450. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76451. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76452. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76453. roundToInt (w_), roundToInt (h_));
  76454. }
  76455. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76456. double& x_, double& y_,
  76457. double& w_, double& h_) const throw()
  76458. {
  76459. jassert (! target.isEmpty());
  76460. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76461. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76462. }
  76463. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76464. {
  76465. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76466. }
  76467. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76468. const Rectangle<int>& target) throw()
  76469. {
  76470. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76471. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76472. }
  76473. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76474. const double newW, const double newH,
  76475. const Rectangle<int>& target) throw()
  76476. {
  76477. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76478. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76479. }
  76480. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76481. {
  76482. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76483. updateFrom (comp.getBounds(), Rectangle<int>());
  76484. else
  76485. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76486. }
  76487. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76488. {
  76489. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76490. }
  76491. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76492. {
  76493. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76494. | absoluteFromParentBottomRight
  76495. | absoluteFromParentCentre
  76496. | proportionOfParentSize));
  76497. }
  76498. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76499. {
  76500. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76501. }
  76502. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76503. {
  76504. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76505. | absoluteFromParentBottomRight
  76506. | absoluteFromParentCentre
  76507. | proportionOfParentSize));
  76508. }
  76509. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76510. {
  76511. return (SizeMode) wMode;
  76512. }
  76513. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76514. {
  76515. return (SizeMode) hMode;
  76516. }
  76517. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76518. const PositionMode xMode_,
  76519. const AnchorPoint yAnchor,
  76520. const PositionMode yMode_,
  76521. const SizeMode widthMode,
  76522. const SizeMode heightMode,
  76523. const Rectangle<int>& target) throw()
  76524. {
  76525. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76526. {
  76527. double tx, tw;
  76528. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76529. xMode = (uint8) (xAnchor | xMode_);
  76530. wMode = (uint8) widthMode;
  76531. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76532. }
  76533. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76534. {
  76535. double ty, th;
  76536. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76537. yMode = (uint8) (yAnchor | yMode_);
  76538. hMode = (uint8) heightMode;
  76539. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76540. }
  76541. }
  76542. bool PositionedRectangle::isPositionAbsolute() const throw()
  76543. {
  76544. return xMode == absoluteFromParentTopLeft
  76545. && yMode == absoluteFromParentTopLeft
  76546. && wMode == absoluteSize
  76547. && hMode == absoluteSize;
  76548. }
  76549. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76550. {
  76551. if ((mode & proportionOfParentSize) != 0)
  76552. {
  76553. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76554. }
  76555. else
  76556. {
  76557. s << (roundToInt (value * 100.0) / 100.0);
  76558. if ((mode & absoluteFromParentBottomRight) != 0)
  76559. s << 'R';
  76560. else if ((mode & absoluteFromParentCentre) != 0)
  76561. s << 'C';
  76562. }
  76563. if ((mode & anchorAtRightOrBottom) != 0)
  76564. s << 'r';
  76565. else if ((mode & anchorAtCentre) != 0)
  76566. s << 'c';
  76567. }
  76568. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76569. {
  76570. if (mode == proportionalSize)
  76571. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76572. else if (mode == parentSizeMinusAbsolute)
  76573. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76574. else
  76575. s << (roundToInt (value * 100.0) / 100.0);
  76576. }
  76577. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76578. {
  76579. if (s.containsChar ('r'))
  76580. mode = anchorAtRightOrBottom;
  76581. else if (s.containsChar ('c'))
  76582. mode = anchorAtCentre;
  76583. else
  76584. mode = anchorAtLeftOrTop;
  76585. if (s.containsChar ('%'))
  76586. {
  76587. mode |= proportionOfParentSize;
  76588. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76589. }
  76590. else
  76591. {
  76592. if (s.containsChar ('R'))
  76593. mode |= absoluteFromParentBottomRight;
  76594. else if (s.containsChar ('C'))
  76595. mode |= absoluteFromParentCentre;
  76596. else
  76597. mode |= absoluteFromParentTopLeft;
  76598. value = s.removeCharacters ("rcRC").getDoubleValue();
  76599. }
  76600. }
  76601. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76602. {
  76603. if (s.containsChar ('%'))
  76604. {
  76605. mode = proportionalSize;
  76606. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76607. }
  76608. else if (s.containsChar ('M'))
  76609. {
  76610. mode = parentSizeMinusAbsolute;
  76611. value = s.getDoubleValue();
  76612. }
  76613. else
  76614. {
  76615. mode = absoluteSize;
  76616. value = s.getDoubleValue();
  76617. }
  76618. }
  76619. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76620. const double x_, const double w_,
  76621. const uint8 xMode_, const uint8 wMode_,
  76622. const int parentPos,
  76623. const int parentSize) const throw()
  76624. {
  76625. if (wMode_ == proportionalSize)
  76626. wOut = roundToInt (w_ * parentSize);
  76627. else if (wMode_ == parentSizeMinusAbsolute)
  76628. wOut = jmax (0, parentSize - roundToInt (w_));
  76629. else
  76630. wOut = roundToInt (w_);
  76631. if ((xMode_ & proportionOfParentSize) != 0)
  76632. xOut = parentPos + x_ * parentSize;
  76633. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76634. xOut = (parentPos + parentSize) - x_;
  76635. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76636. xOut = x_ + (parentPos + parentSize / 2);
  76637. else
  76638. xOut = x_ + parentPos;
  76639. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76640. xOut -= wOut;
  76641. else if ((xMode_ & anchorAtCentre) != 0)
  76642. xOut -= wOut / 2;
  76643. }
  76644. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76645. double x_, const double w_,
  76646. const uint8 xMode_, const uint8 wMode_,
  76647. const int parentPos,
  76648. const int parentSize) const throw()
  76649. {
  76650. if (wMode_ == proportionalSize)
  76651. {
  76652. if (parentSize > 0)
  76653. wOut = w_ / parentSize;
  76654. }
  76655. else if (wMode_ == parentSizeMinusAbsolute)
  76656. wOut = parentSize - w_;
  76657. else
  76658. wOut = w_;
  76659. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76660. x_ += w_;
  76661. else if ((xMode_ & anchorAtCentre) != 0)
  76662. x_ += w_ / 2;
  76663. if ((xMode_ & proportionOfParentSize) != 0)
  76664. {
  76665. if (parentSize > 0)
  76666. xOut = (x_ - parentPos) / parentSize;
  76667. }
  76668. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76669. xOut = (parentPos + parentSize) - x_;
  76670. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76671. xOut = x_ - (parentPos + parentSize / 2);
  76672. else
  76673. xOut = x_ - parentPos;
  76674. }
  76675. END_JUCE_NAMESPACE
  76676. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76677. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76678. BEGIN_JUCE_NAMESPACE
  76679. RectangleList::RectangleList() throw()
  76680. {
  76681. }
  76682. RectangleList::RectangleList (const Rectangle<int>& rect)
  76683. {
  76684. if (! rect.isEmpty())
  76685. rects.add (rect);
  76686. }
  76687. RectangleList::RectangleList (const RectangleList& other)
  76688. : rects (other.rects)
  76689. {
  76690. }
  76691. RectangleList& RectangleList::operator= (const RectangleList& other)
  76692. {
  76693. rects = other.rects;
  76694. return *this;
  76695. }
  76696. RectangleList::~RectangleList()
  76697. {
  76698. }
  76699. void RectangleList::clear()
  76700. {
  76701. rects.clearQuick();
  76702. }
  76703. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76704. {
  76705. if (isPositiveAndBelow (index, rects.size()))
  76706. return rects.getReference (index);
  76707. return Rectangle<int>();
  76708. }
  76709. bool RectangleList::isEmpty() const throw()
  76710. {
  76711. return rects.size() == 0;
  76712. }
  76713. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76714. : current (0),
  76715. owner (list),
  76716. index (list.rects.size())
  76717. {
  76718. }
  76719. RectangleList::Iterator::~Iterator()
  76720. {
  76721. }
  76722. bool RectangleList::Iterator::next() throw()
  76723. {
  76724. if (--index >= 0)
  76725. {
  76726. current = & (owner.rects.getReference (index));
  76727. return true;
  76728. }
  76729. return false;
  76730. }
  76731. void RectangleList::add (const Rectangle<int>& rect)
  76732. {
  76733. if (! rect.isEmpty())
  76734. {
  76735. if (rects.size() == 0)
  76736. {
  76737. rects.add (rect);
  76738. }
  76739. else
  76740. {
  76741. bool anyOverlaps = false;
  76742. int i;
  76743. for (i = rects.size(); --i >= 0;)
  76744. {
  76745. Rectangle<int>& ourRect = rects.getReference (i);
  76746. if (rect.intersects (ourRect))
  76747. {
  76748. if (rect.contains (ourRect))
  76749. rects.remove (i);
  76750. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76751. anyOverlaps = true;
  76752. }
  76753. }
  76754. if (anyOverlaps && rects.size() > 0)
  76755. {
  76756. RectangleList r (rect);
  76757. for (i = rects.size(); --i >= 0;)
  76758. {
  76759. const Rectangle<int>& ourRect = rects.getReference (i);
  76760. if (rect.intersects (ourRect))
  76761. {
  76762. r.subtract (ourRect);
  76763. if (r.rects.size() == 0)
  76764. return;
  76765. }
  76766. }
  76767. for (i = r.getNumRectangles(); --i >= 0;)
  76768. rects.add (r.rects.getReference (i));
  76769. }
  76770. else
  76771. {
  76772. rects.add (rect);
  76773. }
  76774. }
  76775. }
  76776. }
  76777. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76778. {
  76779. if (! rect.isEmpty())
  76780. rects.add (rect);
  76781. }
  76782. void RectangleList::add (const int x, const int y, const int w, const int h)
  76783. {
  76784. if (rects.size() == 0)
  76785. {
  76786. if (w > 0 && h > 0)
  76787. rects.add (Rectangle<int> (x, y, w, h));
  76788. }
  76789. else
  76790. {
  76791. add (Rectangle<int> (x, y, w, h));
  76792. }
  76793. }
  76794. void RectangleList::add (const RectangleList& other)
  76795. {
  76796. for (int i = 0; i < other.rects.size(); ++i)
  76797. add (other.rects.getReference (i));
  76798. }
  76799. void RectangleList::subtract (const Rectangle<int>& rect)
  76800. {
  76801. const int originalNumRects = rects.size();
  76802. if (originalNumRects > 0)
  76803. {
  76804. const int x1 = rect.x;
  76805. const int y1 = rect.y;
  76806. const int x2 = x1 + rect.w;
  76807. const int y2 = y1 + rect.h;
  76808. for (int i = getNumRectangles(); --i >= 0;)
  76809. {
  76810. Rectangle<int>& r = rects.getReference (i);
  76811. const int rx1 = r.x;
  76812. const int ry1 = r.y;
  76813. const int rx2 = rx1 + r.w;
  76814. const int ry2 = ry1 + r.h;
  76815. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76816. {
  76817. if (x1 > rx1 && x1 < rx2)
  76818. {
  76819. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76820. {
  76821. r.w = x1 - rx1;
  76822. }
  76823. else
  76824. {
  76825. r.x = x1;
  76826. r.w = rx2 - x1;
  76827. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76828. i += 2;
  76829. }
  76830. }
  76831. else if (x2 > rx1 && x2 < rx2)
  76832. {
  76833. r.x = x2;
  76834. r.w = rx2 - x2;
  76835. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76836. {
  76837. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76838. i += 2;
  76839. }
  76840. }
  76841. else if (y1 > ry1 && y1 < ry2)
  76842. {
  76843. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76844. {
  76845. r.h = y1 - ry1;
  76846. }
  76847. else
  76848. {
  76849. r.y = y1;
  76850. r.h = ry2 - y1;
  76851. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76852. i += 2;
  76853. }
  76854. }
  76855. else if (y2 > ry1 && y2 < ry2)
  76856. {
  76857. r.y = y2;
  76858. r.h = ry2 - y2;
  76859. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76860. {
  76861. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76862. i += 2;
  76863. }
  76864. }
  76865. else
  76866. {
  76867. rects.remove (i);
  76868. }
  76869. }
  76870. }
  76871. }
  76872. }
  76873. bool RectangleList::subtract (const RectangleList& otherList)
  76874. {
  76875. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76876. subtract (otherList.rects.getReference (i));
  76877. return rects.size() > 0;
  76878. }
  76879. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76880. {
  76881. bool notEmpty = false;
  76882. if (rect.isEmpty())
  76883. {
  76884. clear();
  76885. }
  76886. else
  76887. {
  76888. for (int i = rects.size(); --i >= 0;)
  76889. {
  76890. Rectangle<int>& r = rects.getReference (i);
  76891. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76892. rects.remove (i);
  76893. else
  76894. notEmpty = true;
  76895. }
  76896. }
  76897. return notEmpty;
  76898. }
  76899. bool RectangleList::clipTo (const RectangleList& other)
  76900. {
  76901. if (rects.size() == 0)
  76902. return false;
  76903. RectangleList result;
  76904. for (int j = 0; j < rects.size(); ++j)
  76905. {
  76906. const Rectangle<int>& rect = rects.getReference (j);
  76907. for (int i = other.rects.size(); --i >= 0;)
  76908. {
  76909. Rectangle<int> r (other.rects.getReference (i));
  76910. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76911. result.rects.add (r);
  76912. }
  76913. }
  76914. swapWith (result);
  76915. return ! isEmpty();
  76916. }
  76917. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76918. {
  76919. destRegion.clear();
  76920. if (! rect.isEmpty())
  76921. {
  76922. for (int i = rects.size(); --i >= 0;)
  76923. {
  76924. Rectangle<int> r (rects.getReference (i));
  76925. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76926. destRegion.rects.add (r);
  76927. }
  76928. }
  76929. return destRegion.rects.size() > 0;
  76930. }
  76931. void RectangleList::swapWith (RectangleList& otherList) throw()
  76932. {
  76933. rects.swapWithArray (otherList.rects);
  76934. }
  76935. void RectangleList::consolidate()
  76936. {
  76937. int i;
  76938. for (i = 0; i < getNumRectangles() - 1; ++i)
  76939. {
  76940. Rectangle<int>& r = rects.getReference (i);
  76941. const int rx1 = r.x;
  76942. const int ry1 = r.y;
  76943. const int rx2 = rx1 + r.w;
  76944. const int ry2 = ry1 + r.h;
  76945. for (int j = rects.size(); --j > i;)
  76946. {
  76947. Rectangle<int>& r2 = rects.getReference (j);
  76948. const int jrx1 = r2.x;
  76949. const int jry1 = r2.y;
  76950. const int jrx2 = jrx1 + r2.w;
  76951. const int jry2 = jry1 + r2.h;
  76952. // if the vertical edges of any blocks are touching and their horizontals don't
  76953. // line up, split them horizontally..
  76954. if (jrx1 == rx2 || jrx2 == rx1)
  76955. {
  76956. if (jry1 > ry1 && jry1 < ry2)
  76957. {
  76958. r.h = jry1 - ry1;
  76959. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76960. i = -1;
  76961. break;
  76962. }
  76963. if (jry2 > ry1 && jry2 < ry2)
  76964. {
  76965. r.h = jry2 - ry1;
  76966. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76967. i = -1;
  76968. break;
  76969. }
  76970. else if (ry1 > jry1 && ry1 < jry2)
  76971. {
  76972. r2.h = ry1 - jry1;
  76973. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76974. i = -1;
  76975. break;
  76976. }
  76977. else if (ry2 > jry1 && ry2 < jry2)
  76978. {
  76979. r2.h = ry2 - jry1;
  76980. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76981. i = -1;
  76982. break;
  76983. }
  76984. }
  76985. }
  76986. }
  76987. for (i = 0; i < rects.size() - 1; ++i)
  76988. {
  76989. Rectangle<int>& r = rects.getReference (i);
  76990. for (int j = rects.size(); --j > i;)
  76991. {
  76992. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76993. {
  76994. rects.remove (j);
  76995. i = -1;
  76996. break;
  76997. }
  76998. }
  76999. }
  77000. }
  77001. bool RectangleList::containsPoint (const int x, const int y) const throw()
  77002. {
  77003. for (int i = getNumRectangles(); --i >= 0;)
  77004. if (rects.getReference (i).contains (x, y))
  77005. return true;
  77006. return false;
  77007. }
  77008. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  77009. {
  77010. if (rects.size() > 1)
  77011. {
  77012. RectangleList r (rectangleToCheck);
  77013. for (int i = rects.size(); --i >= 0;)
  77014. {
  77015. r.subtract (rects.getReference (i));
  77016. if (r.rects.size() == 0)
  77017. return true;
  77018. }
  77019. }
  77020. else if (rects.size() > 0)
  77021. {
  77022. return rects.getReference (0).contains (rectangleToCheck);
  77023. }
  77024. return false;
  77025. }
  77026. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  77027. {
  77028. for (int i = rects.size(); --i >= 0;)
  77029. if (rects.getReference (i).intersects (rectangleToCheck))
  77030. return true;
  77031. return false;
  77032. }
  77033. bool RectangleList::intersects (const RectangleList& other) const throw()
  77034. {
  77035. for (int i = rects.size(); --i >= 0;)
  77036. if (other.intersectsRectangle (rects.getReference (i)))
  77037. return true;
  77038. return false;
  77039. }
  77040. const Rectangle<int> RectangleList::getBounds() const throw()
  77041. {
  77042. if (rects.size() <= 1)
  77043. {
  77044. if (rects.size() == 0)
  77045. return Rectangle<int>();
  77046. else
  77047. return rects.getReference (0);
  77048. }
  77049. else
  77050. {
  77051. const Rectangle<int>& r = rects.getReference (0);
  77052. int minX = r.x;
  77053. int minY = r.y;
  77054. int maxX = minX + r.w;
  77055. int maxY = minY + r.h;
  77056. for (int i = rects.size(); --i > 0;)
  77057. {
  77058. const Rectangle<int>& r2 = rects.getReference (i);
  77059. minX = jmin (minX, r2.x);
  77060. minY = jmin (minY, r2.y);
  77061. maxX = jmax (maxX, r2.getRight());
  77062. maxY = jmax (maxY, r2.getBottom());
  77063. }
  77064. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  77065. }
  77066. }
  77067. void RectangleList::offsetAll (const int dx, const int dy) throw()
  77068. {
  77069. for (int i = rects.size(); --i >= 0;)
  77070. {
  77071. Rectangle<int>& r = rects.getReference (i);
  77072. r.x += dx;
  77073. r.y += dy;
  77074. }
  77075. }
  77076. const Path RectangleList::toPath() const
  77077. {
  77078. Path p;
  77079. for (int i = rects.size(); --i >= 0;)
  77080. {
  77081. const Rectangle<int>& r = rects.getReference (i);
  77082. p.addRectangle ((float) r.x,
  77083. (float) r.y,
  77084. (float) r.w,
  77085. (float) r.h);
  77086. }
  77087. return p;
  77088. }
  77089. END_JUCE_NAMESPACE
  77090. /*** End of inlined file: juce_RectangleList.cpp ***/
  77091. /*** Start of inlined file: juce_Image.cpp ***/
  77092. BEGIN_JUCE_NAMESPACE
  77093. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  77094. : format (format_), width (width_), height (height_)
  77095. {
  77096. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  77097. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  77098. }
  77099. Image::SharedImage::~SharedImage()
  77100. {
  77101. }
  77102. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  77103. {
  77104. return imageData + lineStride * y + pixelStride * x;
  77105. }
  77106. class SoftwareSharedImage : public Image::SharedImage
  77107. {
  77108. public:
  77109. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  77110. : Image::SharedImage (format_, width_, height_)
  77111. {
  77112. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  77113. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  77114. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  77115. imageData = imageDataAllocated;
  77116. }
  77117. Image::ImageType getType() const
  77118. {
  77119. return Image::SoftwareImage;
  77120. }
  77121. LowLevelGraphicsContext* createLowLevelContext()
  77122. {
  77123. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  77124. }
  77125. Image::SharedImage* clone()
  77126. {
  77127. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  77128. memcpy (s->imageData, imageData, lineStride * height);
  77129. return s;
  77130. }
  77131. private:
  77132. HeapBlock<uint8> imageDataAllocated;
  77133. JUCE_LEAK_DETECTOR (SoftwareSharedImage);
  77134. };
  77135. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  77136. {
  77137. return new SoftwareSharedImage (format, width, height, clearImage);
  77138. }
  77139. class SubsectionSharedImage : public Image::SharedImage
  77140. {
  77141. public:
  77142. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  77143. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  77144. image (image_), area (area_)
  77145. {
  77146. pixelStride = image_->getPixelStride();
  77147. lineStride = image_->getLineStride();
  77148. imageData = image_->getPixelData (area_.getX(), area_.getY());
  77149. }
  77150. Image::ImageType getType() const
  77151. {
  77152. return Image::SoftwareImage;
  77153. }
  77154. LowLevelGraphicsContext* createLowLevelContext()
  77155. {
  77156. LowLevelGraphicsContext* g = image->createLowLevelContext();
  77157. g->clipToRectangle (area);
  77158. g->setOrigin (area.getX(), area.getY());
  77159. return g;
  77160. }
  77161. Image::SharedImage* clone()
  77162. {
  77163. return new SubsectionSharedImage (image->clone(), area);
  77164. }
  77165. private:
  77166. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  77167. const Rectangle<int> area;
  77168. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionSharedImage);
  77169. };
  77170. const Image Image::getClippedImage (const Rectangle<int>& area) const
  77171. {
  77172. if (area.contains (getBounds()))
  77173. return *this;
  77174. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  77175. if (validArea.isEmpty())
  77176. return Image::null;
  77177. return Image (new SubsectionSharedImage (image, validArea));
  77178. }
  77179. Image::Image()
  77180. {
  77181. }
  77182. Image::Image (SharedImage* const instance)
  77183. : image (instance)
  77184. {
  77185. }
  77186. Image::Image (const PixelFormat format,
  77187. const int width, const int height,
  77188. const bool clearImage, const ImageType type)
  77189. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  77190. : new SoftwareSharedImage (format, width, height, clearImage))
  77191. {
  77192. }
  77193. Image::Image (const Image& other)
  77194. : image (other.image)
  77195. {
  77196. }
  77197. Image& Image::operator= (const Image& other)
  77198. {
  77199. image = other.image;
  77200. return *this;
  77201. }
  77202. Image::~Image()
  77203. {
  77204. }
  77205. const Image Image::null;
  77206. LowLevelGraphicsContext* Image::createLowLevelContext() const
  77207. {
  77208. return image == 0 ? 0 : image->createLowLevelContext();
  77209. }
  77210. void Image::duplicateIfShared()
  77211. {
  77212. if (image != 0 && image->getReferenceCount() > 1)
  77213. image = image->clone();
  77214. }
  77215. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  77216. {
  77217. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77218. return *this;
  77219. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77220. Graphics g (newImage);
  77221. g.setImageResamplingQuality (quality);
  77222. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77223. return newImage;
  77224. }
  77225. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77226. {
  77227. if (image == 0 || newFormat == image->format)
  77228. return *this;
  77229. Image newImage (newFormat, image->width, image->height, false, image->getType());
  77230. if (newFormat == SingleChannel)
  77231. {
  77232. if (! hasAlphaChannel())
  77233. {
  77234. newImage.clear (getBounds(), Colours::black);
  77235. }
  77236. else
  77237. {
  77238. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  77239. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  77240. for (int y = 0; y < image->height; ++y)
  77241. {
  77242. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77243. uint8* dst = destData.getLinePointer (y);
  77244. for (int x = image->width; --x >= 0;)
  77245. {
  77246. *dst++ = src->getAlpha();
  77247. ++src;
  77248. }
  77249. }
  77250. }
  77251. }
  77252. else
  77253. {
  77254. if (hasAlphaChannel())
  77255. newImage.clear (getBounds());
  77256. Graphics g (newImage);
  77257. g.drawImageAt (*this, 0, 0);
  77258. }
  77259. return newImage;
  77260. }
  77261. NamedValueSet* Image::getProperties() const
  77262. {
  77263. return image == 0 ? 0 : &(image->userData);
  77264. }
  77265. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77266. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77267. pixelFormat (image.getFormat()),
  77268. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77269. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77270. width (w),
  77271. height (h)
  77272. {
  77273. jassert (data != 0);
  77274. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77275. }
  77276. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77277. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77278. pixelFormat (image.getFormat()),
  77279. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77280. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77281. width (w),
  77282. height (h)
  77283. {
  77284. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77285. }
  77286. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77287. : data (image.image == 0 ? 0 : image.image->imageData),
  77288. pixelFormat (image.getFormat()),
  77289. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77290. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77291. width (image.getWidth()),
  77292. height (image.getHeight())
  77293. {
  77294. }
  77295. Image::BitmapData::~BitmapData()
  77296. {
  77297. }
  77298. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77299. {
  77300. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  77301. const uint8* const pixel = getPixelPointer (x, y);
  77302. switch (pixelFormat)
  77303. {
  77304. case Image::ARGB:
  77305. {
  77306. PixelARGB p (*(const PixelARGB*) pixel);
  77307. p.unpremultiply();
  77308. return Colour (p.getARGB());
  77309. }
  77310. case Image::RGB:
  77311. return Colour (((const PixelRGB*) pixel)->getARGB());
  77312. case Image::SingleChannel:
  77313. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77314. default:
  77315. jassertfalse;
  77316. break;
  77317. }
  77318. return Colour();
  77319. }
  77320. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77321. {
  77322. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  77323. uint8* const pixel = getPixelPointer (x, y);
  77324. const PixelARGB col (colour.getPixelARGB());
  77325. switch (pixelFormat)
  77326. {
  77327. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77328. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77329. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77330. default: jassertfalse; break;
  77331. }
  77332. }
  77333. void Image::setPixelData (int x, int y, int w, int h,
  77334. const uint8* const sourcePixelData, const int sourceLineStride)
  77335. {
  77336. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77337. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77338. {
  77339. const BitmapData dest (*this, x, y, w, h, true);
  77340. for (int i = 0; i < h; ++i)
  77341. {
  77342. memcpy (dest.getLinePointer(i),
  77343. sourcePixelData + sourceLineStride * i,
  77344. w * dest.pixelStride);
  77345. }
  77346. }
  77347. }
  77348. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77349. {
  77350. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77351. if (! clipped.isEmpty())
  77352. {
  77353. const PixelARGB col (colourToClearTo.getPixelARGB());
  77354. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77355. uint8* dest = destData.data;
  77356. int dh = clipped.getHeight();
  77357. while (--dh >= 0)
  77358. {
  77359. uint8* line = dest;
  77360. dest += destData.lineStride;
  77361. if (isARGB())
  77362. {
  77363. for (int x = clipped.getWidth(); --x >= 0;)
  77364. {
  77365. ((PixelARGB*) line)->set (col);
  77366. line += destData.pixelStride;
  77367. }
  77368. }
  77369. else if (isRGB())
  77370. {
  77371. for (int x = clipped.getWidth(); --x >= 0;)
  77372. {
  77373. ((PixelRGB*) line)->set (col);
  77374. line += destData.pixelStride;
  77375. }
  77376. }
  77377. else
  77378. {
  77379. for (int x = clipped.getWidth(); --x >= 0;)
  77380. {
  77381. *line = col.getAlpha();
  77382. line += destData.pixelStride;
  77383. }
  77384. }
  77385. }
  77386. }
  77387. }
  77388. const Colour Image::getPixelAt (const int x, const int y) const
  77389. {
  77390. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  77391. {
  77392. const BitmapData srcData (*this, x, y, 1, 1);
  77393. return srcData.getPixelColour (0, 0);
  77394. }
  77395. return Colour();
  77396. }
  77397. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77398. {
  77399. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  77400. {
  77401. const BitmapData destData (*this, x, y, 1, 1, true);
  77402. destData.setPixelColour (0, 0, colour);
  77403. }
  77404. }
  77405. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77406. {
  77407. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  77408. && hasAlphaChannel())
  77409. {
  77410. const BitmapData destData (*this, x, y, 1, 1, true);
  77411. if (isARGB())
  77412. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77413. else
  77414. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77415. }
  77416. }
  77417. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77418. {
  77419. if (hasAlphaChannel())
  77420. {
  77421. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77422. if (isARGB())
  77423. {
  77424. for (int y = 0; y < destData.height; ++y)
  77425. {
  77426. uint8* p = destData.getLinePointer (y);
  77427. for (int x = 0; x < destData.width; ++x)
  77428. {
  77429. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77430. p += destData.pixelStride;
  77431. }
  77432. }
  77433. }
  77434. else
  77435. {
  77436. for (int y = 0; y < destData.height; ++y)
  77437. {
  77438. uint8* p = destData.getLinePointer (y);
  77439. for (int x = 0; x < destData.width; ++x)
  77440. {
  77441. *p = (uint8) (*p * amountToMultiplyBy);
  77442. p += destData.pixelStride;
  77443. }
  77444. }
  77445. }
  77446. }
  77447. else
  77448. {
  77449. jassertfalse; // can't do this without an alpha-channel!
  77450. }
  77451. }
  77452. void Image::desaturate()
  77453. {
  77454. if (isARGB() || isRGB())
  77455. {
  77456. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77457. if (isARGB())
  77458. {
  77459. for (int y = 0; y < destData.height; ++y)
  77460. {
  77461. uint8* p = destData.getLinePointer (y);
  77462. for (int x = 0; x < destData.width; ++x)
  77463. {
  77464. ((PixelARGB*) p)->desaturate();
  77465. p += destData.pixelStride;
  77466. }
  77467. }
  77468. }
  77469. else
  77470. {
  77471. for (int y = 0; y < destData.height; ++y)
  77472. {
  77473. uint8* p = destData.getLinePointer (y);
  77474. for (int x = 0; x < destData.width; ++x)
  77475. {
  77476. ((PixelRGB*) p)->desaturate();
  77477. p += destData.pixelStride;
  77478. }
  77479. }
  77480. }
  77481. }
  77482. }
  77483. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77484. {
  77485. if (hasAlphaChannel())
  77486. {
  77487. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77488. SparseSet<int> pixelsOnRow;
  77489. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77490. for (int y = 0; y < srcData.height; ++y)
  77491. {
  77492. pixelsOnRow.clear();
  77493. const uint8* lineData = srcData.getLinePointer (y);
  77494. if (isARGB())
  77495. {
  77496. for (int x = 0; x < srcData.width; ++x)
  77497. {
  77498. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77499. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77500. lineData += srcData.pixelStride;
  77501. }
  77502. }
  77503. else
  77504. {
  77505. for (int x = 0; x < srcData.width; ++x)
  77506. {
  77507. if (*lineData >= threshold)
  77508. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77509. lineData += srcData.pixelStride;
  77510. }
  77511. }
  77512. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77513. {
  77514. const Range<int> range (pixelsOnRow.getRange (i));
  77515. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77516. }
  77517. result.consolidate();
  77518. }
  77519. }
  77520. else
  77521. {
  77522. result.add (0, 0, getWidth(), getHeight());
  77523. }
  77524. }
  77525. void Image::moveImageSection (int dx, int dy,
  77526. int sx, int sy,
  77527. int w, int h)
  77528. {
  77529. if (dx < 0)
  77530. {
  77531. w += dx;
  77532. sx -= dx;
  77533. dx = 0;
  77534. }
  77535. if (dy < 0)
  77536. {
  77537. h += dy;
  77538. sy -= dy;
  77539. dy = 0;
  77540. }
  77541. if (sx < 0)
  77542. {
  77543. w += sx;
  77544. dx -= sx;
  77545. sx = 0;
  77546. }
  77547. if (sy < 0)
  77548. {
  77549. h += sy;
  77550. dy -= sy;
  77551. sy = 0;
  77552. }
  77553. const int minX = jmin (dx, sx);
  77554. const int minY = jmin (dy, sy);
  77555. w = jmin (w, getWidth() - jmax (sx, dx));
  77556. h = jmin (h, getHeight() - jmax (sy, dy));
  77557. if (w > 0 && h > 0)
  77558. {
  77559. const int maxX = jmax (dx, sx) + w;
  77560. const int maxY = jmax (dy, sy) + h;
  77561. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77562. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77563. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77564. const int lineSize = destData.pixelStride * w;
  77565. if (dy > sy)
  77566. {
  77567. while (--h >= 0)
  77568. {
  77569. const int offset = h * destData.lineStride;
  77570. memmove (dst + offset, src + offset, lineSize);
  77571. }
  77572. }
  77573. else if (dst != src)
  77574. {
  77575. while (--h >= 0)
  77576. {
  77577. memmove (dst, src, lineSize);
  77578. dst += destData.lineStride;
  77579. src += destData.lineStride;
  77580. }
  77581. }
  77582. }
  77583. }
  77584. END_JUCE_NAMESPACE
  77585. /*** End of inlined file: juce_Image.cpp ***/
  77586. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77587. BEGIN_JUCE_NAMESPACE
  77588. class ImageCache::Pimpl : public Timer,
  77589. public DeletedAtShutdown
  77590. {
  77591. public:
  77592. Pimpl()
  77593. : cacheTimeout (5000)
  77594. {
  77595. }
  77596. ~Pimpl()
  77597. {
  77598. clearSingletonInstance();
  77599. }
  77600. const Image getFromHashCode (const int64 hashCode)
  77601. {
  77602. const ScopedLock sl (lock);
  77603. for (int i = images.size(); --i >= 0;)
  77604. {
  77605. Item* const item = images.getUnchecked(i);
  77606. if (item->hashCode == hashCode)
  77607. return item->image;
  77608. }
  77609. return Image::null;
  77610. }
  77611. void addImageToCache (const Image& image, const int64 hashCode)
  77612. {
  77613. if (image.isValid())
  77614. {
  77615. if (! isTimerRunning())
  77616. startTimer (2000);
  77617. Item* const item = new Item();
  77618. item->hashCode = hashCode;
  77619. item->image = image;
  77620. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77621. const ScopedLock sl (lock);
  77622. images.add (item);
  77623. }
  77624. }
  77625. void timerCallback()
  77626. {
  77627. const uint32 now = Time::getApproximateMillisecondCounter();
  77628. const ScopedLock sl (lock);
  77629. for (int i = images.size(); --i >= 0;)
  77630. {
  77631. Item* const item = images.getUnchecked(i);
  77632. if (item->image.getReferenceCount() <= 1)
  77633. {
  77634. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77635. images.remove (i);
  77636. }
  77637. else
  77638. {
  77639. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77640. }
  77641. }
  77642. if (images.size() == 0)
  77643. stopTimer();
  77644. }
  77645. struct Item
  77646. {
  77647. Image image;
  77648. int64 hashCode;
  77649. uint32 lastUseTime;
  77650. };
  77651. int cacheTimeout;
  77652. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77653. private:
  77654. OwnedArray<Item> images;
  77655. CriticalSection lock;
  77656. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  77657. };
  77658. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77659. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77660. {
  77661. if (Pimpl::getInstanceWithoutCreating() != 0)
  77662. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77663. return Image::null;
  77664. }
  77665. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77666. {
  77667. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77668. }
  77669. const Image ImageCache::getFromFile (const File& file)
  77670. {
  77671. const int64 hashCode = file.hashCode64();
  77672. Image image (getFromHashCode (hashCode));
  77673. if (image.isNull())
  77674. {
  77675. image = ImageFileFormat::loadFrom (file);
  77676. addImageToCache (image, hashCode);
  77677. }
  77678. return image;
  77679. }
  77680. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77681. {
  77682. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77683. Image image (getFromHashCode (hashCode));
  77684. if (image.isNull())
  77685. {
  77686. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77687. addImageToCache (image, hashCode);
  77688. }
  77689. return image;
  77690. }
  77691. void ImageCache::setCacheTimeout (const int millisecs)
  77692. {
  77693. Pimpl::getInstance()->cacheTimeout = millisecs;
  77694. }
  77695. END_JUCE_NAMESPACE
  77696. /*** End of inlined file: juce_ImageCache.cpp ***/
  77697. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77698. BEGIN_JUCE_NAMESPACE
  77699. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77700. : values (size_ * size_),
  77701. size (size_)
  77702. {
  77703. clear();
  77704. }
  77705. ImageConvolutionKernel::~ImageConvolutionKernel()
  77706. {
  77707. }
  77708. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77709. {
  77710. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77711. return values [x + y * size];
  77712. jassertfalse;
  77713. return 0;
  77714. }
  77715. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77716. {
  77717. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77718. {
  77719. values [x + y * size] = value;
  77720. }
  77721. else
  77722. {
  77723. jassertfalse;
  77724. }
  77725. }
  77726. void ImageConvolutionKernel::clear()
  77727. {
  77728. for (int i = size * size; --i >= 0;)
  77729. values[i] = 0;
  77730. }
  77731. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77732. {
  77733. double currentTotal = 0.0;
  77734. for (int i = size * size; --i >= 0;)
  77735. currentTotal += values[i];
  77736. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77737. }
  77738. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77739. {
  77740. for (int i = size * size; --i >= 0;)
  77741. values[i] *= multiplier;
  77742. }
  77743. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77744. {
  77745. const double radiusFactor = -1.0 / (radius * radius * 2);
  77746. const int centre = size >> 1;
  77747. for (int y = size; --y >= 0;)
  77748. {
  77749. for (int x = size; --x >= 0;)
  77750. {
  77751. const int cx = x - centre;
  77752. const int cy = y - centre;
  77753. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77754. }
  77755. }
  77756. setOverallSum (1.0f);
  77757. }
  77758. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77759. const Image& sourceImage,
  77760. const Rectangle<int>& destinationArea) const
  77761. {
  77762. if (sourceImage == destImage)
  77763. {
  77764. destImage.duplicateIfShared();
  77765. }
  77766. else
  77767. {
  77768. if (sourceImage.getWidth() != destImage.getWidth()
  77769. || sourceImage.getHeight() != destImage.getHeight()
  77770. || sourceImage.getFormat() != destImage.getFormat())
  77771. {
  77772. jassertfalse;
  77773. return;
  77774. }
  77775. }
  77776. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77777. if (area.isEmpty())
  77778. return;
  77779. const int right = area.getRight();
  77780. const int bottom = area.getBottom();
  77781. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77782. uint8* line = destData.data;
  77783. const Image::BitmapData srcData (sourceImage, false);
  77784. if (destData.pixelStride == 4)
  77785. {
  77786. for (int y = area.getY(); y < bottom; ++y)
  77787. {
  77788. uint8* dest = line;
  77789. line += destData.lineStride;
  77790. for (int x = area.getX(); x < right; ++x)
  77791. {
  77792. float c1 = 0;
  77793. float c2 = 0;
  77794. float c3 = 0;
  77795. float c4 = 0;
  77796. for (int yy = 0; yy < size; ++yy)
  77797. {
  77798. const int sy = y + yy - (size >> 1);
  77799. if (sy >= srcData.height)
  77800. break;
  77801. if (sy >= 0)
  77802. {
  77803. int sx = x - (size >> 1);
  77804. const uint8* src = srcData.getPixelPointer (sx, sy);
  77805. for (int xx = 0; xx < size; ++xx)
  77806. {
  77807. if (sx >= srcData.width)
  77808. break;
  77809. if (sx >= 0)
  77810. {
  77811. const float kernelMult = values [xx + yy * size];
  77812. c1 += kernelMult * *src++;
  77813. c2 += kernelMult * *src++;
  77814. c3 += kernelMult * *src++;
  77815. c4 += kernelMult * *src++;
  77816. }
  77817. else
  77818. {
  77819. src += 4;
  77820. }
  77821. ++sx;
  77822. }
  77823. }
  77824. }
  77825. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77826. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77827. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77828. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77829. }
  77830. }
  77831. }
  77832. else if (destData.pixelStride == 3)
  77833. {
  77834. for (int y = area.getY(); y < bottom; ++y)
  77835. {
  77836. uint8* dest = line;
  77837. line += destData.lineStride;
  77838. for (int x = area.getX(); x < right; ++x)
  77839. {
  77840. float c1 = 0;
  77841. float c2 = 0;
  77842. float c3 = 0;
  77843. for (int yy = 0; yy < size; ++yy)
  77844. {
  77845. const int sy = y + yy - (size >> 1);
  77846. if (sy >= srcData.height)
  77847. break;
  77848. if (sy >= 0)
  77849. {
  77850. int sx = x - (size >> 1);
  77851. const uint8* src = srcData.getPixelPointer (sx, sy);
  77852. for (int xx = 0; xx < size; ++xx)
  77853. {
  77854. if (sx >= srcData.width)
  77855. break;
  77856. if (sx >= 0)
  77857. {
  77858. const float kernelMult = values [xx + yy * size];
  77859. c1 += kernelMult * *src++;
  77860. c2 += kernelMult * *src++;
  77861. c3 += kernelMult * *src++;
  77862. }
  77863. else
  77864. {
  77865. src += 3;
  77866. }
  77867. ++sx;
  77868. }
  77869. }
  77870. }
  77871. *dest++ = (uint8) roundToInt (c1);
  77872. *dest++ = (uint8) roundToInt (c2);
  77873. *dest++ = (uint8) roundToInt (c3);
  77874. }
  77875. }
  77876. }
  77877. }
  77878. END_JUCE_NAMESPACE
  77879. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77880. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77881. BEGIN_JUCE_NAMESPACE
  77882. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77883. {
  77884. static PNGImageFormat png;
  77885. static JPEGImageFormat jpg;
  77886. static GIFImageFormat gif;
  77887. ImageFileFormat* formats[4];
  77888. int numFormats = 0;
  77889. formats [numFormats++] = &png;
  77890. formats [numFormats++] = &jpg;
  77891. formats [numFormats++] = &gif;
  77892. const int64 streamPos = input.getPosition();
  77893. for (int i = 0; i < numFormats; ++i)
  77894. {
  77895. const bool found = formats[i]->canUnderstand (input);
  77896. input.setPosition (streamPos);
  77897. if (found)
  77898. return formats[i];
  77899. }
  77900. return 0;
  77901. }
  77902. const Image ImageFileFormat::loadFrom (InputStream& input)
  77903. {
  77904. ImageFileFormat* const format = findImageFormatForStream (input);
  77905. if (format != 0)
  77906. return format->decodeImage (input);
  77907. return Image::null;
  77908. }
  77909. const Image ImageFileFormat::loadFrom (const File& file)
  77910. {
  77911. InputStream* const in = file.createInputStream();
  77912. if (in != 0)
  77913. {
  77914. BufferedInputStream b (in, 8192, true);
  77915. return loadFrom (b);
  77916. }
  77917. return Image::null;
  77918. }
  77919. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77920. {
  77921. if (rawData != 0 && numBytes > 4)
  77922. {
  77923. MemoryInputStream stream (rawData, numBytes, false);
  77924. return loadFrom (stream);
  77925. }
  77926. return Image::null;
  77927. }
  77928. END_JUCE_NAMESPACE
  77929. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77930. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77931. BEGIN_JUCE_NAMESPACE
  77932. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77933. const Image juce_loadWithCoreImage (InputStream& input);
  77934. #else
  77935. class GIFLoader
  77936. {
  77937. public:
  77938. GIFLoader (InputStream& in)
  77939. : input (in),
  77940. dataBlockIsZero (false),
  77941. fresh (false),
  77942. finished (false)
  77943. {
  77944. currentBit = lastBit = lastByteIndex = 0;
  77945. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77946. firstcode = oldcode = 0;
  77947. clearCode = end_code = 0;
  77948. int imageWidth, imageHeight;
  77949. int transparent = -1;
  77950. if (! getSizeFromHeader (imageWidth, imageHeight))
  77951. return;
  77952. if ((imageWidth <= 0) || (imageHeight <= 0))
  77953. return;
  77954. unsigned char buf [16];
  77955. if (in.read (buf, 3) != 3)
  77956. return;
  77957. int numColours = 2 << (buf[0] & 7);
  77958. if ((buf[0] & 0x80) != 0)
  77959. readPalette (numColours);
  77960. for (;;)
  77961. {
  77962. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77963. break;
  77964. if (buf[0] == '!')
  77965. {
  77966. if (input.read (buf, 1) != 1)
  77967. break;
  77968. if (processExtension (buf[0], transparent) < 0)
  77969. break;
  77970. continue;
  77971. }
  77972. if (buf[0] != ',')
  77973. continue;
  77974. if (input.read (buf, 9) != 9)
  77975. break;
  77976. imageWidth = makeWord (buf[4], buf[5]);
  77977. imageHeight = makeWord (buf[6], buf[7]);
  77978. numColours = 2 << (buf[8] & 7);
  77979. if ((buf[8] & 0x80) != 0)
  77980. if (! readPalette (numColours))
  77981. break;
  77982. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77983. imageWidth, imageHeight, (transparent >= 0));
  77984. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77985. readImage ((buf[8] & 0x40) != 0, transparent);
  77986. break;
  77987. }
  77988. }
  77989. ~GIFLoader() {}
  77990. Image image;
  77991. private:
  77992. InputStream& input;
  77993. uint8 buffer [300];
  77994. uint8 palette [256][4];
  77995. bool dataBlockIsZero, fresh, finished;
  77996. int currentBit, lastBit, lastByteIndex;
  77997. int codeSize, setCodeSize;
  77998. int maxCode, maxCodeSize;
  77999. int firstcode, oldcode;
  78000. int clearCode, end_code;
  78001. enum { maxGifCode = 1 << 12 };
  78002. int table [2] [maxGifCode];
  78003. int stack [2 * maxGifCode];
  78004. int *sp;
  78005. bool getSizeFromHeader (int& w, int& h)
  78006. {
  78007. char b[8];
  78008. if (input.read (b, 6) == 6)
  78009. {
  78010. if ((strncmp ("GIF87a", b, 6) == 0)
  78011. || (strncmp ("GIF89a", b, 6) == 0))
  78012. {
  78013. if (input.read (b, 4) == 4)
  78014. {
  78015. w = makeWord (b[0], b[1]);
  78016. h = makeWord (b[2], b[3]);
  78017. return true;
  78018. }
  78019. }
  78020. }
  78021. return false;
  78022. }
  78023. bool readPalette (const int numCols)
  78024. {
  78025. unsigned char rgb[4];
  78026. for (int i = 0; i < numCols; ++i)
  78027. {
  78028. input.read (rgb, 3);
  78029. palette [i][0] = rgb[0];
  78030. palette [i][1] = rgb[1];
  78031. palette [i][2] = rgb[2];
  78032. palette [i][3] = 0xff;
  78033. }
  78034. return true;
  78035. }
  78036. int readDataBlock (unsigned char* dest)
  78037. {
  78038. unsigned char n;
  78039. if (input.read (&n, 1) == 1)
  78040. {
  78041. dataBlockIsZero = (n == 0);
  78042. if (dataBlockIsZero || (input.read (dest, n) == n))
  78043. return n;
  78044. }
  78045. return -1;
  78046. }
  78047. int processExtension (const int type, int& transparent)
  78048. {
  78049. unsigned char b [300];
  78050. int n = 0;
  78051. if (type == 0xf9)
  78052. {
  78053. n = readDataBlock (b);
  78054. if (n < 0)
  78055. return 1;
  78056. if ((b[0] & 0x1) != 0)
  78057. transparent = b[3];
  78058. }
  78059. do
  78060. {
  78061. n = readDataBlock (b);
  78062. }
  78063. while (n > 0);
  78064. return n;
  78065. }
  78066. int readLZWByte (const bool initialise, const int inputCodeSize)
  78067. {
  78068. int code, incode, i;
  78069. if (initialise)
  78070. {
  78071. setCodeSize = inputCodeSize;
  78072. codeSize = setCodeSize + 1;
  78073. clearCode = 1 << setCodeSize;
  78074. end_code = clearCode + 1;
  78075. maxCodeSize = 2 * clearCode;
  78076. maxCode = clearCode + 2;
  78077. getCode (0, true);
  78078. fresh = true;
  78079. for (i = 0; i < clearCode; ++i)
  78080. {
  78081. table[0][i] = 0;
  78082. table[1][i] = i;
  78083. }
  78084. for (; i < maxGifCode; ++i)
  78085. {
  78086. table[0][i] = 0;
  78087. table[1][i] = 0;
  78088. }
  78089. sp = stack;
  78090. return 0;
  78091. }
  78092. else if (fresh)
  78093. {
  78094. fresh = false;
  78095. do
  78096. {
  78097. firstcode = oldcode
  78098. = getCode (codeSize, false);
  78099. }
  78100. while (firstcode == clearCode);
  78101. return firstcode;
  78102. }
  78103. if (sp > stack)
  78104. return *--sp;
  78105. while ((code = getCode (codeSize, false)) >= 0)
  78106. {
  78107. if (code == clearCode)
  78108. {
  78109. for (i = 0; i < clearCode; ++i)
  78110. {
  78111. table[0][i] = 0;
  78112. table[1][i] = i;
  78113. }
  78114. for (; i < maxGifCode; ++i)
  78115. {
  78116. table[0][i] = 0;
  78117. table[1][i] = 0;
  78118. }
  78119. codeSize = setCodeSize + 1;
  78120. maxCodeSize = 2 * clearCode;
  78121. maxCode = clearCode + 2;
  78122. sp = stack;
  78123. firstcode = oldcode = getCode (codeSize, false);
  78124. return firstcode;
  78125. }
  78126. else if (code == end_code)
  78127. {
  78128. if (dataBlockIsZero)
  78129. return -2;
  78130. unsigned char buf [260];
  78131. int n;
  78132. while ((n = readDataBlock (buf)) > 0)
  78133. {}
  78134. if (n != 0)
  78135. return -2;
  78136. }
  78137. incode = code;
  78138. if (code >= maxCode)
  78139. {
  78140. *sp++ = firstcode;
  78141. code = oldcode;
  78142. }
  78143. while (code >= clearCode)
  78144. {
  78145. *sp++ = table[1][code];
  78146. if (code == table[0][code])
  78147. return -2;
  78148. code = table[0][code];
  78149. }
  78150. *sp++ = firstcode = table[1][code];
  78151. if ((code = maxCode) < maxGifCode)
  78152. {
  78153. table[0][code] = oldcode;
  78154. table[1][code] = firstcode;
  78155. ++maxCode;
  78156. if ((maxCode >= maxCodeSize)
  78157. && (maxCodeSize < maxGifCode))
  78158. {
  78159. maxCodeSize <<= 1;
  78160. ++codeSize;
  78161. }
  78162. }
  78163. oldcode = incode;
  78164. if (sp > stack)
  78165. return *--sp;
  78166. }
  78167. return code;
  78168. }
  78169. int getCode (const int codeSize_, const bool initialise)
  78170. {
  78171. if (initialise)
  78172. {
  78173. currentBit = 0;
  78174. lastBit = 0;
  78175. finished = false;
  78176. return 0;
  78177. }
  78178. if ((currentBit + codeSize_) >= lastBit)
  78179. {
  78180. if (finished)
  78181. return -1;
  78182. buffer[0] = buffer [lastByteIndex - 2];
  78183. buffer[1] = buffer [lastByteIndex - 1];
  78184. const int n = readDataBlock (&buffer[2]);
  78185. if (n == 0)
  78186. finished = true;
  78187. lastByteIndex = 2 + n;
  78188. currentBit = (currentBit - lastBit) + 16;
  78189. lastBit = (2 + n) * 8 ;
  78190. }
  78191. int result = 0;
  78192. int i = currentBit;
  78193. for (int j = 0; j < codeSize_; ++j)
  78194. {
  78195. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  78196. ++i;
  78197. }
  78198. currentBit += codeSize_;
  78199. return result;
  78200. }
  78201. bool readImage (const int interlace, const int transparent)
  78202. {
  78203. unsigned char c;
  78204. if (input.read (&c, 1) != 1
  78205. || readLZWByte (true, c) < 0)
  78206. return false;
  78207. if (transparent >= 0)
  78208. {
  78209. palette [transparent][0] = 0;
  78210. palette [transparent][1] = 0;
  78211. palette [transparent][2] = 0;
  78212. palette [transparent][3] = 0;
  78213. }
  78214. int index;
  78215. int xpos = 0, ypos = 0, pass = 0;
  78216. const Image::BitmapData destData (image, true);
  78217. uint8* p = destData.data;
  78218. const bool hasAlpha = image.hasAlphaChannel();
  78219. while ((index = readLZWByte (false, c)) >= 0)
  78220. {
  78221. const uint8* const paletteEntry = palette [index];
  78222. if (hasAlpha)
  78223. {
  78224. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78225. paletteEntry[0],
  78226. paletteEntry[1],
  78227. paletteEntry[2]);
  78228. ((PixelARGB*) p)->premultiply();
  78229. }
  78230. else
  78231. {
  78232. ((PixelRGB*) p)->setARGB (0,
  78233. paletteEntry[0],
  78234. paletteEntry[1],
  78235. paletteEntry[2]);
  78236. }
  78237. p += destData.pixelStride;
  78238. ++xpos;
  78239. if (xpos == destData.width)
  78240. {
  78241. xpos = 0;
  78242. if (interlace)
  78243. {
  78244. switch (pass)
  78245. {
  78246. case 0:
  78247. case 1: ypos += 8; break;
  78248. case 2: ypos += 4; break;
  78249. case 3: ypos += 2; break;
  78250. }
  78251. while (ypos >= destData.height)
  78252. {
  78253. ++pass;
  78254. switch (pass)
  78255. {
  78256. case 1: ypos = 4; break;
  78257. case 2: ypos = 2; break;
  78258. case 3: ypos = 1; break;
  78259. default: return true;
  78260. }
  78261. }
  78262. }
  78263. else
  78264. {
  78265. ++ypos;
  78266. }
  78267. p = destData.getPixelPointer (xpos, ypos);
  78268. }
  78269. if (ypos >= destData.height)
  78270. break;
  78271. }
  78272. return true;
  78273. }
  78274. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78275. JUCE_DECLARE_NON_COPYABLE (GIFLoader);
  78276. };
  78277. #endif
  78278. GIFImageFormat::GIFImageFormat() {}
  78279. GIFImageFormat::~GIFImageFormat() {}
  78280. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78281. bool GIFImageFormat::canUnderstand (InputStream& in)
  78282. {
  78283. char header [4];
  78284. return (in.read (header, sizeof (header)) == sizeof (header))
  78285. && header[0] == 'G'
  78286. && header[1] == 'I'
  78287. && header[2] == 'F';
  78288. }
  78289. const Image GIFImageFormat::decodeImage (InputStream& in)
  78290. {
  78291. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78292. return juce_loadWithCoreImage (in);
  78293. #else
  78294. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78295. return loader->image;
  78296. #endif
  78297. }
  78298. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78299. {
  78300. jassertfalse; // writing isn't implemented for GIFs!
  78301. return false;
  78302. }
  78303. END_JUCE_NAMESPACE
  78304. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78305. #endif
  78306. //==============================================================================
  78307. // some files include lots of library code, so leave them to the end to avoid cluttering
  78308. // up the build for the clean files.
  78309. #if JUCE_BUILD_CORE
  78310. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78311. namespace zlibNamespace
  78312. {
  78313. #if JUCE_INCLUDE_ZLIB_CODE
  78314. #undef OS_CODE
  78315. #undef fdopen
  78316. /*** Start of inlined file: zlib.h ***/
  78317. #ifndef ZLIB_H
  78318. #define ZLIB_H
  78319. /*** Start of inlined file: zconf.h ***/
  78320. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78321. #ifndef ZCONF_H
  78322. #define ZCONF_H
  78323. // *** Just a few hacks here to make it compile nicely with Juce..
  78324. #define Z_PREFIX 1
  78325. #undef __MACTYPES__
  78326. #ifdef _MSC_VER
  78327. #pragma warning (disable : 4131 4127 4244 4267)
  78328. #endif
  78329. /*
  78330. * If you *really* need a unique prefix for all types and library functions,
  78331. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78332. */
  78333. #ifdef Z_PREFIX
  78334. # define deflateInit_ z_deflateInit_
  78335. # define deflate z_deflate
  78336. # define deflateEnd z_deflateEnd
  78337. # define inflateInit_ z_inflateInit_
  78338. # define inflate z_inflate
  78339. # define inflateEnd z_inflateEnd
  78340. # define inflatePrime z_inflatePrime
  78341. # define inflateGetHeader z_inflateGetHeader
  78342. # define adler32_combine z_adler32_combine
  78343. # define crc32_combine z_crc32_combine
  78344. # define deflateInit2_ z_deflateInit2_
  78345. # define deflateSetDictionary z_deflateSetDictionary
  78346. # define deflateCopy z_deflateCopy
  78347. # define deflateReset z_deflateReset
  78348. # define deflateParams z_deflateParams
  78349. # define deflateBound z_deflateBound
  78350. # define deflatePrime z_deflatePrime
  78351. # define inflateInit2_ z_inflateInit2_
  78352. # define inflateSetDictionary z_inflateSetDictionary
  78353. # define inflateSync z_inflateSync
  78354. # define inflateSyncPoint z_inflateSyncPoint
  78355. # define inflateCopy z_inflateCopy
  78356. # define inflateReset z_inflateReset
  78357. # define inflateBack z_inflateBack
  78358. # define inflateBackEnd z_inflateBackEnd
  78359. # define compress z_compress
  78360. # define compress2 z_compress2
  78361. # define compressBound z_compressBound
  78362. # define uncompress z_uncompress
  78363. # define adler32 z_adler32
  78364. # define crc32 z_crc32
  78365. # define get_crc_table z_get_crc_table
  78366. # define zError z_zError
  78367. # define alloc_func z_alloc_func
  78368. # define free_func z_free_func
  78369. # define in_func z_in_func
  78370. # define out_func z_out_func
  78371. # define Byte z_Byte
  78372. # define uInt z_uInt
  78373. # define uLong z_uLong
  78374. # define Bytef z_Bytef
  78375. # define charf z_charf
  78376. # define intf z_intf
  78377. # define uIntf z_uIntf
  78378. # define uLongf z_uLongf
  78379. # define voidpf z_voidpf
  78380. # define voidp z_voidp
  78381. #endif
  78382. #if defined(__MSDOS__) && !defined(MSDOS)
  78383. # define MSDOS
  78384. #endif
  78385. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78386. # define OS2
  78387. #endif
  78388. #if defined(_WINDOWS) && !defined(WINDOWS)
  78389. # define WINDOWS
  78390. #endif
  78391. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78392. # ifndef WIN32
  78393. # define WIN32
  78394. # endif
  78395. #endif
  78396. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78397. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78398. # ifndef SYS16BIT
  78399. # define SYS16BIT
  78400. # endif
  78401. # endif
  78402. #endif
  78403. /*
  78404. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78405. * than 64k bytes at a time (needed on systems with 16-bit int).
  78406. */
  78407. #ifdef SYS16BIT
  78408. # define MAXSEG_64K
  78409. #endif
  78410. #ifdef MSDOS
  78411. # define UNALIGNED_OK
  78412. #endif
  78413. #ifdef __STDC_VERSION__
  78414. # ifndef STDC
  78415. # define STDC
  78416. # endif
  78417. # if __STDC_VERSION__ >= 199901L
  78418. # ifndef STDC99
  78419. # define STDC99
  78420. # endif
  78421. # endif
  78422. #endif
  78423. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78424. # define STDC
  78425. #endif
  78426. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78427. # define STDC
  78428. #endif
  78429. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78430. # define STDC
  78431. #endif
  78432. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78433. # define STDC
  78434. #endif
  78435. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78436. # define STDC
  78437. #endif
  78438. #ifndef STDC
  78439. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78440. # define const /* note: need a more gentle solution here */
  78441. # endif
  78442. #endif
  78443. /* Some Mac compilers merge all .h files incorrectly: */
  78444. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78445. # define NO_DUMMY_DECL
  78446. #endif
  78447. /* Maximum value for memLevel in deflateInit2 */
  78448. #ifndef MAX_MEM_LEVEL
  78449. # ifdef MAXSEG_64K
  78450. # define MAX_MEM_LEVEL 8
  78451. # else
  78452. # define MAX_MEM_LEVEL 9
  78453. # endif
  78454. #endif
  78455. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78456. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78457. * created by gzip. (Files created by minigzip can still be extracted by
  78458. * gzip.)
  78459. */
  78460. #ifndef MAX_WBITS
  78461. # define MAX_WBITS 15 /* 32K LZ77 window */
  78462. #endif
  78463. /* The memory requirements for deflate are (in bytes):
  78464. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78465. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78466. plus a few kilobytes for small objects. For example, if you want to reduce
  78467. the default memory requirements from 256K to 128K, compile with
  78468. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78469. Of course this will generally degrade compression (there's no free lunch).
  78470. The memory requirements for inflate are (in bytes) 1 << windowBits
  78471. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78472. for small objects.
  78473. */
  78474. /* Type declarations */
  78475. #ifndef OF /* function prototypes */
  78476. # ifdef STDC
  78477. # define OF(args) args
  78478. # else
  78479. # define OF(args) ()
  78480. # endif
  78481. #endif
  78482. /* The following definitions for FAR are needed only for MSDOS mixed
  78483. * model programming (small or medium model with some far allocations).
  78484. * This was tested only with MSC; for other MSDOS compilers you may have
  78485. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78486. * just define FAR to be empty.
  78487. */
  78488. #ifdef SYS16BIT
  78489. # if defined(M_I86SM) || defined(M_I86MM)
  78490. /* MSC small or medium model */
  78491. # define SMALL_MEDIUM
  78492. # ifdef _MSC_VER
  78493. # define FAR _far
  78494. # else
  78495. # define FAR far
  78496. # endif
  78497. # endif
  78498. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78499. /* Turbo C small or medium model */
  78500. # define SMALL_MEDIUM
  78501. # ifdef __BORLANDC__
  78502. # define FAR _far
  78503. # else
  78504. # define FAR far
  78505. # endif
  78506. # endif
  78507. #endif
  78508. #if defined(WINDOWS) || defined(WIN32)
  78509. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78510. * This is not mandatory, but it offers a little performance increase.
  78511. */
  78512. # ifdef ZLIB_DLL
  78513. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78514. # ifdef ZLIB_INTERNAL
  78515. # define ZEXTERN extern __declspec(dllexport)
  78516. # else
  78517. # define ZEXTERN extern __declspec(dllimport)
  78518. # endif
  78519. # endif
  78520. # endif /* ZLIB_DLL */
  78521. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78522. * define ZLIB_WINAPI.
  78523. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78524. */
  78525. # ifdef ZLIB_WINAPI
  78526. # ifdef FAR
  78527. # undef FAR
  78528. # endif
  78529. # include <windows.h>
  78530. /* No need for _export, use ZLIB.DEF instead. */
  78531. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78532. # define ZEXPORT WINAPI
  78533. # ifdef WIN32
  78534. # define ZEXPORTVA WINAPIV
  78535. # else
  78536. # define ZEXPORTVA FAR CDECL
  78537. # endif
  78538. # endif
  78539. #endif
  78540. #if defined (__BEOS__)
  78541. # ifdef ZLIB_DLL
  78542. # ifdef ZLIB_INTERNAL
  78543. # define ZEXPORT __declspec(dllexport)
  78544. # define ZEXPORTVA __declspec(dllexport)
  78545. # else
  78546. # define ZEXPORT __declspec(dllimport)
  78547. # define ZEXPORTVA __declspec(dllimport)
  78548. # endif
  78549. # endif
  78550. #endif
  78551. #ifndef ZEXTERN
  78552. # define ZEXTERN extern
  78553. #endif
  78554. #ifndef ZEXPORT
  78555. # define ZEXPORT
  78556. #endif
  78557. #ifndef ZEXPORTVA
  78558. # define ZEXPORTVA
  78559. #endif
  78560. #ifndef FAR
  78561. # define FAR
  78562. #endif
  78563. #if !defined(__MACTYPES__)
  78564. typedef unsigned char Byte; /* 8 bits */
  78565. #endif
  78566. typedef unsigned int uInt; /* 16 bits or more */
  78567. typedef unsigned long uLong; /* 32 bits or more */
  78568. #ifdef SMALL_MEDIUM
  78569. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78570. # define Bytef Byte FAR
  78571. #else
  78572. typedef Byte FAR Bytef;
  78573. #endif
  78574. typedef char FAR charf;
  78575. typedef int FAR intf;
  78576. typedef uInt FAR uIntf;
  78577. typedef uLong FAR uLongf;
  78578. #ifdef STDC
  78579. typedef void const *voidpc;
  78580. typedef void FAR *voidpf;
  78581. typedef void *voidp;
  78582. #else
  78583. typedef Byte const *voidpc;
  78584. typedef Byte FAR *voidpf;
  78585. typedef Byte *voidp;
  78586. #endif
  78587. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78588. # include <sys/types.h> /* for off_t */
  78589. # include <unistd.h> /* for SEEK_* and off_t */
  78590. # ifdef VMS
  78591. # include <unixio.h> /* for off_t */
  78592. # endif
  78593. # define z_off_t off_t
  78594. #endif
  78595. #ifndef SEEK_SET
  78596. # define SEEK_SET 0 /* Seek from beginning of file. */
  78597. # define SEEK_CUR 1 /* Seek from current position. */
  78598. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78599. #endif
  78600. #ifndef z_off_t
  78601. # define z_off_t long
  78602. #endif
  78603. #if defined(__OS400__)
  78604. # define NO_vsnprintf
  78605. #endif
  78606. #if defined(__MVS__)
  78607. # define NO_vsnprintf
  78608. # ifdef FAR
  78609. # undef FAR
  78610. # endif
  78611. #endif
  78612. /* MVS linker does not support external names larger than 8 bytes */
  78613. #if defined(__MVS__)
  78614. # pragma map(deflateInit_,"DEIN")
  78615. # pragma map(deflateInit2_,"DEIN2")
  78616. # pragma map(deflateEnd,"DEEND")
  78617. # pragma map(deflateBound,"DEBND")
  78618. # pragma map(inflateInit_,"ININ")
  78619. # pragma map(inflateInit2_,"ININ2")
  78620. # pragma map(inflateEnd,"INEND")
  78621. # pragma map(inflateSync,"INSY")
  78622. # pragma map(inflateSetDictionary,"INSEDI")
  78623. # pragma map(compressBound,"CMBND")
  78624. # pragma map(inflate_table,"INTABL")
  78625. # pragma map(inflate_fast,"INFA")
  78626. # pragma map(inflate_copyright,"INCOPY")
  78627. #endif
  78628. #endif /* ZCONF_H */
  78629. /*** End of inlined file: zconf.h ***/
  78630. #ifdef __cplusplus
  78631. //extern "C" {
  78632. #endif
  78633. #define ZLIB_VERSION "1.2.3"
  78634. #define ZLIB_VERNUM 0x1230
  78635. /*
  78636. The 'zlib' compression library provides in-memory compression and
  78637. decompression functions, including integrity checks of the uncompressed
  78638. data. This version of the library supports only one compression method
  78639. (deflation) but other algorithms will be added later and will have the same
  78640. stream interface.
  78641. Compression can be done in a single step if the buffers are large
  78642. enough (for example if an input file is mmap'ed), or can be done by
  78643. repeated calls of the compression function. In the latter case, the
  78644. application must provide more input and/or consume the output
  78645. (providing more output space) before each call.
  78646. The compressed data format used by default by the in-memory functions is
  78647. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78648. around a deflate stream, which is itself documented in RFC 1951.
  78649. The library also supports reading and writing files in gzip (.gz) format
  78650. with an interface similar to that of stdio using the functions that start
  78651. with "gz". The gzip format is different from the zlib format. gzip is a
  78652. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78653. This library can optionally read and write gzip streams in memory as well.
  78654. The zlib format was designed to be compact and fast for use in memory
  78655. and on communications channels. The gzip format was designed for single-
  78656. file compression on file systems, has a larger header than zlib to maintain
  78657. directory information, and uses a different, slower check method than zlib.
  78658. The library does not install any signal handler. The decoder checks
  78659. the consistency of the compressed data, so the library should never
  78660. crash even in case of corrupted input.
  78661. */
  78662. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78663. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78664. struct internal_state;
  78665. typedef struct z_stream_s {
  78666. Bytef *next_in; /* next input byte */
  78667. uInt avail_in; /* number of bytes available at next_in */
  78668. uLong total_in; /* total nb of input bytes read so far */
  78669. Bytef *next_out; /* next output byte should be put there */
  78670. uInt avail_out; /* remaining free space at next_out */
  78671. uLong total_out; /* total nb of bytes output so far */
  78672. char *msg; /* last error message, NULL if no error */
  78673. struct internal_state FAR *state; /* not visible by applications */
  78674. alloc_func zalloc; /* used to allocate the internal state */
  78675. free_func zfree; /* used to free the internal state */
  78676. voidpf opaque; /* private data object passed to zalloc and zfree */
  78677. int data_type; /* best guess about the data type: binary or text */
  78678. uLong adler; /* adler32 value of the uncompressed data */
  78679. uLong reserved; /* reserved for future use */
  78680. } z_stream;
  78681. typedef z_stream FAR *z_streamp;
  78682. /*
  78683. gzip header information passed to and from zlib routines. See RFC 1952
  78684. for more details on the meanings of these fields.
  78685. */
  78686. typedef struct gz_header_s {
  78687. int text; /* true if compressed data believed to be text */
  78688. uLong time; /* modification time */
  78689. int xflags; /* extra flags (not used when writing a gzip file) */
  78690. int os; /* operating system */
  78691. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78692. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78693. uInt extra_max; /* space at extra (only when reading header) */
  78694. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78695. uInt name_max; /* space at name (only when reading header) */
  78696. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78697. uInt comm_max; /* space at comment (only when reading header) */
  78698. int hcrc; /* true if there was or will be a header crc */
  78699. int done; /* true when done reading gzip header (not used
  78700. when writing a gzip file) */
  78701. } gz_header;
  78702. typedef gz_header FAR *gz_headerp;
  78703. /*
  78704. The application must update next_in and avail_in when avail_in has
  78705. dropped to zero. It must update next_out and avail_out when avail_out
  78706. has dropped to zero. The application must initialize zalloc, zfree and
  78707. opaque before calling the init function. All other fields are set by the
  78708. compression library and must not be updated by the application.
  78709. The opaque value provided by the application will be passed as the first
  78710. parameter for calls of zalloc and zfree. This can be useful for custom
  78711. memory management. The compression library attaches no meaning to the
  78712. opaque value.
  78713. zalloc must return Z_NULL if there is not enough memory for the object.
  78714. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78715. thread safe.
  78716. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78717. exactly 65536 bytes, but will not be required to allocate more than this
  78718. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78719. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78720. have their offset normalized to zero. The default allocation function
  78721. provided by this library ensures this (see zutil.c). To reduce memory
  78722. requirements and avoid any allocation of 64K objects, at the expense of
  78723. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78724. The fields total_in and total_out can be used for statistics or
  78725. progress reports. After compression, total_in holds the total size of
  78726. the uncompressed data and may be saved for use in the decompressor
  78727. (particularly if the decompressor wants to decompress everything in
  78728. a single step).
  78729. */
  78730. /* constants */
  78731. #define Z_NO_FLUSH 0
  78732. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78733. #define Z_SYNC_FLUSH 2
  78734. #define Z_FULL_FLUSH 3
  78735. #define Z_FINISH 4
  78736. #define Z_BLOCK 5
  78737. /* Allowed flush values; see deflate() and inflate() below for details */
  78738. #define Z_OK 0
  78739. #define Z_STREAM_END 1
  78740. #define Z_NEED_DICT 2
  78741. #define Z_ERRNO (-1)
  78742. #define Z_STREAM_ERROR (-2)
  78743. #define Z_DATA_ERROR (-3)
  78744. #define Z_MEM_ERROR (-4)
  78745. #define Z_BUF_ERROR (-5)
  78746. #define Z_VERSION_ERROR (-6)
  78747. /* Return codes for the compression/decompression functions. Negative
  78748. * values are errors, positive values are used for special but normal events.
  78749. */
  78750. #define Z_NO_COMPRESSION 0
  78751. #define Z_BEST_SPEED 1
  78752. #define Z_BEST_COMPRESSION 9
  78753. #define Z_DEFAULT_COMPRESSION (-1)
  78754. /* compression levels */
  78755. #define Z_FILTERED 1
  78756. #define Z_HUFFMAN_ONLY 2
  78757. #define Z_RLE 3
  78758. #define Z_FIXED 4
  78759. #define Z_DEFAULT_STRATEGY 0
  78760. /* compression strategy; see deflateInit2() below for details */
  78761. #define Z_BINARY 0
  78762. #define Z_TEXT 1
  78763. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78764. #define Z_UNKNOWN 2
  78765. /* Possible values of the data_type field (though see inflate()) */
  78766. #define Z_DEFLATED 8
  78767. /* The deflate compression method (the only one supported in this version) */
  78768. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78769. #define zlib_version zlibVersion()
  78770. /* for compatibility with versions < 1.0.2 */
  78771. /* basic functions */
  78772. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78773. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78774. If the first character differs, the library code actually used is
  78775. not compatible with the zlib.h header file used by the application.
  78776. This check is automatically made by deflateInit and inflateInit.
  78777. */
  78778. /*
  78779. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78780. Initializes the internal stream state for compression. The fields
  78781. zalloc, zfree and opaque must be initialized before by the caller.
  78782. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78783. use default allocation functions.
  78784. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78785. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78786. all (the input data is simply copied a block at a time).
  78787. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78788. compression (currently equivalent to level 6).
  78789. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78790. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78791. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78792. with the version assumed by the caller (ZLIB_VERSION).
  78793. msg is set to null if there is no error message. deflateInit does not
  78794. perform any compression: this will be done by deflate().
  78795. */
  78796. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78797. /*
  78798. deflate compresses as much data as possible, and stops when the input
  78799. buffer becomes empty or the output buffer becomes full. It may introduce some
  78800. output latency (reading input without producing any output) except when
  78801. forced to flush.
  78802. The detailed semantics are as follows. deflate performs one or both of the
  78803. following actions:
  78804. - Compress more input starting at next_in and update next_in and avail_in
  78805. accordingly. If not all input can be processed (because there is not
  78806. enough room in the output buffer), next_in and avail_in are updated and
  78807. processing will resume at this point for the next call of deflate().
  78808. - Provide more output starting at next_out and update next_out and avail_out
  78809. accordingly. This action is forced if the parameter flush is non zero.
  78810. Forcing flush frequently degrades the compression ratio, so this parameter
  78811. should be set only when necessary (in interactive applications).
  78812. Some output may be provided even if flush is not set.
  78813. Before the call of deflate(), the application should ensure that at least
  78814. one of the actions is possible, by providing more input and/or consuming
  78815. more output, and updating avail_in or avail_out accordingly; avail_out
  78816. should never be zero before the call. The application can consume the
  78817. compressed output when it wants, for example when the output buffer is full
  78818. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78819. and with zero avail_out, it must be called again after making room in the
  78820. output buffer because there might be more output pending.
  78821. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78822. decide how much data to accumualte before producing output, in order to
  78823. maximize compression.
  78824. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78825. flushed to the output buffer and the output is aligned on a byte boundary, so
  78826. that the decompressor can get all input data available so far. (In particular
  78827. avail_in is zero after the call if enough output space has been provided
  78828. before the call.) Flushing may degrade compression for some compression
  78829. algorithms and so it should be used only when necessary.
  78830. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78831. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78832. restart from this point if previous compressed data has been damaged or if
  78833. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78834. compression.
  78835. If deflate returns with avail_out == 0, this function must be called again
  78836. with the same value of the flush parameter and more output space (updated
  78837. avail_out), until the flush is complete (deflate returns with non-zero
  78838. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78839. avail_out is greater than six to avoid repeated flush markers due to
  78840. avail_out == 0 on return.
  78841. If the parameter flush is set to Z_FINISH, pending input is processed,
  78842. pending output is flushed and deflate returns with Z_STREAM_END if there
  78843. was enough output space; if deflate returns with Z_OK, this function must be
  78844. called again with Z_FINISH and more output space (updated avail_out) but no
  78845. more input data, until it returns with Z_STREAM_END or an error. After
  78846. deflate has returned Z_STREAM_END, the only possible operations on the
  78847. stream are deflateReset or deflateEnd.
  78848. Z_FINISH can be used immediately after deflateInit if all the compression
  78849. is to be done in a single step. In this case, avail_out must be at least
  78850. the value returned by deflateBound (see below). If deflate does not return
  78851. Z_STREAM_END, then it must be called again as described above.
  78852. deflate() sets strm->adler to the adler32 checksum of all input read
  78853. so far (that is, total_in bytes).
  78854. deflate() may update strm->data_type if it can make a good guess about
  78855. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78856. binary. This field is only for information purposes and does not affect
  78857. the compression algorithm in any manner.
  78858. deflate() returns Z_OK if some progress has been made (more input
  78859. processed or more output produced), Z_STREAM_END if all input has been
  78860. consumed and all output has been produced (only when flush is set to
  78861. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78862. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78863. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78864. fatal, and deflate() can be called again with more input and more output
  78865. space to continue compressing.
  78866. */
  78867. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78868. /*
  78869. All dynamically allocated data structures for this stream are freed.
  78870. This function discards any unprocessed input and does not flush any
  78871. pending output.
  78872. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78873. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78874. prematurely (some input or output was discarded). In the error case,
  78875. msg may be set but then points to a static string (which must not be
  78876. deallocated).
  78877. */
  78878. /*
  78879. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78880. Initializes the internal stream state for decompression. The fields
  78881. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78882. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78883. value depends on the compression method), inflateInit determines the
  78884. compression method from the zlib header and allocates all data structures
  78885. accordingly; otherwise the allocation will be deferred to the first call of
  78886. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78887. use default allocation functions.
  78888. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78889. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78890. version assumed by the caller. msg is set to null if there is no error
  78891. message. inflateInit does not perform any decompression apart from reading
  78892. the zlib header if present: this will be done by inflate(). (So next_in and
  78893. avail_in may be modified, but next_out and avail_out are unchanged.)
  78894. */
  78895. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78896. /*
  78897. inflate decompresses as much data as possible, and stops when the input
  78898. buffer becomes empty or the output buffer becomes full. It may introduce
  78899. some output latency (reading input without producing any output) except when
  78900. forced to flush.
  78901. The detailed semantics are as follows. inflate performs one or both of the
  78902. following actions:
  78903. - Decompress more input starting at next_in and update next_in and avail_in
  78904. accordingly. If not all input can be processed (because there is not
  78905. enough room in the output buffer), next_in is updated and processing
  78906. will resume at this point for the next call of inflate().
  78907. - Provide more output starting at next_out and update next_out and avail_out
  78908. accordingly. inflate() provides as much output as possible, until there
  78909. is no more input data or no more space in the output buffer (see below
  78910. about the flush parameter).
  78911. Before the call of inflate(), the application should ensure that at least
  78912. one of the actions is possible, by providing more input and/or consuming
  78913. more output, and updating the next_* and avail_* values accordingly.
  78914. The application can consume the uncompressed output when it wants, for
  78915. example when the output buffer is full (avail_out == 0), or after each
  78916. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78917. must be called again after making room in the output buffer because there
  78918. might be more output pending.
  78919. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78920. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78921. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78922. if and when it gets to the next deflate block boundary. When decoding the
  78923. zlib or gzip format, this will cause inflate() to return immediately after
  78924. the header and before the first block. When doing a raw inflate, inflate()
  78925. will go ahead and process the first block, and will return when it gets to
  78926. the end of that block, or when it runs out of data.
  78927. The Z_BLOCK option assists in appending to or combining deflate streams.
  78928. Also to assist in this, on return inflate() will set strm->data_type to the
  78929. number of unused bits in the last byte taken from strm->next_in, plus 64
  78930. if inflate() is currently decoding the last block in the deflate stream,
  78931. plus 128 if inflate() returned immediately after decoding an end-of-block
  78932. code or decoding the complete header up to just before the first byte of the
  78933. deflate stream. The end-of-block will not be indicated until all of the
  78934. uncompressed data from that block has been written to strm->next_out. The
  78935. number of unused bits may in general be greater than seven, except when
  78936. bit 7 of data_type is set, in which case the number of unused bits will be
  78937. less than eight.
  78938. inflate() should normally be called until it returns Z_STREAM_END or an
  78939. error. However if all decompression is to be performed in a single step
  78940. (a single call of inflate), the parameter flush should be set to
  78941. Z_FINISH. In this case all pending input is processed and all pending
  78942. output is flushed; avail_out must be large enough to hold all the
  78943. uncompressed data. (The size of the uncompressed data may have been saved
  78944. by the compressor for this purpose.) The next operation on this stream must
  78945. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78946. is never required, but can be used to inform inflate that a faster approach
  78947. may be used for the single inflate() call.
  78948. In this implementation, inflate() always flushes as much output as
  78949. possible to the output buffer, and always uses the faster approach on the
  78950. first call. So the only effect of the flush parameter in this implementation
  78951. is on the return value of inflate(), as noted below, or when it returns early
  78952. because Z_BLOCK is used.
  78953. If a preset dictionary is needed after this call (see inflateSetDictionary
  78954. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78955. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78956. strm->adler to the adler32 checksum of all output produced so far (that is,
  78957. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78958. below. At the end of the stream, inflate() checks that its computed adler32
  78959. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78960. only if the checksum is correct.
  78961. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78962. deflate data. The header type is detected automatically. Any information
  78963. contained in the gzip header is not retained, so applications that need that
  78964. information should instead use raw inflate, see inflateInit2() below, or
  78965. inflateBack() and perform their own processing of the gzip header and
  78966. trailer.
  78967. inflate() returns Z_OK if some progress has been made (more input processed
  78968. or more output produced), Z_STREAM_END if the end of the compressed data has
  78969. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78970. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78971. corrupted (input stream not conforming to the zlib format or incorrect check
  78972. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78973. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78974. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78975. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78976. inflate() can be called again with more input and more output space to
  78977. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78978. call inflateSync() to look for a good compression block if a partial recovery
  78979. of the data is desired.
  78980. */
  78981. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78982. /*
  78983. All dynamically allocated data structures for this stream are freed.
  78984. This function discards any unprocessed input and does not flush any
  78985. pending output.
  78986. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78987. was inconsistent. In the error case, msg may be set but then points to a
  78988. static string (which must not be deallocated).
  78989. */
  78990. /* Advanced functions */
  78991. /*
  78992. The following functions are needed only in some special applications.
  78993. */
  78994. /*
  78995. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78996. int level,
  78997. int method,
  78998. int windowBits,
  78999. int memLevel,
  79000. int strategy));
  79001. This is another version of deflateInit with more compression options. The
  79002. fields next_in, zalloc, zfree and opaque must be initialized before by
  79003. the caller.
  79004. The method parameter is the compression method. It must be Z_DEFLATED in
  79005. this version of the library.
  79006. The windowBits parameter is the base two logarithm of the window size
  79007. (the size of the history buffer). It should be in the range 8..15 for this
  79008. version of the library. Larger values of this parameter result in better
  79009. compression at the expense of memory usage. The default value is 15 if
  79010. deflateInit is used instead.
  79011. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  79012. determines the window size. deflate() will then generate raw deflate data
  79013. with no zlib header or trailer, and will not compute an adler32 check value.
  79014. windowBits can also be greater than 15 for optional gzip encoding. Add
  79015. 16 to windowBits to write a simple gzip header and trailer around the
  79016. compressed data instead of a zlib wrapper. The gzip header will have no
  79017. file name, no extra data, no comment, no modification time (set to zero),
  79018. no header crc, and the operating system will be set to 255 (unknown). If a
  79019. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  79020. The memLevel parameter specifies how much memory should be allocated
  79021. for the internal compression state. memLevel=1 uses minimum memory but
  79022. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  79023. for optimal speed. The default value is 8. See zconf.h for total memory
  79024. usage as a function of windowBits and memLevel.
  79025. The strategy parameter is used to tune the compression algorithm. Use the
  79026. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  79027. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  79028. string match), or Z_RLE to limit match distances to one (run-length
  79029. encoding). Filtered data consists mostly of small values with a somewhat
  79030. random distribution. In this case, the compression algorithm is tuned to
  79031. compress them better. The effect of Z_FILTERED is to force more Huffman
  79032. coding and less string matching; it is somewhat intermediate between
  79033. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  79034. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  79035. parameter only affects the compression ratio but not the correctness of the
  79036. compressed output even if it is not set appropriately. Z_FIXED prevents the
  79037. use of dynamic Huffman codes, allowing for a simpler decoder for special
  79038. applications.
  79039. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79040. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  79041. method). msg is set to null if there is no error message. deflateInit2 does
  79042. not perform any compression: this will be done by deflate().
  79043. */
  79044. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  79045. const Bytef *dictionary,
  79046. uInt dictLength));
  79047. /*
  79048. Initializes the compression dictionary from the given byte sequence
  79049. without producing any compressed output. This function must be called
  79050. immediately after deflateInit, deflateInit2 or deflateReset, before any
  79051. call of deflate. The compressor and decompressor must use exactly the same
  79052. dictionary (see inflateSetDictionary).
  79053. The dictionary should consist of strings (byte sequences) that are likely
  79054. to be encountered later in the data to be compressed, with the most commonly
  79055. used strings preferably put towards the end of the dictionary. Using a
  79056. dictionary is most useful when the data to be compressed is short and can be
  79057. predicted with good accuracy; the data can then be compressed better than
  79058. with the default empty dictionary.
  79059. Depending on the size of the compression data structures selected by
  79060. deflateInit or deflateInit2, a part of the dictionary may in effect be
  79061. discarded, for example if the dictionary is larger than the window size in
  79062. deflate or deflate2. Thus the strings most likely to be useful should be
  79063. put at the end of the dictionary, not at the front. In addition, the
  79064. current implementation of deflate will use at most the window size minus
  79065. 262 bytes of the provided dictionary.
  79066. Upon return of this function, strm->adler is set to the adler32 value
  79067. of the dictionary; the decompressor may later use this value to determine
  79068. which dictionary has been used by the compressor. (The adler32 value
  79069. applies to the whole dictionary even if only a subset of the dictionary is
  79070. actually used by the compressor.) If a raw deflate was requested, then the
  79071. adler32 value is not computed and strm->adler is not set.
  79072. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  79073. parameter is invalid (such as NULL dictionary) or the stream state is
  79074. inconsistent (for example if deflate has already been called for this stream
  79075. or if the compression method is bsort). deflateSetDictionary does not
  79076. perform any compression: this will be done by deflate().
  79077. */
  79078. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  79079. z_streamp source));
  79080. /*
  79081. Sets the destination stream as a complete copy of the source stream.
  79082. This function can be useful when several compression strategies will be
  79083. tried, for example when there are several ways of pre-processing the input
  79084. data with a filter. The streams that will be discarded should then be freed
  79085. by calling deflateEnd. Note that deflateCopy duplicates the internal
  79086. compression state which can be quite large, so this strategy is slow and
  79087. can consume lots of memory.
  79088. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79089. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79090. (such as zalloc being NULL). msg is left unchanged in both source and
  79091. destination.
  79092. */
  79093. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  79094. /*
  79095. This function is equivalent to deflateEnd followed by deflateInit,
  79096. but does not free and reallocate all the internal compression state.
  79097. The stream will keep the same compression level and any other attributes
  79098. that may have been set by deflateInit2.
  79099. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79100. stream state was inconsistent (such as zalloc or state being NULL).
  79101. */
  79102. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  79103. int level,
  79104. int strategy));
  79105. /*
  79106. Dynamically update the compression level and compression strategy. The
  79107. interpretation of level and strategy is as in deflateInit2. This can be
  79108. used to switch between compression and straight copy of the input data, or
  79109. to switch to a different kind of input data requiring a different
  79110. strategy. If the compression level is changed, the input available so far
  79111. is compressed with the old level (and may be flushed); the new level will
  79112. take effect only at the next call of deflate().
  79113. Before the call of deflateParams, the stream state must be set as for
  79114. a call of deflate(), since the currently available input may have to
  79115. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  79116. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  79117. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  79118. if strm->avail_out was zero.
  79119. */
  79120. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  79121. int good_length,
  79122. int max_lazy,
  79123. int nice_length,
  79124. int max_chain));
  79125. /*
  79126. Fine tune deflate's internal compression parameters. This should only be
  79127. used by someone who understands the algorithm used by zlib's deflate for
  79128. searching for the best matching string, and even then only by the most
  79129. fanatic optimizer trying to squeeze out the last compressed bit for their
  79130. specific input data. Read the deflate.c source code for the meaning of the
  79131. max_lazy, good_length, nice_length, and max_chain parameters.
  79132. deflateTune() can be called after deflateInit() or deflateInit2(), and
  79133. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  79134. */
  79135. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  79136. uLong sourceLen));
  79137. /*
  79138. deflateBound() returns an upper bound on the compressed size after
  79139. deflation of sourceLen bytes. It must be called after deflateInit()
  79140. or deflateInit2(). This would be used to allocate an output buffer
  79141. for deflation in a single pass, and so would be called before deflate().
  79142. */
  79143. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  79144. int bits,
  79145. int value));
  79146. /*
  79147. deflatePrime() inserts bits in the deflate output stream. The intent
  79148. is that this function is used to start off the deflate output with the
  79149. bits leftover from a previous deflate stream when appending to it. As such,
  79150. this function can only be used for raw deflate, and must be used before the
  79151. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  79152. less than or equal to 16, and that many of the least significant bits of
  79153. value will be inserted in the output.
  79154. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79155. stream state was inconsistent.
  79156. */
  79157. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  79158. gz_headerp head));
  79159. /*
  79160. deflateSetHeader() provides gzip header information for when a gzip
  79161. stream is requested by deflateInit2(). deflateSetHeader() may be called
  79162. after deflateInit2() or deflateReset() and before the first call of
  79163. deflate(). The text, time, os, extra field, name, and comment information
  79164. in the provided gz_header structure are written to the gzip header (xflag is
  79165. ignored -- the extra flags are set according to the compression level). The
  79166. caller must assure that, if not Z_NULL, name and comment are terminated with
  79167. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  79168. available there. If hcrc is true, a gzip header crc is included. Note that
  79169. the current versions of the command-line version of gzip (up through version
  79170. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  79171. gzip file" and give up.
  79172. If deflateSetHeader is not used, the default gzip header has text false,
  79173. the time set to zero, and os set to 255, with no extra, name, or comment
  79174. fields. The gzip header is returned to the default state by deflateReset().
  79175. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79176. stream state was inconsistent.
  79177. */
  79178. /*
  79179. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  79180. int windowBits));
  79181. This is another version of inflateInit with an extra parameter. The
  79182. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  79183. before by the caller.
  79184. The windowBits parameter is the base two logarithm of the maximum window
  79185. size (the size of the history buffer). It should be in the range 8..15 for
  79186. this version of the library. The default value is 15 if inflateInit is used
  79187. instead. windowBits must be greater than or equal to the windowBits value
  79188. provided to deflateInit2() while compressing, or it must be equal to 15 if
  79189. deflateInit2() was not used. If a compressed stream with a larger window
  79190. size is given as input, inflate() will return with the error code
  79191. Z_DATA_ERROR instead of trying to allocate a larger window.
  79192. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  79193. determines the window size. inflate() will then process raw deflate data,
  79194. not looking for a zlib or gzip header, not generating a check value, and not
  79195. looking for any check values for comparison at the end of the stream. This
  79196. is for use with other formats that use the deflate compressed data format
  79197. such as zip. Those formats provide their own check values. If a custom
  79198. format is developed using the raw deflate format for compressed data, it is
  79199. recommended that a check value such as an adler32 or a crc32 be applied to
  79200. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  79201. most applications, the zlib format should be used as is. Note that comments
  79202. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79203. windowBits can also be greater than 15 for optional gzip decoding. Add
  79204. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79205. detection, or add 16 to decode only the gzip format (the zlib format will
  79206. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79207. a crc32 instead of an adler32.
  79208. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79209. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79210. is set to null if there is no error message. inflateInit2 does not perform
  79211. any decompression apart from reading the zlib header if present: this will
  79212. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79213. and avail_out are unchanged.)
  79214. */
  79215. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79216. const Bytef *dictionary,
  79217. uInt dictLength));
  79218. /*
  79219. Initializes the decompression dictionary from the given uncompressed byte
  79220. sequence. This function must be called immediately after a call of inflate,
  79221. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79222. can be determined from the adler32 value returned by that call of inflate.
  79223. The compressor and decompressor must use exactly the same dictionary (see
  79224. deflateSetDictionary). For raw inflate, this function can be called
  79225. immediately after inflateInit2() or inflateReset() and before any call of
  79226. inflate() to set the dictionary. The application must insure that the
  79227. dictionary that was used for compression is provided.
  79228. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79229. parameter is invalid (such as NULL dictionary) or the stream state is
  79230. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79231. expected one (incorrect adler32 value). inflateSetDictionary does not
  79232. perform any decompression: this will be done by subsequent calls of
  79233. inflate().
  79234. */
  79235. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79236. /*
  79237. Skips invalid compressed data until a full flush point (see above the
  79238. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79239. available input is skipped. No output is provided.
  79240. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79241. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79242. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79243. case, the application may save the current current value of total_in which
  79244. indicates where valid compressed data was found. In the error case, the
  79245. application may repeatedly call inflateSync, providing more input each time,
  79246. until success or end of the input data.
  79247. */
  79248. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79249. z_streamp source));
  79250. /*
  79251. Sets the destination stream as a complete copy of the source stream.
  79252. This function can be useful when randomly accessing a large stream. The
  79253. first pass through the stream can periodically record the inflate state,
  79254. allowing restarting inflate at those points when randomly accessing the
  79255. stream.
  79256. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79257. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79258. (such as zalloc being NULL). msg is left unchanged in both source and
  79259. destination.
  79260. */
  79261. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79262. /*
  79263. This function is equivalent to inflateEnd followed by inflateInit,
  79264. but does not free and reallocate all the internal decompression state.
  79265. The stream will keep attributes that may have been set by inflateInit2.
  79266. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79267. stream state was inconsistent (such as zalloc or state being NULL).
  79268. */
  79269. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79270. int bits,
  79271. int value));
  79272. /*
  79273. This function inserts bits in the inflate input stream. The intent is
  79274. that this function is used to start inflating at a bit position in the
  79275. middle of a byte. The provided bits will be used before any bytes are used
  79276. from next_in. This function should only be used with raw inflate, and
  79277. should be used before the first inflate() call after inflateInit2() or
  79278. inflateReset(). bits must be less than or equal to 16, and that many of the
  79279. least significant bits of value will be inserted in the input.
  79280. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79281. stream state was inconsistent.
  79282. */
  79283. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79284. gz_headerp head));
  79285. /*
  79286. inflateGetHeader() requests that gzip header information be stored in the
  79287. provided gz_header structure. inflateGetHeader() may be called after
  79288. inflateInit2() or inflateReset(), and before the first call of inflate().
  79289. As inflate() processes the gzip stream, head->done is zero until the header
  79290. is completed, at which time head->done is set to one. If a zlib stream is
  79291. being decoded, then head->done is set to -1 to indicate that there will be
  79292. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79293. force inflate() to return immediately after header processing is complete
  79294. and before any actual data is decompressed.
  79295. The text, time, xflags, and os fields are filled in with the gzip header
  79296. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79297. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79298. contains the maximum number of bytes to write to extra. Once done is true,
  79299. extra_len contains the actual extra field length, and extra contains the
  79300. extra field, or that field truncated if extra_max is less than extra_len.
  79301. If name is not Z_NULL, then up to name_max characters are written there,
  79302. terminated with a zero unless the length is greater than name_max. If
  79303. comment is not Z_NULL, then up to comm_max characters are written there,
  79304. terminated with a zero unless the length is greater than comm_max. When
  79305. any of extra, name, or comment are not Z_NULL and the respective field is
  79306. not present in the header, then that field is set to Z_NULL to signal its
  79307. absence. This allows the use of deflateSetHeader() with the returned
  79308. structure to duplicate the header. However if those fields are set to
  79309. allocated memory, then the application will need to save those pointers
  79310. elsewhere so that they can be eventually freed.
  79311. If inflateGetHeader is not used, then the header information is simply
  79312. discarded. The header is always checked for validity, including the header
  79313. CRC if present. inflateReset() will reset the process to discard the header
  79314. information. The application would need to call inflateGetHeader() again to
  79315. retrieve the header from the next gzip stream.
  79316. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79317. stream state was inconsistent.
  79318. */
  79319. /*
  79320. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79321. unsigned char FAR *window));
  79322. Initialize the internal stream state for decompression using inflateBack()
  79323. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79324. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79325. derived memory allocation routines are used. windowBits is the base two
  79326. logarithm of the window size, in the range 8..15. window is a caller
  79327. supplied buffer of that size. Except for special applications where it is
  79328. assured that deflate was used with small window sizes, windowBits must be 15
  79329. and a 32K byte window must be supplied to be able to decompress general
  79330. deflate streams.
  79331. See inflateBack() for the usage of these routines.
  79332. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79333. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79334. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79335. match the version of the header file.
  79336. */
  79337. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79338. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79339. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79340. in_func in, void FAR *in_desc,
  79341. out_func out, void FAR *out_desc));
  79342. /*
  79343. inflateBack() does a raw inflate with a single call using a call-back
  79344. interface for input and output. This is more efficient than inflate() for
  79345. file i/o applications in that it avoids copying between the output and the
  79346. sliding window by simply making the window itself the output buffer. This
  79347. function trusts the application to not change the output buffer passed by
  79348. the output function, at least until inflateBack() returns.
  79349. inflateBackInit() must be called first to allocate the internal state
  79350. and to initialize the state with the user-provided window buffer.
  79351. inflateBack() may then be used multiple times to inflate a complete, raw
  79352. deflate stream with each call. inflateBackEnd() is then called to free
  79353. the allocated state.
  79354. A raw deflate stream is one with no zlib or gzip header or trailer.
  79355. This routine would normally be used in a utility that reads zip or gzip
  79356. files and writes out uncompressed files. The utility would decode the
  79357. header and process the trailer on its own, hence this routine expects
  79358. only the raw deflate stream to decompress. This is different from the
  79359. normal behavior of inflate(), which expects either a zlib or gzip header and
  79360. trailer around the deflate stream.
  79361. inflateBack() uses two subroutines supplied by the caller that are then
  79362. called by inflateBack() for input and output. inflateBack() calls those
  79363. routines until it reads a complete deflate stream and writes out all of the
  79364. uncompressed data, or until it encounters an error. The function's
  79365. parameters and return types are defined above in the in_func and out_func
  79366. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79367. number of bytes of provided input, and a pointer to that input in buf. If
  79368. there is no input available, in() must return zero--buf is ignored in that
  79369. case--and inflateBack() will return a buffer error. inflateBack() will call
  79370. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79371. should return zero on success, or non-zero on failure. If out() returns
  79372. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79373. are permitted to change the contents of the window provided to
  79374. inflateBackInit(), which is also the buffer that out() uses to write from.
  79375. The length written by out() will be at most the window size. Any non-zero
  79376. amount of input may be provided by in().
  79377. For convenience, inflateBack() can be provided input on the first call by
  79378. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79379. in() will be called. Therefore strm->next_in must be initialized before
  79380. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79381. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79382. must also be initialized, and then if strm->avail_in is not zero, input will
  79383. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79384. The in_desc and out_desc parameters of inflateBack() is passed as the
  79385. first parameter of in() and out() respectively when they are called. These
  79386. descriptors can be optionally used to pass any information that the caller-
  79387. supplied in() and out() functions need to do their job.
  79388. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79389. pass back any unused input that was provided by the last in() call. The
  79390. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79391. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79392. error in the deflate stream (in which case strm->msg is set to indicate the
  79393. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79394. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79395. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79396. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79397. out() returning non-zero. (in() will always be called before out(), so
  79398. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79399. that inflateBack() cannot return Z_OK.
  79400. */
  79401. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79402. /*
  79403. All memory allocated by inflateBackInit() is freed.
  79404. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79405. state was inconsistent.
  79406. */
  79407. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79408. /* Return flags indicating compile-time options.
  79409. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79410. 1.0: size of uInt
  79411. 3.2: size of uLong
  79412. 5.4: size of voidpf (pointer)
  79413. 7.6: size of z_off_t
  79414. Compiler, assembler, and debug options:
  79415. 8: DEBUG
  79416. 9: ASMV or ASMINF -- use ASM code
  79417. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79418. 11: 0 (reserved)
  79419. One-time table building (smaller code, but not thread-safe if true):
  79420. 12: BUILDFIXED -- build static block decoding tables when needed
  79421. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79422. 14,15: 0 (reserved)
  79423. Library content (indicates missing functionality):
  79424. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79425. deflate code when not needed)
  79426. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79427. and decode gzip streams (to avoid linking crc code)
  79428. 18-19: 0 (reserved)
  79429. Operation variations (changes in library functionality):
  79430. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79431. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79432. 22,23: 0 (reserved)
  79433. The sprintf variant used by gzprintf (zero is best):
  79434. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79435. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79436. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79437. Remainder:
  79438. 27-31: 0 (reserved)
  79439. */
  79440. /* utility functions */
  79441. /*
  79442. The following utility functions are implemented on top of the
  79443. basic stream-oriented functions. To simplify the interface, some
  79444. default options are assumed (compression level and memory usage,
  79445. standard memory allocation functions). The source code of these
  79446. utility functions can easily be modified if you need special options.
  79447. */
  79448. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79449. const Bytef *source, uLong sourceLen));
  79450. /*
  79451. Compresses the source buffer into the destination buffer. sourceLen is
  79452. the byte length of the source buffer. Upon entry, destLen is the total
  79453. size of the destination buffer, which must be at least the value returned
  79454. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79455. compressed buffer.
  79456. This function can be used to compress a whole file at once if the
  79457. input file is mmap'ed.
  79458. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79459. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79460. buffer.
  79461. */
  79462. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79463. const Bytef *source, uLong sourceLen,
  79464. int level));
  79465. /*
  79466. Compresses the source buffer into the destination buffer. The level
  79467. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79468. length of the source buffer. Upon entry, destLen is the total size of the
  79469. destination buffer, which must be at least the value returned by
  79470. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79471. compressed buffer.
  79472. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79473. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79474. Z_STREAM_ERROR if the level parameter is invalid.
  79475. */
  79476. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79477. /*
  79478. compressBound() returns an upper bound on the compressed size after
  79479. compress() or compress2() on sourceLen bytes. It would be used before
  79480. a compress() or compress2() call to allocate the destination buffer.
  79481. */
  79482. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79483. const Bytef *source, uLong sourceLen));
  79484. /*
  79485. Decompresses the source buffer into the destination buffer. sourceLen is
  79486. the byte length of the source buffer. Upon entry, destLen is the total
  79487. size of the destination buffer, which must be large enough to hold the
  79488. entire uncompressed data. (The size of the uncompressed data must have
  79489. been saved previously by the compressor and transmitted to the decompressor
  79490. by some mechanism outside the scope of this compression library.)
  79491. Upon exit, destLen is the actual size of the compressed buffer.
  79492. This function can be used to decompress a whole file at once if the
  79493. input file is mmap'ed.
  79494. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79495. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79496. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79497. */
  79498. typedef voidp gzFile;
  79499. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79500. /*
  79501. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79502. is as in fopen ("rb" or "wb") but can also include a compression level
  79503. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79504. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79505. as in "wb1R". (See the description of deflateInit2 for more information
  79506. about the strategy parameter.)
  79507. gzopen can be used to read a file which is not in gzip format; in this
  79508. case gzread will directly read from the file without decompression.
  79509. gzopen returns NULL if the file could not be opened or if there was
  79510. insufficient memory to allocate the (de)compression state; errno
  79511. can be checked to distinguish the two cases (if errno is zero, the
  79512. zlib error is Z_MEM_ERROR). */
  79513. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79514. /*
  79515. gzdopen() associates a gzFile with the file descriptor fd. File
  79516. descriptors are obtained from calls like open, dup, creat, pipe or
  79517. fileno (in the file has been previously opened with fopen).
  79518. The mode parameter is as in gzopen.
  79519. The next call of gzclose on the returned gzFile will also close the
  79520. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79521. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79522. gzdopen returns NULL if there was insufficient memory to allocate
  79523. the (de)compression state.
  79524. */
  79525. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79526. /*
  79527. Dynamically update the compression level or strategy. See the description
  79528. of deflateInit2 for the meaning of these parameters.
  79529. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79530. opened for writing.
  79531. */
  79532. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79533. /*
  79534. Reads the given number of uncompressed bytes from the compressed file.
  79535. If the input file was not in gzip format, gzread copies the given number
  79536. of bytes into the buffer.
  79537. gzread returns the number of uncompressed bytes actually read (0 for
  79538. end of file, -1 for error). */
  79539. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79540. voidpc buf, unsigned len));
  79541. /*
  79542. Writes the given number of uncompressed bytes into the compressed file.
  79543. gzwrite returns the number of uncompressed bytes actually written
  79544. (0 in case of error).
  79545. */
  79546. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79547. /*
  79548. Converts, formats, and writes the args to the compressed file under
  79549. control of the format string, as in fprintf. gzprintf returns the number of
  79550. uncompressed bytes actually written (0 in case of error). The number of
  79551. uncompressed bytes written is limited to 4095. The caller should assure that
  79552. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79553. return an error (0) with nothing written. In this case, there may also be a
  79554. buffer overflow with unpredictable consequences, which is possible only if
  79555. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79556. because the secure snprintf() or vsnprintf() functions were not available.
  79557. */
  79558. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79559. /*
  79560. Writes the given null-terminated string to the compressed file, excluding
  79561. the terminating null character.
  79562. gzputs returns the number of characters written, or -1 in case of error.
  79563. */
  79564. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79565. /*
  79566. Reads bytes from the compressed file until len-1 characters are read, or
  79567. a newline character is read and transferred to buf, or an end-of-file
  79568. condition is encountered. The string is then terminated with a null
  79569. character.
  79570. gzgets returns buf, or Z_NULL in case of error.
  79571. */
  79572. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79573. /*
  79574. Writes c, converted to an unsigned char, into the compressed file.
  79575. gzputc returns the value that was written, or -1 in case of error.
  79576. */
  79577. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79578. /*
  79579. Reads one byte from the compressed file. gzgetc returns this byte
  79580. or -1 in case of end of file or error.
  79581. */
  79582. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79583. /*
  79584. Push one character back onto the stream to be read again later.
  79585. Only one character of push-back is allowed. gzungetc() returns the
  79586. character pushed, or -1 on failure. gzungetc() will fail if a
  79587. character has been pushed but not read yet, or if c is -1. The pushed
  79588. character will be discarded if the stream is repositioned with gzseek()
  79589. or gzrewind().
  79590. */
  79591. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79592. /*
  79593. Flushes all pending output into the compressed file. The parameter
  79594. flush is as in the deflate() function. The return value is the zlib
  79595. error number (see function gzerror below). gzflush returns Z_OK if
  79596. the flush parameter is Z_FINISH and all output could be flushed.
  79597. gzflush should be called only when strictly necessary because it can
  79598. degrade compression.
  79599. */
  79600. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79601. z_off_t offset, int whence));
  79602. /*
  79603. Sets the starting position for the next gzread or gzwrite on the
  79604. given compressed file. The offset represents a number of bytes in the
  79605. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79606. the value SEEK_END is not supported.
  79607. If the file is opened for reading, this function is emulated but can be
  79608. extremely slow. If the file is opened for writing, only forward seeks are
  79609. supported; gzseek then compresses a sequence of zeroes up to the new
  79610. starting position.
  79611. gzseek returns the resulting offset location as measured in bytes from
  79612. the beginning of the uncompressed stream, or -1 in case of error, in
  79613. particular if the file is opened for writing and the new starting position
  79614. would be before the current position.
  79615. */
  79616. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79617. /*
  79618. Rewinds the given file. This function is supported only for reading.
  79619. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79620. */
  79621. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79622. /*
  79623. Returns the starting position for the next gzread or gzwrite on the
  79624. given compressed file. This position represents a number of bytes in the
  79625. uncompressed data stream.
  79626. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79627. */
  79628. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79629. /*
  79630. Returns 1 when EOF has previously been detected reading the given
  79631. input stream, otherwise zero.
  79632. */
  79633. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79634. /*
  79635. Returns 1 if file is being read directly without decompression, otherwise
  79636. zero.
  79637. */
  79638. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79639. /*
  79640. Flushes all pending output if necessary, closes the compressed file
  79641. and deallocates all the (de)compression state. The return value is the zlib
  79642. error number (see function gzerror below).
  79643. */
  79644. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79645. /*
  79646. Returns the error message for the last error which occurred on the
  79647. given compressed file. errnum is set to zlib error number. If an
  79648. error occurred in the file system and not in the compression library,
  79649. errnum is set to Z_ERRNO and the application may consult errno
  79650. to get the exact error code.
  79651. */
  79652. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79653. /*
  79654. Clears the error and end-of-file flags for file. This is analogous to the
  79655. clearerr() function in stdio. This is useful for continuing to read a gzip
  79656. file that is being written concurrently.
  79657. */
  79658. /* checksum functions */
  79659. /*
  79660. These functions are not related to compression but are exported
  79661. anyway because they might be useful in applications using the
  79662. compression library.
  79663. */
  79664. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79665. /*
  79666. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79667. return the updated checksum. If buf is NULL, this function returns
  79668. the required initial value for the checksum.
  79669. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79670. much faster. Usage example:
  79671. uLong adler = adler32(0L, Z_NULL, 0);
  79672. while (read_buffer(buffer, length) != EOF) {
  79673. adler = adler32(adler, buffer, length);
  79674. }
  79675. if (adler != original_adler) error();
  79676. */
  79677. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79678. z_off_t len2));
  79679. /*
  79680. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79681. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79682. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79683. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79684. */
  79685. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79686. /*
  79687. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79688. updated CRC-32. If buf is NULL, this function returns the required initial
  79689. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79690. performed within this function so it shouldn't be done by the application.
  79691. Usage example:
  79692. uLong crc = crc32(0L, Z_NULL, 0);
  79693. while (read_buffer(buffer, length) != EOF) {
  79694. crc = crc32(crc, buffer, length);
  79695. }
  79696. if (crc != original_crc) error();
  79697. */
  79698. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79699. /*
  79700. Combine two CRC-32 check values into one. For two sequences of bytes,
  79701. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79702. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79703. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79704. len2.
  79705. */
  79706. /* various hacks, don't look :) */
  79707. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79708. * and the compiler's view of z_stream:
  79709. */
  79710. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79711. const char *version, int stream_size));
  79712. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79713. const char *version, int stream_size));
  79714. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79715. int windowBits, int memLevel,
  79716. int strategy, const char *version,
  79717. int stream_size));
  79718. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79719. const char *version, int stream_size));
  79720. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79721. unsigned char FAR *window,
  79722. const char *version,
  79723. int stream_size));
  79724. #define deflateInit(strm, level) \
  79725. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79726. #define inflateInit(strm) \
  79727. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79728. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79729. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79730. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79731. #define inflateInit2(strm, windowBits) \
  79732. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79733. #define inflateBackInit(strm, windowBits, window) \
  79734. inflateBackInit_((strm), (windowBits), (window), \
  79735. ZLIB_VERSION, sizeof(z_stream))
  79736. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79737. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79738. #endif
  79739. ZEXTERN const char * ZEXPORT zError OF((int));
  79740. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79741. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79742. #ifdef __cplusplus
  79743. //}
  79744. #endif
  79745. #endif /* ZLIB_H */
  79746. /*** End of inlined file: zlib.h ***/
  79747. #undef OS_CODE
  79748. #else
  79749. #include <zlib.h>
  79750. #endif
  79751. }
  79752. BEGIN_JUCE_NAMESPACE
  79753. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79754. {
  79755. public:
  79756. GZIPCompressorHelper (const int compressionLevel, const int windowBits)
  79757. : data (0),
  79758. dataSize (0),
  79759. compLevel (compressionLevel),
  79760. strategy (0),
  79761. setParams (true),
  79762. streamIsValid (false),
  79763. finished (false),
  79764. shouldFinish (false)
  79765. {
  79766. using namespace zlibNamespace;
  79767. zerostruct (stream);
  79768. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79769. windowBits != 0 ? windowBits : MAX_WBITS,
  79770. 8, strategy) == Z_OK);
  79771. }
  79772. ~GZIPCompressorHelper()
  79773. {
  79774. using namespace zlibNamespace;
  79775. if (streamIsValid)
  79776. deflateEnd (&stream);
  79777. }
  79778. bool needsInput() const throw()
  79779. {
  79780. return dataSize <= 0;
  79781. }
  79782. void setInput (const uint8* const newData, const int size) throw()
  79783. {
  79784. data = newData;
  79785. dataSize = size;
  79786. }
  79787. int doNextBlock (uint8* const dest, const int destSize) throw()
  79788. {
  79789. using namespace zlibNamespace;
  79790. if (streamIsValid)
  79791. {
  79792. stream.next_in = const_cast <uint8*> (data);
  79793. stream.next_out = dest;
  79794. stream.avail_in = dataSize;
  79795. stream.avail_out = destSize;
  79796. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79797. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79798. setParams = false;
  79799. switch (result)
  79800. {
  79801. case Z_STREAM_END:
  79802. finished = true;
  79803. // Deliberate fall-through..
  79804. case Z_OK:
  79805. data += dataSize - stream.avail_in;
  79806. dataSize = stream.avail_in;
  79807. return destSize - stream.avail_out;
  79808. default:
  79809. break;
  79810. }
  79811. }
  79812. return 0;
  79813. }
  79814. enum { gzipCompBufferSize = 32768 };
  79815. private:
  79816. zlibNamespace::z_stream stream;
  79817. const uint8* data;
  79818. int dataSize, compLevel, strategy;
  79819. bool setParams, streamIsValid;
  79820. public:
  79821. bool finished, shouldFinish;
  79822. };
  79823. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79824. int compressionLevel,
  79825. const bool deleteDestStream,
  79826. const int windowBits)
  79827. : destStream (destStream_),
  79828. streamToDelete (deleteDestStream ? destStream_ : 0),
  79829. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79830. {
  79831. if (compressionLevel < 1 || compressionLevel > 9)
  79832. compressionLevel = -1;
  79833. helper = new GZIPCompressorHelper (compressionLevel, windowBits);
  79834. }
  79835. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79836. {
  79837. flush();
  79838. }
  79839. void GZIPCompressorOutputStream::flush()
  79840. {
  79841. if (! helper->finished)
  79842. {
  79843. helper->shouldFinish = true;
  79844. while (! helper->finished)
  79845. doNextBlock();
  79846. }
  79847. destStream->flush();
  79848. }
  79849. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79850. {
  79851. if (! helper->finished)
  79852. {
  79853. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79854. while (! helper->needsInput())
  79855. {
  79856. if (! doNextBlock())
  79857. return false;
  79858. }
  79859. }
  79860. return true;
  79861. }
  79862. bool GZIPCompressorOutputStream::doNextBlock()
  79863. {
  79864. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79865. return len <= 0 || destStream->write (buffer, len);
  79866. }
  79867. int64 GZIPCompressorOutputStream::getPosition()
  79868. {
  79869. return destStream->getPosition();
  79870. }
  79871. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79872. {
  79873. jassertfalse; // can't do it!
  79874. return false;
  79875. }
  79876. END_JUCE_NAMESPACE
  79877. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79878. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79879. #if JUCE_MSVC
  79880. #pragma warning (push)
  79881. #pragma warning (disable: 4309 4305)
  79882. #endif
  79883. namespace zlibNamespace
  79884. {
  79885. #if JUCE_INCLUDE_ZLIB_CODE
  79886. #undef OS_CODE
  79887. #undef fdopen
  79888. #define ZLIB_INTERNAL
  79889. #define NO_DUMMY_DECL
  79890. /*** Start of inlined file: adler32.c ***/
  79891. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79892. #define ZLIB_INTERNAL
  79893. #define BASE 65521UL /* largest prime smaller than 65536 */
  79894. #define NMAX 5552
  79895. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79896. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79897. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79898. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79899. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79900. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79901. /* use NO_DIVIDE if your processor does not do division in hardware */
  79902. #ifdef NO_DIVIDE
  79903. # define MOD(a) \
  79904. do { \
  79905. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79906. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79907. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79908. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79909. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79910. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79911. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79912. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79913. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79914. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79915. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79916. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79917. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79918. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79919. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79920. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79921. if (a >= BASE) a -= BASE; \
  79922. } while (0)
  79923. # define MOD4(a) \
  79924. do { \
  79925. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79926. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79927. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79928. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79929. if (a >= BASE) a -= BASE; \
  79930. } while (0)
  79931. #else
  79932. # define MOD(a) a %= BASE
  79933. # define MOD4(a) a %= BASE
  79934. #endif
  79935. /* ========================================================================= */
  79936. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79937. {
  79938. unsigned long sum2;
  79939. unsigned n;
  79940. /* split Adler-32 into component sums */
  79941. sum2 = (adler >> 16) & 0xffff;
  79942. adler &= 0xffff;
  79943. /* in case user likes doing a byte at a time, keep it fast */
  79944. if (len == 1) {
  79945. adler += buf[0];
  79946. if (adler >= BASE)
  79947. adler -= BASE;
  79948. sum2 += adler;
  79949. if (sum2 >= BASE)
  79950. sum2 -= BASE;
  79951. return adler | (sum2 << 16);
  79952. }
  79953. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79954. if (buf == Z_NULL)
  79955. return 1L;
  79956. /* in case short lengths are provided, keep it somewhat fast */
  79957. if (len < 16) {
  79958. while (len--) {
  79959. adler += *buf++;
  79960. sum2 += adler;
  79961. }
  79962. if (adler >= BASE)
  79963. adler -= BASE;
  79964. MOD4(sum2); /* only added so many BASE's */
  79965. return adler | (sum2 << 16);
  79966. }
  79967. /* do length NMAX blocks -- requires just one modulo operation */
  79968. while (len >= NMAX) {
  79969. len -= NMAX;
  79970. n = NMAX / 16; /* NMAX is divisible by 16 */
  79971. do {
  79972. DO16(buf); /* 16 sums unrolled */
  79973. buf += 16;
  79974. } while (--n);
  79975. MOD(adler);
  79976. MOD(sum2);
  79977. }
  79978. /* do remaining bytes (less than NMAX, still just one modulo) */
  79979. if (len) { /* avoid modulos if none remaining */
  79980. while (len >= 16) {
  79981. len -= 16;
  79982. DO16(buf);
  79983. buf += 16;
  79984. }
  79985. while (len--) {
  79986. adler += *buf++;
  79987. sum2 += adler;
  79988. }
  79989. MOD(adler);
  79990. MOD(sum2);
  79991. }
  79992. /* return recombined sums */
  79993. return adler | (sum2 << 16);
  79994. }
  79995. /* ========================================================================= */
  79996. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79997. {
  79998. unsigned long sum1;
  79999. unsigned long sum2;
  80000. unsigned rem;
  80001. /* the derivation of this formula is left as an exercise for the reader */
  80002. rem = (unsigned)(len2 % BASE);
  80003. sum1 = adler1 & 0xffff;
  80004. sum2 = rem * sum1;
  80005. MOD(sum2);
  80006. sum1 += (adler2 & 0xffff) + BASE - 1;
  80007. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  80008. if (sum1 > BASE) sum1 -= BASE;
  80009. if (sum1 > BASE) sum1 -= BASE;
  80010. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  80011. if (sum2 > BASE) sum2 -= BASE;
  80012. return sum1 | (sum2 << 16);
  80013. }
  80014. /*** End of inlined file: adler32.c ***/
  80015. /*** Start of inlined file: compress.c ***/
  80016. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80017. #define ZLIB_INTERNAL
  80018. /* ===========================================================================
  80019. Compresses the source buffer into the destination buffer. The level
  80020. parameter has the same meaning as in deflateInit. sourceLen is the byte
  80021. length of the source buffer. Upon entry, destLen is the total size of the
  80022. destination buffer, which must be at least 0.1% larger than sourceLen plus
  80023. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  80024. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  80025. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  80026. Z_STREAM_ERROR if the level parameter is invalid.
  80027. */
  80028. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  80029. uLong sourceLen, int level)
  80030. {
  80031. z_stream stream;
  80032. int err;
  80033. stream.next_in = (Bytef*)source;
  80034. stream.avail_in = (uInt)sourceLen;
  80035. #ifdef MAXSEG_64K
  80036. /* Check for source > 64K on 16-bit machine: */
  80037. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  80038. #endif
  80039. stream.next_out = dest;
  80040. stream.avail_out = (uInt)*destLen;
  80041. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  80042. stream.zalloc = (alloc_func)0;
  80043. stream.zfree = (free_func)0;
  80044. stream.opaque = (voidpf)0;
  80045. err = deflateInit(&stream, level);
  80046. if (err != Z_OK) return err;
  80047. err = deflate(&stream, Z_FINISH);
  80048. if (err != Z_STREAM_END) {
  80049. deflateEnd(&stream);
  80050. return err == Z_OK ? Z_BUF_ERROR : err;
  80051. }
  80052. *destLen = stream.total_out;
  80053. err = deflateEnd(&stream);
  80054. return err;
  80055. }
  80056. /* ===========================================================================
  80057. */
  80058. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  80059. {
  80060. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  80061. }
  80062. /* ===========================================================================
  80063. If the default memLevel or windowBits for deflateInit() is changed, then
  80064. this function needs to be updated.
  80065. */
  80066. uLong ZEXPORT compressBound (uLong sourceLen)
  80067. {
  80068. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  80069. }
  80070. /*** End of inlined file: compress.c ***/
  80071. #undef DO1
  80072. #undef DO8
  80073. /*** Start of inlined file: crc32.c ***/
  80074. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80075. /*
  80076. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  80077. protection on the static variables used to control the first-use generation
  80078. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  80079. first call get_crc_table() to initialize the tables before allowing more than
  80080. one thread to use crc32().
  80081. */
  80082. #ifdef MAKECRCH
  80083. # include <stdio.h>
  80084. # ifndef DYNAMIC_CRC_TABLE
  80085. # define DYNAMIC_CRC_TABLE
  80086. # endif /* !DYNAMIC_CRC_TABLE */
  80087. #endif /* MAKECRCH */
  80088. /*** Start of inlined file: zutil.h ***/
  80089. /* WARNING: this file should *not* be used by applications. It is
  80090. part of the implementation of the compression library and is
  80091. subject to change. Applications should only use zlib.h.
  80092. */
  80093. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80094. #ifndef ZUTIL_H
  80095. #define ZUTIL_H
  80096. #define ZLIB_INTERNAL
  80097. #ifdef STDC
  80098. # ifndef _WIN32_WCE
  80099. # include <stddef.h>
  80100. # endif
  80101. # include <string.h>
  80102. # include <stdlib.h>
  80103. #endif
  80104. #ifdef NO_ERRNO_H
  80105. # ifdef _WIN32_WCE
  80106. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80107. * errno. We define it as a global variable to simplify porting.
  80108. * Its value is always 0 and should not be used. We rename it to
  80109. * avoid conflict with other libraries that use the same workaround.
  80110. */
  80111. # define errno z_errno
  80112. # endif
  80113. extern int errno;
  80114. #else
  80115. # ifndef _WIN32_WCE
  80116. # include <errno.h>
  80117. # endif
  80118. #endif
  80119. #ifndef local
  80120. # define local static
  80121. #endif
  80122. /* compile with -Dlocal if your debugger can't find static symbols */
  80123. typedef unsigned char uch;
  80124. typedef uch FAR uchf;
  80125. typedef unsigned short ush;
  80126. typedef ush FAR ushf;
  80127. typedef unsigned long ulg;
  80128. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  80129. /* (size given to avoid silly warnings with Visual C++) */
  80130. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  80131. #define ERR_RETURN(strm,err) \
  80132. return (strm->msg = (char*)ERR_MSG(err), (err))
  80133. /* To be used only when the state is known to be valid */
  80134. /* common constants */
  80135. #ifndef DEF_WBITS
  80136. # define DEF_WBITS MAX_WBITS
  80137. #endif
  80138. /* default windowBits for decompression. MAX_WBITS is for compression only */
  80139. #if MAX_MEM_LEVEL >= 8
  80140. # define DEF_MEM_LEVEL 8
  80141. #else
  80142. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  80143. #endif
  80144. /* default memLevel */
  80145. #define STORED_BLOCK 0
  80146. #define STATIC_TREES 1
  80147. #define DYN_TREES 2
  80148. /* The three kinds of block type */
  80149. #define MIN_MATCH 3
  80150. #define MAX_MATCH 258
  80151. /* The minimum and maximum match lengths */
  80152. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  80153. /* target dependencies */
  80154. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  80155. # define OS_CODE 0x00
  80156. # if defined(__TURBOC__) || defined(__BORLANDC__)
  80157. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  80158. /* Allow compilation with ANSI keywords only enabled */
  80159. void _Cdecl farfree( void *block );
  80160. void *_Cdecl farmalloc( unsigned long nbytes );
  80161. # else
  80162. # include <alloc.h>
  80163. # endif
  80164. # else /* MSC or DJGPP */
  80165. # include <malloc.h>
  80166. # endif
  80167. #endif
  80168. #ifdef AMIGA
  80169. # define OS_CODE 0x01
  80170. #endif
  80171. #if defined(VAXC) || defined(VMS)
  80172. # define OS_CODE 0x02
  80173. # define F_OPEN(name, mode) \
  80174. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  80175. #endif
  80176. #if defined(ATARI) || defined(atarist)
  80177. # define OS_CODE 0x05
  80178. #endif
  80179. #ifdef OS2
  80180. # define OS_CODE 0x06
  80181. # ifdef M_I86
  80182. #include <malloc.h>
  80183. # endif
  80184. #endif
  80185. #if defined(MACOS) || TARGET_OS_MAC
  80186. # define OS_CODE 0x07
  80187. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  80188. # include <unix.h> /* for fdopen */
  80189. # else
  80190. # ifndef fdopen
  80191. # define fdopen(fd,mode) NULL /* No fdopen() */
  80192. # endif
  80193. # endif
  80194. #endif
  80195. #ifdef TOPS20
  80196. # define OS_CODE 0x0a
  80197. #endif
  80198. #ifdef WIN32
  80199. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80200. # define OS_CODE 0x0b
  80201. # endif
  80202. #endif
  80203. #ifdef __50SERIES /* Prime/PRIMOS */
  80204. # define OS_CODE 0x0f
  80205. #endif
  80206. #if defined(_BEOS_) || defined(RISCOS)
  80207. # define fdopen(fd,mode) NULL /* No fdopen() */
  80208. #endif
  80209. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80210. # if defined(_WIN32_WCE)
  80211. # define fdopen(fd,mode) NULL /* No fdopen() */
  80212. # ifndef _PTRDIFF_T_DEFINED
  80213. typedef int ptrdiff_t;
  80214. # define _PTRDIFF_T_DEFINED
  80215. # endif
  80216. # else
  80217. # define fdopen(fd,type) _fdopen(fd,type)
  80218. # endif
  80219. #endif
  80220. /* common defaults */
  80221. #ifndef OS_CODE
  80222. # define OS_CODE 0x03 /* assume Unix */
  80223. #endif
  80224. #ifndef F_OPEN
  80225. # define F_OPEN(name, mode) fopen((name), (mode))
  80226. #endif
  80227. /* functions */
  80228. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80229. # ifndef HAVE_VSNPRINTF
  80230. # define HAVE_VSNPRINTF
  80231. # endif
  80232. #endif
  80233. #if defined(__CYGWIN__)
  80234. # ifndef HAVE_VSNPRINTF
  80235. # define HAVE_VSNPRINTF
  80236. # endif
  80237. #endif
  80238. #ifndef HAVE_VSNPRINTF
  80239. # ifdef MSDOS
  80240. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80241. but for now we just assume it doesn't. */
  80242. # define NO_vsnprintf
  80243. # endif
  80244. # ifdef __TURBOC__
  80245. # define NO_vsnprintf
  80246. # endif
  80247. # ifdef WIN32
  80248. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80249. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80250. # define vsnprintf _vsnprintf
  80251. # endif
  80252. # endif
  80253. # ifdef __SASC
  80254. # define NO_vsnprintf
  80255. # endif
  80256. #endif
  80257. #ifdef VMS
  80258. # define NO_vsnprintf
  80259. #endif
  80260. #if defined(pyr)
  80261. # define NO_MEMCPY
  80262. #endif
  80263. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80264. /* Use our own functions for small and medium model with MSC <= 5.0.
  80265. * You may have to use the same strategy for Borland C (untested).
  80266. * The __SC__ check is for Symantec.
  80267. */
  80268. # define NO_MEMCPY
  80269. #endif
  80270. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80271. # define HAVE_MEMCPY
  80272. #endif
  80273. #ifdef HAVE_MEMCPY
  80274. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80275. # define zmemcpy _fmemcpy
  80276. # define zmemcmp _fmemcmp
  80277. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80278. # else
  80279. # define zmemcpy memcpy
  80280. # define zmemcmp memcmp
  80281. # define zmemzero(dest, len) memset(dest, 0, len)
  80282. # endif
  80283. #else
  80284. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80285. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80286. extern void zmemzero OF((Bytef* dest, uInt len));
  80287. #endif
  80288. /* Diagnostic functions */
  80289. #ifdef DEBUG
  80290. # include <stdio.h>
  80291. extern int z_verbose;
  80292. extern void z_error OF((const char *m));
  80293. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80294. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80295. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80296. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80297. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80298. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80299. #else
  80300. # define Assert(cond,msg)
  80301. # define Trace(x)
  80302. # define Tracev(x)
  80303. # define Tracevv(x)
  80304. # define Tracec(c,x)
  80305. # define Tracecv(c,x)
  80306. #endif
  80307. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80308. void zcfree OF((voidpf opaque, voidpf ptr));
  80309. #define ZALLOC(strm, items, size) \
  80310. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80311. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80312. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80313. #endif /* ZUTIL_H */
  80314. /*** End of inlined file: zutil.h ***/
  80315. /* for STDC and FAR definitions */
  80316. #define local static
  80317. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80318. #ifndef NOBYFOUR
  80319. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80320. # include <limits.h>
  80321. # define BYFOUR
  80322. # if (UINT_MAX == 0xffffffffUL)
  80323. typedef unsigned int u4;
  80324. # else
  80325. # if (ULONG_MAX == 0xffffffffUL)
  80326. typedef unsigned long u4;
  80327. # else
  80328. # if (USHRT_MAX == 0xffffffffUL)
  80329. typedef unsigned short u4;
  80330. # else
  80331. # undef BYFOUR /* can't find a four-byte integer type! */
  80332. # endif
  80333. # endif
  80334. # endif
  80335. # endif /* STDC */
  80336. #endif /* !NOBYFOUR */
  80337. /* Definitions for doing the crc four data bytes at a time. */
  80338. #ifdef BYFOUR
  80339. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80340. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80341. local unsigned long crc32_little OF((unsigned long,
  80342. const unsigned char FAR *, unsigned));
  80343. local unsigned long crc32_big OF((unsigned long,
  80344. const unsigned char FAR *, unsigned));
  80345. # define TBLS 8
  80346. #else
  80347. # define TBLS 1
  80348. #endif /* BYFOUR */
  80349. /* Local functions for crc concatenation */
  80350. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80351. unsigned long vec));
  80352. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80353. #ifdef DYNAMIC_CRC_TABLE
  80354. local volatile int crc_table_empty = 1;
  80355. local unsigned long FAR crc_table[TBLS][256];
  80356. local void make_crc_table OF((void));
  80357. #ifdef MAKECRCH
  80358. local void write_table OF((FILE *, const unsigned long FAR *));
  80359. #endif /* MAKECRCH */
  80360. /*
  80361. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80362. 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.
  80363. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80364. with the lowest powers in the most significant bit. Then adding polynomials
  80365. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80366. one. If we call the above polynomial p, and represent a byte as the
  80367. polynomial q, also with the lowest power in the most significant bit (so the
  80368. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80369. where a mod b means the remainder after dividing a by b.
  80370. This calculation is done using the shift-register method of multiplying and
  80371. taking the remainder. The register is initialized to zero, and for each
  80372. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80373. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80374. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80375. out is a one). We start with the highest power (least significant bit) of
  80376. q and repeat for all eight bits of q.
  80377. The first table is simply the CRC of all possible eight bit values. This is
  80378. all the information needed to generate CRCs on data a byte at a time for all
  80379. combinations of CRC register values and incoming bytes. The remaining tables
  80380. allow for word-at-a-time CRC calculation for both big-endian and little-
  80381. endian machines, where a word is four bytes.
  80382. */
  80383. local void make_crc_table()
  80384. {
  80385. unsigned long c;
  80386. int n, k;
  80387. unsigned long poly; /* polynomial exclusive-or pattern */
  80388. /* terms of polynomial defining this crc (except x^32): */
  80389. static volatile int first = 1; /* flag to limit concurrent making */
  80390. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80391. /* See if another task is already doing this (not thread-safe, but better
  80392. than nothing -- significantly reduces duration of vulnerability in
  80393. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80394. if (first) {
  80395. first = 0;
  80396. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80397. poly = 0UL;
  80398. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80399. poly |= 1UL << (31 - p[n]);
  80400. /* generate a crc for every 8-bit value */
  80401. for (n = 0; n < 256; n++) {
  80402. c = (unsigned long)n;
  80403. for (k = 0; k < 8; k++)
  80404. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80405. crc_table[0][n] = c;
  80406. }
  80407. #ifdef BYFOUR
  80408. /* generate crc for each value followed by one, two, and three zeros,
  80409. and then the byte reversal of those as well as the first table */
  80410. for (n = 0; n < 256; n++) {
  80411. c = crc_table[0][n];
  80412. crc_table[4][n] = REV(c);
  80413. for (k = 1; k < 4; k++) {
  80414. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80415. crc_table[k][n] = c;
  80416. crc_table[k + 4][n] = REV(c);
  80417. }
  80418. }
  80419. #endif /* BYFOUR */
  80420. crc_table_empty = 0;
  80421. }
  80422. else { /* not first */
  80423. /* wait for the other guy to finish (not efficient, but rare) */
  80424. while (crc_table_empty)
  80425. ;
  80426. }
  80427. #ifdef MAKECRCH
  80428. /* write out CRC tables to crc32.h */
  80429. {
  80430. FILE *out;
  80431. out = fopen("crc32.h", "w");
  80432. if (out == NULL) return;
  80433. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80434. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80435. fprintf(out, "local const unsigned long FAR ");
  80436. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80437. write_table(out, crc_table[0]);
  80438. # ifdef BYFOUR
  80439. fprintf(out, "#ifdef BYFOUR\n");
  80440. for (k = 1; k < 8; k++) {
  80441. fprintf(out, " },\n {\n");
  80442. write_table(out, crc_table[k]);
  80443. }
  80444. fprintf(out, "#endif\n");
  80445. # endif /* BYFOUR */
  80446. fprintf(out, " }\n};\n");
  80447. fclose(out);
  80448. }
  80449. #endif /* MAKECRCH */
  80450. }
  80451. #ifdef MAKECRCH
  80452. local void write_table(out, table)
  80453. FILE *out;
  80454. const unsigned long FAR *table;
  80455. {
  80456. int n;
  80457. for (n = 0; n < 256; n++)
  80458. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80459. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80460. }
  80461. #endif /* MAKECRCH */
  80462. #else /* !DYNAMIC_CRC_TABLE */
  80463. /* ========================================================================
  80464. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80465. */
  80466. /*** Start of inlined file: crc32.h ***/
  80467. local const unsigned long FAR crc_table[TBLS][256] =
  80468. {
  80469. {
  80470. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80471. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80472. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80473. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80474. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80475. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80476. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80477. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80478. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80479. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80480. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80481. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80482. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80483. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80484. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80485. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80486. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80487. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80488. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80489. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80490. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80491. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80492. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80493. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80494. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80495. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80496. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80497. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80498. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80499. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80500. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80501. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80502. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80503. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80504. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80505. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80506. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80507. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80508. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80509. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80510. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80511. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80512. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80513. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80514. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80515. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80516. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80517. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80518. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80519. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80520. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80521. 0x2d02ef8dUL
  80522. #ifdef BYFOUR
  80523. },
  80524. {
  80525. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80526. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80527. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80528. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80529. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80530. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80531. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80532. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80533. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80534. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80535. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80536. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80537. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80538. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80539. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80540. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80541. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80542. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80543. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80544. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80545. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80546. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80547. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80548. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80549. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80550. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80551. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80552. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80553. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80554. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80555. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80556. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80557. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80558. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80559. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80560. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80561. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80562. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80563. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80564. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80565. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80566. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80567. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80568. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80569. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80570. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80571. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80572. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80573. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80574. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80575. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80576. 0x9324fd72UL
  80577. },
  80578. {
  80579. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80580. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80581. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80582. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80583. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80584. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80585. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80586. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80587. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80588. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80589. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80590. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80591. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80592. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80593. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80594. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80595. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80596. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80597. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80598. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80599. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80600. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80601. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80602. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80603. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80604. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80605. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80606. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80607. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80608. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80609. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80610. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80611. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80612. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80613. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80614. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80615. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80616. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80617. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80618. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80619. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80620. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80621. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80622. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80623. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80624. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80625. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80626. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80627. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80628. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80629. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80630. 0xbe9834edUL
  80631. },
  80632. {
  80633. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80634. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80635. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80636. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80637. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80638. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80639. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80640. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80641. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80642. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80643. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80644. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80645. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80646. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80647. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80648. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80649. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80650. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80651. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80652. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80653. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80654. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80655. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80656. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80657. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80658. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80659. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80660. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80661. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80662. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80663. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80664. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80665. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80666. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80667. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80668. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80669. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80670. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80671. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80672. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80673. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80674. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80675. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80676. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80677. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80678. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80679. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80680. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80681. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80682. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80683. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80684. 0xde0506f1UL
  80685. },
  80686. {
  80687. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80688. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80689. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80690. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80691. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80692. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80693. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80694. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80695. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80696. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80697. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80698. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80699. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80700. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80701. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80702. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80703. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80704. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80705. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80706. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80707. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80708. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80709. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80710. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80711. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80712. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80713. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80714. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80715. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80716. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80717. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80718. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80719. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80720. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80721. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80722. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80723. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80724. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80725. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80726. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80727. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80728. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80729. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80730. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80731. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80732. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80733. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80734. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80735. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80736. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80737. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80738. 0x8def022dUL
  80739. },
  80740. {
  80741. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80742. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80743. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80744. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80745. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80746. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80747. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80748. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80749. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80750. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80751. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80752. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80753. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80754. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80755. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80756. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80757. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80758. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80759. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80760. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80761. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80762. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80763. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80764. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80765. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80766. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80767. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80768. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80769. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80770. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80771. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80772. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80773. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80774. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80775. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80776. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80777. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80778. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80779. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80780. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80781. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80782. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80783. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80784. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80785. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80786. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80787. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80788. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80789. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80790. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80791. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80792. 0x72fd2493UL
  80793. },
  80794. {
  80795. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80796. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80797. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80798. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80799. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80800. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80801. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80802. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80803. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80804. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80805. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80806. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80807. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80808. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80809. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80810. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80811. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80812. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80813. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80814. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80815. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80816. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80817. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80818. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80819. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80820. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80821. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80822. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80823. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80824. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80825. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80826. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80827. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80828. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80829. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80830. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80831. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80832. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80833. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80834. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80835. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80836. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80837. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80838. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80839. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80840. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80841. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80842. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80843. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80844. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80845. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80846. 0xed3498beUL
  80847. },
  80848. {
  80849. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80850. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80851. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80852. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80853. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80854. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80855. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80856. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80857. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80858. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80859. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80860. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80861. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80862. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80863. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80864. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80865. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80866. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80867. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80868. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80869. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80870. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80871. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80872. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80873. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80874. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80875. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80876. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80877. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80878. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80879. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80880. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80881. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80882. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80883. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80884. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80885. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80886. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80887. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80888. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80889. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80890. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80891. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80892. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80893. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80894. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80895. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80896. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80897. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80898. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80899. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80900. 0xf10605deUL
  80901. #endif
  80902. }
  80903. };
  80904. /*** End of inlined file: crc32.h ***/
  80905. #endif /* DYNAMIC_CRC_TABLE */
  80906. /* =========================================================================
  80907. * This function can be used by asm versions of crc32()
  80908. */
  80909. const unsigned long FAR * ZEXPORT get_crc_table()
  80910. {
  80911. #ifdef DYNAMIC_CRC_TABLE
  80912. if (crc_table_empty)
  80913. make_crc_table();
  80914. #endif /* DYNAMIC_CRC_TABLE */
  80915. return (const unsigned long FAR *)crc_table;
  80916. }
  80917. /* ========================================================================= */
  80918. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80919. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80920. /* ========================================================================= */
  80921. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80922. {
  80923. if (buf == Z_NULL) return 0UL;
  80924. #ifdef DYNAMIC_CRC_TABLE
  80925. if (crc_table_empty)
  80926. make_crc_table();
  80927. #endif /* DYNAMIC_CRC_TABLE */
  80928. #ifdef BYFOUR
  80929. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80930. u4 endian;
  80931. endian = 1;
  80932. if (*((unsigned char *)(&endian)))
  80933. return crc32_little(crc, buf, len);
  80934. else
  80935. return crc32_big(crc, buf, len);
  80936. }
  80937. #endif /* BYFOUR */
  80938. crc = crc ^ 0xffffffffUL;
  80939. while (len >= 8) {
  80940. DO8;
  80941. len -= 8;
  80942. }
  80943. if (len) do {
  80944. DO1;
  80945. } while (--len);
  80946. return crc ^ 0xffffffffUL;
  80947. }
  80948. #ifdef BYFOUR
  80949. /* ========================================================================= */
  80950. #define DOLIT4 c ^= *buf4++; \
  80951. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80952. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80953. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80954. /* ========================================================================= */
  80955. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80956. {
  80957. register u4 c;
  80958. register const u4 FAR *buf4;
  80959. c = (u4)crc;
  80960. c = ~c;
  80961. while (len && ((ptrdiff_t)buf & 3)) {
  80962. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80963. len--;
  80964. }
  80965. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80966. while (len >= 32) {
  80967. DOLIT32;
  80968. len -= 32;
  80969. }
  80970. while (len >= 4) {
  80971. DOLIT4;
  80972. len -= 4;
  80973. }
  80974. buf = (const unsigned char FAR *)buf4;
  80975. if (len) do {
  80976. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80977. } while (--len);
  80978. c = ~c;
  80979. return (unsigned long)c;
  80980. }
  80981. /* ========================================================================= */
  80982. #define DOBIG4 c ^= *++buf4; \
  80983. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80984. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80985. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80986. /* ========================================================================= */
  80987. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80988. {
  80989. register u4 c;
  80990. register const u4 FAR *buf4;
  80991. c = REV((u4)crc);
  80992. c = ~c;
  80993. while (len && ((ptrdiff_t)buf & 3)) {
  80994. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80995. len--;
  80996. }
  80997. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80998. buf4--;
  80999. while (len >= 32) {
  81000. DOBIG32;
  81001. len -= 32;
  81002. }
  81003. while (len >= 4) {
  81004. DOBIG4;
  81005. len -= 4;
  81006. }
  81007. buf4++;
  81008. buf = (const unsigned char FAR *)buf4;
  81009. if (len) do {
  81010. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  81011. } while (--len);
  81012. c = ~c;
  81013. return (unsigned long)(REV(c));
  81014. }
  81015. #endif /* BYFOUR */
  81016. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  81017. /* ========================================================================= */
  81018. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  81019. {
  81020. unsigned long sum;
  81021. sum = 0;
  81022. while (vec) {
  81023. if (vec & 1)
  81024. sum ^= *mat;
  81025. vec >>= 1;
  81026. mat++;
  81027. }
  81028. return sum;
  81029. }
  81030. /* ========================================================================= */
  81031. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  81032. {
  81033. int n;
  81034. for (n = 0; n < GF2_DIM; n++)
  81035. square[n] = gf2_matrix_times(mat, mat[n]);
  81036. }
  81037. /* ========================================================================= */
  81038. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  81039. {
  81040. int n;
  81041. unsigned long row;
  81042. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  81043. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  81044. /* degenerate case */
  81045. if (len2 == 0)
  81046. return crc1;
  81047. /* put operator for one zero bit in odd */
  81048. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  81049. row = 1;
  81050. for (n = 1; n < GF2_DIM; n++) {
  81051. odd[n] = row;
  81052. row <<= 1;
  81053. }
  81054. /* put operator for two zero bits in even */
  81055. gf2_matrix_square(even, odd);
  81056. /* put operator for four zero bits in odd */
  81057. gf2_matrix_square(odd, even);
  81058. /* apply len2 zeros to crc1 (first square will put the operator for one
  81059. zero byte, eight zero bits, in even) */
  81060. do {
  81061. /* apply zeros operator for this bit of len2 */
  81062. gf2_matrix_square(even, odd);
  81063. if (len2 & 1)
  81064. crc1 = gf2_matrix_times(even, crc1);
  81065. len2 >>= 1;
  81066. /* if no more bits set, then done */
  81067. if (len2 == 0)
  81068. break;
  81069. /* another iteration of the loop with odd and even swapped */
  81070. gf2_matrix_square(odd, even);
  81071. if (len2 & 1)
  81072. crc1 = gf2_matrix_times(odd, crc1);
  81073. len2 >>= 1;
  81074. /* if no more bits set, then done */
  81075. } while (len2 != 0);
  81076. /* return combined crc */
  81077. crc1 ^= crc2;
  81078. return crc1;
  81079. }
  81080. /*** End of inlined file: crc32.c ***/
  81081. /*** Start of inlined file: deflate.c ***/
  81082. /*
  81083. * ALGORITHM
  81084. *
  81085. * The "deflation" process depends on being able to identify portions
  81086. * of the input text which are identical to earlier input (within a
  81087. * sliding window trailing behind the input currently being processed).
  81088. *
  81089. * The most straightforward technique turns out to be the fastest for
  81090. * most input files: try all possible matches and select the longest.
  81091. * The key feature of this algorithm is that insertions into the string
  81092. * dictionary are very simple and thus fast, and deletions are avoided
  81093. * completely. Insertions are performed at each input character, whereas
  81094. * string matches are performed only when the previous match ends. So it
  81095. * is preferable to spend more time in matches to allow very fast string
  81096. * insertions and avoid deletions. The matching algorithm for small
  81097. * strings is inspired from that of Rabin & Karp. A brute force approach
  81098. * is used to find longer strings when a small match has been found.
  81099. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  81100. * (by Leonid Broukhis).
  81101. * A previous version of this file used a more sophisticated algorithm
  81102. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  81103. * time, but has a larger average cost, uses more memory and is patented.
  81104. * However the F&G algorithm may be faster for some highly redundant
  81105. * files if the parameter max_chain_length (described below) is too large.
  81106. *
  81107. * ACKNOWLEDGEMENTS
  81108. *
  81109. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  81110. * I found it in 'freeze' written by Leonid Broukhis.
  81111. * Thanks to many people for bug reports and testing.
  81112. *
  81113. * REFERENCES
  81114. *
  81115. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  81116. * Available in http://www.ietf.org/rfc/rfc1951.txt
  81117. *
  81118. * A description of the Rabin and Karp algorithm is given in the book
  81119. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  81120. *
  81121. * Fiala,E.R., and Greene,D.H.
  81122. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  81123. *
  81124. */
  81125. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81126. /*** Start of inlined file: deflate.h ***/
  81127. /* WARNING: this file should *not* be used by applications. It is
  81128. part of the implementation of the compression library and is
  81129. subject to change. Applications should only use zlib.h.
  81130. */
  81131. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81132. #ifndef DEFLATE_H
  81133. #define DEFLATE_H
  81134. /* define NO_GZIP when compiling if you want to disable gzip header and
  81135. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  81136. the crc code when it is not needed. For shared libraries, gzip encoding
  81137. should be left enabled. */
  81138. #ifndef NO_GZIP
  81139. # define GZIP
  81140. #endif
  81141. #define NO_DUMMY_DECL
  81142. /* ===========================================================================
  81143. * Internal compression state.
  81144. */
  81145. #define LENGTH_CODES 29
  81146. /* number of length codes, not counting the special END_BLOCK code */
  81147. #define LITERALS 256
  81148. /* number of literal bytes 0..255 */
  81149. #define L_CODES (LITERALS+1+LENGTH_CODES)
  81150. /* number of Literal or Length codes, including the END_BLOCK code */
  81151. #define D_CODES 30
  81152. /* number of distance codes */
  81153. #define BL_CODES 19
  81154. /* number of codes used to transfer the bit lengths */
  81155. #define HEAP_SIZE (2*L_CODES+1)
  81156. /* maximum heap size */
  81157. #define MAX_BITS 15
  81158. /* All codes must not exceed MAX_BITS bits */
  81159. #define INIT_STATE 42
  81160. #define EXTRA_STATE 69
  81161. #define NAME_STATE 73
  81162. #define COMMENT_STATE 91
  81163. #define HCRC_STATE 103
  81164. #define BUSY_STATE 113
  81165. #define FINISH_STATE 666
  81166. /* Stream status */
  81167. /* Data structure describing a single value and its code string. */
  81168. typedef struct ct_data_s {
  81169. union {
  81170. ush freq; /* frequency count */
  81171. ush code; /* bit string */
  81172. } fc;
  81173. union {
  81174. ush dad; /* father node in Huffman tree */
  81175. ush len; /* length of bit string */
  81176. } dl;
  81177. } FAR ct_data;
  81178. #define Freq fc.freq
  81179. #define Code fc.code
  81180. #define Dad dl.dad
  81181. #define Len dl.len
  81182. typedef struct static_tree_desc_s static_tree_desc;
  81183. typedef struct tree_desc_s {
  81184. ct_data *dyn_tree; /* the dynamic tree */
  81185. int max_code; /* largest code with non zero frequency */
  81186. static_tree_desc *stat_desc; /* the corresponding static tree */
  81187. } FAR tree_desc;
  81188. typedef ush Pos;
  81189. typedef Pos FAR Posf;
  81190. typedef unsigned IPos;
  81191. /* A Pos is an index in the character window. We use short instead of int to
  81192. * save space in the various tables. IPos is used only for parameter passing.
  81193. */
  81194. typedef struct internal_state {
  81195. z_streamp strm; /* pointer back to this zlib stream */
  81196. int status; /* as the name implies */
  81197. Bytef *pending_buf; /* output still pending */
  81198. ulg pending_buf_size; /* size of pending_buf */
  81199. Bytef *pending_out; /* next pending byte to output to the stream */
  81200. uInt pending; /* nb of bytes in the pending buffer */
  81201. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81202. gz_headerp gzhead; /* gzip header information to write */
  81203. uInt gzindex; /* where in extra, name, or comment */
  81204. Byte method; /* STORED (for zip only) or DEFLATED */
  81205. int last_flush; /* value of flush param for previous deflate call */
  81206. /* used by deflate.c: */
  81207. uInt w_size; /* LZ77 window size (32K by default) */
  81208. uInt w_bits; /* log2(w_size) (8..16) */
  81209. uInt w_mask; /* w_size - 1 */
  81210. Bytef *window;
  81211. /* Sliding window. Input bytes are read into the second half of the window,
  81212. * and move to the first half later to keep a dictionary of at least wSize
  81213. * bytes. With this organization, matches are limited to a distance of
  81214. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81215. * performed with a length multiple of the block size. Also, it limits
  81216. * the window size to 64K, which is quite useful on MSDOS.
  81217. * To do: use the user input buffer as sliding window.
  81218. */
  81219. ulg window_size;
  81220. /* Actual size of window: 2*wSize, except when the user input buffer
  81221. * is directly used as sliding window.
  81222. */
  81223. Posf *prev;
  81224. /* Link to older string with same hash index. To limit the size of this
  81225. * array to 64K, this link is maintained only for the last 32K strings.
  81226. * An index in this array is thus a window index modulo 32K.
  81227. */
  81228. Posf *head; /* Heads of the hash chains or NIL. */
  81229. uInt ins_h; /* hash index of string to be inserted */
  81230. uInt hash_size; /* number of elements in hash table */
  81231. uInt hash_bits; /* log2(hash_size) */
  81232. uInt hash_mask; /* hash_size-1 */
  81233. uInt hash_shift;
  81234. /* Number of bits by which ins_h must be shifted at each input
  81235. * step. It must be such that after MIN_MATCH steps, the oldest
  81236. * byte no longer takes part in the hash key, that is:
  81237. * hash_shift * MIN_MATCH >= hash_bits
  81238. */
  81239. long block_start;
  81240. /* Window position at the beginning of the current output block. Gets
  81241. * negative when the window is moved backwards.
  81242. */
  81243. uInt match_length; /* length of best match */
  81244. IPos prev_match; /* previous match */
  81245. int match_available; /* set if previous match exists */
  81246. uInt strstart; /* start of string to insert */
  81247. uInt match_start; /* start of matching string */
  81248. uInt lookahead; /* number of valid bytes ahead in window */
  81249. uInt prev_length;
  81250. /* Length of the best match at previous step. Matches not greater than this
  81251. * are discarded. This is used in the lazy match evaluation.
  81252. */
  81253. uInt max_chain_length;
  81254. /* To speed up deflation, hash chains are never searched beyond this
  81255. * length. A higher limit improves compression ratio but degrades the
  81256. * speed.
  81257. */
  81258. uInt max_lazy_match;
  81259. /* Attempt to find a better match only when the current match is strictly
  81260. * smaller than this value. This mechanism is used only for compression
  81261. * levels >= 4.
  81262. */
  81263. # define max_insert_length max_lazy_match
  81264. /* Insert new strings in the hash table only if the match length is not
  81265. * greater than this length. This saves time but degrades compression.
  81266. * max_insert_length is used only for compression levels <= 3.
  81267. */
  81268. int level; /* compression level (1..9) */
  81269. int strategy; /* favor or force Huffman coding*/
  81270. uInt good_match;
  81271. /* Use a faster search when the previous match is longer than this */
  81272. int nice_match; /* Stop searching when current match exceeds this */
  81273. /* used by trees.c: */
  81274. /* Didn't use ct_data typedef below to supress compiler warning */
  81275. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81276. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81277. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81278. struct tree_desc_s l_desc; /* desc. for literal tree */
  81279. struct tree_desc_s d_desc; /* desc. for distance tree */
  81280. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81281. ush bl_count[MAX_BITS+1];
  81282. /* number of codes at each bit length for an optimal tree */
  81283. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81284. int heap_len; /* number of elements in the heap */
  81285. int heap_max; /* element of largest frequency */
  81286. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81287. * The same heap array is used to build all trees.
  81288. */
  81289. uch depth[2*L_CODES+1];
  81290. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81291. */
  81292. uchf *l_buf; /* buffer for literals or lengths */
  81293. uInt lit_bufsize;
  81294. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81295. * limiting lit_bufsize to 64K:
  81296. * - frequencies can be kept in 16 bit counters
  81297. * - if compression is not successful for the first block, all input
  81298. * data is still in the window so we can still emit a stored block even
  81299. * when input comes from standard input. (This can also be done for
  81300. * all blocks if lit_bufsize is not greater than 32K.)
  81301. * - if compression is not successful for a file smaller than 64K, we can
  81302. * even emit a stored file instead of a stored block (saving 5 bytes).
  81303. * This is applicable only for zip (not gzip or zlib).
  81304. * - creating new Huffman trees less frequently may not provide fast
  81305. * adaptation to changes in the input data statistics. (Take for
  81306. * example a binary file with poorly compressible code followed by
  81307. * a highly compressible string table.) Smaller buffer sizes give
  81308. * fast adaptation but have of course the overhead of transmitting
  81309. * trees more frequently.
  81310. * - I can't count above 4
  81311. */
  81312. uInt last_lit; /* running index in l_buf */
  81313. ushf *d_buf;
  81314. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81315. * the same number of elements. To use different lengths, an extra flag
  81316. * array would be necessary.
  81317. */
  81318. ulg opt_len; /* bit length of current block with optimal trees */
  81319. ulg static_len; /* bit length of current block with static trees */
  81320. uInt matches; /* number of string matches in current block */
  81321. int last_eob_len; /* bit length of EOB code for last block */
  81322. #ifdef DEBUG
  81323. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81324. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81325. #endif
  81326. ush bi_buf;
  81327. /* Output buffer. bits are inserted starting at the bottom (least
  81328. * significant bits).
  81329. */
  81330. int bi_valid;
  81331. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81332. * are always zero.
  81333. */
  81334. } FAR deflate_state;
  81335. /* Output a byte on the stream.
  81336. * IN assertion: there is enough room in pending_buf.
  81337. */
  81338. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81339. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81340. /* Minimum amount of lookahead, except at the end of the input file.
  81341. * See deflate.c for comments about the MIN_MATCH+1.
  81342. */
  81343. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81344. /* In order to simplify the code, particularly on 16 bit machines, match
  81345. * distances are limited to MAX_DIST instead of WSIZE.
  81346. */
  81347. /* in trees.c */
  81348. void _tr_init OF((deflate_state *s));
  81349. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81350. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81351. int eof));
  81352. void _tr_align OF((deflate_state *s));
  81353. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81354. int eof));
  81355. #define d_code(dist) \
  81356. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81357. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81358. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81359. * used.
  81360. */
  81361. #ifndef DEBUG
  81362. /* Inline versions of _tr_tally for speed: */
  81363. #if defined(GEN_TREES_H) || !defined(STDC)
  81364. extern uch _length_code[];
  81365. extern uch _dist_code[];
  81366. #else
  81367. extern const uch _length_code[];
  81368. extern const uch _dist_code[];
  81369. #endif
  81370. # define _tr_tally_lit(s, c, flush) \
  81371. { uch cc = (c); \
  81372. s->d_buf[s->last_lit] = 0; \
  81373. s->l_buf[s->last_lit++] = cc; \
  81374. s->dyn_ltree[cc].Freq++; \
  81375. flush = (s->last_lit == s->lit_bufsize-1); \
  81376. }
  81377. # define _tr_tally_dist(s, distance, length, flush) \
  81378. { uch len = (length); \
  81379. ush dist = (distance); \
  81380. s->d_buf[s->last_lit] = dist; \
  81381. s->l_buf[s->last_lit++] = len; \
  81382. dist--; \
  81383. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81384. s->dyn_dtree[d_code(dist)].Freq++; \
  81385. flush = (s->last_lit == s->lit_bufsize-1); \
  81386. }
  81387. #else
  81388. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81389. # define _tr_tally_dist(s, distance, length, flush) \
  81390. flush = _tr_tally(s, distance, length)
  81391. #endif
  81392. #endif /* DEFLATE_H */
  81393. /*** End of inlined file: deflate.h ***/
  81394. const char deflate_copyright[] =
  81395. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81396. /*
  81397. If you use the zlib library in a product, an acknowledgment is welcome
  81398. in the documentation of your product. If for some reason you cannot
  81399. include such an acknowledgment, I would appreciate that you keep this
  81400. copyright string in the executable of your product.
  81401. */
  81402. /* ===========================================================================
  81403. * Function prototypes.
  81404. */
  81405. typedef enum {
  81406. need_more, /* block not completed, need more input or more output */
  81407. block_done, /* block flush performed */
  81408. finish_started, /* finish started, need only more output at next deflate */
  81409. finish_done /* finish done, accept no more input or output */
  81410. } block_state;
  81411. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81412. /* Compression function. Returns the block state after the call. */
  81413. local void fill_window OF((deflate_state *s));
  81414. local block_state deflate_stored OF((deflate_state *s, int flush));
  81415. local block_state deflate_fast OF((deflate_state *s, int flush));
  81416. #ifndef FASTEST
  81417. local block_state deflate_slow OF((deflate_state *s, int flush));
  81418. #endif
  81419. local void lm_init OF((deflate_state *s));
  81420. local void putShortMSB OF((deflate_state *s, uInt b));
  81421. local void flush_pending OF((z_streamp strm));
  81422. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81423. #ifndef FASTEST
  81424. #ifdef ASMV
  81425. void match_init OF((void)); /* asm code initialization */
  81426. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81427. #else
  81428. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81429. #endif
  81430. #endif
  81431. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81432. #ifdef DEBUG
  81433. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81434. int length));
  81435. #endif
  81436. /* ===========================================================================
  81437. * Local data
  81438. */
  81439. #define NIL 0
  81440. /* Tail of hash chains */
  81441. #ifndef TOO_FAR
  81442. # define TOO_FAR 4096
  81443. #endif
  81444. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81445. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81446. /* Minimum amount of lookahead, except at the end of the input file.
  81447. * See deflate.c for comments about the MIN_MATCH+1.
  81448. */
  81449. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81450. * the desired pack level (0..9). The values given below have been tuned to
  81451. * exclude worst case performance for pathological files. Better values may be
  81452. * found for specific files.
  81453. */
  81454. typedef struct config_s {
  81455. ush good_length; /* reduce lazy search above this match length */
  81456. ush max_lazy; /* do not perform lazy search above this match length */
  81457. ush nice_length; /* quit search above this match length */
  81458. ush max_chain;
  81459. compress_func func;
  81460. } config;
  81461. #ifdef FASTEST
  81462. local const config configuration_table[2] = {
  81463. /* good lazy nice chain */
  81464. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81465. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81466. #else
  81467. local const config configuration_table[10] = {
  81468. /* good lazy nice chain */
  81469. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81470. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81471. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81472. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81473. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81474. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81475. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81476. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81477. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81478. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81479. #endif
  81480. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81481. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81482. * meaning.
  81483. */
  81484. #define EQUAL 0
  81485. /* result of memcmp for equal strings */
  81486. #ifndef NO_DUMMY_DECL
  81487. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81488. #endif
  81489. /* ===========================================================================
  81490. * Update a hash value with the given input byte
  81491. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81492. * input characters, so that a running hash key can be computed from the
  81493. * previous key instead of complete recalculation each time.
  81494. */
  81495. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81496. /* ===========================================================================
  81497. * Insert string str in the dictionary and set match_head to the previous head
  81498. * of the hash chain (the most recent string with same hash key). Return
  81499. * the previous length of the hash chain.
  81500. * If this file is compiled with -DFASTEST, the compression level is forced
  81501. * to 1, and no hash chains are maintained.
  81502. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81503. * input characters and the first MIN_MATCH bytes of str are valid
  81504. * (except for the last MIN_MATCH-1 bytes of the input file).
  81505. */
  81506. #ifdef FASTEST
  81507. #define INSERT_STRING(s, str, match_head) \
  81508. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81509. match_head = s->head[s->ins_h], \
  81510. s->head[s->ins_h] = (Pos)(str))
  81511. #else
  81512. #define INSERT_STRING(s, str, match_head) \
  81513. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81514. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81515. s->head[s->ins_h] = (Pos)(str))
  81516. #endif
  81517. /* ===========================================================================
  81518. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81519. * prev[] will be initialized on the fly.
  81520. */
  81521. #define CLEAR_HASH(s) \
  81522. s->head[s->hash_size-1] = NIL; \
  81523. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81524. /* ========================================================================= */
  81525. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81526. {
  81527. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81528. Z_DEFAULT_STRATEGY, version, stream_size);
  81529. /* To do: ignore strm->next_in if we use it as window */
  81530. }
  81531. /* ========================================================================= */
  81532. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81533. {
  81534. deflate_state *s;
  81535. int wrap = 1;
  81536. static const char my_version[] = ZLIB_VERSION;
  81537. ushf *overlay;
  81538. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81539. * output size for (length,distance) codes is <= 24 bits.
  81540. */
  81541. if (version == Z_NULL || version[0] != my_version[0] ||
  81542. stream_size != sizeof(z_stream)) {
  81543. return Z_VERSION_ERROR;
  81544. }
  81545. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81546. strm->msg = Z_NULL;
  81547. if (strm->zalloc == (alloc_func)0) {
  81548. strm->zalloc = zcalloc;
  81549. strm->opaque = (voidpf)0;
  81550. }
  81551. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81552. #ifdef FASTEST
  81553. if (level != 0) level = 1;
  81554. #else
  81555. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81556. #endif
  81557. if (windowBits < 0) { /* suppress zlib wrapper */
  81558. wrap = 0;
  81559. windowBits = -windowBits;
  81560. }
  81561. #ifdef GZIP
  81562. else if (windowBits > 15) {
  81563. wrap = 2; /* write gzip wrapper instead */
  81564. windowBits -= 16;
  81565. }
  81566. #endif
  81567. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81568. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81569. strategy < 0 || strategy > Z_FIXED) {
  81570. return Z_STREAM_ERROR;
  81571. }
  81572. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81573. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81574. if (s == Z_NULL) return Z_MEM_ERROR;
  81575. strm->state = (struct internal_state FAR *)s;
  81576. s->strm = strm;
  81577. s->wrap = wrap;
  81578. s->gzhead = Z_NULL;
  81579. s->w_bits = windowBits;
  81580. s->w_size = 1 << s->w_bits;
  81581. s->w_mask = s->w_size - 1;
  81582. s->hash_bits = memLevel + 7;
  81583. s->hash_size = 1 << s->hash_bits;
  81584. s->hash_mask = s->hash_size - 1;
  81585. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81586. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81587. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81588. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81589. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81590. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81591. s->pending_buf = (uchf *) overlay;
  81592. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81593. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81594. s->pending_buf == Z_NULL) {
  81595. s->status = FINISH_STATE;
  81596. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81597. deflateEnd (strm);
  81598. return Z_MEM_ERROR;
  81599. }
  81600. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81601. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81602. s->level = level;
  81603. s->strategy = strategy;
  81604. s->method = (Byte)method;
  81605. return deflateReset(strm);
  81606. }
  81607. /* ========================================================================= */
  81608. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81609. {
  81610. deflate_state *s;
  81611. uInt length = dictLength;
  81612. uInt n;
  81613. IPos hash_head = 0;
  81614. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81615. strm->state->wrap == 2 ||
  81616. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81617. return Z_STREAM_ERROR;
  81618. s = strm->state;
  81619. if (s->wrap)
  81620. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81621. if (length < MIN_MATCH) return Z_OK;
  81622. if (length > MAX_DIST(s)) {
  81623. length = MAX_DIST(s);
  81624. dictionary += dictLength - length; /* use the tail of the dictionary */
  81625. }
  81626. zmemcpy(s->window, dictionary, length);
  81627. s->strstart = length;
  81628. s->block_start = (long)length;
  81629. /* Insert all strings in the hash table (except for the last two bytes).
  81630. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81631. * call of fill_window.
  81632. */
  81633. s->ins_h = s->window[0];
  81634. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81635. for (n = 0; n <= length - MIN_MATCH; n++) {
  81636. INSERT_STRING(s, n, hash_head);
  81637. }
  81638. if (hash_head) hash_head = 0; /* to make compiler happy */
  81639. return Z_OK;
  81640. }
  81641. /* ========================================================================= */
  81642. int ZEXPORT deflateReset (z_streamp strm)
  81643. {
  81644. deflate_state *s;
  81645. if (strm == Z_NULL || strm->state == Z_NULL ||
  81646. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81647. return Z_STREAM_ERROR;
  81648. }
  81649. strm->total_in = strm->total_out = 0;
  81650. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81651. strm->data_type = Z_UNKNOWN;
  81652. s = (deflate_state *)strm->state;
  81653. s->pending = 0;
  81654. s->pending_out = s->pending_buf;
  81655. if (s->wrap < 0) {
  81656. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81657. }
  81658. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81659. strm->adler =
  81660. #ifdef GZIP
  81661. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81662. #endif
  81663. adler32(0L, Z_NULL, 0);
  81664. s->last_flush = Z_NO_FLUSH;
  81665. _tr_init(s);
  81666. lm_init(s);
  81667. return Z_OK;
  81668. }
  81669. /* ========================================================================= */
  81670. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81671. {
  81672. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81673. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81674. strm->state->gzhead = head;
  81675. return Z_OK;
  81676. }
  81677. /* ========================================================================= */
  81678. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81679. {
  81680. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81681. strm->state->bi_valid = bits;
  81682. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81683. return Z_OK;
  81684. }
  81685. /* ========================================================================= */
  81686. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81687. {
  81688. deflate_state *s;
  81689. compress_func func;
  81690. int err = Z_OK;
  81691. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81692. s = strm->state;
  81693. #ifdef FASTEST
  81694. if (level != 0) level = 1;
  81695. #else
  81696. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81697. #endif
  81698. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81699. return Z_STREAM_ERROR;
  81700. }
  81701. func = configuration_table[s->level].func;
  81702. if (func != configuration_table[level].func && strm->total_in != 0) {
  81703. /* Flush the last buffer: */
  81704. err = deflate(strm, Z_PARTIAL_FLUSH);
  81705. }
  81706. if (s->level != level) {
  81707. s->level = level;
  81708. s->max_lazy_match = configuration_table[level].max_lazy;
  81709. s->good_match = configuration_table[level].good_length;
  81710. s->nice_match = configuration_table[level].nice_length;
  81711. s->max_chain_length = configuration_table[level].max_chain;
  81712. }
  81713. s->strategy = strategy;
  81714. return err;
  81715. }
  81716. /* ========================================================================= */
  81717. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81718. {
  81719. deflate_state *s;
  81720. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81721. s = strm->state;
  81722. s->good_match = good_length;
  81723. s->max_lazy_match = max_lazy;
  81724. s->nice_match = nice_length;
  81725. s->max_chain_length = max_chain;
  81726. return Z_OK;
  81727. }
  81728. /* =========================================================================
  81729. * For the default windowBits of 15 and memLevel of 8, this function returns
  81730. * a close to exact, as well as small, upper bound on the compressed size.
  81731. * They are coded as constants here for a reason--if the #define's are
  81732. * changed, then this function needs to be changed as well. The return
  81733. * value for 15 and 8 only works for those exact settings.
  81734. *
  81735. * For any setting other than those defaults for windowBits and memLevel,
  81736. * the value returned is a conservative worst case for the maximum expansion
  81737. * resulting from using fixed blocks instead of stored blocks, which deflate
  81738. * can emit on compressed data for some combinations of the parameters.
  81739. *
  81740. * This function could be more sophisticated to provide closer upper bounds
  81741. * for every combination of windowBits and memLevel, as well as wrap.
  81742. * But even the conservative upper bound of about 14% expansion does not
  81743. * seem onerous for output buffer allocation.
  81744. */
  81745. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81746. {
  81747. deflate_state *s;
  81748. uLong destLen;
  81749. /* conservative upper bound */
  81750. destLen = sourceLen +
  81751. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81752. /* if can't get parameters, return conservative bound */
  81753. if (strm == Z_NULL || strm->state == Z_NULL)
  81754. return destLen;
  81755. /* if not default parameters, return conservative bound */
  81756. s = strm->state;
  81757. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81758. return destLen;
  81759. /* default settings: return tight bound for that case */
  81760. return compressBound(sourceLen);
  81761. }
  81762. /* =========================================================================
  81763. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81764. * IN assertion: the stream state is correct and there is enough room in
  81765. * pending_buf.
  81766. */
  81767. local void putShortMSB (deflate_state *s, uInt b)
  81768. {
  81769. put_byte(s, (Byte)(b >> 8));
  81770. put_byte(s, (Byte)(b & 0xff));
  81771. }
  81772. /* =========================================================================
  81773. * Flush as much pending output as possible. All deflate() output goes
  81774. * through this function so some applications may wish to modify it
  81775. * to avoid allocating a large strm->next_out buffer and copying into it.
  81776. * (See also read_buf()).
  81777. */
  81778. local void flush_pending (z_streamp strm)
  81779. {
  81780. unsigned len = strm->state->pending;
  81781. if (len > strm->avail_out) len = strm->avail_out;
  81782. if (len == 0) return;
  81783. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81784. strm->next_out += len;
  81785. strm->state->pending_out += len;
  81786. strm->total_out += len;
  81787. strm->avail_out -= len;
  81788. strm->state->pending -= len;
  81789. if (strm->state->pending == 0) {
  81790. strm->state->pending_out = strm->state->pending_buf;
  81791. }
  81792. }
  81793. /* ========================================================================= */
  81794. int ZEXPORT deflate (z_streamp strm, int flush)
  81795. {
  81796. int old_flush; /* value of flush param for previous deflate call */
  81797. deflate_state *s;
  81798. if (strm == Z_NULL || strm->state == Z_NULL ||
  81799. flush > Z_FINISH || flush < 0) {
  81800. return Z_STREAM_ERROR;
  81801. }
  81802. s = strm->state;
  81803. if (strm->next_out == Z_NULL ||
  81804. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81805. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81806. ERR_RETURN(strm, Z_STREAM_ERROR);
  81807. }
  81808. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81809. s->strm = strm; /* just in case */
  81810. old_flush = s->last_flush;
  81811. s->last_flush = flush;
  81812. /* Write the header */
  81813. if (s->status == INIT_STATE) {
  81814. #ifdef GZIP
  81815. if (s->wrap == 2) {
  81816. strm->adler = crc32(0L, Z_NULL, 0);
  81817. put_byte(s, 31);
  81818. put_byte(s, 139);
  81819. put_byte(s, 8);
  81820. if (s->gzhead == NULL) {
  81821. put_byte(s, 0);
  81822. put_byte(s, 0);
  81823. put_byte(s, 0);
  81824. put_byte(s, 0);
  81825. put_byte(s, 0);
  81826. put_byte(s, s->level == 9 ? 2 :
  81827. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81828. 4 : 0));
  81829. put_byte(s, OS_CODE);
  81830. s->status = BUSY_STATE;
  81831. }
  81832. else {
  81833. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81834. (s->gzhead->hcrc ? 2 : 0) +
  81835. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81836. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81837. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81838. );
  81839. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81840. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81841. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81842. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81843. put_byte(s, s->level == 9 ? 2 :
  81844. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81845. 4 : 0));
  81846. put_byte(s, s->gzhead->os & 0xff);
  81847. if (s->gzhead->extra != NULL) {
  81848. put_byte(s, s->gzhead->extra_len & 0xff);
  81849. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81850. }
  81851. if (s->gzhead->hcrc)
  81852. strm->adler = crc32(strm->adler, s->pending_buf,
  81853. s->pending);
  81854. s->gzindex = 0;
  81855. s->status = EXTRA_STATE;
  81856. }
  81857. }
  81858. else
  81859. #endif
  81860. {
  81861. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81862. uInt level_flags;
  81863. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81864. level_flags = 0;
  81865. else if (s->level < 6)
  81866. level_flags = 1;
  81867. else if (s->level == 6)
  81868. level_flags = 2;
  81869. else
  81870. level_flags = 3;
  81871. header |= (level_flags << 6);
  81872. if (s->strstart != 0) header |= PRESET_DICT;
  81873. header += 31 - (header % 31);
  81874. s->status = BUSY_STATE;
  81875. putShortMSB(s, header);
  81876. /* Save the adler32 of the preset dictionary: */
  81877. if (s->strstart != 0) {
  81878. putShortMSB(s, (uInt)(strm->adler >> 16));
  81879. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81880. }
  81881. strm->adler = adler32(0L, Z_NULL, 0);
  81882. }
  81883. }
  81884. #ifdef GZIP
  81885. if (s->status == EXTRA_STATE) {
  81886. if (s->gzhead->extra != NULL) {
  81887. uInt beg = s->pending; /* start of bytes to update crc */
  81888. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81889. if (s->pending == s->pending_buf_size) {
  81890. if (s->gzhead->hcrc && s->pending > beg)
  81891. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81892. s->pending - beg);
  81893. flush_pending(strm);
  81894. beg = s->pending;
  81895. if (s->pending == s->pending_buf_size)
  81896. break;
  81897. }
  81898. put_byte(s, s->gzhead->extra[s->gzindex]);
  81899. s->gzindex++;
  81900. }
  81901. if (s->gzhead->hcrc && s->pending > beg)
  81902. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81903. s->pending - beg);
  81904. if (s->gzindex == s->gzhead->extra_len) {
  81905. s->gzindex = 0;
  81906. s->status = NAME_STATE;
  81907. }
  81908. }
  81909. else
  81910. s->status = NAME_STATE;
  81911. }
  81912. if (s->status == NAME_STATE) {
  81913. if (s->gzhead->name != NULL) {
  81914. uInt beg = s->pending; /* start of bytes to update crc */
  81915. int val;
  81916. do {
  81917. if (s->pending == s->pending_buf_size) {
  81918. if (s->gzhead->hcrc && s->pending > beg)
  81919. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81920. s->pending - beg);
  81921. flush_pending(strm);
  81922. beg = s->pending;
  81923. if (s->pending == s->pending_buf_size) {
  81924. val = 1;
  81925. break;
  81926. }
  81927. }
  81928. val = s->gzhead->name[s->gzindex++];
  81929. put_byte(s, val);
  81930. } while (val != 0);
  81931. if (s->gzhead->hcrc && s->pending > beg)
  81932. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81933. s->pending - beg);
  81934. if (val == 0) {
  81935. s->gzindex = 0;
  81936. s->status = COMMENT_STATE;
  81937. }
  81938. }
  81939. else
  81940. s->status = COMMENT_STATE;
  81941. }
  81942. if (s->status == COMMENT_STATE) {
  81943. if (s->gzhead->comment != NULL) {
  81944. uInt beg = s->pending; /* start of bytes to update crc */
  81945. int val;
  81946. do {
  81947. if (s->pending == s->pending_buf_size) {
  81948. if (s->gzhead->hcrc && s->pending > beg)
  81949. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81950. s->pending - beg);
  81951. flush_pending(strm);
  81952. beg = s->pending;
  81953. if (s->pending == s->pending_buf_size) {
  81954. val = 1;
  81955. break;
  81956. }
  81957. }
  81958. val = s->gzhead->comment[s->gzindex++];
  81959. put_byte(s, val);
  81960. } while (val != 0);
  81961. if (s->gzhead->hcrc && s->pending > beg)
  81962. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81963. s->pending - beg);
  81964. if (val == 0)
  81965. s->status = HCRC_STATE;
  81966. }
  81967. else
  81968. s->status = HCRC_STATE;
  81969. }
  81970. if (s->status == HCRC_STATE) {
  81971. if (s->gzhead->hcrc) {
  81972. if (s->pending + 2 > s->pending_buf_size)
  81973. flush_pending(strm);
  81974. if (s->pending + 2 <= s->pending_buf_size) {
  81975. put_byte(s, (Byte)(strm->adler & 0xff));
  81976. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81977. strm->adler = crc32(0L, Z_NULL, 0);
  81978. s->status = BUSY_STATE;
  81979. }
  81980. }
  81981. else
  81982. s->status = BUSY_STATE;
  81983. }
  81984. #endif
  81985. /* Flush as much pending output as possible */
  81986. if (s->pending != 0) {
  81987. flush_pending(strm);
  81988. if (strm->avail_out == 0) {
  81989. /* Since avail_out is 0, deflate will be called again with
  81990. * more output space, but possibly with both pending and
  81991. * avail_in equal to zero. There won't be anything to do,
  81992. * but this is not an error situation so make sure we
  81993. * return OK instead of BUF_ERROR at next call of deflate:
  81994. */
  81995. s->last_flush = -1;
  81996. return Z_OK;
  81997. }
  81998. /* Make sure there is something to do and avoid duplicate consecutive
  81999. * flushes. For repeated and useless calls with Z_FINISH, we keep
  82000. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  82001. */
  82002. } else if (strm->avail_in == 0 && flush <= old_flush &&
  82003. flush != Z_FINISH) {
  82004. ERR_RETURN(strm, Z_BUF_ERROR);
  82005. }
  82006. /* User must not provide more input after the first FINISH: */
  82007. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  82008. ERR_RETURN(strm, Z_BUF_ERROR);
  82009. }
  82010. /* Start a new block or continue the current one.
  82011. */
  82012. if (strm->avail_in != 0 || s->lookahead != 0 ||
  82013. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  82014. block_state bstate;
  82015. bstate = (*(configuration_table[s->level].func))(s, flush);
  82016. if (bstate == finish_started || bstate == finish_done) {
  82017. s->status = FINISH_STATE;
  82018. }
  82019. if (bstate == need_more || bstate == finish_started) {
  82020. if (strm->avail_out == 0) {
  82021. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  82022. }
  82023. return Z_OK;
  82024. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  82025. * of deflate should use the same flush parameter to make sure
  82026. * that the flush is complete. So we don't have to output an
  82027. * empty block here, this will be done at next call. This also
  82028. * ensures that for a very small output buffer, we emit at most
  82029. * one empty block.
  82030. */
  82031. }
  82032. if (bstate == block_done) {
  82033. if (flush == Z_PARTIAL_FLUSH) {
  82034. _tr_align(s);
  82035. } else { /* FULL_FLUSH or SYNC_FLUSH */
  82036. _tr_stored_block(s, (char*)0, 0L, 0);
  82037. /* For a full flush, this empty block will be recognized
  82038. * as a special marker by inflate_sync().
  82039. */
  82040. if (flush == Z_FULL_FLUSH) {
  82041. CLEAR_HASH(s); /* forget history */
  82042. }
  82043. }
  82044. flush_pending(strm);
  82045. if (strm->avail_out == 0) {
  82046. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  82047. return Z_OK;
  82048. }
  82049. }
  82050. }
  82051. Assert(strm->avail_out > 0, "bug2");
  82052. if (flush != Z_FINISH) return Z_OK;
  82053. if (s->wrap <= 0) return Z_STREAM_END;
  82054. /* Write the trailer */
  82055. #ifdef GZIP
  82056. if (s->wrap == 2) {
  82057. put_byte(s, (Byte)(strm->adler & 0xff));
  82058. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  82059. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  82060. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  82061. put_byte(s, (Byte)(strm->total_in & 0xff));
  82062. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  82063. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  82064. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  82065. }
  82066. else
  82067. #endif
  82068. {
  82069. putShortMSB(s, (uInt)(strm->adler >> 16));
  82070. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  82071. }
  82072. flush_pending(strm);
  82073. /* If avail_out is zero, the application will call deflate again
  82074. * to flush the rest.
  82075. */
  82076. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  82077. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  82078. }
  82079. /* ========================================================================= */
  82080. int ZEXPORT deflateEnd (z_streamp strm)
  82081. {
  82082. int status;
  82083. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82084. status = strm->state->status;
  82085. if (status != INIT_STATE &&
  82086. status != EXTRA_STATE &&
  82087. status != NAME_STATE &&
  82088. status != COMMENT_STATE &&
  82089. status != HCRC_STATE &&
  82090. status != BUSY_STATE &&
  82091. status != FINISH_STATE) {
  82092. return Z_STREAM_ERROR;
  82093. }
  82094. /* Deallocate in reverse order of allocations: */
  82095. TRY_FREE(strm, strm->state->pending_buf);
  82096. TRY_FREE(strm, strm->state->head);
  82097. TRY_FREE(strm, strm->state->prev);
  82098. TRY_FREE(strm, strm->state->window);
  82099. ZFREE(strm, strm->state);
  82100. strm->state = Z_NULL;
  82101. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  82102. }
  82103. /* =========================================================================
  82104. * Copy the source state to the destination state.
  82105. * To simplify the source, this is not supported for 16-bit MSDOS (which
  82106. * doesn't have enough memory anyway to duplicate compression states).
  82107. */
  82108. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  82109. {
  82110. #ifdef MAXSEG_64K
  82111. return Z_STREAM_ERROR;
  82112. #else
  82113. deflate_state *ds;
  82114. deflate_state *ss;
  82115. ushf *overlay;
  82116. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  82117. return Z_STREAM_ERROR;
  82118. }
  82119. ss = source->state;
  82120. zmemcpy(dest, source, sizeof(z_stream));
  82121. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  82122. if (ds == Z_NULL) return Z_MEM_ERROR;
  82123. dest->state = (struct internal_state FAR *) ds;
  82124. zmemcpy(ds, ss, sizeof(deflate_state));
  82125. ds->strm = dest;
  82126. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  82127. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  82128. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  82129. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  82130. ds->pending_buf = (uchf *) overlay;
  82131. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  82132. ds->pending_buf == Z_NULL) {
  82133. deflateEnd (dest);
  82134. return Z_MEM_ERROR;
  82135. }
  82136. /* following zmemcpy do not work for 16-bit MSDOS */
  82137. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  82138. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  82139. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  82140. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  82141. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  82142. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  82143. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  82144. ds->l_desc.dyn_tree = ds->dyn_ltree;
  82145. ds->d_desc.dyn_tree = ds->dyn_dtree;
  82146. ds->bl_desc.dyn_tree = ds->bl_tree;
  82147. return Z_OK;
  82148. #endif /* MAXSEG_64K */
  82149. }
  82150. /* ===========================================================================
  82151. * Read a new buffer from the current input stream, update the adler32
  82152. * and total number of bytes read. All deflate() input goes through
  82153. * this function so some applications may wish to modify it to avoid
  82154. * allocating a large strm->next_in buffer and copying from it.
  82155. * (See also flush_pending()).
  82156. */
  82157. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  82158. {
  82159. unsigned len = strm->avail_in;
  82160. if (len > size) len = size;
  82161. if (len == 0) return 0;
  82162. strm->avail_in -= len;
  82163. if (strm->state->wrap == 1) {
  82164. strm->adler = adler32(strm->adler, strm->next_in, len);
  82165. }
  82166. #ifdef GZIP
  82167. else if (strm->state->wrap == 2) {
  82168. strm->adler = crc32(strm->adler, strm->next_in, len);
  82169. }
  82170. #endif
  82171. zmemcpy(buf, strm->next_in, len);
  82172. strm->next_in += len;
  82173. strm->total_in += len;
  82174. return (int)len;
  82175. }
  82176. /* ===========================================================================
  82177. * Initialize the "longest match" routines for a new zlib stream
  82178. */
  82179. local void lm_init (deflate_state *s)
  82180. {
  82181. s->window_size = (ulg)2L*s->w_size;
  82182. CLEAR_HASH(s);
  82183. /* Set the default configuration parameters:
  82184. */
  82185. s->max_lazy_match = configuration_table[s->level].max_lazy;
  82186. s->good_match = configuration_table[s->level].good_length;
  82187. s->nice_match = configuration_table[s->level].nice_length;
  82188. s->max_chain_length = configuration_table[s->level].max_chain;
  82189. s->strstart = 0;
  82190. s->block_start = 0L;
  82191. s->lookahead = 0;
  82192. s->match_length = s->prev_length = MIN_MATCH-1;
  82193. s->match_available = 0;
  82194. s->ins_h = 0;
  82195. #ifndef FASTEST
  82196. #ifdef ASMV
  82197. match_init(); /* initialize the asm code */
  82198. #endif
  82199. #endif
  82200. }
  82201. #ifndef FASTEST
  82202. /* ===========================================================================
  82203. * Set match_start to the longest match starting at the given string and
  82204. * return its length. Matches shorter or equal to prev_length are discarded,
  82205. * in which case the result is equal to prev_length and match_start is
  82206. * garbage.
  82207. * IN assertions: cur_match is the head of the hash chain for the current
  82208. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82209. * OUT assertion: the match length is not greater than s->lookahead.
  82210. */
  82211. #ifndef ASMV
  82212. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82213. * match.S. The code will be functionally equivalent.
  82214. */
  82215. local uInt longest_match(deflate_state *s, IPos cur_match)
  82216. {
  82217. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82218. register Bytef *scan = s->window + s->strstart; /* current string */
  82219. register Bytef *match; /* matched string */
  82220. register int len; /* length of current match */
  82221. int best_len = s->prev_length; /* best match length so far */
  82222. int nice_match = s->nice_match; /* stop if match long enough */
  82223. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82224. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82225. /* Stop when cur_match becomes <= limit. To simplify the code,
  82226. * we prevent matches with the string of window index 0.
  82227. */
  82228. Posf *prev = s->prev;
  82229. uInt wmask = s->w_mask;
  82230. #ifdef UNALIGNED_OK
  82231. /* Compare two bytes at a time. Note: this is not always beneficial.
  82232. * Try with and without -DUNALIGNED_OK to check.
  82233. */
  82234. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82235. register ush scan_start = *(ushf*)scan;
  82236. register ush scan_end = *(ushf*)(scan+best_len-1);
  82237. #else
  82238. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82239. register Byte scan_end1 = scan[best_len-1];
  82240. register Byte scan_end = scan[best_len];
  82241. #endif
  82242. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82243. * It is easy to get rid of this optimization if necessary.
  82244. */
  82245. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82246. /* Do not waste too much time if we already have a good match: */
  82247. if (s->prev_length >= s->good_match) {
  82248. chain_length >>= 2;
  82249. }
  82250. /* Do not look for matches beyond the end of the input. This is necessary
  82251. * to make deflate deterministic.
  82252. */
  82253. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82254. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82255. do {
  82256. Assert(cur_match < s->strstart, "no future");
  82257. match = s->window + cur_match;
  82258. /* Skip to next match if the match length cannot increase
  82259. * or if the match length is less than 2. Note that the checks below
  82260. * for insufficient lookahead only occur occasionally for performance
  82261. * reasons. Therefore uninitialized memory will be accessed, and
  82262. * conditional jumps will be made that depend on those values.
  82263. * However the length of the match is limited to the lookahead, so
  82264. * the output of deflate is not affected by the uninitialized values.
  82265. */
  82266. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82267. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82268. * UNALIGNED_OK if your compiler uses a different size.
  82269. */
  82270. if (*(ushf*)(match+best_len-1) != scan_end ||
  82271. *(ushf*)match != scan_start) continue;
  82272. /* It is not necessary to compare scan[2] and match[2] since they are
  82273. * always equal when the other bytes match, given that the hash keys
  82274. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82275. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82276. * lookahead only every 4th comparison; the 128th check will be made
  82277. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82278. * necessary to put more guard bytes at the end of the window, or
  82279. * to check more often for insufficient lookahead.
  82280. */
  82281. Assert(scan[2] == match[2], "scan[2]?");
  82282. scan++, match++;
  82283. do {
  82284. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82285. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82286. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82287. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82288. scan < strend);
  82289. /* The funny "do {}" generates better code on most compilers */
  82290. /* Here, scan <= window+strstart+257 */
  82291. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82292. if (*scan == *match) scan++;
  82293. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82294. scan = strend - (MAX_MATCH-1);
  82295. #else /* UNALIGNED_OK */
  82296. if (match[best_len] != scan_end ||
  82297. match[best_len-1] != scan_end1 ||
  82298. *match != *scan ||
  82299. *++match != scan[1]) continue;
  82300. /* The check at best_len-1 can be removed because it will be made
  82301. * again later. (This heuristic is not always a win.)
  82302. * It is not necessary to compare scan[2] and match[2] since they
  82303. * are always equal when the other bytes match, given that
  82304. * the hash keys are equal and that HASH_BITS >= 8.
  82305. */
  82306. scan += 2, match++;
  82307. Assert(*scan == *match, "match[2]?");
  82308. /* We check for insufficient lookahead only every 8th comparison;
  82309. * the 256th check will be made at strstart+258.
  82310. */
  82311. do {
  82312. } while (*++scan == *++match && *++scan == *++match &&
  82313. *++scan == *++match && *++scan == *++match &&
  82314. *++scan == *++match && *++scan == *++match &&
  82315. *++scan == *++match && *++scan == *++match &&
  82316. scan < strend);
  82317. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82318. len = MAX_MATCH - (int)(strend - scan);
  82319. scan = strend - MAX_MATCH;
  82320. #endif /* UNALIGNED_OK */
  82321. if (len > best_len) {
  82322. s->match_start = cur_match;
  82323. best_len = len;
  82324. if (len >= nice_match) break;
  82325. #ifdef UNALIGNED_OK
  82326. scan_end = *(ushf*)(scan+best_len-1);
  82327. #else
  82328. scan_end1 = scan[best_len-1];
  82329. scan_end = scan[best_len];
  82330. #endif
  82331. }
  82332. } while ((cur_match = prev[cur_match & wmask]) > limit
  82333. && --chain_length != 0);
  82334. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82335. return s->lookahead;
  82336. }
  82337. #endif /* ASMV */
  82338. #endif /* FASTEST */
  82339. /* ---------------------------------------------------------------------------
  82340. * Optimized version for level == 1 or strategy == Z_RLE only
  82341. */
  82342. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82343. {
  82344. register Bytef *scan = s->window + s->strstart; /* current string */
  82345. register Bytef *match; /* matched string */
  82346. register int len; /* length of current match */
  82347. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82348. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82349. * It is easy to get rid of this optimization if necessary.
  82350. */
  82351. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82352. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82353. Assert(cur_match < s->strstart, "no future");
  82354. match = s->window + cur_match;
  82355. /* Return failure if the match length is less than 2:
  82356. */
  82357. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82358. /* The check at best_len-1 can be removed because it will be made
  82359. * again later. (This heuristic is not always a win.)
  82360. * It is not necessary to compare scan[2] and match[2] since they
  82361. * are always equal when the other bytes match, given that
  82362. * the hash keys are equal and that HASH_BITS >= 8.
  82363. */
  82364. scan += 2, match += 2;
  82365. Assert(*scan == *match, "match[2]?");
  82366. /* We check for insufficient lookahead only every 8th comparison;
  82367. * the 256th check will be made at strstart+258.
  82368. */
  82369. do {
  82370. } while (*++scan == *++match && *++scan == *++match &&
  82371. *++scan == *++match && *++scan == *++match &&
  82372. *++scan == *++match && *++scan == *++match &&
  82373. *++scan == *++match && *++scan == *++match &&
  82374. scan < strend);
  82375. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82376. len = MAX_MATCH - (int)(strend - scan);
  82377. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82378. s->match_start = cur_match;
  82379. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82380. }
  82381. #ifdef DEBUG
  82382. /* ===========================================================================
  82383. * Check that the match at match_start is indeed a match.
  82384. */
  82385. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82386. {
  82387. /* check that the match is indeed a match */
  82388. if (zmemcmp(s->window + match,
  82389. s->window + start, length) != EQUAL) {
  82390. fprintf(stderr, " start %u, match %u, length %d\n",
  82391. start, match, length);
  82392. do {
  82393. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82394. } while (--length != 0);
  82395. z_error("invalid match");
  82396. }
  82397. if (z_verbose > 1) {
  82398. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82399. do { putc(s->window[start++], stderr); } while (--length != 0);
  82400. }
  82401. }
  82402. #else
  82403. # define check_match(s, start, match, length)
  82404. #endif /* DEBUG */
  82405. /* ===========================================================================
  82406. * Fill the window when the lookahead becomes insufficient.
  82407. * Updates strstart and lookahead.
  82408. *
  82409. * IN assertion: lookahead < MIN_LOOKAHEAD
  82410. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82411. * At least one byte has been read, or avail_in == 0; reads are
  82412. * performed for at least two bytes (required for the zip translate_eol
  82413. * option -- not supported here).
  82414. */
  82415. local void fill_window (deflate_state *s)
  82416. {
  82417. register unsigned n, m;
  82418. register Posf *p;
  82419. unsigned more; /* Amount of free space at the end of the window. */
  82420. uInt wsize = s->w_size;
  82421. do {
  82422. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82423. /* Deal with !@#$% 64K limit: */
  82424. if (sizeof(int) <= 2) {
  82425. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82426. more = wsize;
  82427. } else if (more == (unsigned)(-1)) {
  82428. /* Very unlikely, but possible on 16 bit machine if
  82429. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82430. */
  82431. more--;
  82432. }
  82433. }
  82434. /* If the window is almost full and there is insufficient lookahead,
  82435. * move the upper half to the lower one to make room in the upper half.
  82436. */
  82437. if (s->strstart >= wsize+MAX_DIST(s)) {
  82438. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82439. s->match_start -= wsize;
  82440. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82441. s->block_start -= (long) wsize;
  82442. /* Slide the hash table (could be avoided with 32 bit values
  82443. at the expense of memory usage). We slide even when level == 0
  82444. to keep the hash table consistent if we switch back to level > 0
  82445. later. (Using level 0 permanently is not an optimal usage of
  82446. zlib, so we don't care about this pathological case.)
  82447. */
  82448. /* %%% avoid this when Z_RLE */
  82449. n = s->hash_size;
  82450. p = &s->head[n];
  82451. do {
  82452. m = *--p;
  82453. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82454. } while (--n);
  82455. n = wsize;
  82456. #ifndef FASTEST
  82457. p = &s->prev[n];
  82458. do {
  82459. m = *--p;
  82460. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82461. /* If n is not on any hash chain, prev[n] is garbage but
  82462. * its value will never be used.
  82463. */
  82464. } while (--n);
  82465. #endif
  82466. more += wsize;
  82467. }
  82468. if (s->strm->avail_in == 0) return;
  82469. /* If there was no sliding:
  82470. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82471. * more == window_size - lookahead - strstart
  82472. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82473. * => more >= window_size - 2*WSIZE + 2
  82474. * In the BIG_MEM or MMAP case (not yet supported),
  82475. * window_size == input_size + MIN_LOOKAHEAD &&
  82476. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82477. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82478. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82479. */
  82480. Assert(more >= 2, "more < 2");
  82481. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82482. s->lookahead += n;
  82483. /* Initialize the hash value now that we have some input: */
  82484. if (s->lookahead >= MIN_MATCH) {
  82485. s->ins_h = s->window[s->strstart];
  82486. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82487. #if MIN_MATCH != 3
  82488. Call UPDATE_HASH() MIN_MATCH-3 more times
  82489. #endif
  82490. }
  82491. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82492. * but this is not important since only literal bytes will be emitted.
  82493. */
  82494. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82495. }
  82496. /* ===========================================================================
  82497. * Flush the current block, with given end-of-file flag.
  82498. * IN assertion: strstart is set to the end of the current match.
  82499. */
  82500. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82501. _tr_flush_block(s, (s->block_start >= 0L ? \
  82502. (charf *)&s->window[(unsigned)s->block_start] : \
  82503. (charf *)Z_NULL), \
  82504. (ulg)((long)s->strstart - s->block_start), \
  82505. (eof)); \
  82506. s->block_start = s->strstart; \
  82507. flush_pending(s->strm); \
  82508. Tracev((stderr,"[FLUSH]")); \
  82509. }
  82510. /* Same but force premature exit if necessary. */
  82511. #define FLUSH_BLOCK(s, eof) { \
  82512. FLUSH_BLOCK_ONLY(s, eof); \
  82513. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82514. }
  82515. /* ===========================================================================
  82516. * Copy without compression as much as possible from the input stream, return
  82517. * the current block state.
  82518. * This function does not insert new strings in the dictionary since
  82519. * uncompressible data is probably not useful. This function is used
  82520. * only for the level=0 compression option.
  82521. * NOTE: this function should be optimized to avoid extra copying from
  82522. * window to pending_buf.
  82523. */
  82524. local block_state deflate_stored(deflate_state *s, int flush)
  82525. {
  82526. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82527. * to pending_buf_size, and each stored block has a 5 byte header:
  82528. */
  82529. ulg max_block_size = 0xffff;
  82530. ulg max_start;
  82531. if (max_block_size > s->pending_buf_size - 5) {
  82532. max_block_size = s->pending_buf_size - 5;
  82533. }
  82534. /* Copy as much as possible from input to output: */
  82535. for (;;) {
  82536. /* Fill the window as much as possible: */
  82537. if (s->lookahead <= 1) {
  82538. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82539. s->block_start >= (long)s->w_size, "slide too late");
  82540. fill_window(s);
  82541. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82542. if (s->lookahead == 0) break; /* flush the current block */
  82543. }
  82544. Assert(s->block_start >= 0L, "block gone");
  82545. s->strstart += s->lookahead;
  82546. s->lookahead = 0;
  82547. /* Emit a stored block if pending_buf will be full: */
  82548. max_start = s->block_start + max_block_size;
  82549. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82550. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82551. s->lookahead = (uInt)(s->strstart - max_start);
  82552. s->strstart = (uInt)max_start;
  82553. FLUSH_BLOCK(s, 0);
  82554. }
  82555. /* Flush if we may have to slide, otherwise block_start may become
  82556. * negative and the data will be gone:
  82557. */
  82558. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82559. FLUSH_BLOCK(s, 0);
  82560. }
  82561. }
  82562. FLUSH_BLOCK(s, flush == Z_FINISH);
  82563. return flush == Z_FINISH ? finish_done : block_done;
  82564. }
  82565. /* ===========================================================================
  82566. * Compress as much as possible from the input stream, return the current
  82567. * block state.
  82568. * This function does not perform lazy evaluation of matches and inserts
  82569. * new strings in the dictionary only for unmatched strings or for short
  82570. * matches. It is used only for the fast compression options.
  82571. */
  82572. local block_state deflate_fast(deflate_state *s, int flush)
  82573. {
  82574. IPos hash_head = NIL; /* head of the hash chain */
  82575. int bflush; /* set if current block must be flushed */
  82576. for (;;) {
  82577. /* Make sure that we always have enough lookahead, except
  82578. * at the end of the input file. We need MAX_MATCH bytes
  82579. * for the next match, plus MIN_MATCH bytes to insert the
  82580. * string following the next match.
  82581. */
  82582. if (s->lookahead < MIN_LOOKAHEAD) {
  82583. fill_window(s);
  82584. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82585. return need_more;
  82586. }
  82587. if (s->lookahead == 0) break; /* flush the current block */
  82588. }
  82589. /* Insert the string window[strstart .. strstart+2] in the
  82590. * dictionary, and set hash_head to the head of the hash chain:
  82591. */
  82592. if (s->lookahead >= MIN_MATCH) {
  82593. INSERT_STRING(s, s->strstart, hash_head);
  82594. }
  82595. /* Find the longest match, discarding those <= prev_length.
  82596. * At this point we have always match_length < MIN_MATCH
  82597. */
  82598. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82599. /* To simplify the code, we prevent matches with the string
  82600. * of window index 0 (in particular we have to avoid a match
  82601. * of the string with itself at the start of the input file).
  82602. */
  82603. #ifdef FASTEST
  82604. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82605. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82606. s->match_length = longest_match_fast (s, hash_head);
  82607. }
  82608. #else
  82609. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82610. s->match_length = longest_match (s, hash_head);
  82611. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82612. s->match_length = longest_match_fast (s, hash_head);
  82613. }
  82614. #endif
  82615. /* longest_match() or longest_match_fast() sets match_start */
  82616. }
  82617. if (s->match_length >= MIN_MATCH) {
  82618. check_match(s, s->strstart, s->match_start, s->match_length);
  82619. _tr_tally_dist(s, s->strstart - s->match_start,
  82620. s->match_length - MIN_MATCH, bflush);
  82621. s->lookahead -= s->match_length;
  82622. /* Insert new strings in the hash table only if the match length
  82623. * is not too large. This saves time but degrades compression.
  82624. */
  82625. #ifndef FASTEST
  82626. if (s->match_length <= s->max_insert_length &&
  82627. s->lookahead >= MIN_MATCH) {
  82628. s->match_length--; /* string at strstart already in table */
  82629. do {
  82630. s->strstart++;
  82631. INSERT_STRING(s, s->strstart, hash_head);
  82632. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82633. * always MIN_MATCH bytes ahead.
  82634. */
  82635. } while (--s->match_length != 0);
  82636. s->strstart++;
  82637. } else
  82638. #endif
  82639. {
  82640. s->strstart += s->match_length;
  82641. s->match_length = 0;
  82642. s->ins_h = s->window[s->strstart];
  82643. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82644. #if MIN_MATCH != 3
  82645. Call UPDATE_HASH() MIN_MATCH-3 more times
  82646. #endif
  82647. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82648. * matter since it will be recomputed at next deflate call.
  82649. */
  82650. }
  82651. } else {
  82652. /* No match, output a literal byte */
  82653. Tracevv((stderr,"%c", s->window[s->strstart]));
  82654. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82655. s->lookahead--;
  82656. s->strstart++;
  82657. }
  82658. if (bflush) FLUSH_BLOCK(s, 0);
  82659. }
  82660. FLUSH_BLOCK(s, flush == Z_FINISH);
  82661. return flush == Z_FINISH ? finish_done : block_done;
  82662. }
  82663. #ifndef FASTEST
  82664. /* ===========================================================================
  82665. * Same as above, but achieves better compression. We use a lazy
  82666. * evaluation for matches: a match is finally adopted only if there is
  82667. * no better match at the next window position.
  82668. */
  82669. local block_state deflate_slow(deflate_state *s, int flush)
  82670. {
  82671. IPos hash_head = NIL; /* head of hash chain */
  82672. int bflush; /* set if current block must be flushed */
  82673. /* Process the input block. */
  82674. for (;;) {
  82675. /* Make sure that we always have enough lookahead, except
  82676. * at the end of the input file. We need MAX_MATCH bytes
  82677. * for the next match, plus MIN_MATCH bytes to insert the
  82678. * string following the next match.
  82679. */
  82680. if (s->lookahead < MIN_LOOKAHEAD) {
  82681. fill_window(s);
  82682. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82683. return need_more;
  82684. }
  82685. if (s->lookahead == 0) break; /* flush the current block */
  82686. }
  82687. /* Insert the string window[strstart .. strstart+2] in the
  82688. * dictionary, and set hash_head to the head of the hash chain:
  82689. */
  82690. if (s->lookahead >= MIN_MATCH) {
  82691. INSERT_STRING(s, s->strstart, hash_head);
  82692. }
  82693. /* Find the longest match, discarding those <= prev_length.
  82694. */
  82695. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82696. s->match_length = MIN_MATCH-1;
  82697. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82698. s->strstart - hash_head <= MAX_DIST(s)) {
  82699. /* To simplify the code, we prevent matches with the string
  82700. * of window index 0 (in particular we have to avoid a match
  82701. * of the string with itself at the start of the input file).
  82702. */
  82703. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82704. s->match_length = longest_match (s, hash_head);
  82705. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82706. s->match_length = longest_match_fast (s, hash_head);
  82707. }
  82708. /* longest_match() or longest_match_fast() sets match_start */
  82709. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82710. #if TOO_FAR <= 32767
  82711. || (s->match_length == MIN_MATCH &&
  82712. s->strstart - s->match_start > TOO_FAR)
  82713. #endif
  82714. )) {
  82715. /* If prev_match is also MIN_MATCH, match_start is garbage
  82716. * but we will ignore the current match anyway.
  82717. */
  82718. s->match_length = MIN_MATCH-1;
  82719. }
  82720. }
  82721. /* If there was a match at the previous step and the current
  82722. * match is not better, output the previous match:
  82723. */
  82724. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82725. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82726. /* Do not insert strings in hash table beyond this. */
  82727. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82728. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82729. s->prev_length - MIN_MATCH, bflush);
  82730. /* Insert in hash table all strings up to the end of the match.
  82731. * strstart-1 and strstart are already inserted. If there is not
  82732. * enough lookahead, the last two strings are not inserted in
  82733. * the hash table.
  82734. */
  82735. s->lookahead -= s->prev_length-1;
  82736. s->prev_length -= 2;
  82737. do {
  82738. if (++s->strstart <= max_insert) {
  82739. INSERT_STRING(s, s->strstart, hash_head);
  82740. }
  82741. } while (--s->prev_length != 0);
  82742. s->match_available = 0;
  82743. s->match_length = MIN_MATCH-1;
  82744. s->strstart++;
  82745. if (bflush) FLUSH_BLOCK(s, 0);
  82746. } else if (s->match_available) {
  82747. /* If there was no match at the previous position, output a
  82748. * single literal. If there was a match but the current match
  82749. * is longer, truncate the previous match to a single literal.
  82750. */
  82751. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82752. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82753. if (bflush) {
  82754. FLUSH_BLOCK_ONLY(s, 0);
  82755. }
  82756. s->strstart++;
  82757. s->lookahead--;
  82758. if (s->strm->avail_out == 0) return need_more;
  82759. } else {
  82760. /* There is no previous match to compare with, wait for
  82761. * the next step to decide.
  82762. */
  82763. s->match_available = 1;
  82764. s->strstart++;
  82765. s->lookahead--;
  82766. }
  82767. }
  82768. Assert (flush != Z_NO_FLUSH, "no flush?");
  82769. if (s->match_available) {
  82770. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82771. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82772. s->match_available = 0;
  82773. }
  82774. FLUSH_BLOCK(s, flush == Z_FINISH);
  82775. return flush == Z_FINISH ? finish_done : block_done;
  82776. }
  82777. #endif /* FASTEST */
  82778. #if 0
  82779. /* ===========================================================================
  82780. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82781. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82782. * deflate switches away from Z_RLE.)
  82783. */
  82784. local block_state deflate_rle(s, flush)
  82785. deflate_state *s;
  82786. int flush;
  82787. {
  82788. int bflush; /* set if current block must be flushed */
  82789. uInt run; /* length of run */
  82790. uInt max; /* maximum length of run */
  82791. uInt prev; /* byte at distance one to match */
  82792. Bytef *scan; /* scan for end of run */
  82793. for (;;) {
  82794. /* Make sure that we always have enough lookahead, except
  82795. * at the end of the input file. We need MAX_MATCH bytes
  82796. * for the longest encodable run.
  82797. */
  82798. if (s->lookahead < MAX_MATCH) {
  82799. fill_window(s);
  82800. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82801. return need_more;
  82802. }
  82803. if (s->lookahead == 0) break; /* flush the current block */
  82804. }
  82805. /* See how many times the previous byte repeats */
  82806. run = 0;
  82807. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82808. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82809. scan = s->window + s->strstart - 1;
  82810. prev = *scan++;
  82811. do {
  82812. if (*scan++ != prev)
  82813. break;
  82814. } while (++run < max);
  82815. }
  82816. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82817. if (run >= MIN_MATCH) {
  82818. check_match(s, s->strstart, s->strstart - 1, run);
  82819. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82820. s->lookahead -= run;
  82821. s->strstart += run;
  82822. } else {
  82823. /* No match, output a literal byte */
  82824. Tracevv((stderr,"%c", s->window[s->strstart]));
  82825. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82826. s->lookahead--;
  82827. s->strstart++;
  82828. }
  82829. if (bflush) FLUSH_BLOCK(s, 0);
  82830. }
  82831. FLUSH_BLOCK(s, flush == Z_FINISH);
  82832. return flush == Z_FINISH ? finish_done : block_done;
  82833. }
  82834. #endif
  82835. /*** End of inlined file: deflate.c ***/
  82836. /*** Start of inlined file: inffast.c ***/
  82837. /*** Start of inlined file: inftrees.h ***/
  82838. /* WARNING: this file should *not* be used by applications. It is
  82839. part of the implementation of the compression library and is
  82840. subject to change. Applications should only use zlib.h.
  82841. */
  82842. #ifndef _INFTREES_H_
  82843. #define _INFTREES_H_
  82844. /* Structure for decoding tables. Each entry provides either the
  82845. information needed to do the operation requested by the code that
  82846. indexed that table entry, or it provides a pointer to another
  82847. table that indexes more bits of the code. op indicates whether
  82848. the entry is a pointer to another table, a literal, a length or
  82849. distance, an end-of-block, or an invalid code. For a table
  82850. pointer, the low four bits of op is the number of index bits of
  82851. that table. For a length or distance, the low four bits of op
  82852. is the number of extra bits to get after the code. bits is
  82853. the number of bits in this code or part of the code to drop off
  82854. of the bit buffer. val is the actual byte to output in the case
  82855. of a literal, the base length or distance, or the offset from
  82856. the current table to the next table. Each entry is four bytes. */
  82857. typedef struct {
  82858. unsigned char op; /* operation, extra bits, table bits */
  82859. unsigned char bits; /* bits in this part of the code */
  82860. unsigned short val; /* offset in table or code value */
  82861. } code;
  82862. /* op values as set by inflate_table():
  82863. 00000000 - literal
  82864. 0000tttt - table link, tttt != 0 is the number of table index bits
  82865. 0001eeee - length or distance, eeee is the number of extra bits
  82866. 01100000 - end of block
  82867. 01000000 - invalid code
  82868. */
  82869. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82870. exhaustive search was 1444 code structures (852 for length/literals
  82871. and 592 for distances, the latter actually the result of an
  82872. exhaustive search). The true maximum is not known, but the value
  82873. below is more than safe. */
  82874. #define ENOUGH 2048
  82875. #define MAXD 592
  82876. /* Type of code to build for inftable() */
  82877. typedef enum {
  82878. CODES,
  82879. LENS,
  82880. DISTS
  82881. } codetype;
  82882. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82883. unsigned codes, code FAR * FAR *table,
  82884. unsigned FAR *bits, unsigned short FAR *work));
  82885. #endif
  82886. /*** End of inlined file: inftrees.h ***/
  82887. /*** Start of inlined file: inflate.h ***/
  82888. /* WARNING: this file should *not* be used by applications. It is
  82889. part of the implementation of the compression library and is
  82890. subject to change. Applications should only use zlib.h.
  82891. */
  82892. #ifndef _INFLATE_H_
  82893. #define _INFLATE_H_
  82894. /* define NO_GZIP when compiling if you want to disable gzip header and
  82895. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82896. the crc code when it is not needed. For shared libraries, gzip decoding
  82897. should be left enabled. */
  82898. #ifndef NO_GZIP
  82899. # define GUNZIP
  82900. #endif
  82901. /* Possible inflate modes between inflate() calls */
  82902. typedef enum {
  82903. HEAD, /* i: waiting for magic header */
  82904. FLAGS, /* i: waiting for method and flags (gzip) */
  82905. TIME, /* i: waiting for modification time (gzip) */
  82906. OS, /* i: waiting for extra flags and operating system (gzip) */
  82907. EXLEN, /* i: waiting for extra length (gzip) */
  82908. EXTRA, /* i: waiting for extra bytes (gzip) */
  82909. NAME, /* i: waiting for end of file name (gzip) */
  82910. COMMENT, /* i: waiting for end of comment (gzip) */
  82911. HCRC, /* i: waiting for header crc (gzip) */
  82912. DICTID, /* i: waiting for dictionary check value */
  82913. DICT, /* waiting for inflateSetDictionary() call */
  82914. TYPE, /* i: waiting for type bits, including last-flag bit */
  82915. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82916. STORED, /* i: waiting for stored size (length and complement) */
  82917. COPY, /* i/o: waiting for input or output to copy stored block */
  82918. TABLE, /* i: waiting for dynamic block table lengths */
  82919. LENLENS, /* i: waiting for code length code lengths */
  82920. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82921. LEN, /* i: waiting for length/lit code */
  82922. LENEXT, /* i: waiting for length extra bits */
  82923. DIST, /* i: waiting for distance code */
  82924. DISTEXT, /* i: waiting for distance extra bits */
  82925. MATCH, /* o: waiting for output space to copy string */
  82926. LIT, /* o: waiting for output space to write literal */
  82927. CHECK, /* i: waiting for 32-bit check value */
  82928. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82929. DONE, /* finished check, done -- remain here until reset */
  82930. BAD, /* got a data error -- remain here until reset */
  82931. MEM, /* got an inflate() memory error -- remain here until reset */
  82932. SYNC /* looking for synchronization bytes to restart inflate() */
  82933. } inflate_mode;
  82934. /*
  82935. State transitions between above modes -
  82936. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82937. Process header:
  82938. HEAD -> (gzip) or (zlib)
  82939. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82940. NAME -> COMMENT -> HCRC -> TYPE
  82941. (zlib) -> DICTID or TYPE
  82942. DICTID -> DICT -> TYPE
  82943. Read deflate blocks:
  82944. TYPE -> STORED or TABLE or LEN or CHECK
  82945. STORED -> COPY -> TYPE
  82946. TABLE -> LENLENS -> CODELENS -> LEN
  82947. Read deflate codes:
  82948. LEN -> LENEXT or LIT or TYPE
  82949. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82950. LIT -> LEN
  82951. Process trailer:
  82952. CHECK -> LENGTH -> DONE
  82953. */
  82954. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82955. struct inflate_state {
  82956. inflate_mode mode; /* current inflate mode */
  82957. int last; /* true if processing last block */
  82958. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82959. int havedict; /* true if dictionary provided */
  82960. int flags; /* gzip header method and flags (0 if zlib) */
  82961. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82962. unsigned long check; /* protected copy of check value */
  82963. unsigned long total; /* protected copy of output count */
  82964. gz_headerp head; /* where to save gzip header information */
  82965. /* sliding window */
  82966. unsigned wbits; /* log base 2 of requested window size */
  82967. unsigned wsize; /* window size or zero if not using window */
  82968. unsigned whave; /* valid bytes in the window */
  82969. unsigned write; /* window write index */
  82970. unsigned char FAR *window; /* allocated sliding window, if needed */
  82971. /* bit accumulator */
  82972. unsigned long hold; /* input bit accumulator */
  82973. unsigned bits; /* number of bits in "in" */
  82974. /* for string and stored block copying */
  82975. unsigned length; /* literal or length of data to copy */
  82976. unsigned offset; /* distance back to copy string from */
  82977. /* for table and code decoding */
  82978. unsigned extra; /* extra bits needed */
  82979. /* fixed and dynamic code tables */
  82980. code const FAR *lencode; /* starting table for length/literal codes */
  82981. code const FAR *distcode; /* starting table for distance codes */
  82982. unsigned lenbits; /* index bits for lencode */
  82983. unsigned distbits; /* index bits for distcode */
  82984. /* dynamic table building */
  82985. unsigned ncode; /* number of code length code lengths */
  82986. unsigned nlen; /* number of length code lengths */
  82987. unsigned ndist; /* number of distance code lengths */
  82988. unsigned have; /* number of code lengths in lens[] */
  82989. code FAR *next; /* next available space in codes[] */
  82990. unsigned short lens[320]; /* temporary storage for code lengths */
  82991. unsigned short work[288]; /* work area for code table building */
  82992. code codes[ENOUGH]; /* space for code tables */
  82993. };
  82994. #endif
  82995. /*** End of inlined file: inflate.h ***/
  82996. /*** Start of inlined file: inffast.h ***/
  82997. /* WARNING: this file should *not* be used by applications. It is
  82998. part of the implementation of the compression library and is
  82999. subject to change. Applications should only use zlib.h.
  83000. */
  83001. void inflate_fast OF((z_streamp strm, unsigned start));
  83002. /*** End of inlined file: inffast.h ***/
  83003. #ifndef ASMINF
  83004. /* Allow machine dependent optimization for post-increment or pre-increment.
  83005. Based on testing to date,
  83006. Pre-increment preferred for:
  83007. - PowerPC G3 (Adler)
  83008. - MIPS R5000 (Randers-Pehrson)
  83009. Post-increment preferred for:
  83010. - none
  83011. No measurable difference:
  83012. - Pentium III (Anderson)
  83013. - M68060 (Nikl)
  83014. */
  83015. #ifdef POSTINC
  83016. # define OFF 0
  83017. # define PUP(a) *(a)++
  83018. #else
  83019. # define OFF 1
  83020. # define PUP(a) *++(a)
  83021. #endif
  83022. /*
  83023. Decode literal, length, and distance codes and write out the resulting
  83024. literal and match bytes until either not enough input or output is
  83025. available, an end-of-block is encountered, or a data error is encountered.
  83026. When large enough input and output buffers are supplied to inflate(), for
  83027. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  83028. inflate execution time is spent in this routine.
  83029. Entry assumptions:
  83030. state->mode == LEN
  83031. strm->avail_in >= 6
  83032. strm->avail_out >= 258
  83033. start >= strm->avail_out
  83034. state->bits < 8
  83035. On return, state->mode is one of:
  83036. LEN -- ran out of enough output space or enough available input
  83037. TYPE -- reached end of block code, inflate() to interpret next block
  83038. BAD -- error in block data
  83039. Notes:
  83040. - The maximum input bits used by a length/distance pair is 15 bits for the
  83041. length code, 5 bits for the length extra, 15 bits for the distance code,
  83042. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  83043. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  83044. checking for available input while decoding.
  83045. - The maximum bytes that a single length/distance pair can output is 258
  83046. bytes, which is the maximum length that can be coded. inflate_fast()
  83047. requires strm->avail_out >= 258 for each loop to avoid checking for
  83048. output space.
  83049. */
  83050. void inflate_fast (z_streamp strm, unsigned start)
  83051. {
  83052. struct inflate_state FAR *state;
  83053. unsigned char FAR *in; /* local strm->next_in */
  83054. unsigned char FAR *last; /* while in < last, enough input available */
  83055. unsigned char FAR *out; /* local strm->next_out */
  83056. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  83057. unsigned char FAR *end; /* while out < end, enough space available */
  83058. #ifdef INFLATE_STRICT
  83059. unsigned dmax; /* maximum distance from zlib header */
  83060. #endif
  83061. unsigned wsize; /* window size or zero if not using window */
  83062. unsigned whave; /* valid bytes in the window */
  83063. unsigned write; /* window write index */
  83064. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  83065. unsigned long hold; /* local strm->hold */
  83066. unsigned bits; /* local strm->bits */
  83067. code const FAR *lcode; /* local strm->lencode */
  83068. code const FAR *dcode; /* local strm->distcode */
  83069. unsigned lmask; /* mask for first level of length codes */
  83070. unsigned dmask; /* mask for first level of distance codes */
  83071. code thisx; /* retrieved table entry */
  83072. unsigned op; /* code bits, operation, extra bits, or */
  83073. /* window position, window bytes to copy */
  83074. unsigned len; /* match length, unused bytes */
  83075. unsigned dist; /* match distance */
  83076. unsigned char FAR *from; /* where to copy match from */
  83077. /* copy state to local variables */
  83078. state = (struct inflate_state FAR *)strm->state;
  83079. in = strm->next_in - OFF;
  83080. last = in + (strm->avail_in - 5);
  83081. out = strm->next_out - OFF;
  83082. beg = out - (start - strm->avail_out);
  83083. end = out + (strm->avail_out - 257);
  83084. #ifdef INFLATE_STRICT
  83085. dmax = state->dmax;
  83086. #endif
  83087. wsize = state->wsize;
  83088. whave = state->whave;
  83089. write = state->write;
  83090. window = state->window;
  83091. hold = state->hold;
  83092. bits = state->bits;
  83093. lcode = state->lencode;
  83094. dcode = state->distcode;
  83095. lmask = (1U << state->lenbits) - 1;
  83096. dmask = (1U << state->distbits) - 1;
  83097. /* decode literals and length/distances until end-of-block or not enough
  83098. input data or output space */
  83099. do {
  83100. if (bits < 15) {
  83101. hold += (unsigned long)(PUP(in)) << bits;
  83102. bits += 8;
  83103. hold += (unsigned long)(PUP(in)) << bits;
  83104. bits += 8;
  83105. }
  83106. thisx = lcode[hold & lmask];
  83107. dolen:
  83108. op = (unsigned)(thisx.bits);
  83109. hold >>= op;
  83110. bits -= op;
  83111. op = (unsigned)(thisx.op);
  83112. if (op == 0) { /* literal */
  83113. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83114. "inflate: literal '%c'\n" :
  83115. "inflate: literal 0x%02x\n", thisx.val));
  83116. PUP(out) = (unsigned char)(thisx.val);
  83117. }
  83118. else if (op & 16) { /* length base */
  83119. len = (unsigned)(thisx.val);
  83120. op &= 15; /* number of extra bits */
  83121. if (op) {
  83122. if (bits < op) {
  83123. hold += (unsigned long)(PUP(in)) << bits;
  83124. bits += 8;
  83125. }
  83126. len += (unsigned)hold & ((1U << op) - 1);
  83127. hold >>= op;
  83128. bits -= op;
  83129. }
  83130. Tracevv((stderr, "inflate: length %u\n", len));
  83131. if (bits < 15) {
  83132. hold += (unsigned long)(PUP(in)) << bits;
  83133. bits += 8;
  83134. hold += (unsigned long)(PUP(in)) << bits;
  83135. bits += 8;
  83136. }
  83137. thisx = dcode[hold & dmask];
  83138. dodist:
  83139. op = (unsigned)(thisx.bits);
  83140. hold >>= op;
  83141. bits -= op;
  83142. op = (unsigned)(thisx.op);
  83143. if (op & 16) { /* distance base */
  83144. dist = (unsigned)(thisx.val);
  83145. op &= 15; /* number of extra bits */
  83146. if (bits < op) {
  83147. hold += (unsigned long)(PUP(in)) << bits;
  83148. bits += 8;
  83149. if (bits < op) {
  83150. hold += (unsigned long)(PUP(in)) << bits;
  83151. bits += 8;
  83152. }
  83153. }
  83154. dist += (unsigned)hold & ((1U << op) - 1);
  83155. #ifdef INFLATE_STRICT
  83156. if (dist > dmax) {
  83157. strm->msg = (char *)"invalid distance too far back";
  83158. state->mode = BAD;
  83159. break;
  83160. }
  83161. #endif
  83162. hold >>= op;
  83163. bits -= op;
  83164. Tracevv((stderr, "inflate: distance %u\n", dist));
  83165. op = (unsigned)(out - beg); /* max distance in output */
  83166. if (dist > op) { /* see if copy from window */
  83167. op = dist - op; /* distance back in window */
  83168. if (op > whave) {
  83169. strm->msg = (char *)"invalid distance too far back";
  83170. state->mode = BAD;
  83171. break;
  83172. }
  83173. from = window - OFF;
  83174. if (write == 0) { /* very common case */
  83175. from += wsize - op;
  83176. if (op < len) { /* some from window */
  83177. len -= op;
  83178. do {
  83179. PUP(out) = PUP(from);
  83180. } while (--op);
  83181. from = out - dist; /* rest from output */
  83182. }
  83183. }
  83184. else if (write < op) { /* wrap around window */
  83185. from += wsize + write - op;
  83186. op -= write;
  83187. if (op < len) { /* some from end of window */
  83188. len -= op;
  83189. do {
  83190. PUP(out) = PUP(from);
  83191. } while (--op);
  83192. from = window - OFF;
  83193. if (write < len) { /* some from start of window */
  83194. op = write;
  83195. len -= op;
  83196. do {
  83197. PUP(out) = PUP(from);
  83198. } while (--op);
  83199. from = out - dist; /* rest from output */
  83200. }
  83201. }
  83202. }
  83203. else { /* contiguous in window */
  83204. from += write - op;
  83205. if (op < len) { /* some from window */
  83206. len -= op;
  83207. do {
  83208. PUP(out) = PUP(from);
  83209. } while (--op);
  83210. from = out - dist; /* rest from output */
  83211. }
  83212. }
  83213. while (len > 2) {
  83214. PUP(out) = PUP(from);
  83215. PUP(out) = PUP(from);
  83216. PUP(out) = PUP(from);
  83217. len -= 3;
  83218. }
  83219. if (len) {
  83220. PUP(out) = PUP(from);
  83221. if (len > 1)
  83222. PUP(out) = PUP(from);
  83223. }
  83224. }
  83225. else {
  83226. from = out - dist; /* copy direct from output */
  83227. do { /* minimum length is three */
  83228. PUP(out) = PUP(from);
  83229. PUP(out) = PUP(from);
  83230. PUP(out) = PUP(from);
  83231. len -= 3;
  83232. } while (len > 2);
  83233. if (len) {
  83234. PUP(out) = PUP(from);
  83235. if (len > 1)
  83236. PUP(out) = PUP(from);
  83237. }
  83238. }
  83239. }
  83240. else if ((op & 64) == 0) { /* 2nd level distance code */
  83241. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83242. goto dodist;
  83243. }
  83244. else {
  83245. strm->msg = (char *)"invalid distance code";
  83246. state->mode = BAD;
  83247. break;
  83248. }
  83249. }
  83250. else if ((op & 64) == 0) { /* 2nd level length code */
  83251. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83252. goto dolen;
  83253. }
  83254. else if (op & 32) { /* end-of-block */
  83255. Tracevv((stderr, "inflate: end of block\n"));
  83256. state->mode = TYPE;
  83257. break;
  83258. }
  83259. else {
  83260. strm->msg = (char *)"invalid literal/length code";
  83261. state->mode = BAD;
  83262. break;
  83263. }
  83264. } while (in < last && out < end);
  83265. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83266. len = bits >> 3;
  83267. in -= len;
  83268. bits -= len << 3;
  83269. hold &= (1U << bits) - 1;
  83270. /* update state and return */
  83271. strm->next_in = in + OFF;
  83272. strm->next_out = out + OFF;
  83273. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83274. strm->avail_out = (unsigned)(out < end ?
  83275. 257 + (end - out) : 257 - (out - end));
  83276. state->hold = hold;
  83277. state->bits = bits;
  83278. return;
  83279. }
  83280. /*
  83281. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83282. - Using bit fields for code structure
  83283. - Different op definition to avoid & for extra bits (do & for table bits)
  83284. - Three separate decoding do-loops for direct, window, and write == 0
  83285. - Special case for distance > 1 copies to do overlapped load and store copy
  83286. - Explicit branch predictions (based on measured branch probabilities)
  83287. - Deferring match copy and interspersed it with decoding subsequent codes
  83288. - Swapping literal/length else
  83289. - Swapping window/direct else
  83290. - Larger unrolled copy loops (three is about right)
  83291. - Moving len -= 3 statement into middle of loop
  83292. */
  83293. #endif /* !ASMINF */
  83294. /*** End of inlined file: inffast.c ***/
  83295. #undef PULLBYTE
  83296. #undef LOAD
  83297. #undef RESTORE
  83298. #undef INITBITS
  83299. #undef NEEDBITS
  83300. #undef DROPBITS
  83301. #undef BYTEBITS
  83302. /*** Start of inlined file: inflate.c ***/
  83303. /*
  83304. * Change history:
  83305. *
  83306. * 1.2.beta0 24 Nov 2002
  83307. * - First version -- complete rewrite of inflate to simplify code, avoid
  83308. * creation of window when not needed, minimize use of window when it is
  83309. * needed, make inffast.c even faster, implement gzip decoding, and to
  83310. * improve code readability and style over the previous zlib inflate code
  83311. *
  83312. * 1.2.beta1 25 Nov 2002
  83313. * - Use pointers for available input and output checking in inffast.c
  83314. * - Remove input and output counters in inffast.c
  83315. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83316. * - Remove unnecessary second byte pull from length extra in inffast.c
  83317. * - Unroll direct copy to three copies per loop in inffast.c
  83318. *
  83319. * 1.2.beta2 4 Dec 2002
  83320. * - Change external routine names to reduce potential conflicts
  83321. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83322. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83323. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83324. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83325. *
  83326. * 1.2.beta3 22 Dec 2002
  83327. * - Add comments on state->bits assertion in inffast.c
  83328. * - Add comments on op field in inftrees.h
  83329. * - Fix bug in reuse of allocated window after inflateReset()
  83330. * - Remove bit fields--back to byte structure for speed
  83331. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83332. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83333. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83334. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83335. * - Use local copies of stream next and avail values, as well as local bit
  83336. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83337. *
  83338. * 1.2.beta4 1 Jan 2003
  83339. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83340. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83341. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83342. * - Rearrange window copies in inflate_fast() for speed and simplification
  83343. * - Unroll last copy for window match in inflate_fast()
  83344. * - Use local copies of window variables in inflate_fast() for speed
  83345. * - Pull out common write == 0 case for speed in inflate_fast()
  83346. * - Make op and len in inflate_fast() unsigned for consistency
  83347. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83348. * - Simplified bad distance check in inflate_fast()
  83349. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83350. * source file infback.c to provide a call-back interface to inflate for
  83351. * programs like gzip and unzip -- uses window as output buffer to avoid
  83352. * window copying
  83353. *
  83354. * 1.2.beta5 1 Jan 2003
  83355. * - Improved inflateBack() interface to allow the caller to provide initial
  83356. * input in strm.
  83357. * - Fixed stored blocks bug in inflateBack()
  83358. *
  83359. * 1.2.beta6 4 Jan 2003
  83360. * - Added comments in inffast.c on effectiveness of POSTINC
  83361. * - Typecasting all around to reduce compiler warnings
  83362. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83363. * make compilers happy
  83364. * - Changed type of window in inflateBackInit() to unsigned char *
  83365. *
  83366. * 1.2.beta7 27 Jan 2003
  83367. * - Changed many types to unsigned or unsigned short to avoid warnings
  83368. * - Added inflateCopy() function
  83369. *
  83370. * 1.2.0 9 Mar 2003
  83371. * - Changed inflateBack() interface to provide separate opaque descriptors
  83372. * for the in() and out() functions
  83373. * - Changed inflateBack() argument and in_func typedef to swap the length
  83374. * and buffer address return values for the input function
  83375. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83376. *
  83377. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83378. */
  83379. /*** Start of inlined file: inffast.h ***/
  83380. /* WARNING: this file should *not* be used by applications. It is
  83381. part of the implementation of the compression library and is
  83382. subject to change. Applications should only use zlib.h.
  83383. */
  83384. void inflate_fast OF((z_streamp strm, unsigned start));
  83385. /*** End of inlined file: inffast.h ***/
  83386. #ifdef MAKEFIXED
  83387. # ifndef BUILDFIXED
  83388. # define BUILDFIXED
  83389. # endif
  83390. #endif
  83391. /* function prototypes */
  83392. local void fixedtables OF((struct inflate_state FAR *state));
  83393. local int updatewindow OF((z_streamp strm, unsigned out));
  83394. #ifdef BUILDFIXED
  83395. void makefixed OF((void));
  83396. #endif
  83397. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83398. unsigned len));
  83399. int ZEXPORT inflateReset (z_streamp strm)
  83400. {
  83401. struct inflate_state FAR *state;
  83402. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83403. state = (struct inflate_state FAR *)strm->state;
  83404. strm->total_in = strm->total_out = state->total = 0;
  83405. strm->msg = Z_NULL;
  83406. strm->adler = 1; /* to support ill-conceived Java test suite */
  83407. state->mode = HEAD;
  83408. state->last = 0;
  83409. state->havedict = 0;
  83410. state->dmax = 32768U;
  83411. state->head = Z_NULL;
  83412. state->wsize = 0;
  83413. state->whave = 0;
  83414. state->write = 0;
  83415. state->hold = 0;
  83416. state->bits = 0;
  83417. state->lencode = state->distcode = state->next = state->codes;
  83418. Tracev((stderr, "inflate: reset\n"));
  83419. return Z_OK;
  83420. }
  83421. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83422. {
  83423. struct inflate_state FAR *state;
  83424. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83425. state = (struct inflate_state FAR *)strm->state;
  83426. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83427. value &= (1L << bits) - 1;
  83428. state->hold += value << state->bits;
  83429. state->bits += bits;
  83430. return Z_OK;
  83431. }
  83432. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83433. {
  83434. struct inflate_state FAR *state;
  83435. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83436. stream_size != (int)(sizeof(z_stream)))
  83437. return Z_VERSION_ERROR;
  83438. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83439. strm->msg = Z_NULL; /* in case we return an error */
  83440. if (strm->zalloc == (alloc_func)0) {
  83441. strm->zalloc = zcalloc;
  83442. strm->opaque = (voidpf)0;
  83443. }
  83444. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83445. state = (struct inflate_state FAR *)
  83446. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83447. if (state == Z_NULL) return Z_MEM_ERROR;
  83448. Tracev((stderr, "inflate: allocated\n"));
  83449. strm->state = (struct internal_state FAR *)state;
  83450. if (windowBits < 0) {
  83451. state->wrap = 0;
  83452. windowBits = -windowBits;
  83453. }
  83454. else {
  83455. state->wrap = (windowBits >> 4) + 1;
  83456. #ifdef GUNZIP
  83457. if (windowBits < 48) windowBits &= 15;
  83458. #endif
  83459. }
  83460. if (windowBits < 8 || windowBits > 15) {
  83461. ZFREE(strm, state);
  83462. strm->state = Z_NULL;
  83463. return Z_STREAM_ERROR;
  83464. }
  83465. state->wbits = (unsigned)windowBits;
  83466. state->window = Z_NULL;
  83467. return inflateReset(strm);
  83468. }
  83469. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83470. {
  83471. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83472. }
  83473. /*
  83474. Return state with length and distance decoding tables and index sizes set to
  83475. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83476. If BUILDFIXED is defined, then instead this routine builds the tables the
  83477. first time it's called, and returns those tables the first time and
  83478. thereafter. This reduces the size of the code by about 2K bytes, in
  83479. exchange for a little execution time. However, BUILDFIXED should not be
  83480. used for threaded applications, since the rewriting of the tables and virgin
  83481. may not be thread-safe.
  83482. */
  83483. local void fixedtables (struct inflate_state FAR *state)
  83484. {
  83485. #ifdef BUILDFIXED
  83486. static int virgin = 1;
  83487. static code *lenfix, *distfix;
  83488. static code fixed[544];
  83489. /* build fixed huffman tables if first call (may not be thread safe) */
  83490. if (virgin) {
  83491. unsigned sym, bits;
  83492. static code *next;
  83493. /* literal/length table */
  83494. sym = 0;
  83495. while (sym < 144) state->lens[sym++] = 8;
  83496. while (sym < 256) state->lens[sym++] = 9;
  83497. while (sym < 280) state->lens[sym++] = 7;
  83498. while (sym < 288) state->lens[sym++] = 8;
  83499. next = fixed;
  83500. lenfix = next;
  83501. bits = 9;
  83502. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83503. /* distance table */
  83504. sym = 0;
  83505. while (sym < 32) state->lens[sym++] = 5;
  83506. distfix = next;
  83507. bits = 5;
  83508. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83509. /* do this just once */
  83510. virgin = 0;
  83511. }
  83512. #else /* !BUILDFIXED */
  83513. /*** Start of inlined file: inffixed.h ***/
  83514. /* WARNING: this file should *not* be used by applications. It
  83515. is part of the implementation of the compression library and
  83516. is subject to change. Applications should only use zlib.h.
  83517. */
  83518. static const code lenfix[512] = {
  83519. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83520. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83521. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83522. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83523. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83524. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83525. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83526. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83527. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83528. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83529. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83530. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83531. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83532. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83533. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83534. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83535. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83536. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83537. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83538. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83539. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83540. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83541. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83542. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83543. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83544. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83545. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83546. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83547. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83548. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83549. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83550. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83551. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83552. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83553. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83554. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83555. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83556. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83557. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83558. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83559. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83560. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83561. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83562. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83563. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83564. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83565. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83566. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83567. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83568. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83569. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83570. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83571. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83572. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83573. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83574. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83575. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83576. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83577. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83578. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83579. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83580. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83581. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83582. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83583. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83584. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83585. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83586. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83587. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83588. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83589. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83590. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83591. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83592. {0,9,255}
  83593. };
  83594. static const code distfix[32] = {
  83595. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83596. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83597. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83598. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83599. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83600. {22,5,193},{64,5,0}
  83601. };
  83602. /*** End of inlined file: inffixed.h ***/
  83603. #endif /* BUILDFIXED */
  83604. state->lencode = lenfix;
  83605. state->lenbits = 9;
  83606. state->distcode = distfix;
  83607. state->distbits = 5;
  83608. }
  83609. #ifdef MAKEFIXED
  83610. #include <stdio.h>
  83611. /*
  83612. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83613. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83614. those tables to stdout, which would be piped to inffixed.h. A small program
  83615. can simply call makefixed to do this:
  83616. void makefixed(void);
  83617. int main(void)
  83618. {
  83619. makefixed();
  83620. return 0;
  83621. }
  83622. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83623. a.out > inffixed.h
  83624. */
  83625. void makefixed()
  83626. {
  83627. unsigned low, size;
  83628. struct inflate_state state;
  83629. fixedtables(&state);
  83630. puts(" /* inffixed.h -- table for decoding fixed codes");
  83631. puts(" * Generated automatically by makefixed().");
  83632. puts(" */");
  83633. puts("");
  83634. puts(" /* WARNING: this file should *not* be used by applications.");
  83635. puts(" It is part of the implementation of this library and is");
  83636. puts(" subject to change. Applications should only use zlib.h.");
  83637. puts(" */");
  83638. puts("");
  83639. size = 1U << 9;
  83640. printf(" static const code lenfix[%u] = {", size);
  83641. low = 0;
  83642. for (;;) {
  83643. if ((low % 7) == 0) printf("\n ");
  83644. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83645. state.lencode[low].val);
  83646. if (++low == size) break;
  83647. putchar(',');
  83648. }
  83649. puts("\n };");
  83650. size = 1U << 5;
  83651. printf("\n static const code distfix[%u] = {", size);
  83652. low = 0;
  83653. for (;;) {
  83654. if ((low % 6) == 0) printf("\n ");
  83655. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83656. state.distcode[low].val);
  83657. if (++low == size) break;
  83658. putchar(',');
  83659. }
  83660. puts("\n };");
  83661. }
  83662. #endif /* MAKEFIXED */
  83663. /*
  83664. Update the window with the last wsize (normally 32K) bytes written before
  83665. returning. If window does not exist yet, create it. This is only called
  83666. when a window is already in use, or when output has been written during this
  83667. inflate call, but the end of the deflate stream has not been reached yet.
  83668. It is also called to create a window for dictionary data when a dictionary
  83669. is loaded.
  83670. Providing output buffers larger than 32K to inflate() should provide a speed
  83671. advantage, since only the last 32K of output is copied to the sliding window
  83672. upon return from inflate(), and since all distances after the first 32K of
  83673. output will fall in the output data, making match copies simpler and faster.
  83674. The advantage may be dependent on the size of the processor's data caches.
  83675. */
  83676. local int updatewindow (z_streamp strm, unsigned out)
  83677. {
  83678. struct inflate_state FAR *state;
  83679. unsigned copy, dist;
  83680. state = (struct inflate_state FAR *)strm->state;
  83681. /* if it hasn't been done already, allocate space for the window */
  83682. if (state->window == Z_NULL) {
  83683. state->window = (unsigned char FAR *)
  83684. ZALLOC(strm, 1U << state->wbits,
  83685. sizeof(unsigned char));
  83686. if (state->window == Z_NULL) return 1;
  83687. }
  83688. /* if window not in use yet, initialize */
  83689. if (state->wsize == 0) {
  83690. state->wsize = 1U << state->wbits;
  83691. state->write = 0;
  83692. state->whave = 0;
  83693. }
  83694. /* copy state->wsize or less output bytes into the circular window */
  83695. copy = out - strm->avail_out;
  83696. if (copy >= state->wsize) {
  83697. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83698. state->write = 0;
  83699. state->whave = state->wsize;
  83700. }
  83701. else {
  83702. dist = state->wsize - state->write;
  83703. if (dist > copy) dist = copy;
  83704. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83705. copy -= dist;
  83706. if (copy) {
  83707. zmemcpy(state->window, strm->next_out - copy, copy);
  83708. state->write = copy;
  83709. state->whave = state->wsize;
  83710. }
  83711. else {
  83712. state->write += dist;
  83713. if (state->write == state->wsize) state->write = 0;
  83714. if (state->whave < state->wsize) state->whave += dist;
  83715. }
  83716. }
  83717. return 0;
  83718. }
  83719. /* Macros for inflate(): */
  83720. /* check function to use adler32() for zlib or crc32() for gzip */
  83721. #ifdef GUNZIP
  83722. # define UPDATE(check, buf, len) \
  83723. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83724. #else
  83725. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83726. #endif
  83727. /* check macros for header crc */
  83728. #ifdef GUNZIP
  83729. # define CRC2(check, word) \
  83730. do { \
  83731. hbuf[0] = (unsigned char)(word); \
  83732. hbuf[1] = (unsigned char)((word) >> 8); \
  83733. check = crc32(check, hbuf, 2); \
  83734. } while (0)
  83735. # define CRC4(check, word) \
  83736. do { \
  83737. hbuf[0] = (unsigned char)(word); \
  83738. hbuf[1] = (unsigned char)((word) >> 8); \
  83739. hbuf[2] = (unsigned char)((word) >> 16); \
  83740. hbuf[3] = (unsigned char)((word) >> 24); \
  83741. check = crc32(check, hbuf, 4); \
  83742. } while (0)
  83743. #endif
  83744. /* Load registers with state in inflate() for speed */
  83745. #define LOAD() \
  83746. do { \
  83747. put = strm->next_out; \
  83748. left = strm->avail_out; \
  83749. next = strm->next_in; \
  83750. have = strm->avail_in; \
  83751. hold = state->hold; \
  83752. bits = state->bits; \
  83753. } while (0)
  83754. /* Restore state from registers in inflate() */
  83755. #define RESTORE() \
  83756. do { \
  83757. strm->next_out = put; \
  83758. strm->avail_out = left; \
  83759. strm->next_in = next; \
  83760. strm->avail_in = have; \
  83761. state->hold = hold; \
  83762. state->bits = bits; \
  83763. } while (0)
  83764. /* Clear the input bit accumulator */
  83765. #define INITBITS() \
  83766. do { \
  83767. hold = 0; \
  83768. bits = 0; \
  83769. } while (0)
  83770. /* Get a byte of input into the bit accumulator, or return from inflate()
  83771. if there is no input available. */
  83772. #define PULLBYTE() \
  83773. do { \
  83774. if (have == 0) goto inf_leave; \
  83775. have--; \
  83776. hold += (unsigned long)(*next++) << bits; \
  83777. bits += 8; \
  83778. } while (0)
  83779. /* Assure that there are at least n bits in the bit accumulator. If there is
  83780. not enough available input to do that, then return from inflate(). */
  83781. #define NEEDBITS(n) \
  83782. do { \
  83783. while (bits < (unsigned)(n)) \
  83784. PULLBYTE(); \
  83785. } while (0)
  83786. /* Return the low n bits of the bit accumulator (n < 16) */
  83787. #define BITS(n) \
  83788. ((unsigned)hold & ((1U << (n)) - 1))
  83789. /* Remove n bits from the bit accumulator */
  83790. #define DROPBITS(n) \
  83791. do { \
  83792. hold >>= (n); \
  83793. bits -= (unsigned)(n); \
  83794. } while (0)
  83795. /* Remove zero to seven bits as needed to go to a byte boundary */
  83796. #define BYTEBITS() \
  83797. do { \
  83798. hold >>= bits & 7; \
  83799. bits -= bits & 7; \
  83800. } while (0)
  83801. /* Reverse the bytes in a 32-bit value */
  83802. #define REVERSE(q) \
  83803. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83804. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83805. /*
  83806. inflate() uses a state machine to process as much input data and generate as
  83807. much output data as possible before returning. The state machine is
  83808. structured roughly as follows:
  83809. for (;;) switch (state) {
  83810. ...
  83811. case STATEn:
  83812. if (not enough input data or output space to make progress)
  83813. return;
  83814. ... make progress ...
  83815. state = STATEm;
  83816. break;
  83817. ...
  83818. }
  83819. so when inflate() is called again, the same case is attempted again, and
  83820. if the appropriate resources are provided, the machine proceeds to the
  83821. next state. The NEEDBITS() macro is usually the way the state evaluates
  83822. whether it can proceed or should return. NEEDBITS() does the return if
  83823. the requested bits are not available. The typical use of the BITS macros
  83824. is:
  83825. NEEDBITS(n);
  83826. ... do something with BITS(n) ...
  83827. DROPBITS(n);
  83828. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83829. input left to load n bits into the accumulator, or it continues. BITS(n)
  83830. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83831. the low n bits off the accumulator. INITBITS() clears the accumulator
  83832. and sets the number of available bits to zero. BYTEBITS() discards just
  83833. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83834. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83835. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83836. if there is no input available. The decoding of variable length codes uses
  83837. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83838. code, and no more.
  83839. Some states loop until they get enough input, making sure that enough
  83840. state information is maintained to continue the loop where it left off
  83841. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83842. would all have to actually be part of the saved state in case NEEDBITS()
  83843. returns:
  83844. case STATEw:
  83845. while (want < need) {
  83846. NEEDBITS(n);
  83847. keep[want++] = BITS(n);
  83848. DROPBITS(n);
  83849. }
  83850. state = STATEx;
  83851. case STATEx:
  83852. As shown above, if the next state is also the next case, then the break
  83853. is omitted.
  83854. A state may also return if there is not enough output space available to
  83855. complete that state. Those states are copying stored data, writing a
  83856. literal byte, and copying a matching string.
  83857. When returning, a "goto inf_leave" is used to update the total counters,
  83858. update the check value, and determine whether any progress has been made
  83859. during that inflate() call in order to return the proper return code.
  83860. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83861. When there is a window, goto inf_leave will update the window with the last
  83862. output written. If a goto inf_leave occurs in the middle of decompression
  83863. and there is no window currently, goto inf_leave will create one and copy
  83864. output to the window for the next call of inflate().
  83865. In this implementation, the flush parameter of inflate() only affects the
  83866. return code (per zlib.h). inflate() always writes as much as possible to
  83867. strm->next_out, given the space available and the provided input--the effect
  83868. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83869. the allocation of and copying into a sliding window until necessary, which
  83870. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83871. stream available. So the only thing the flush parameter actually does is:
  83872. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83873. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83874. */
  83875. int ZEXPORT inflate (z_streamp strm, int flush)
  83876. {
  83877. struct inflate_state FAR *state;
  83878. unsigned char FAR *next; /* next input */
  83879. unsigned char FAR *put; /* next output */
  83880. unsigned have, left; /* available input and output */
  83881. unsigned long hold; /* bit buffer */
  83882. unsigned bits; /* bits in bit buffer */
  83883. unsigned in, out; /* save starting available input and output */
  83884. unsigned copy; /* number of stored or match bytes to copy */
  83885. unsigned char FAR *from; /* where to copy match bytes from */
  83886. code thisx; /* current decoding table entry */
  83887. code last; /* parent table entry */
  83888. unsigned len; /* length to copy for repeats, bits to drop */
  83889. int ret; /* return code */
  83890. #ifdef GUNZIP
  83891. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83892. #endif
  83893. static const unsigned short order[19] = /* permutation of code lengths */
  83894. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83895. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83896. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83897. return Z_STREAM_ERROR;
  83898. state = (struct inflate_state FAR *)strm->state;
  83899. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83900. LOAD();
  83901. in = have;
  83902. out = left;
  83903. ret = Z_OK;
  83904. for (;;)
  83905. switch (state->mode) {
  83906. case HEAD:
  83907. if (state->wrap == 0) {
  83908. state->mode = TYPEDO;
  83909. break;
  83910. }
  83911. NEEDBITS(16);
  83912. #ifdef GUNZIP
  83913. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83914. state->check = crc32(0L, Z_NULL, 0);
  83915. CRC2(state->check, hold);
  83916. INITBITS();
  83917. state->mode = FLAGS;
  83918. break;
  83919. }
  83920. state->flags = 0; /* expect zlib header */
  83921. if (state->head != Z_NULL)
  83922. state->head->done = -1;
  83923. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83924. #else
  83925. if (
  83926. #endif
  83927. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83928. strm->msg = (char *)"incorrect header check";
  83929. state->mode = BAD;
  83930. break;
  83931. }
  83932. if (BITS(4) != Z_DEFLATED) {
  83933. strm->msg = (char *)"unknown compression method";
  83934. state->mode = BAD;
  83935. break;
  83936. }
  83937. DROPBITS(4);
  83938. len = BITS(4) + 8;
  83939. if (len > state->wbits) {
  83940. strm->msg = (char *)"invalid window size";
  83941. state->mode = BAD;
  83942. break;
  83943. }
  83944. state->dmax = 1U << len;
  83945. Tracev((stderr, "inflate: zlib header ok\n"));
  83946. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83947. state->mode = hold & 0x200 ? DICTID : TYPE;
  83948. INITBITS();
  83949. break;
  83950. #ifdef GUNZIP
  83951. case FLAGS:
  83952. NEEDBITS(16);
  83953. state->flags = (int)(hold);
  83954. if ((state->flags & 0xff) != Z_DEFLATED) {
  83955. strm->msg = (char *)"unknown compression method";
  83956. state->mode = BAD;
  83957. break;
  83958. }
  83959. if (state->flags & 0xe000) {
  83960. strm->msg = (char *)"unknown header flags set";
  83961. state->mode = BAD;
  83962. break;
  83963. }
  83964. if (state->head != Z_NULL)
  83965. state->head->text = (int)((hold >> 8) & 1);
  83966. if (state->flags & 0x0200) CRC2(state->check, hold);
  83967. INITBITS();
  83968. state->mode = TIME;
  83969. case TIME:
  83970. NEEDBITS(32);
  83971. if (state->head != Z_NULL)
  83972. state->head->time = hold;
  83973. if (state->flags & 0x0200) CRC4(state->check, hold);
  83974. INITBITS();
  83975. state->mode = OS;
  83976. case OS:
  83977. NEEDBITS(16);
  83978. if (state->head != Z_NULL) {
  83979. state->head->xflags = (int)(hold & 0xff);
  83980. state->head->os = (int)(hold >> 8);
  83981. }
  83982. if (state->flags & 0x0200) CRC2(state->check, hold);
  83983. INITBITS();
  83984. state->mode = EXLEN;
  83985. case EXLEN:
  83986. if (state->flags & 0x0400) {
  83987. NEEDBITS(16);
  83988. state->length = (unsigned)(hold);
  83989. if (state->head != Z_NULL)
  83990. state->head->extra_len = (unsigned)hold;
  83991. if (state->flags & 0x0200) CRC2(state->check, hold);
  83992. INITBITS();
  83993. }
  83994. else if (state->head != Z_NULL)
  83995. state->head->extra = Z_NULL;
  83996. state->mode = EXTRA;
  83997. case EXTRA:
  83998. if (state->flags & 0x0400) {
  83999. copy = state->length;
  84000. if (copy > have) copy = have;
  84001. if (copy) {
  84002. if (state->head != Z_NULL &&
  84003. state->head->extra != Z_NULL) {
  84004. len = state->head->extra_len - state->length;
  84005. zmemcpy(state->head->extra + len, next,
  84006. len + copy > state->head->extra_max ?
  84007. state->head->extra_max - len : copy);
  84008. }
  84009. if (state->flags & 0x0200)
  84010. state->check = crc32(state->check, next, copy);
  84011. have -= copy;
  84012. next += copy;
  84013. state->length -= copy;
  84014. }
  84015. if (state->length) goto inf_leave;
  84016. }
  84017. state->length = 0;
  84018. state->mode = NAME;
  84019. case NAME:
  84020. if (state->flags & 0x0800) {
  84021. if (have == 0) goto inf_leave;
  84022. copy = 0;
  84023. do {
  84024. len = (unsigned)(next[copy++]);
  84025. if (state->head != Z_NULL &&
  84026. state->head->name != Z_NULL &&
  84027. state->length < state->head->name_max)
  84028. state->head->name[state->length++] = len;
  84029. } while (len && copy < have);
  84030. if (state->flags & 0x0200)
  84031. state->check = crc32(state->check, next, copy);
  84032. have -= copy;
  84033. next += copy;
  84034. if (len) goto inf_leave;
  84035. }
  84036. else if (state->head != Z_NULL)
  84037. state->head->name = Z_NULL;
  84038. state->length = 0;
  84039. state->mode = COMMENT;
  84040. case COMMENT:
  84041. if (state->flags & 0x1000) {
  84042. if (have == 0) goto inf_leave;
  84043. copy = 0;
  84044. do {
  84045. len = (unsigned)(next[copy++]);
  84046. if (state->head != Z_NULL &&
  84047. state->head->comment != Z_NULL &&
  84048. state->length < state->head->comm_max)
  84049. state->head->comment[state->length++] = len;
  84050. } while (len && copy < have);
  84051. if (state->flags & 0x0200)
  84052. state->check = crc32(state->check, next, copy);
  84053. have -= copy;
  84054. next += copy;
  84055. if (len) goto inf_leave;
  84056. }
  84057. else if (state->head != Z_NULL)
  84058. state->head->comment = Z_NULL;
  84059. state->mode = HCRC;
  84060. case HCRC:
  84061. if (state->flags & 0x0200) {
  84062. NEEDBITS(16);
  84063. if (hold != (state->check & 0xffff)) {
  84064. strm->msg = (char *)"header crc mismatch";
  84065. state->mode = BAD;
  84066. break;
  84067. }
  84068. INITBITS();
  84069. }
  84070. if (state->head != Z_NULL) {
  84071. state->head->hcrc = (int)((state->flags >> 9) & 1);
  84072. state->head->done = 1;
  84073. }
  84074. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  84075. state->mode = TYPE;
  84076. break;
  84077. #endif
  84078. case DICTID:
  84079. NEEDBITS(32);
  84080. strm->adler = state->check = REVERSE(hold);
  84081. INITBITS();
  84082. state->mode = DICT;
  84083. case DICT:
  84084. if (state->havedict == 0) {
  84085. RESTORE();
  84086. return Z_NEED_DICT;
  84087. }
  84088. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  84089. state->mode = TYPE;
  84090. case TYPE:
  84091. if (flush == Z_BLOCK) goto inf_leave;
  84092. case TYPEDO:
  84093. if (state->last) {
  84094. BYTEBITS();
  84095. state->mode = CHECK;
  84096. break;
  84097. }
  84098. NEEDBITS(3);
  84099. state->last = BITS(1);
  84100. DROPBITS(1);
  84101. switch (BITS(2)) {
  84102. case 0: /* stored block */
  84103. Tracev((stderr, "inflate: stored block%s\n",
  84104. state->last ? " (last)" : ""));
  84105. state->mode = STORED;
  84106. break;
  84107. case 1: /* fixed block */
  84108. fixedtables(state);
  84109. Tracev((stderr, "inflate: fixed codes block%s\n",
  84110. state->last ? " (last)" : ""));
  84111. state->mode = LEN; /* decode codes */
  84112. break;
  84113. case 2: /* dynamic block */
  84114. Tracev((stderr, "inflate: dynamic codes block%s\n",
  84115. state->last ? " (last)" : ""));
  84116. state->mode = TABLE;
  84117. break;
  84118. case 3:
  84119. strm->msg = (char *)"invalid block type";
  84120. state->mode = BAD;
  84121. }
  84122. DROPBITS(2);
  84123. break;
  84124. case STORED:
  84125. BYTEBITS(); /* go to byte boundary */
  84126. NEEDBITS(32);
  84127. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  84128. strm->msg = (char *)"invalid stored block lengths";
  84129. state->mode = BAD;
  84130. break;
  84131. }
  84132. state->length = (unsigned)hold & 0xffff;
  84133. Tracev((stderr, "inflate: stored length %u\n",
  84134. state->length));
  84135. INITBITS();
  84136. state->mode = COPY;
  84137. case COPY:
  84138. copy = state->length;
  84139. if (copy) {
  84140. if (copy > have) copy = have;
  84141. if (copy > left) copy = left;
  84142. if (copy == 0) goto inf_leave;
  84143. zmemcpy(put, next, copy);
  84144. have -= copy;
  84145. next += copy;
  84146. left -= copy;
  84147. put += copy;
  84148. state->length -= copy;
  84149. break;
  84150. }
  84151. Tracev((stderr, "inflate: stored end\n"));
  84152. state->mode = TYPE;
  84153. break;
  84154. case TABLE:
  84155. NEEDBITS(14);
  84156. state->nlen = BITS(5) + 257;
  84157. DROPBITS(5);
  84158. state->ndist = BITS(5) + 1;
  84159. DROPBITS(5);
  84160. state->ncode = BITS(4) + 4;
  84161. DROPBITS(4);
  84162. #ifndef PKZIP_BUG_WORKAROUND
  84163. if (state->nlen > 286 || state->ndist > 30) {
  84164. strm->msg = (char *)"too many length or distance symbols";
  84165. state->mode = BAD;
  84166. break;
  84167. }
  84168. #endif
  84169. Tracev((stderr, "inflate: table sizes ok\n"));
  84170. state->have = 0;
  84171. state->mode = LENLENS;
  84172. case LENLENS:
  84173. while (state->have < state->ncode) {
  84174. NEEDBITS(3);
  84175. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  84176. DROPBITS(3);
  84177. }
  84178. while (state->have < 19)
  84179. state->lens[order[state->have++]] = 0;
  84180. state->next = state->codes;
  84181. state->lencode = (code const FAR *)(state->next);
  84182. state->lenbits = 7;
  84183. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  84184. &(state->lenbits), state->work);
  84185. if (ret) {
  84186. strm->msg = (char *)"invalid code lengths set";
  84187. state->mode = BAD;
  84188. break;
  84189. }
  84190. Tracev((stderr, "inflate: code lengths ok\n"));
  84191. state->have = 0;
  84192. state->mode = CODELENS;
  84193. case CODELENS:
  84194. while (state->have < state->nlen + state->ndist) {
  84195. for (;;) {
  84196. thisx = state->lencode[BITS(state->lenbits)];
  84197. if ((unsigned)(thisx.bits) <= bits) break;
  84198. PULLBYTE();
  84199. }
  84200. if (thisx.val < 16) {
  84201. NEEDBITS(thisx.bits);
  84202. DROPBITS(thisx.bits);
  84203. state->lens[state->have++] = thisx.val;
  84204. }
  84205. else {
  84206. if (thisx.val == 16) {
  84207. NEEDBITS(thisx.bits + 2);
  84208. DROPBITS(thisx.bits);
  84209. if (state->have == 0) {
  84210. strm->msg = (char *)"invalid bit length repeat";
  84211. state->mode = BAD;
  84212. break;
  84213. }
  84214. len = state->lens[state->have - 1];
  84215. copy = 3 + BITS(2);
  84216. DROPBITS(2);
  84217. }
  84218. else if (thisx.val == 17) {
  84219. NEEDBITS(thisx.bits + 3);
  84220. DROPBITS(thisx.bits);
  84221. len = 0;
  84222. copy = 3 + BITS(3);
  84223. DROPBITS(3);
  84224. }
  84225. else {
  84226. NEEDBITS(thisx.bits + 7);
  84227. DROPBITS(thisx.bits);
  84228. len = 0;
  84229. copy = 11 + BITS(7);
  84230. DROPBITS(7);
  84231. }
  84232. if (state->have + copy > state->nlen + state->ndist) {
  84233. strm->msg = (char *)"invalid bit length repeat";
  84234. state->mode = BAD;
  84235. break;
  84236. }
  84237. while (copy--)
  84238. state->lens[state->have++] = (unsigned short)len;
  84239. }
  84240. }
  84241. /* handle error breaks in while */
  84242. if (state->mode == BAD) break;
  84243. /* build code tables */
  84244. state->next = state->codes;
  84245. state->lencode = (code const FAR *)(state->next);
  84246. state->lenbits = 9;
  84247. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84248. &(state->lenbits), state->work);
  84249. if (ret) {
  84250. strm->msg = (char *)"invalid literal/lengths set";
  84251. state->mode = BAD;
  84252. break;
  84253. }
  84254. state->distcode = (code const FAR *)(state->next);
  84255. state->distbits = 6;
  84256. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84257. &(state->next), &(state->distbits), state->work);
  84258. if (ret) {
  84259. strm->msg = (char *)"invalid distances set";
  84260. state->mode = BAD;
  84261. break;
  84262. }
  84263. Tracev((stderr, "inflate: codes ok\n"));
  84264. state->mode = LEN;
  84265. case LEN:
  84266. if (have >= 6 && left >= 258) {
  84267. RESTORE();
  84268. inflate_fast(strm, out);
  84269. LOAD();
  84270. break;
  84271. }
  84272. for (;;) {
  84273. thisx = state->lencode[BITS(state->lenbits)];
  84274. if ((unsigned)(thisx.bits) <= bits) break;
  84275. PULLBYTE();
  84276. }
  84277. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84278. last = thisx;
  84279. for (;;) {
  84280. thisx = state->lencode[last.val +
  84281. (BITS(last.bits + last.op) >> last.bits)];
  84282. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84283. PULLBYTE();
  84284. }
  84285. DROPBITS(last.bits);
  84286. }
  84287. DROPBITS(thisx.bits);
  84288. state->length = (unsigned)thisx.val;
  84289. if ((int)(thisx.op) == 0) {
  84290. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84291. "inflate: literal '%c'\n" :
  84292. "inflate: literal 0x%02x\n", thisx.val));
  84293. state->mode = LIT;
  84294. break;
  84295. }
  84296. if (thisx.op & 32) {
  84297. Tracevv((stderr, "inflate: end of block\n"));
  84298. state->mode = TYPE;
  84299. break;
  84300. }
  84301. if (thisx.op & 64) {
  84302. strm->msg = (char *)"invalid literal/length code";
  84303. state->mode = BAD;
  84304. break;
  84305. }
  84306. state->extra = (unsigned)(thisx.op) & 15;
  84307. state->mode = LENEXT;
  84308. case LENEXT:
  84309. if (state->extra) {
  84310. NEEDBITS(state->extra);
  84311. state->length += BITS(state->extra);
  84312. DROPBITS(state->extra);
  84313. }
  84314. Tracevv((stderr, "inflate: length %u\n", state->length));
  84315. state->mode = DIST;
  84316. case DIST:
  84317. for (;;) {
  84318. thisx = state->distcode[BITS(state->distbits)];
  84319. if ((unsigned)(thisx.bits) <= bits) break;
  84320. PULLBYTE();
  84321. }
  84322. if ((thisx.op & 0xf0) == 0) {
  84323. last = thisx;
  84324. for (;;) {
  84325. thisx = state->distcode[last.val +
  84326. (BITS(last.bits + last.op) >> last.bits)];
  84327. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84328. PULLBYTE();
  84329. }
  84330. DROPBITS(last.bits);
  84331. }
  84332. DROPBITS(thisx.bits);
  84333. if (thisx.op & 64) {
  84334. strm->msg = (char *)"invalid distance code";
  84335. state->mode = BAD;
  84336. break;
  84337. }
  84338. state->offset = (unsigned)thisx.val;
  84339. state->extra = (unsigned)(thisx.op) & 15;
  84340. state->mode = DISTEXT;
  84341. case DISTEXT:
  84342. if (state->extra) {
  84343. NEEDBITS(state->extra);
  84344. state->offset += BITS(state->extra);
  84345. DROPBITS(state->extra);
  84346. }
  84347. #ifdef INFLATE_STRICT
  84348. if (state->offset > state->dmax) {
  84349. strm->msg = (char *)"invalid distance too far back";
  84350. state->mode = BAD;
  84351. break;
  84352. }
  84353. #endif
  84354. if (state->offset > state->whave + out - left) {
  84355. strm->msg = (char *)"invalid distance too far back";
  84356. state->mode = BAD;
  84357. break;
  84358. }
  84359. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84360. state->mode = MATCH;
  84361. case MATCH:
  84362. if (left == 0) goto inf_leave;
  84363. copy = out - left;
  84364. if (state->offset > copy) { /* copy from window */
  84365. copy = state->offset - copy;
  84366. if (copy > state->write) {
  84367. copy -= state->write;
  84368. from = state->window + (state->wsize - copy);
  84369. }
  84370. else
  84371. from = state->window + (state->write - copy);
  84372. if (copy > state->length) copy = state->length;
  84373. }
  84374. else { /* copy from output */
  84375. from = put - state->offset;
  84376. copy = state->length;
  84377. }
  84378. if (copy > left) copy = left;
  84379. left -= copy;
  84380. state->length -= copy;
  84381. do {
  84382. *put++ = *from++;
  84383. } while (--copy);
  84384. if (state->length == 0) state->mode = LEN;
  84385. break;
  84386. case LIT:
  84387. if (left == 0) goto inf_leave;
  84388. *put++ = (unsigned char)(state->length);
  84389. left--;
  84390. state->mode = LEN;
  84391. break;
  84392. case CHECK:
  84393. if (state->wrap) {
  84394. NEEDBITS(32);
  84395. out -= left;
  84396. strm->total_out += out;
  84397. state->total += out;
  84398. if (out)
  84399. strm->adler = state->check =
  84400. UPDATE(state->check, put - out, out);
  84401. out = left;
  84402. if ((
  84403. #ifdef GUNZIP
  84404. state->flags ? hold :
  84405. #endif
  84406. REVERSE(hold)) != state->check) {
  84407. strm->msg = (char *)"incorrect data check";
  84408. state->mode = BAD;
  84409. break;
  84410. }
  84411. INITBITS();
  84412. Tracev((stderr, "inflate: check matches trailer\n"));
  84413. }
  84414. #ifdef GUNZIP
  84415. state->mode = LENGTH;
  84416. case LENGTH:
  84417. if (state->wrap && state->flags) {
  84418. NEEDBITS(32);
  84419. if (hold != (state->total & 0xffffffffUL)) {
  84420. strm->msg = (char *)"incorrect length check";
  84421. state->mode = BAD;
  84422. break;
  84423. }
  84424. INITBITS();
  84425. Tracev((stderr, "inflate: length matches trailer\n"));
  84426. }
  84427. #endif
  84428. state->mode = DONE;
  84429. case DONE:
  84430. ret = Z_STREAM_END;
  84431. goto inf_leave;
  84432. case BAD:
  84433. ret = Z_DATA_ERROR;
  84434. goto inf_leave;
  84435. case MEM:
  84436. return Z_MEM_ERROR;
  84437. case SYNC:
  84438. default:
  84439. return Z_STREAM_ERROR;
  84440. }
  84441. /*
  84442. Return from inflate(), updating the total counts and the check value.
  84443. If there was no progress during the inflate() call, return a buffer
  84444. error. Call updatewindow() to create and/or update the window state.
  84445. Note: a memory error from inflate() is non-recoverable.
  84446. */
  84447. inf_leave:
  84448. RESTORE();
  84449. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84450. if (updatewindow(strm, out)) {
  84451. state->mode = MEM;
  84452. return Z_MEM_ERROR;
  84453. }
  84454. in -= strm->avail_in;
  84455. out -= strm->avail_out;
  84456. strm->total_in += in;
  84457. strm->total_out += out;
  84458. state->total += out;
  84459. if (state->wrap && out)
  84460. strm->adler = state->check =
  84461. UPDATE(state->check, strm->next_out - out, out);
  84462. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84463. (state->mode == TYPE ? 128 : 0);
  84464. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84465. ret = Z_BUF_ERROR;
  84466. return ret;
  84467. }
  84468. int ZEXPORT inflateEnd (z_streamp strm)
  84469. {
  84470. struct inflate_state FAR *state;
  84471. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84472. return Z_STREAM_ERROR;
  84473. state = (struct inflate_state FAR *)strm->state;
  84474. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84475. ZFREE(strm, strm->state);
  84476. strm->state = Z_NULL;
  84477. Tracev((stderr, "inflate: end\n"));
  84478. return Z_OK;
  84479. }
  84480. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84481. {
  84482. struct inflate_state FAR *state;
  84483. unsigned long id_;
  84484. /* check state */
  84485. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84486. state = (struct inflate_state FAR *)strm->state;
  84487. if (state->wrap != 0 && state->mode != DICT)
  84488. return Z_STREAM_ERROR;
  84489. /* check for correct dictionary id */
  84490. if (state->mode == DICT) {
  84491. id_ = adler32(0L, Z_NULL, 0);
  84492. id_ = adler32(id_, dictionary, dictLength);
  84493. if (id_ != state->check)
  84494. return Z_DATA_ERROR;
  84495. }
  84496. /* copy dictionary to window */
  84497. if (updatewindow(strm, strm->avail_out)) {
  84498. state->mode = MEM;
  84499. return Z_MEM_ERROR;
  84500. }
  84501. if (dictLength > state->wsize) {
  84502. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84503. state->wsize);
  84504. state->whave = state->wsize;
  84505. }
  84506. else {
  84507. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84508. dictLength);
  84509. state->whave = dictLength;
  84510. }
  84511. state->havedict = 1;
  84512. Tracev((stderr, "inflate: dictionary set\n"));
  84513. return Z_OK;
  84514. }
  84515. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84516. {
  84517. struct inflate_state FAR *state;
  84518. /* check state */
  84519. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84520. state = (struct inflate_state FAR *)strm->state;
  84521. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84522. /* save header structure */
  84523. state->head = head;
  84524. head->done = 0;
  84525. return Z_OK;
  84526. }
  84527. /*
  84528. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84529. or when out of input. When called, *have is the number of pattern bytes
  84530. found in order so far, in 0..3. On return *have is updated to the new
  84531. state. If on return *have equals four, then the pattern was found and the
  84532. return value is how many bytes were read including the last byte of the
  84533. pattern. If *have is less than four, then the pattern has not been found
  84534. yet and the return value is len. In the latter case, syncsearch() can be
  84535. called again with more data and the *have state. *have is initialized to
  84536. zero for the first call.
  84537. */
  84538. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84539. {
  84540. unsigned got;
  84541. unsigned next;
  84542. got = *have;
  84543. next = 0;
  84544. while (next < len && got < 4) {
  84545. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84546. got++;
  84547. else if (buf[next])
  84548. got = 0;
  84549. else
  84550. got = 4 - got;
  84551. next++;
  84552. }
  84553. *have = got;
  84554. return next;
  84555. }
  84556. int ZEXPORT inflateSync (z_streamp strm)
  84557. {
  84558. unsigned len; /* number of bytes to look at or looked at */
  84559. unsigned long in, out; /* temporary to save total_in and total_out */
  84560. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84561. struct inflate_state FAR *state;
  84562. /* check parameters */
  84563. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84564. state = (struct inflate_state FAR *)strm->state;
  84565. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84566. /* if first time, start search in bit buffer */
  84567. if (state->mode != SYNC) {
  84568. state->mode = SYNC;
  84569. state->hold <<= state->bits & 7;
  84570. state->bits -= state->bits & 7;
  84571. len = 0;
  84572. while (state->bits >= 8) {
  84573. buf[len++] = (unsigned char)(state->hold);
  84574. state->hold >>= 8;
  84575. state->bits -= 8;
  84576. }
  84577. state->have = 0;
  84578. syncsearch(&(state->have), buf, len);
  84579. }
  84580. /* search available input */
  84581. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84582. strm->avail_in -= len;
  84583. strm->next_in += len;
  84584. strm->total_in += len;
  84585. /* return no joy or set up to restart inflate() on a new block */
  84586. if (state->have != 4) return Z_DATA_ERROR;
  84587. in = strm->total_in; out = strm->total_out;
  84588. inflateReset(strm);
  84589. strm->total_in = in; strm->total_out = out;
  84590. state->mode = TYPE;
  84591. return Z_OK;
  84592. }
  84593. /*
  84594. Returns true if inflate is currently at the end of a block generated by
  84595. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84596. implementation to provide an additional safety check. PPP uses
  84597. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84598. block. When decompressing, PPP checks that at the end of input packet,
  84599. inflate is waiting for these length bytes.
  84600. */
  84601. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84602. {
  84603. struct inflate_state FAR *state;
  84604. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84605. state = (struct inflate_state FAR *)strm->state;
  84606. return state->mode == STORED && state->bits == 0;
  84607. }
  84608. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84609. {
  84610. struct inflate_state FAR *state;
  84611. struct inflate_state FAR *copy;
  84612. unsigned char FAR *window;
  84613. unsigned wsize;
  84614. /* check input */
  84615. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84616. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84617. return Z_STREAM_ERROR;
  84618. state = (struct inflate_state FAR *)source->state;
  84619. /* allocate space */
  84620. copy = (struct inflate_state FAR *)
  84621. ZALLOC(source, 1, sizeof(struct inflate_state));
  84622. if (copy == Z_NULL) return Z_MEM_ERROR;
  84623. window = Z_NULL;
  84624. if (state->window != Z_NULL) {
  84625. window = (unsigned char FAR *)
  84626. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84627. if (window == Z_NULL) {
  84628. ZFREE(source, copy);
  84629. return Z_MEM_ERROR;
  84630. }
  84631. }
  84632. /* copy state */
  84633. zmemcpy(dest, source, sizeof(z_stream));
  84634. zmemcpy(copy, state, sizeof(struct inflate_state));
  84635. if (state->lencode >= state->codes &&
  84636. state->lencode <= state->codes + ENOUGH - 1) {
  84637. copy->lencode = copy->codes + (state->lencode - state->codes);
  84638. copy->distcode = copy->codes + (state->distcode - state->codes);
  84639. }
  84640. copy->next = copy->codes + (state->next - state->codes);
  84641. if (window != Z_NULL) {
  84642. wsize = 1U << state->wbits;
  84643. zmemcpy(window, state->window, wsize);
  84644. }
  84645. copy->window = window;
  84646. dest->state = (struct internal_state FAR *)copy;
  84647. return Z_OK;
  84648. }
  84649. /*** End of inlined file: inflate.c ***/
  84650. /*** Start of inlined file: inftrees.c ***/
  84651. #define MAXBITS 15
  84652. const char inflate_copyright[] =
  84653. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84654. /*
  84655. If you use the zlib library in a product, an acknowledgment is welcome
  84656. in the documentation of your product. If for some reason you cannot
  84657. include such an acknowledgment, I would appreciate that you keep this
  84658. copyright string in the executable of your product.
  84659. */
  84660. /*
  84661. Build a set of tables to decode the provided canonical Huffman code.
  84662. The code lengths are lens[0..codes-1]. The result starts at *table,
  84663. whose indices are 0..2^bits-1. work is a writable array of at least
  84664. lens shorts, which is used as a work area. type is the type of code
  84665. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84666. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84667. on return points to the next available entry's address. bits is the
  84668. requested root table index bits, and on return it is the actual root
  84669. table index bits. It will differ if the request is greater than the
  84670. longest code or if it is less than the shortest code.
  84671. */
  84672. int inflate_table (codetype type,
  84673. unsigned short FAR *lens,
  84674. unsigned codes,
  84675. code FAR * FAR *table,
  84676. unsigned FAR *bits,
  84677. unsigned short FAR *work)
  84678. {
  84679. unsigned len; /* a code's length in bits */
  84680. unsigned sym; /* index of code symbols */
  84681. unsigned min, max; /* minimum and maximum code lengths */
  84682. unsigned root; /* number of index bits for root table */
  84683. unsigned curr; /* number of index bits for current table */
  84684. unsigned drop; /* code bits to drop for sub-table */
  84685. int left; /* number of prefix codes available */
  84686. unsigned used; /* code entries in table used */
  84687. unsigned huff; /* Huffman code */
  84688. unsigned incr; /* for incrementing code, index */
  84689. unsigned fill; /* index for replicating entries */
  84690. unsigned low; /* low bits for current root entry */
  84691. unsigned mask; /* mask for low root bits */
  84692. code thisx; /* table entry for duplication */
  84693. code FAR *next; /* next available space in table */
  84694. const unsigned short FAR *base; /* base value table to use */
  84695. const unsigned short FAR *extra; /* extra bits table to use */
  84696. int end; /* use base and extra for symbol > end */
  84697. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84698. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84699. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84700. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84701. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84702. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84703. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84704. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84705. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84706. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84707. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84708. 8193, 12289, 16385, 24577, 0, 0};
  84709. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84710. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84711. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84712. 28, 28, 29, 29, 64, 64};
  84713. /*
  84714. Process a set of code lengths to create a canonical Huffman code. The
  84715. code lengths are lens[0..codes-1]. Each length corresponds to the
  84716. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84717. symbols by length from short to long, and retaining the symbol order
  84718. for codes with equal lengths. Then the code starts with all zero bits
  84719. for the first code of the shortest length, and the codes are integer
  84720. increments for the same length, and zeros are appended as the length
  84721. increases. For the deflate format, these bits are stored backwards
  84722. from their more natural integer increment ordering, and so when the
  84723. decoding tables are built in the large loop below, the integer codes
  84724. are incremented backwards.
  84725. This routine assumes, but does not check, that all of the entries in
  84726. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84727. 1..MAXBITS is interpreted as that code length. zero means that that
  84728. symbol does not occur in this code.
  84729. The codes are sorted by computing a count of codes for each length,
  84730. creating from that a table of starting indices for each length in the
  84731. sorted table, and then entering the symbols in order in the sorted
  84732. table. The sorted table is work[], with that space being provided by
  84733. the caller.
  84734. The length counts are used for other purposes as well, i.e. finding
  84735. the minimum and maximum length codes, determining if there are any
  84736. codes at all, checking for a valid set of lengths, and looking ahead
  84737. at length counts to determine sub-table sizes when building the
  84738. decoding tables.
  84739. */
  84740. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84741. for (len = 0; len <= MAXBITS; len++)
  84742. count[len] = 0;
  84743. for (sym = 0; sym < codes; sym++)
  84744. count[lens[sym]]++;
  84745. /* bound code lengths, force root to be within code lengths */
  84746. root = *bits;
  84747. for (max = MAXBITS; max >= 1; max--)
  84748. if (count[max] != 0) break;
  84749. if (root > max) root = max;
  84750. if (max == 0) { /* no symbols to code at all */
  84751. thisx.op = (unsigned char)64; /* invalid code marker */
  84752. thisx.bits = (unsigned char)1;
  84753. thisx.val = (unsigned short)0;
  84754. *(*table)++ = thisx; /* make a table to force an error */
  84755. *(*table)++ = thisx;
  84756. *bits = 1;
  84757. return 0; /* no symbols, but wait for decoding to report error */
  84758. }
  84759. for (min = 1; min <= MAXBITS; min++)
  84760. if (count[min] != 0) break;
  84761. if (root < min) root = min;
  84762. /* check for an over-subscribed or incomplete set of lengths */
  84763. left = 1;
  84764. for (len = 1; len <= MAXBITS; len++) {
  84765. left <<= 1;
  84766. left -= count[len];
  84767. if (left < 0) return -1; /* over-subscribed */
  84768. }
  84769. if (left > 0 && (type == CODES || max != 1))
  84770. return -1; /* incomplete set */
  84771. /* generate offsets into symbol table for each length for sorting */
  84772. offs[1] = 0;
  84773. for (len = 1; len < MAXBITS; len++)
  84774. offs[len + 1] = offs[len] + count[len];
  84775. /* sort symbols by length, by symbol order within each length */
  84776. for (sym = 0; sym < codes; sym++)
  84777. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84778. /*
  84779. Create and fill in decoding tables. In this loop, the table being
  84780. filled is at next and has curr index bits. The code being used is huff
  84781. with length len. That code is converted to an index by dropping drop
  84782. bits off of the bottom. For codes where len is less than drop + curr,
  84783. those top drop + curr - len bits are incremented through all values to
  84784. fill the table with replicated entries.
  84785. root is the number of index bits for the root table. When len exceeds
  84786. root, sub-tables are created pointed to by the root entry with an index
  84787. of the low root bits of huff. This is saved in low to check for when a
  84788. new sub-table should be started. drop is zero when the root table is
  84789. being filled, and drop is root when sub-tables are being filled.
  84790. When a new sub-table is needed, it is necessary to look ahead in the
  84791. code lengths to determine what size sub-table is needed. The length
  84792. counts are used for this, and so count[] is decremented as codes are
  84793. entered in the tables.
  84794. used keeps track of how many table entries have been allocated from the
  84795. provided *table space. It is checked when a LENS table is being made
  84796. against the space in *table, ENOUGH, minus the maximum space needed by
  84797. the worst case distance code, MAXD. This should never happen, but the
  84798. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84799. This assumes that when type == LENS, bits == 9.
  84800. sym increments through all symbols, and the loop terminates when
  84801. all codes of length max, i.e. all codes, have been processed. This
  84802. routine permits incomplete codes, so another loop after this one fills
  84803. in the rest of the decoding tables with invalid code markers.
  84804. */
  84805. /* set up for code type */
  84806. switch (type) {
  84807. case CODES:
  84808. base = extra = work; /* dummy value--not used */
  84809. end = 19;
  84810. break;
  84811. case LENS:
  84812. base = lbase;
  84813. base -= 257;
  84814. extra = lext;
  84815. extra -= 257;
  84816. end = 256;
  84817. break;
  84818. default: /* DISTS */
  84819. base = dbase;
  84820. extra = dext;
  84821. end = -1;
  84822. }
  84823. /* initialize state for loop */
  84824. huff = 0; /* starting code */
  84825. sym = 0; /* starting code symbol */
  84826. len = min; /* starting code length */
  84827. next = *table; /* current table to fill in */
  84828. curr = root; /* current table index bits */
  84829. drop = 0; /* current bits to drop from code for index */
  84830. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84831. used = 1U << root; /* use root table entries */
  84832. mask = used - 1; /* mask for comparing low */
  84833. /* check available table space */
  84834. if (type == LENS && used >= ENOUGH - MAXD)
  84835. return 1;
  84836. /* process all codes and make table entries */
  84837. for (;;) {
  84838. /* create table entry */
  84839. thisx.bits = (unsigned char)(len - drop);
  84840. if ((int)(work[sym]) < end) {
  84841. thisx.op = (unsigned char)0;
  84842. thisx.val = work[sym];
  84843. }
  84844. else if ((int)(work[sym]) > end) {
  84845. thisx.op = (unsigned char)(extra[work[sym]]);
  84846. thisx.val = base[work[sym]];
  84847. }
  84848. else {
  84849. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84850. thisx.val = 0;
  84851. }
  84852. /* replicate for those indices with low len bits equal to huff */
  84853. incr = 1U << (len - drop);
  84854. fill = 1U << curr;
  84855. min = fill; /* save offset to next table */
  84856. do {
  84857. fill -= incr;
  84858. next[(huff >> drop) + fill] = thisx;
  84859. } while (fill != 0);
  84860. /* backwards increment the len-bit code huff */
  84861. incr = 1U << (len - 1);
  84862. while (huff & incr)
  84863. incr >>= 1;
  84864. if (incr != 0) {
  84865. huff &= incr - 1;
  84866. huff += incr;
  84867. }
  84868. else
  84869. huff = 0;
  84870. /* go to next symbol, update count, len */
  84871. sym++;
  84872. if (--(count[len]) == 0) {
  84873. if (len == max) break;
  84874. len = lens[work[sym]];
  84875. }
  84876. /* create new sub-table if needed */
  84877. if (len > root && (huff & mask) != low) {
  84878. /* if first time, transition to sub-tables */
  84879. if (drop == 0)
  84880. drop = root;
  84881. /* increment past last table */
  84882. next += min; /* here min is 1 << curr */
  84883. /* determine length of next table */
  84884. curr = len - drop;
  84885. left = (int)(1 << curr);
  84886. while (curr + drop < max) {
  84887. left -= count[curr + drop];
  84888. if (left <= 0) break;
  84889. curr++;
  84890. left <<= 1;
  84891. }
  84892. /* check for enough space */
  84893. used += 1U << curr;
  84894. if (type == LENS && used >= ENOUGH - MAXD)
  84895. return 1;
  84896. /* point entry in root table to sub-table */
  84897. low = huff & mask;
  84898. (*table)[low].op = (unsigned char)curr;
  84899. (*table)[low].bits = (unsigned char)root;
  84900. (*table)[low].val = (unsigned short)(next - *table);
  84901. }
  84902. }
  84903. /*
  84904. Fill in rest of table for incomplete codes. This loop is similar to the
  84905. loop above in incrementing huff for table indices. It is assumed that
  84906. len is equal to curr + drop, so there is no loop needed to increment
  84907. through high index bits. When the current sub-table is filled, the loop
  84908. drops back to the root table to fill in any remaining entries there.
  84909. */
  84910. thisx.op = (unsigned char)64; /* invalid code marker */
  84911. thisx.bits = (unsigned char)(len - drop);
  84912. thisx.val = (unsigned short)0;
  84913. while (huff != 0) {
  84914. /* when done with sub-table, drop back to root table */
  84915. if (drop != 0 && (huff & mask) != low) {
  84916. drop = 0;
  84917. len = root;
  84918. next = *table;
  84919. thisx.bits = (unsigned char)len;
  84920. }
  84921. /* put invalid code marker in table */
  84922. next[huff >> drop] = thisx;
  84923. /* backwards increment the len-bit code huff */
  84924. incr = 1U << (len - 1);
  84925. while (huff & incr)
  84926. incr >>= 1;
  84927. if (incr != 0) {
  84928. huff &= incr - 1;
  84929. huff += incr;
  84930. }
  84931. else
  84932. huff = 0;
  84933. }
  84934. /* set return parameters */
  84935. *table += used;
  84936. *bits = root;
  84937. return 0;
  84938. }
  84939. /*** End of inlined file: inftrees.c ***/
  84940. /*** Start of inlined file: trees.c ***/
  84941. /*
  84942. * ALGORITHM
  84943. *
  84944. * The "deflation" process uses several Huffman trees. The more
  84945. * common source values are represented by shorter bit sequences.
  84946. *
  84947. * Each code tree is stored in a compressed form which is itself
  84948. * a Huffman encoding of the lengths of all the code strings (in
  84949. * ascending order by source values). The actual code strings are
  84950. * reconstructed from the lengths in the inflate process, as described
  84951. * in the deflate specification.
  84952. *
  84953. * REFERENCES
  84954. *
  84955. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84956. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84957. *
  84958. * Storer, James A.
  84959. * Data Compression: Methods and Theory, pp. 49-50.
  84960. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84961. *
  84962. * Sedgewick, R.
  84963. * Algorithms, p290.
  84964. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84965. */
  84966. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84967. /* #define GEN_TREES_H */
  84968. #ifdef DEBUG
  84969. # include <ctype.h>
  84970. #endif
  84971. /* ===========================================================================
  84972. * Constants
  84973. */
  84974. #define MAX_BL_BITS 7
  84975. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84976. #define END_BLOCK 256
  84977. /* end of block literal code */
  84978. #define REP_3_6 16
  84979. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84980. #define REPZ_3_10 17
  84981. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84982. #define REPZ_11_138 18
  84983. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84984. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84985. = {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};
  84986. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84987. = {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};
  84988. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84989. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84990. local const uch bl_order[BL_CODES]
  84991. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84992. /* The lengths of the bit length codes are sent in order of decreasing
  84993. * probability, to avoid transmitting the lengths for unused bit length codes.
  84994. */
  84995. #define Buf_size (8 * 2*sizeof(char))
  84996. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84997. * more than 16 bits on some systems.)
  84998. */
  84999. /* ===========================================================================
  85000. * Local data. These are initialized only once.
  85001. */
  85002. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  85003. #if defined(GEN_TREES_H) || !defined(STDC)
  85004. /* non ANSI compilers may not accept trees.h */
  85005. local ct_data static_ltree[L_CODES+2];
  85006. /* The static literal tree. Since the bit lengths are imposed, there is no
  85007. * need for the L_CODES extra codes used during heap construction. However
  85008. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  85009. * below).
  85010. */
  85011. local ct_data static_dtree[D_CODES];
  85012. /* The static distance tree. (Actually a trivial tree since all codes use
  85013. * 5 bits.)
  85014. */
  85015. uch _dist_code[DIST_CODE_LEN];
  85016. /* Distance codes. The first 256 values correspond to the distances
  85017. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  85018. * the 15 bit distances.
  85019. */
  85020. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  85021. /* length code for each normalized match length (0 == MIN_MATCH) */
  85022. local int base_length[LENGTH_CODES];
  85023. /* First normalized length for each code (0 = MIN_MATCH) */
  85024. local int base_dist[D_CODES];
  85025. /* First normalized distance for each code (0 = distance of 1) */
  85026. #else
  85027. /*** Start of inlined file: trees.h ***/
  85028. local const ct_data static_ltree[L_CODES+2] = {
  85029. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  85030. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  85031. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  85032. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  85033. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  85034. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  85035. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  85036. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  85037. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  85038. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  85039. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  85040. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  85041. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  85042. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  85043. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  85044. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  85045. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  85046. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  85047. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  85048. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  85049. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  85050. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  85051. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  85052. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  85053. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  85054. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  85055. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  85056. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  85057. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  85058. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  85059. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  85060. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  85061. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  85062. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  85063. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  85064. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  85065. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  85066. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  85067. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  85068. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  85069. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  85070. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  85071. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  85072. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  85073. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  85074. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  85075. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  85076. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  85077. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  85078. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  85079. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  85080. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  85081. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  85082. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  85083. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  85084. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  85085. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  85086. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  85087. };
  85088. local const ct_data static_dtree[D_CODES] = {
  85089. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  85090. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  85091. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  85092. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  85093. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  85094. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  85095. };
  85096. const uch _dist_code[DIST_CODE_LEN] = {
  85097. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  85098. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  85099. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  85100. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  85101. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  85102. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  85103. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85104. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85105. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85106. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  85107. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85108. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85109. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  85110. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  85111. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85112. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85113. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85114. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  85115. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85116. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85117. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85118. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85119. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85120. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85121. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85122. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  85123. };
  85124. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  85125. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  85126. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  85127. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  85128. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  85129. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  85130. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  85131. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85132. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85133. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85134. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  85135. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85136. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85137. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  85138. };
  85139. local const int base_length[LENGTH_CODES] = {
  85140. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  85141. 64, 80, 96, 112, 128, 160, 192, 224, 0
  85142. };
  85143. local const int base_dist[D_CODES] = {
  85144. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  85145. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  85146. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  85147. };
  85148. /*** End of inlined file: trees.h ***/
  85149. #endif /* GEN_TREES_H */
  85150. struct static_tree_desc_s {
  85151. const ct_data *static_tree; /* static tree or NULL */
  85152. const intf *extra_bits; /* extra bits for each code or NULL */
  85153. int extra_base; /* base index for extra_bits */
  85154. int elems; /* max number of elements in the tree */
  85155. int max_length; /* max bit length for the codes */
  85156. };
  85157. local static_tree_desc static_l_desc =
  85158. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  85159. local static_tree_desc static_d_desc =
  85160. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  85161. local static_tree_desc static_bl_desc =
  85162. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  85163. /* ===========================================================================
  85164. * Local (static) routines in this file.
  85165. */
  85166. local void tr_static_init OF((void));
  85167. local void init_block OF((deflate_state *s));
  85168. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  85169. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  85170. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  85171. local void build_tree OF((deflate_state *s, tree_desc *desc));
  85172. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85173. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85174. local int build_bl_tree OF((deflate_state *s));
  85175. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  85176. int blcodes));
  85177. local void compress_block OF((deflate_state *s, ct_data *ltree,
  85178. ct_data *dtree));
  85179. local void set_data_type OF((deflate_state *s));
  85180. local unsigned bi_reverse OF((unsigned value, int length));
  85181. local void bi_windup OF((deflate_state *s));
  85182. local void bi_flush OF((deflate_state *s));
  85183. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  85184. int header));
  85185. #ifdef GEN_TREES_H
  85186. local void gen_trees_header OF((void));
  85187. #endif
  85188. #ifndef DEBUG
  85189. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  85190. /* Send a code of the given tree. c and tree must not have side effects */
  85191. #else /* DEBUG */
  85192. # define send_code(s, c, tree) \
  85193. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  85194. send_bits(s, tree[c].Code, tree[c].Len); }
  85195. #endif
  85196. /* ===========================================================================
  85197. * Output a short LSB first on the stream.
  85198. * IN assertion: there is enough room in pendingBuf.
  85199. */
  85200. #define put_short(s, w) { \
  85201. put_byte(s, (uch)((w) & 0xff)); \
  85202. put_byte(s, (uch)((ush)(w) >> 8)); \
  85203. }
  85204. /* ===========================================================================
  85205. * Send a value on a given number of bits.
  85206. * IN assertion: length <= 16 and value fits in length bits.
  85207. */
  85208. #ifdef DEBUG
  85209. local void send_bits OF((deflate_state *s, int value, int length));
  85210. local void send_bits (deflate_state *s, int value, int length)
  85211. {
  85212. Tracevv((stderr," l %2d v %4x ", length, value));
  85213. Assert(length > 0 && length <= 15, "invalid length");
  85214. s->bits_sent += (ulg)length;
  85215. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85216. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85217. * unused bits in value.
  85218. */
  85219. if (s->bi_valid > (int)Buf_size - length) {
  85220. s->bi_buf |= (value << s->bi_valid);
  85221. put_short(s, s->bi_buf);
  85222. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85223. s->bi_valid += length - Buf_size;
  85224. } else {
  85225. s->bi_buf |= value << s->bi_valid;
  85226. s->bi_valid += length;
  85227. }
  85228. }
  85229. #else /* !DEBUG */
  85230. #define send_bits(s, value, length) \
  85231. { int len = length;\
  85232. if (s->bi_valid > (int)Buf_size - len) {\
  85233. int val = value;\
  85234. s->bi_buf |= (val << s->bi_valid);\
  85235. put_short(s, s->bi_buf);\
  85236. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85237. s->bi_valid += len - Buf_size;\
  85238. } else {\
  85239. s->bi_buf |= (value) << s->bi_valid;\
  85240. s->bi_valid += len;\
  85241. }\
  85242. }
  85243. #endif /* DEBUG */
  85244. /* the arguments must not have side effects */
  85245. /* ===========================================================================
  85246. * Initialize the various 'constant' tables.
  85247. */
  85248. local void tr_static_init()
  85249. {
  85250. #if defined(GEN_TREES_H) || !defined(STDC)
  85251. static int static_init_done = 0;
  85252. int n; /* iterates over tree elements */
  85253. int bits; /* bit counter */
  85254. int length; /* length value */
  85255. int code; /* code value */
  85256. int dist; /* distance index */
  85257. ush bl_count[MAX_BITS+1];
  85258. /* number of codes at each bit length for an optimal tree */
  85259. if (static_init_done) return;
  85260. /* For some embedded targets, global variables are not initialized: */
  85261. static_l_desc.static_tree = static_ltree;
  85262. static_l_desc.extra_bits = extra_lbits;
  85263. static_d_desc.static_tree = static_dtree;
  85264. static_d_desc.extra_bits = extra_dbits;
  85265. static_bl_desc.extra_bits = extra_blbits;
  85266. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85267. length = 0;
  85268. for (code = 0; code < LENGTH_CODES-1; code++) {
  85269. base_length[code] = length;
  85270. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85271. _length_code[length++] = (uch)code;
  85272. }
  85273. }
  85274. Assert (length == 256, "tr_static_init: length != 256");
  85275. /* Note that the length 255 (match length 258) can be represented
  85276. * in two different ways: code 284 + 5 bits or code 285, so we
  85277. * overwrite length_code[255] to use the best encoding:
  85278. */
  85279. _length_code[length-1] = (uch)code;
  85280. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85281. dist = 0;
  85282. for (code = 0 ; code < 16; code++) {
  85283. base_dist[code] = dist;
  85284. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85285. _dist_code[dist++] = (uch)code;
  85286. }
  85287. }
  85288. Assert (dist == 256, "tr_static_init: dist != 256");
  85289. dist >>= 7; /* from now on, all distances are divided by 128 */
  85290. for ( ; code < D_CODES; code++) {
  85291. base_dist[code] = dist << 7;
  85292. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85293. _dist_code[256 + dist++] = (uch)code;
  85294. }
  85295. }
  85296. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85297. /* Construct the codes of the static literal tree */
  85298. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85299. n = 0;
  85300. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85301. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85302. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85303. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85304. /* Codes 286 and 287 do not exist, but we must include them in the
  85305. * tree construction to get a canonical Huffman tree (longest code
  85306. * all ones)
  85307. */
  85308. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85309. /* The static distance tree is trivial: */
  85310. for (n = 0; n < D_CODES; n++) {
  85311. static_dtree[n].Len = 5;
  85312. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85313. }
  85314. static_init_done = 1;
  85315. # ifdef GEN_TREES_H
  85316. gen_trees_header();
  85317. # endif
  85318. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85319. }
  85320. /* ===========================================================================
  85321. * Genererate the file trees.h describing the static trees.
  85322. */
  85323. #ifdef GEN_TREES_H
  85324. # ifndef DEBUG
  85325. # include <stdio.h>
  85326. # endif
  85327. # define SEPARATOR(i, last, width) \
  85328. ((i) == (last)? "\n};\n\n" : \
  85329. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85330. void gen_trees_header()
  85331. {
  85332. FILE *header = fopen("trees.h", "w");
  85333. int i;
  85334. Assert (header != NULL, "Can't open trees.h");
  85335. fprintf(header,
  85336. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85337. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85338. for (i = 0; i < L_CODES+2; i++) {
  85339. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85340. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85341. }
  85342. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85343. for (i = 0; i < D_CODES; i++) {
  85344. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85345. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85346. }
  85347. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85348. for (i = 0; i < DIST_CODE_LEN; i++) {
  85349. fprintf(header, "%2u%s", _dist_code[i],
  85350. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85351. }
  85352. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85353. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85354. fprintf(header, "%2u%s", _length_code[i],
  85355. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85356. }
  85357. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85358. for (i = 0; i < LENGTH_CODES; i++) {
  85359. fprintf(header, "%1u%s", base_length[i],
  85360. SEPARATOR(i, LENGTH_CODES-1, 20));
  85361. }
  85362. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85363. for (i = 0; i < D_CODES; i++) {
  85364. fprintf(header, "%5u%s", base_dist[i],
  85365. SEPARATOR(i, D_CODES-1, 10));
  85366. }
  85367. fclose(header);
  85368. }
  85369. #endif /* GEN_TREES_H */
  85370. /* ===========================================================================
  85371. * Initialize the tree data structures for a new zlib stream.
  85372. */
  85373. void _tr_init(deflate_state *s)
  85374. {
  85375. tr_static_init();
  85376. s->l_desc.dyn_tree = s->dyn_ltree;
  85377. s->l_desc.stat_desc = &static_l_desc;
  85378. s->d_desc.dyn_tree = s->dyn_dtree;
  85379. s->d_desc.stat_desc = &static_d_desc;
  85380. s->bl_desc.dyn_tree = s->bl_tree;
  85381. s->bl_desc.stat_desc = &static_bl_desc;
  85382. s->bi_buf = 0;
  85383. s->bi_valid = 0;
  85384. s->last_eob_len = 8; /* enough lookahead for inflate */
  85385. #ifdef DEBUG
  85386. s->compressed_len = 0L;
  85387. s->bits_sent = 0L;
  85388. #endif
  85389. /* Initialize the first block of the first file: */
  85390. init_block(s);
  85391. }
  85392. /* ===========================================================================
  85393. * Initialize a new block.
  85394. */
  85395. local void init_block (deflate_state *s)
  85396. {
  85397. int n; /* iterates over tree elements */
  85398. /* Initialize the trees. */
  85399. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85400. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85401. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85402. s->dyn_ltree[END_BLOCK].Freq = 1;
  85403. s->opt_len = s->static_len = 0L;
  85404. s->last_lit = s->matches = 0;
  85405. }
  85406. #define SMALLEST 1
  85407. /* Index within the heap array of least frequent node in the Huffman tree */
  85408. /* ===========================================================================
  85409. * Remove the smallest element from the heap and recreate the heap with
  85410. * one less element. Updates heap and heap_len.
  85411. */
  85412. #define pqremove(s, tree, top) \
  85413. {\
  85414. top = s->heap[SMALLEST]; \
  85415. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85416. pqdownheap(s, tree, SMALLEST); \
  85417. }
  85418. /* ===========================================================================
  85419. * Compares to subtrees, using the tree depth as tie breaker when
  85420. * the subtrees have equal frequency. This minimizes the worst case length.
  85421. */
  85422. #define smaller(tree, n, m, depth) \
  85423. (tree[n].Freq < tree[m].Freq || \
  85424. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85425. /* ===========================================================================
  85426. * Restore the heap property by moving down the tree starting at node k,
  85427. * exchanging a node with the smallest of its two sons if necessary, stopping
  85428. * when the heap property is re-established (each father smaller than its
  85429. * two sons).
  85430. */
  85431. local void pqdownheap (deflate_state *s,
  85432. ct_data *tree, /* the tree to restore */
  85433. int k) /* node to move down */
  85434. {
  85435. int v = s->heap[k];
  85436. int j = k << 1; /* left son of k */
  85437. while (j <= s->heap_len) {
  85438. /* Set j to the smallest of the two sons: */
  85439. if (j < s->heap_len &&
  85440. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85441. j++;
  85442. }
  85443. /* Exit if v is smaller than both sons */
  85444. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85445. /* Exchange v with the smallest son */
  85446. s->heap[k] = s->heap[j]; k = j;
  85447. /* And continue down the tree, setting j to the left son of k */
  85448. j <<= 1;
  85449. }
  85450. s->heap[k] = v;
  85451. }
  85452. /* ===========================================================================
  85453. * Compute the optimal bit lengths for a tree and update the total bit length
  85454. * for the current block.
  85455. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85456. * above are the tree nodes sorted by increasing frequency.
  85457. * OUT assertions: the field len is set to the optimal bit length, the
  85458. * array bl_count contains the frequencies for each bit length.
  85459. * The length opt_len is updated; static_len is also updated if stree is
  85460. * not null.
  85461. */
  85462. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85463. {
  85464. ct_data *tree = desc->dyn_tree;
  85465. int max_code = desc->max_code;
  85466. const ct_data *stree = desc->stat_desc->static_tree;
  85467. const intf *extra = desc->stat_desc->extra_bits;
  85468. int base = desc->stat_desc->extra_base;
  85469. int max_length = desc->stat_desc->max_length;
  85470. int h; /* heap index */
  85471. int n, m; /* iterate over the tree elements */
  85472. int bits; /* bit length */
  85473. int xbits; /* extra bits */
  85474. ush f; /* frequency */
  85475. int overflow = 0; /* number of elements with bit length too large */
  85476. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85477. /* In a first pass, compute the optimal bit lengths (which may
  85478. * overflow in the case of the bit length tree).
  85479. */
  85480. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85481. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85482. n = s->heap[h];
  85483. bits = tree[tree[n].Dad].Len + 1;
  85484. if (bits > max_length) bits = max_length, overflow++;
  85485. tree[n].Len = (ush)bits;
  85486. /* We overwrite tree[n].Dad which is no longer needed */
  85487. if (n > max_code) continue; /* not a leaf node */
  85488. s->bl_count[bits]++;
  85489. xbits = 0;
  85490. if (n >= base) xbits = extra[n-base];
  85491. f = tree[n].Freq;
  85492. s->opt_len += (ulg)f * (bits + xbits);
  85493. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85494. }
  85495. if (overflow == 0) return;
  85496. Trace((stderr,"\nbit length overflow\n"));
  85497. /* This happens for example on obj2 and pic of the Calgary corpus */
  85498. /* Find the first bit length which could increase: */
  85499. do {
  85500. bits = max_length-1;
  85501. while (s->bl_count[bits] == 0) bits--;
  85502. s->bl_count[bits]--; /* move one leaf down the tree */
  85503. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85504. s->bl_count[max_length]--;
  85505. /* The brother of the overflow item also moves one step up,
  85506. * but this does not affect bl_count[max_length]
  85507. */
  85508. overflow -= 2;
  85509. } while (overflow > 0);
  85510. /* Now recompute all bit lengths, scanning in increasing frequency.
  85511. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85512. * lengths instead of fixing only the wrong ones. This idea is taken
  85513. * from 'ar' written by Haruhiko Okumura.)
  85514. */
  85515. for (bits = max_length; bits != 0; bits--) {
  85516. n = s->bl_count[bits];
  85517. while (n != 0) {
  85518. m = s->heap[--h];
  85519. if (m > max_code) continue;
  85520. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85521. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85522. s->opt_len += ((long)bits - (long)tree[m].Len)
  85523. *(long)tree[m].Freq;
  85524. tree[m].Len = (ush)bits;
  85525. }
  85526. n--;
  85527. }
  85528. }
  85529. }
  85530. /* ===========================================================================
  85531. * Generate the codes for a given tree and bit counts (which need not be
  85532. * optimal).
  85533. * IN assertion: the array bl_count contains the bit length statistics for
  85534. * the given tree and the field len is set for all tree elements.
  85535. * OUT assertion: the field code is set for all tree elements of non
  85536. * zero code length.
  85537. */
  85538. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85539. int max_code, /* largest code with non zero frequency */
  85540. ushf *bl_count) /* number of codes at each bit length */
  85541. {
  85542. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85543. ush code = 0; /* running code value */
  85544. int bits; /* bit index */
  85545. int n; /* code index */
  85546. /* The distribution counts are first used to generate the code values
  85547. * without bit reversal.
  85548. */
  85549. for (bits = 1; bits <= MAX_BITS; bits++) {
  85550. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85551. }
  85552. /* Check that the bit counts in bl_count are consistent. The last code
  85553. * must be all ones.
  85554. */
  85555. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85556. "inconsistent bit counts");
  85557. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85558. for (n = 0; n <= max_code; n++) {
  85559. int len = tree[n].Len;
  85560. if (len == 0) continue;
  85561. /* Now reverse the bits */
  85562. tree[n].Code = bi_reverse(next_code[len]++, len);
  85563. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85564. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85565. }
  85566. }
  85567. /* ===========================================================================
  85568. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85569. * Update the total bit length for the current block.
  85570. * IN assertion: the field freq is set for all tree elements.
  85571. * OUT assertions: the fields len and code are set to the optimal bit length
  85572. * and corresponding code. The length opt_len is updated; static_len is
  85573. * also updated if stree is not null. The field max_code is set.
  85574. */
  85575. local void build_tree (deflate_state *s,
  85576. tree_desc *desc) /* the tree descriptor */
  85577. {
  85578. ct_data *tree = desc->dyn_tree;
  85579. const ct_data *stree = desc->stat_desc->static_tree;
  85580. int elems = desc->stat_desc->elems;
  85581. int n, m; /* iterate over heap elements */
  85582. int max_code = -1; /* largest code with non zero frequency */
  85583. int node; /* new node being created */
  85584. /* Construct the initial heap, with least frequent element in
  85585. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85586. * heap[0] is not used.
  85587. */
  85588. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85589. for (n = 0; n < elems; n++) {
  85590. if (tree[n].Freq != 0) {
  85591. s->heap[++(s->heap_len)] = max_code = n;
  85592. s->depth[n] = 0;
  85593. } else {
  85594. tree[n].Len = 0;
  85595. }
  85596. }
  85597. /* The pkzip format requires that at least one distance code exists,
  85598. * and that at least one bit should be sent even if there is only one
  85599. * possible code. So to avoid special checks later on we force at least
  85600. * two codes of non zero frequency.
  85601. */
  85602. while (s->heap_len < 2) {
  85603. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85604. tree[node].Freq = 1;
  85605. s->depth[node] = 0;
  85606. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85607. /* node is 0 or 1 so it does not have extra bits */
  85608. }
  85609. desc->max_code = max_code;
  85610. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85611. * establish sub-heaps of increasing lengths:
  85612. */
  85613. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85614. /* Construct the Huffman tree by repeatedly combining the least two
  85615. * frequent nodes.
  85616. */
  85617. node = elems; /* next internal node of the tree */
  85618. do {
  85619. pqremove(s, tree, n); /* n = node of least frequency */
  85620. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85621. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85622. s->heap[--(s->heap_max)] = m;
  85623. /* Create a new node father of n and m */
  85624. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85625. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85626. s->depth[n] : s->depth[m]) + 1);
  85627. tree[n].Dad = tree[m].Dad = (ush)node;
  85628. #ifdef DUMP_BL_TREE
  85629. if (tree == s->bl_tree) {
  85630. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85631. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85632. }
  85633. #endif
  85634. /* and insert the new node in the heap */
  85635. s->heap[SMALLEST] = node++;
  85636. pqdownheap(s, tree, SMALLEST);
  85637. } while (s->heap_len >= 2);
  85638. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85639. /* At this point, the fields freq and dad are set. We can now
  85640. * generate the bit lengths.
  85641. */
  85642. gen_bitlen(s, (tree_desc *)desc);
  85643. /* The field len is now set, we can generate the bit codes */
  85644. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85645. }
  85646. /* ===========================================================================
  85647. * Scan a literal or distance tree to determine the frequencies of the codes
  85648. * in the bit length tree.
  85649. */
  85650. local void scan_tree (deflate_state *s,
  85651. ct_data *tree, /* the tree to be scanned */
  85652. int max_code) /* and its largest code of non zero frequency */
  85653. {
  85654. int n; /* iterates over all tree elements */
  85655. int prevlen = -1; /* last emitted length */
  85656. int curlen; /* length of current code */
  85657. int nextlen = tree[0].Len; /* length of next code */
  85658. int count = 0; /* repeat count of the current code */
  85659. int max_count = 7; /* max repeat count */
  85660. int min_count = 4; /* min repeat count */
  85661. if (nextlen == 0) max_count = 138, min_count = 3;
  85662. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85663. for (n = 0; n <= max_code; n++) {
  85664. curlen = nextlen; nextlen = tree[n+1].Len;
  85665. if (++count < max_count && curlen == nextlen) {
  85666. continue;
  85667. } else if (count < min_count) {
  85668. s->bl_tree[curlen].Freq += count;
  85669. } else if (curlen != 0) {
  85670. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85671. s->bl_tree[REP_3_6].Freq++;
  85672. } else if (count <= 10) {
  85673. s->bl_tree[REPZ_3_10].Freq++;
  85674. } else {
  85675. s->bl_tree[REPZ_11_138].Freq++;
  85676. }
  85677. count = 0; prevlen = curlen;
  85678. if (nextlen == 0) {
  85679. max_count = 138, min_count = 3;
  85680. } else if (curlen == nextlen) {
  85681. max_count = 6, min_count = 3;
  85682. } else {
  85683. max_count = 7, min_count = 4;
  85684. }
  85685. }
  85686. }
  85687. /* ===========================================================================
  85688. * Send a literal or distance tree in compressed form, using the codes in
  85689. * bl_tree.
  85690. */
  85691. local void send_tree (deflate_state *s,
  85692. ct_data *tree, /* the tree to be scanned */
  85693. int max_code) /* and its largest code of non zero frequency */
  85694. {
  85695. int n; /* iterates over all tree elements */
  85696. int prevlen = -1; /* last emitted length */
  85697. int curlen; /* length of current code */
  85698. int nextlen = tree[0].Len; /* length of next code */
  85699. int count = 0; /* repeat count of the current code */
  85700. int max_count = 7; /* max repeat count */
  85701. int min_count = 4; /* min repeat count */
  85702. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85703. if (nextlen == 0) max_count = 138, min_count = 3;
  85704. for (n = 0; n <= max_code; n++) {
  85705. curlen = nextlen; nextlen = tree[n+1].Len;
  85706. if (++count < max_count && curlen == nextlen) {
  85707. continue;
  85708. } else if (count < min_count) {
  85709. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85710. } else if (curlen != 0) {
  85711. if (curlen != prevlen) {
  85712. send_code(s, curlen, s->bl_tree); count--;
  85713. }
  85714. Assert(count >= 3 && count <= 6, " 3_6?");
  85715. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85716. } else if (count <= 10) {
  85717. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85718. } else {
  85719. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85720. }
  85721. count = 0; prevlen = curlen;
  85722. if (nextlen == 0) {
  85723. max_count = 138, min_count = 3;
  85724. } else if (curlen == nextlen) {
  85725. max_count = 6, min_count = 3;
  85726. } else {
  85727. max_count = 7, min_count = 4;
  85728. }
  85729. }
  85730. }
  85731. /* ===========================================================================
  85732. * Construct the Huffman tree for the bit lengths and return the index in
  85733. * bl_order of the last bit length code to send.
  85734. */
  85735. local int build_bl_tree (deflate_state *s)
  85736. {
  85737. int max_blindex; /* index of last bit length code of non zero freq */
  85738. /* Determine the bit length frequencies for literal and distance trees */
  85739. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85740. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85741. /* Build the bit length tree: */
  85742. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85743. /* opt_len now includes the length of the tree representations, except
  85744. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85745. */
  85746. /* Determine the number of bit length codes to send. The pkzip format
  85747. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85748. * 3 but the actual value used is 4.)
  85749. */
  85750. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85751. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85752. }
  85753. /* Update opt_len to include the bit length tree and counts */
  85754. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85755. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85756. s->opt_len, s->static_len));
  85757. return max_blindex;
  85758. }
  85759. /* ===========================================================================
  85760. * Send the header for a block using dynamic Huffman trees: the counts, the
  85761. * lengths of the bit length codes, the literal tree and the distance tree.
  85762. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85763. */
  85764. local void send_all_trees (deflate_state *s,
  85765. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85766. {
  85767. int rank; /* index in bl_order */
  85768. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85769. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85770. "too many codes");
  85771. Tracev((stderr, "\nbl counts: "));
  85772. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85773. send_bits(s, dcodes-1, 5);
  85774. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85775. for (rank = 0; rank < blcodes; rank++) {
  85776. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85777. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85778. }
  85779. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85780. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85781. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85782. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85783. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85784. }
  85785. /* ===========================================================================
  85786. * Send a stored block
  85787. */
  85788. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85789. {
  85790. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85791. #ifdef DEBUG
  85792. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85793. s->compressed_len += (stored_len + 4) << 3;
  85794. #endif
  85795. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85796. }
  85797. /* ===========================================================================
  85798. * Send one empty static block to give enough lookahead for inflate.
  85799. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85800. * The current inflate code requires 9 bits of lookahead. If the
  85801. * last two codes for the previous block (real code plus EOB) were coded
  85802. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85803. * the last real code. In this case we send two empty static blocks instead
  85804. * of one. (There are no problems if the previous block is stored or fixed.)
  85805. * To simplify the code, we assume the worst case of last real code encoded
  85806. * on one bit only.
  85807. */
  85808. void _tr_align (deflate_state *s)
  85809. {
  85810. send_bits(s, STATIC_TREES<<1, 3);
  85811. send_code(s, END_BLOCK, static_ltree);
  85812. #ifdef DEBUG
  85813. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85814. #endif
  85815. bi_flush(s);
  85816. /* Of the 10 bits for the empty block, we have already sent
  85817. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85818. * the EOB of the previous block) was thus at least one plus the length
  85819. * of the EOB plus what we have just sent of the empty static block.
  85820. */
  85821. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85822. send_bits(s, STATIC_TREES<<1, 3);
  85823. send_code(s, END_BLOCK, static_ltree);
  85824. #ifdef DEBUG
  85825. s->compressed_len += 10L;
  85826. #endif
  85827. bi_flush(s);
  85828. }
  85829. s->last_eob_len = 7;
  85830. }
  85831. /* ===========================================================================
  85832. * Determine the best encoding for the current block: dynamic trees, static
  85833. * trees or store, and output the encoded block to the zip file.
  85834. */
  85835. void _tr_flush_block (deflate_state *s,
  85836. charf *buf, /* input block, or NULL if too old */
  85837. ulg stored_len, /* length of input block */
  85838. int eof) /* true if this is the last block for a file */
  85839. {
  85840. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85841. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85842. /* Build the Huffman trees unless a stored block is forced */
  85843. if (s->level > 0) {
  85844. /* Check if the file is binary or text */
  85845. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85846. set_data_type(s);
  85847. /* Construct the literal and distance trees */
  85848. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85849. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85850. s->static_len));
  85851. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85852. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85853. s->static_len));
  85854. /* At this point, opt_len and static_len are the total bit lengths of
  85855. * the compressed block data, excluding the tree representations.
  85856. */
  85857. /* Build the bit length tree for the above two trees, and get the index
  85858. * in bl_order of the last bit length code to send.
  85859. */
  85860. max_blindex = build_bl_tree(s);
  85861. /* Determine the best encoding. Compute the block lengths in bytes. */
  85862. opt_lenb = (s->opt_len+3+7)>>3;
  85863. static_lenb = (s->static_len+3+7)>>3;
  85864. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85865. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85866. s->last_lit));
  85867. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85868. } else {
  85869. Assert(buf != (char*)0, "lost buf");
  85870. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85871. }
  85872. #ifdef FORCE_STORED
  85873. if (buf != (char*)0) { /* force stored block */
  85874. #else
  85875. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85876. /* 4: two words for the lengths */
  85877. #endif
  85878. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85879. * Otherwise we can't have processed more than WSIZE input bytes since
  85880. * the last block flush, because compression would have been
  85881. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85882. * transform a block into a stored block.
  85883. */
  85884. _tr_stored_block(s, buf, stored_len, eof);
  85885. #ifdef FORCE_STATIC
  85886. } else if (static_lenb >= 0) { /* force static trees */
  85887. #else
  85888. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85889. #endif
  85890. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85891. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85892. #ifdef DEBUG
  85893. s->compressed_len += 3 + s->static_len;
  85894. #endif
  85895. } else {
  85896. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85897. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85898. max_blindex+1);
  85899. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85900. #ifdef DEBUG
  85901. s->compressed_len += 3 + s->opt_len;
  85902. #endif
  85903. }
  85904. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85905. /* The above check is made mod 2^32, for files larger than 512 MB
  85906. * and uLong implemented on 32 bits.
  85907. */
  85908. init_block(s);
  85909. if (eof) {
  85910. bi_windup(s);
  85911. #ifdef DEBUG
  85912. s->compressed_len += 7; /* align on byte boundary */
  85913. #endif
  85914. }
  85915. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85916. s->compressed_len-7*eof));
  85917. }
  85918. /* ===========================================================================
  85919. * Save the match info and tally the frequency counts. Return true if
  85920. * the current block must be flushed.
  85921. */
  85922. int _tr_tally (deflate_state *s,
  85923. unsigned dist, /* distance of matched string */
  85924. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85925. {
  85926. s->d_buf[s->last_lit] = (ush)dist;
  85927. s->l_buf[s->last_lit++] = (uch)lc;
  85928. if (dist == 0) {
  85929. /* lc is the unmatched char */
  85930. s->dyn_ltree[lc].Freq++;
  85931. } else {
  85932. s->matches++;
  85933. /* Here, lc is the match length - MIN_MATCH */
  85934. dist--; /* dist = match distance - 1 */
  85935. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85936. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85937. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85938. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85939. s->dyn_dtree[d_code(dist)].Freq++;
  85940. }
  85941. #ifdef TRUNCATE_BLOCK
  85942. /* Try to guess if it is profitable to stop the current block here */
  85943. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85944. /* Compute an upper bound for the compressed length */
  85945. ulg out_length = (ulg)s->last_lit*8L;
  85946. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85947. int dcode;
  85948. for (dcode = 0; dcode < D_CODES; dcode++) {
  85949. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85950. (5L+extra_dbits[dcode]);
  85951. }
  85952. out_length >>= 3;
  85953. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85954. s->last_lit, in_length, out_length,
  85955. 100L - out_length*100L/in_length));
  85956. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85957. }
  85958. #endif
  85959. return (s->last_lit == s->lit_bufsize-1);
  85960. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85961. * on 16 bit machines and because stored blocks are restricted to
  85962. * 64K-1 bytes.
  85963. */
  85964. }
  85965. /* ===========================================================================
  85966. * Send the block data compressed using the given Huffman trees
  85967. */
  85968. local void compress_block (deflate_state *s,
  85969. ct_data *ltree, /* literal tree */
  85970. ct_data *dtree) /* distance tree */
  85971. {
  85972. unsigned dist; /* distance of matched string */
  85973. int lc; /* match length or unmatched char (if dist == 0) */
  85974. unsigned lx = 0; /* running index in l_buf */
  85975. unsigned code; /* the code to send */
  85976. int extra; /* number of extra bits to send */
  85977. if (s->last_lit != 0) do {
  85978. dist = s->d_buf[lx];
  85979. lc = s->l_buf[lx++];
  85980. if (dist == 0) {
  85981. send_code(s, lc, ltree); /* send a literal byte */
  85982. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85983. } else {
  85984. /* Here, lc is the match length - MIN_MATCH */
  85985. code = _length_code[lc];
  85986. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85987. extra = extra_lbits[code];
  85988. if (extra != 0) {
  85989. lc -= base_length[code];
  85990. send_bits(s, lc, extra); /* send the extra length bits */
  85991. }
  85992. dist--; /* dist is now the match distance - 1 */
  85993. code = d_code(dist);
  85994. Assert (code < D_CODES, "bad d_code");
  85995. send_code(s, code, dtree); /* send the distance code */
  85996. extra = extra_dbits[code];
  85997. if (extra != 0) {
  85998. dist -= base_dist[code];
  85999. send_bits(s, dist, extra); /* send the extra distance bits */
  86000. }
  86001. } /* literal or match pair ? */
  86002. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  86003. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  86004. "pendingBuf overflow");
  86005. } while (lx < s->last_lit);
  86006. send_code(s, END_BLOCK, ltree);
  86007. s->last_eob_len = ltree[END_BLOCK].Len;
  86008. }
  86009. /* ===========================================================================
  86010. * Set the data type to BINARY or TEXT, using a crude approximation:
  86011. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  86012. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  86013. * IN assertion: the fields Freq of dyn_ltree are set.
  86014. */
  86015. local void set_data_type (deflate_state *s)
  86016. {
  86017. int n;
  86018. for (n = 0; n < 9; n++)
  86019. if (s->dyn_ltree[n].Freq != 0)
  86020. break;
  86021. if (n == 9)
  86022. for (n = 14; n < 32; n++)
  86023. if (s->dyn_ltree[n].Freq != 0)
  86024. break;
  86025. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  86026. }
  86027. /* ===========================================================================
  86028. * Reverse the first len bits of a code, using straightforward code (a faster
  86029. * method would use a table)
  86030. * IN assertion: 1 <= len <= 15
  86031. */
  86032. local unsigned bi_reverse (unsigned code, int len)
  86033. {
  86034. register unsigned res = 0;
  86035. do {
  86036. res |= code & 1;
  86037. code >>= 1, res <<= 1;
  86038. } while (--len > 0);
  86039. return res >> 1;
  86040. }
  86041. /* ===========================================================================
  86042. * Flush the bit buffer, keeping at most 7 bits in it.
  86043. */
  86044. local void bi_flush (deflate_state *s)
  86045. {
  86046. if (s->bi_valid == 16) {
  86047. put_short(s, s->bi_buf);
  86048. s->bi_buf = 0;
  86049. s->bi_valid = 0;
  86050. } else if (s->bi_valid >= 8) {
  86051. put_byte(s, (Byte)s->bi_buf);
  86052. s->bi_buf >>= 8;
  86053. s->bi_valid -= 8;
  86054. }
  86055. }
  86056. /* ===========================================================================
  86057. * Flush the bit buffer and align the output on a byte boundary
  86058. */
  86059. local void bi_windup (deflate_state *s)
  86060. {
  86061. if (s->bi_valid > 8) {
  86062. put_short(s, s->bi_buf);
  86063. } else if (s->bi_valid > 0) {
  86064. put_byte(s, (Byte)s->bi_buf);
  86065. }
  86066. s->bi_buf = 0;
  86067. s->bi_valid = 0;
  86068. #ifdef DEBUG
  86069. s->bits_sent = (s->bits_sent+7) & ~7;
  86070. #endif
  86071. }
  86072. /* ===========================================================================
  86073. * Copy a stored block, storing first the length and its
  86074. * one's complement if requested.
  86075. */
  86076. local void copy_block(deflate_state *s,
  86077. charf *buf, /* the input data */
  86078. unsigned len, /* its length */
  86079. int header) /* true if block header must be written */
  86080. {
  86081. bi_windup(s); /* align on byte boundary */
  86082. s->last_eob_len = 8; /* enough lookahead for inflate */
  86083. if (header) {
  86084. put_short(s, (ush)len);
  86085. put_short(s, (ush)~len);
  86086. #ifdef DEBUG
  86087. s->bits_sent += 2*16;
  86088. #endif
  86089. }
  86090. #ifdef DEBUG
  86091. s->bits_sent += (ulg)len<<3;
  86092. #endif
  86093. while (len--) {
  86094. put_byte(s, *buf++);
  86095. }
  86096. }
  86097. /*** End of inlined file: trees.c ***/
  86098. /*** Start of inlined file: zutil.c ***/
  86099. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  86100. #ifndef NO_DUMMY_DECL
  86101. struct internal_state {int dummy;}; /* for buggy compilers */
  86102. #endif
  86103. const char * const z_errmsg[10] = {
  86104. "need dictionary", /* Z_NEED_DICT 2 */
  86105. "stream end", /* Z_STREAM_END 1 */
  86106. "", /* Z_OK 0 */
  86107. "file error", /* Z_ERRNO (-1) */
  86108. "stream error", /* Z_STREAM_ERROR (-2) */
  86109. "data error", /* Z_DATA_ERROR (-3) */
  86110. "insufficient memory", /* Z_MEM_ERROR (-4) */
  86111. "buffer error", /* Z_BUF_ERROR (-5) */
  86112. "incompatible version",/* Z_VERSION_ERROR (-6) */
  86113. ""};
  86114. /*const char * ZEXPORT zlibVersion()
  86115. {
  86116. return ZLIB_VERSION;
  86117. }
  86118. uLong ZEXPORT zlibCompileFlags()
  86119. {
  86120. uLong flags;
  86121. flags = 0;
  86122. switch (sizeof(uInt)) {
  86123. case 2: break;
  86124. case 4: flags += 1; break;
  86125. case 8: flags += 2; break;
  86126. default: flags += 3;
  86127. }
  86128. switch (sizeof(uLong)) {
  86129. case 2: break;
  86130. case 4: flags += 1 << 2; break;
  86131. case 8: flags += 2 << 2; break;
  86132. default: flags += 3 << 2;
  86133. }
  86134. switch (sizeof(voidpf)) {
  86135. case 2: break;
  86136. case 4: flags += 1 << 4; break;
  86137. case 8: flags += 2 << 4; break;
  86138. default: flags += 3 << 4;
  86139. }
  86140. switch (sizeof(z_off_t)) {
  86141. case 2: break;
  86142. case 4: flags += 1 << 6; break;
  86143. case 8: flags += 2 << 6; break;
  86144. default: flags += 3 << 6;
  86145. }
  86146. #ifdef DEBUG
  86147. flags += 1 << 8;
  86148. #endif
  86149. #if defined(ASMV) || defined(ASMINF)
  86150. flags += 1 << 9;
  86151. #endif
  86152. #ifdef ZLIB_WINAPI
  86153. flags += 1 << 10;
  86154. #endif
  86155. #ifdef BUILDFIXED
  86156. flags += 1 << 12;
  86157. #endif
  86158. #ifdef DYNAMIC_CRC_TABLE
  86159. flags += 1 << 13;
  86160. #endif
  86161. #ifdef NO_GZCOMPRESS
  86162. flags += 1L << 16;
  86163. #endif
  86164. #ifdef NO_GZIP
  86165. flags += 1L << 17;
  86166. #endif
  86167. #ifdef PKZIP_BUG_WORKAROUND
  86168. flags += 1L << 20;
  86169. #endif
  86170. #ifdef FASTEST
  86171. flags += 1L << 21;
  86172. #endif
  86173. #ifdef STDC
  86174. # ifdef NO_vsnprintf
  86175. flags += 1L << 25;
  86176. # ifdef HAS_vsprintf_void
  86177. flags += 1L << 26;
  86178. # endif
  86179. # else
  86180. # ifdef HAS_vsnprintf_void
  86181. flags += 1L << 26;
  86182. # endif
  86183. # endif
  86184. #else
  86185. flags += 1L << 24;
  86186. # ifdef NO_snprintf
  86187. flags += 1L << 25;
  86188. # ifdef HAS_sprintf_void
  86189. flags += 1L << 26;
  86190. # endif
  86191. # else
  86192. # ifdef HAS_snprintf_void
  86193. flags += 1L << 26;
  86194. # endif
  86195. # endif
  86196. #endif
  86197. return flags;
  86198. }*/
  86199. #ifdef DEBUG
  86200. # ifndef verbose
  86201. # define verbose 0
  86202. # endif
  86203. int z_verbose = verbose;
  86204. void z_error (const char *m)
  86205. {
  86206. fprintf(stderr, "%s\n", m);
  86207. exit(1);
  86208. }
  86209. #endif
  86210. /* exported to allow conversion of error code to string for compress() and
  86211. * uncompress()
  86212. */
  86213. const char * ZEXPORT zError(int err)
  86214. {
  86215. return ERR_MSG(err);
  86216. }
  86217. #if defined(_WIN32_WCE)
  86218. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86219. * errno. We define it as a global variable to simplify porting.
  86220. * Its value is always 0 and should not be used.
  86221. */
  86222. int errno = 0;
  86223. #endif
  86224. #ifndef HAVE_MEMCPY
  86225. void zmemcpy(dest, source, len)
  86226. Bytef* dest;
  86227. const Bytef* source;
  86228. uInt len;
  86229. {
  86230. if (len == 0) return;
  86231. do {
  86232. *dest++ = *source++; /* ??? to be unrolled */
  86233. } while (--len != 0);
  86234. }
  86235. int zmemcmp(s1, s2, len)
  86236. const Bytef* s1;
  86237. const Bytef* s2;
  86238. uInt len;
  86239. {
  86240. uInt j;
  86241. for (j = 0; j < len; j++) {
  86242. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86243. }
  86244. return 0;
  86245. }
  86246. void zmemzero(dest, len)
  86247. Bytef* dest;
  86248. uInt len;
  86249. {
  86250. if (len == 0) return;
  86251. do {
  86252. *dest++ = 0; /* ??? to be unrolled */
  86253. } while (--len != 0);
  86254. }
  86255. #endif
  86256. #ifdef SYS16BIT
  86257. #ifdef __TURBOC__
  86258. /* Turbo C in 16-bit mode */
  86259. # define MY_ZCALLOC
  86260. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86261. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86262. * must fix the pointer. Warning: the pointer must be put back to its
  86263. * original form in order to free it, use zcfree().
  86264. */
  86265. #define MAX_PTR 10
  86266. /* 10*64K = 640K */
  86267. local int next_ptr = 0;
  86268. typedef struct ptr_table_s {
  86269. voidpf org_ptr;
  86270. voidpf new_ptr;
  86271. } ptr_table;
  86272. local ptr_table table[MAX_PTR];
  86273. /* This table is used to remember the original form of pointers
  86274. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86275. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86276. * protected from concurrent access. This hack doesn't work anyway on
  86277. * a protected system like OS/2. Use Microsoft C instead.
  86278. */
  86279. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86280. {
  86281. voidpf buf = opaque; /* just to make some compilers happy */
  86282. ulg bsize = (ulg)items*size;
  86283. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86284. * will return a usable pointer which doesn't have to be normalized.
  86285. */
  86286. if (bsize < 65520L) {
  86287. buf = farmalloc(bsize);
  86288. if (*(ush*)&buf != 0) return buf;
  86289. } else {
  86290. buf = farmalloc(bsize + 16L);
  86291. }
  86292. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86293. table[next_ptr].org_ptr = buf;
  86294. /* Normalize the pointer to seg:0 */
  86295. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86296. *(ush*)&buf = 0;
  86297. table[next_ptr++].new_ptr = buf;
  86298. return buf;
  86299. }
  86300. void zcfree (voidpf opaque, voidpf ptr)
  86301. {
  86302. int n;
  86303. if (*(ush*)&ptr != 0) { /* object < 64K */
  86304. farfree(ptr);
  86305. return;
  86306. }
  86307. /* Find the original pointer */
  86308. for (n = 0; n < next_ptr; n++) {
  86309. if (ptr != table[n].new_ptr) continue;
  86310. farfree(table[n].org_ptr);
  86311. while (++n < next_ptr) {
  86312. table[n-1] = table[n];
  86313. }
  86314. next_ptr--;
  86315. return;
  86316. }
  86317. ptr = opaque; /* just to make some compilers happy */
  86318. Assert(0, "zcfree: ptr not found");
  86319. }
  86320. #endif /* __TURBOC__ */
  86321. #ifdef M_I86
  86322. /* Microsoft C in 16-bit mode */
  86323. # define MY_ZCALLOC
  86324. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86325. # define _halloc halloc
  86326. # define _hfree hfree
  86327. #endif
  86328. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86329. {
  86330. if (opaque) opaque = 0; /* to make compiler happy */
  86331. return _halloc((long)items, size);
  86332. }
  86333. void zcfree (voidpf opaque, voidpf ptr)
  86334. {
  86335. if (opaque) opaque = 0; /* to make compiler happy */
  86336. _hfree(ptr);
  86337. }
  86338. #endif /* M_I86 */
  86339. #endif /* SYS16BIT */
  86340. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86341. #ifndef STDC
  86342. extern voidp malloc OF((uInt size));
  86343. extern voidp calloc OF((uInt items, uInt size));
  86344. extern void free OF((voidpf ptr));
  86345. #endif
  86346. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86347. {
  86348. if (opaque) items += size - size; /* make compiler happy */
  86349. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86350. (voidpf)calloc(items, size);
  86351. }
  86352. void zcfree (voidpf opaque, voidpf ptr)
  86353. {
  86354. free(ptr);
  86355. if (opaque) return; /* make compiler happy */
  86356. }
  86357. #endif /* MY_ZCALLOC */
  86358. /*** End of inlined file: zutil.c ***/
  86359. #undef Byte
  86360. #else
  86361. #include <zlib.h>
  86362. #endif
  86363. }
  86364. #if JUCE_MSVC
  86365. #pragma warning (pop)
  86366. #endif
  86367. BEGIN_JUCE_NAMESPACE
  86368. // internal helper object that holds the zlib structures so they don't have to be
  86369. // included publicly.
  86370. class GZIPDecompressorInputStream::GZIPDecompressHelper
  86371. {
  86372. public:
  86373. GZIPDecompressHelper (const bool noWrap)
  86374. : finished (true),
  86375. needsDictionary (false),
  86376. error (true),
  86377. streamIsValid (false),
  86378. data (0),
  86379. dataSize (0)
  86380. {
  86381. using namespace zlibNamespace;
  86382. zerostruct (stream);
  86383. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86384. finished = error = ! streamIsValid;
  86385. }
  86386. ~GZIPDecompressHelper()
  86387. {
  86388. using namespace zlibNamespace;
  86389. if (streamIsValid)
  86390. inflateEnd (&stream);
  86391. }
  86392. bool needsInput() const throw() { return dataSize <= 0; }
  86393. void setInput (uint8* const data_, const int size) throw()
  86394. {
  86395. data = data_;
  86396. dataSize = size;
  86397. }
  86398. int doNextBlock (uint8* const dest, const int destSize)
  86399. {
  86400. using namespace zlibNamespace;
  86401. if (streamIsValid && data != 0 && ! finished)
  86402. {
  86403. stream.next_in = data;
  86404. stream.next_out = dest;
  86405. stream.avail_in = dataSize;
  86406. stream.avail_out = destSize;
  86407. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86408. {
  86409. case Z_STREAM_END:
  86410. finished = true;
  86411. // deliberate fall-through
  86412. case Z_OK:
  86413. data += dataSize - stream.avail_in;
  86414. dataSize = stream.avail_in;
  86415. return destSize - stream.avail_out;
  86416. case Z_NEED_DICT:
  86417. needsDictionary = true;
  86418. data += dataSize - stream.avail_in;
  86419. dataSize = stream.avail_in;
  86420. break;
  86421. case Z_DATA_ERROR:
  86422. case Z_MEM_ERROR:
  86423. error = true;
  86424. default:
  86425. break;
  86426. }
  86427. }
  86428. return 0;
  86429. }
  86430. bool finished, needsDictionary, error, streamIsValid;
  86431. enum { gzipDecompBufferSize = 32768 };
  86432. private:
  86433. zlibNamespace::z_stream stream;
  86434. uint8* data;
  86435. int dataSize;
  86436. JUCE_DECLARE_NON_COPYABLE (GZIPDecompressHelper);
  86437. };
  86438. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86439. const bool deleteSourceWhenDestroyed,
  86440. const bool noWrap_,
  86441. const int64 uncompressedStreamLength_)
  86442. : sourceStream (sourceStream_),
  86443. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86444. uncompressedStreamLength (uncompressedStreamLength_),
  86445. noWrap (noWrap_),
  86446. isEof (false),
  86447. activeBufferSize (0),
  86448. originalSourcePos (sourceStream_->getPosition()),
  86449. currentPos (0),
  86450. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86451. helper (new GZIPDecompressHelper (noWrap_))
  86452. {
  86453. }
  86454. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  86455. : sourceStream (&sourceStream_),
  86456. uncompressedStreamLength (-1),
  86457. noWrap (false),
  86458. isEof (false),
  86459. activeBufferSize (0),
  86460. originalSourcePos (sourceStream_.getPosition()),
  86461. currentPos (0),
  86462. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86463. helper (new GZIPDecompressHelper (false))
  86464. {
  86465. }
  86466. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86467. {
  86468. }
  86469. int64 GZIPDecompressorInputStream::getTotalLength()
  86470. {
  86471. return uncompressedStreamLength;
  86472. }
  86473. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86474. {
  86475. if ((howMany > 0) && ! isEof)
  86476. {
  86477. jassert (destBuffer != 0);
  86478. if (destBuffer != 0)
  86479. {
  86480. int numRead = 0;
  86481. uint8* d = static_cast <uint8*> (destBuffer);
  86482. while (! helper->error)
  86483. {
  86484. const int n = helper->doNextBlock (d, howMany);
  86485. currentPos += n;
  86486. if (n == 0)
  86487. {
  86488. if (helper->finished || helper->needsDictionary)
  86489. {
  86490. isEof = true;
  86491. return numRead;
  86492. }
  86493. if (helper->needsInput())
  86494. {
  86495. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  86496. if (activeBufferSize > 0)
  86497. {
  86498. helper->setInput (buffer, activeBufferSize);
  86499. }
  86500. else
  86501. {
  86502. isEof = true;
  86503. return numRead;
  86504. }
  86505. }
  86506. }
  86507. else
  86508. {
  86509. numRead += n;
  86510. howMany -= n;
  86511. d += n;
  86512. if (howMany <= 0)
  86513. return numRead;
  86514. }
  86515. }
  86516. }
  86517. }
  86518. return 0;
  86519. }
  86520. bool GZIPDecompressorInputStream::isExhausted()
  86521. {
  86522. return helper->error || isEof;
  86523. }
  86524. int64 GZIPDecompressorInputStream::getPosition()
  86525. {
  86526. return currentPos;
  86527. }
  86528. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86529. {
  86530. if (newPos < currentPos)
  86531. {
  86532. // to go backwards, reset the stream and start again..
  86533. isEof = false;
  86534. activeBufferSize = 0;
  86535. currentPos = 0;
  86536. helper = new GZIPDecompressHelper (noWrap);
  86537. sourceStream->setPosition (originalSourcePos);
  86538. }
  86539. skipNextBytes (newPos - currentPos);
  86540. return true;
  86541. }
  86542. END_JUCE_NAMESPACE
  86543. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86544. #endif
  86545. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86546. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86547. #if JUCE_USE_FLAC
  86548. #if JUCE_WINDOWS
  86549. #include <windows.h>
  86550. #endif
  86551. namespace FlacNamespace
  86552. {
  86553. #if JUCE_INCLUDE_FLAC_CODE
  86554. #if JUCE_MSVC
  86555. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86556. #endif
  86557. #define FLAC__NO_DLL 1
  86558. #if ! defined (SIZE_MAX)
  86559. #define SIZE_MAX 0xffffffff
  86560. #endif
  86561. #define __STDC_LIMIT_MACROS 1
  86562. /*** Start of inlined file: all.h ***/
  86563. #ifndef FLAC__ALL_H
  86564. #define FLAC__ALL_H
  86565. /*** Start of inlined file: export.h ***/
  86566. #ifndef FLAC__EXPORT_H
  86567. #define FLAC__EXPORT_H
  86568. /** \file include/FLAC/export.h
  86569. *
  86570. * \brief
  86571. * This module contains #defines and symbols for exporting function
  86572. * calls, and providing version information and compiled-in features.
  86573. *
  86574. * See the \link flac_export export \endlink module.
  86575. */
  86576. /** \defgroup flac_export FLAC/export.h: export symbols
  86577. * \ingroup flac
  86578. *
  86579. * \brief
  86580. * This module contains #defines and symbols for exporting function
  86581. * calls, and providing version information and compiled-in features.
  86582. *
  86583. * If you are compiling with MSVC and will link to the static library
  86584. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86585. * make sure the symbols are exported properly.
  86586. *
  86587. * \{
  86588. */
  86589. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86590. #define FLAC_API
  86591. #else
  86592. #ifdef FLAC_API_EXPORTS
  86593. #define FLAC_API _declspec(dllexport)
  86594. #else
  86595. #define FLAC_API _declspec(dllimport)
  86596. #endif
  86597. #endif
  86598. /** These #defines will mirror the libtool-based library version number, see
  86599. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86600. */
  86601. #define FLAC_API_VERSION_CURRENT 10
  86602. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86603. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86604. #ifdef __cplusplus
  86605. extern "C" {
  86606. #endif
  86607. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86608. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86609. #ifdef __cplusplus
  86610. }
  86611. #endif
  86612. /* \} */
  86613. #endif
  86614. /*** End of inlined file: export.h ***/
  86615. /*** Start of inlined file: assert.h ***/
  86616. #ifndef FLAC__ASSERT_H
  86617. #define FLAC__ASSERT_H
  86618. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86619. #ifdef DEBUG
  86620. #include <assert.h>
  86621. #define FLAC__ASSERT(x) assert(x)
  86622. #define FLAC__ASSERT_DECLARATION(x) x
  86623. #else
  86624. #define FLAC__ASSERT(x)
  86625. #define FLAC__ASSERT_DECLARATION(x)
  86626. #endif
  86627. #endif
  86628. /*** End of inlined file: assert.h ***/
  86629. /*** Start of inlined file: callback.h ***/
  86630. #ifndef FLAC__CALLBACK_H
  86631. #define FLAC__CALLBACK_H
  86632. /*** Start of inlined file: ordinals.h ***/
  86633. #ifndef FLAC__ORDINALS_H
  86634. #define FLAC__ORDINALS_H
  86635. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86636. #include <inttypes.h>
  86637. #endif
  86638. typedef signed char FLAC__int8;
  86639. typedef unsigned char FLAC__uint8;
  86640. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86641. typedef __int16 FLAC__int16;
  86642. typedef __int32 FLAC__int32;
  86643. typedef __int64 FLAC__int64;
  86644. typedef unsigned __int16 FLAC__uint16;
  86645. typedef unsigned __int32 FLAC__uint32;
  86646. typedef unsigned __int64 FLAC__uint64;
  86647. #elif defined(__EMX__)
  86648. typedef short FLAC__int16;
  86649. typedef long FLAC__int32;
  86650. typedef long long FLAC__int64;
  86651. typedef unsigned short FLAC__uint16;
  86652. typedef unsigned long FLAC__uint32;
  86653. typedef unsigned long long FLAC__uint64;
  86654. #else
  86655. typedef int16_t FLAC__int16;
  86656. typedef int32_t FLAC__int32;
  86657. typedef int64_t FLAC__int64;
  86658. typedef uint16_t FLAC__uint16;
  86659. typedef uint32_t FLAC__uint32;
  86660. typedef uint64_t FLAC__uint64;
  86661. #endif
  86662. typedef int FLAC__bool;
  86663. typedef FLAC__uint8 FLAC__byte;
  86664. #ifdef true
  86665. #undef true
  86666. #endif
  86667. #ifdef false
  86668. #undef false
  86669. #endif
  86670. #ifndef __cplusplus
  86671. #define true 1
  86672. #define false 0
  86673. #endif
  86674. #endif
  86675. /*** End of inlined file: ordinals.h ***/
  86676. #include <stdlib.h> /* for size_t */
  86677. /** \file include/FLAC/callback.h
  86678. *
  86679. * \brief
  86680. * This module defines the structures for describing I/O callbacks
  86681. * to the other FLAC interfaces.
  86682. *
  86683. * See the detailed documentation for callbacks in the
  86684. * \link flac_callbacks callbacks \endlink module.
  86685. */
  86686. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86687. * \ingroup flac
  86688. *
  86689. * \brief
  86690. * This module defines the structures for describing I/O callbacks
  86691. * to the other FLAC interfaces.
  86692. *
  86693. * The purpose of the I/O callback functions is to create a common way
  86694. * for the metadata interfaces to handle I/O.
  86695. *
  86696. * Originally the metadata interfaces required filenames as the way of
  86697. * specifying FLAC files to operate on. This is problematic in some
  86698. * environments so there is an additional option to specify a set of
  86699. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86700. *
  86701. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86702. * opaque structure for a data source.
  86703. *
  86704. * The callback function prototypes are similar (but not identical) to the
  86705. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86706. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86707. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86708. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86709. * is required. \warning You generally CANNOT directly use fseek or ftell
  86710. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86711. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86712. * large files. You will have to find an equivalent function (e.g. ftello),
  86713. * or write a wrapper. The same is true for feof() since this is usually
  86714. * implemented as a macro, not as a function whose address can be taken.
  86715. *
  86716. * \{
  86717. */
  86718. #ifdef __cplusplus
  86719. extern "C" {
  86720. #endif
  86721. /** This is the opaque handle type used by the callbacks. Typically
  86722. * this is a \c FILE* or address of a file descriptor.
  86723. */
  86724. typedef void* FLAC__IOHandle;
  86725. /** Signature for the read callback.
  86726. * The signature and semantics match POSIX fread() implementations
  86727. * and can generally be used interchangeably.
  86728. *
  86729. * \param ptr The address of the read buffer.
  86730. * \param size The size of the records to be read.
  86731. * \param nmemb The number of records to be read.
  86732. * \param handle The handle to the data source.
  86733. * \retval size_t
  86734. * The number of records read.
  86735. */
  86736. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86737. /** Signature for the write callback.
  86738. * The signature and semantics match POSIX fwrite() implementations
  86739. * and can generally be used interchangeably.
  86740. *
  86741. * \param ptr The address of the write buffer.
  86742. * \param size The size of the records to be written.
  86743. * \param nmemb The number of records to be written.
  86744. * \param handle The handle to the data source.
  86745. * \retval size_t
  86746. * The number of records written.
  86747. */
  86748. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86749. /** Signature for the seek callback.
  86750. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86751. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86752. * and 32-bits wide.
  86753. *
  86754. * \param handle The handle to the data source.
  86755. * \param offset The new position, relative to \a whence
  86756. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86757. * \retval int
  86758. * \c 0 on success, \c -1 on error.
  86759. */
  86760. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86761. /** Signature for the tell callback.
  86762. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86763. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86764. * and 32-bits wide.
  86765. *
  86766. * \param handle The handle to the data source.
  86767. * \retval FLAC__int64
  86768. * The current position on success, \c -1 on error.
  86769. */
  86770. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86771. /** Signature for the EOF callback.
  86772. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86773. * on many systems, feof() is a macro, so in this case a wrapper function
  86774. * must be provided instead.
  86775. *
  86776. * \param handle The handle to the data source.
  86777. * \retval int
  86778. * \c 0 if not at end of file, nonzero if at end of file.
  86779. */
  86780. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86781. /** Signature for the close callback.
  86782. * The signature and semantics match POSIX fclose() implementations
  86783. * and can generally be used interchangeably.
  86784. *
  86785. * \param handle The handle to the data source.
  86786. * \retval int
  86787. * \c 0 on success, \c EOF on error.
  86788. */
  86789. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86790. /** A structure for holding a set of callbacks.
  86791. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86792. * describe which of the callbacks are required. The ones that are not
  86793. * required may be set to NULL.
  86794. *
  86795. * If the seek requirement for an interface is optional, you can signify that
  86796. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86797. */
  86798. typedef struct {
  86799. FLAC__IOCallback_Read read;
  86800. FLAC__IOCallback_Write write;
  86801. FLAC__IOCallback_Seek seek;
  86802. FLAC__IOCallback_Tell tell;
  86803. FLAC__IOCallback_Eof eof;
  86804. FLAC__IOCallback_Close close;
  86805. } FLAC__IOCallbacks;
  86806. /* \} */
  86807. #ifdef __cplusplus
  86808. }
  86809. #endif
  86810. #endif
  86811. /*** End of inlined file: callback.h ***/
  86812. /*** Start of inlined file: format.h ***/
  86813. #ifndef FLAC__FORMAT_H
  86814. #define FLAC__FORMAT_H
  86815. #ifdef __cplusplus
  86816. extern "C" {
  86817. #endif
  86818. /** \file include/FLAC/format.h
  86819. *
  86820. * \brief
  86821. * This module contains structure definitions for the representation
  86822. * of FLAC format components in memory. These are the basic
  86823. * structures used by the rest of the interfaces.
  86824. *
  86825. * See the detailed documentation in the
  86826. * \link flac_format format \endlink module.
  86827. */
  86828. /** \defgroup flac_format FLAC/format.h: format components
  86829. * \ingroup flac
  86830. *
  86831. * \brief
  86832. * This module contains structure definitions for the representation
  86833. * of FLAC format components in memory. These are the basic
  86834. * structures used by the rest of the interfaces.
  86835. *
  86836. * First, you should be familiar with the
  86837. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86838. * follow directly from the specification. As a user of libFLAC, the
  86839. * interesting parts really are the structures that describe the frame
  86840. * header and metadata blocks.
  86841. *
  86842. * The format structures here are very primitive, designed to store
  86843. * information in an efficient way. Reading information from the
  86844. * structures is easy but creating or modifying them directly is
  86845. * more complex. For the most part, as a user of a library, editing
  86846. * is not necessary; however, for metadata blocks it is, so there are
  86847. * convenience functions provided in the \link flac_metadata metadata
  86848. * module \endlink to simplify the manipulation of metadata blocks.
  86849. *
  86850. * \note
  86851. * It's not the best convention, but symbols ending in _LEN are in bits
  86852. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86853. * global variables because they are usually used when declaring byte
  86854. * arrays and some compilers require compile-time knowledge of array
  86855. * sizes when declared on the stack.
  86856. *
  86857. * \{
  86858. */
  86859. /*
  86860. Most of the values described in this file are defined by the FLAC
  86861. format specification. There is nothing to tune here.
  86862. */
  86863. /** The largest legal metadata type code. */
  86864. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86865. /** The minimum block size, in samples, permitted by the format. */
  86866. #define FLAC__MIN_BLOCK_SIZE (16u)
  86867. /** The maximum block size, in samples, permitted by the format. */
  86868. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86869. /** The maximum block size, in samples, permitted by the FLAC subset for
  86870. * sample rates up to 48kHz. */
  86871. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86872. /** The maximum number of channels permitted by the format. */
  86873. #define FLAC__MAX_CHANNELS (8u)
  86874. /** The minimum sample resolution permitted by the format. */
  86875. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86876. /** The maximum sample resolution permitted by the format. */
  86877. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86878. /** The maximum sample resolution permitted by libFLAC.
  86879. *
  86880. * \warning
  86881. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86882. * the reference encoder/decoder is currently limited to 24 bits because
  86883. * of prevalent 32-bit math, so make sure and use this value when
  86884. * appropriate.
  86885. */
  86886. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86887. /** The maximum sample rate permitted by the format. The value is
  86888. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86889. * as to why.
  86890. */
  86891. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86892. /** The maximum LPC order permitted by the format. */
  86893. #define FLAC__MAX_LPC_ORDER (32u)
  86894. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86895. * up to 48kHz. */
  86896. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86897. /** The minimum quantized linear predictor coefficient precision
  86898. * permitted by the format.
  86899. */
  86900. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86901. /** The maximum quantized linear predictor coefficient precision
  86902. * permitted by the format.
  86903. */
  86904. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86905. /** The maximum order of the fixed predictors permitted by the format. */
  86906. #define FLAC__MAX_FIXED_ORDER (4u)
  86907. /** The maximum Rice partition order permitted by the format. */
  86908. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86909. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86910. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86911. /** The version string of the release, stamped onto the libraries and binaries.
  86912. *
  86913. * \note
  86914. * This does not correspond to the shared library version number, which
  86915. * is used to determine binary compatibility.
  86916. */
  86917. extern FLAC_API const char *FLAC__VERSION_STRING;
  86918. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86919. * This is a NUL-terminated ASCII string; when inserted into the
  86920. * VORBIS_COMMENT the trailing null is stripped.
  86921. */
  86922. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86923. /** The byte string representation of the beginning of a FLAC stream. */
  86924. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86925. /** The 32-bit integer big-endian representation of the beginning of
  86926. * a FLAC stream.
  86927. */
  86928. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86929. /** The length of the FLAC signature in bits. */
  86930. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86931. /** The length of the FLAC signature in bytes. */
  86932. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86933. /*****************************************************************************
  86934. *
  86935. * Subframe structures
  86936. *
  86937. *****************************************************************************/
  86938. /*****************************************************************************/
  86939. /** An enumeration of the available entropy coding methods. */
  86940. typedef enum {
  86941. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86942. /**< Residual is coded by partitioning into contexts, each with it's own
  86943. * 4-bit Rice parameter. */
  86944. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86945. /**< Residual is coded by partitioning into contexts, each with it's own
  86946. * 5-bit Rice parameter. */
  86947. } FLAC__EntropyCodingMethodType;
  86948. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86949. *
  86950. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86951. * give the string equivalent. The contents should not be modified.
  86952. */
  86953. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86954. /** Contents of a Rice partitioned residual
  86955. */
  86956. typedef struct {
  86957. unsigned *parameters;
  86958. /**< The Rice parameters for each context. */
  86959. unsigned *raw_bits;
  86960. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86961. * partitions and zero for unescaped partitions.
  86962. */
  86963. unsigned capacity_by_order;
  86964. /**< The capacity of the \a parameters and \a raw_bits arrays
  86965. * specified as an order, i.e. the number of array elements
  86966. * allocated is 2 ^ \a capacity_by_order.
  86967. */
  86968. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86969. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86970. */
  86971. typedef struct {
  86972. unsigned order;
  86973. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86974. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86975. /**< The context's Rice parameters and/or raw bits. */
  86976. } FLAC__EntropyCodingMethod_PartitionedRice;
  86977. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86978. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86979. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86980. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86981. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86982. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86983. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86984. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86985. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86986. */
  86987. typedef struct {
  86988. FLAC__EntropyCodingMethodType type;
  86989. union {
  86990. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86991. } data;
  86992. } FLAC__EntropyCodingMethod;
  86993. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86994. /*****************************************************************************/
  86995. /** An enumeration of the available subframe types. */
  86996. typedef enum {
  86997. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86998. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86999. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  87000. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  87001. } FLAC__SubframeType;
  87002. /** Maps a FLAC__SubframeType to a C string.
  87003. *
  87004. * Using a FLAC__SubframeType as the index to this array will
  87005. * give the string equivalent. The contents should not be modified.
  87006. */
  87007. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  87008. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  87009. */
  87010. typedef struct {
  87011. FLAC__int32 value; /**< The constant signal value. */
  87012. } FLAC__Subframe_Constant;
  87013. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  87014. */
  87015. typedef struct {
  87016. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  87017. } FLAC__Subframe_Verbatim;
  87018. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  87019. */
  87020. typedef struct {
  87021. FLAC__EntropyCodingMethod entropy_coding_method;
  87022. /**< The residual coding method. */
  87023. unsigned order;
  87024. /**< The polynomial order. */
  87025. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  87026. /**< Warmup samples to prime the predictor, length == order. */
  87027. const FLAC__int32 *residual;
  87028. /**< The residual signal, length == (blocksize minus order) samples. */
  87029. } FLAC__Subframe_Fixed;
  87030. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  87031. */
  87032. typedef struct {
  87033. FLAC__EntropyCodingMethod entropy_coding_method;
  87034. /**< The residual coding method. */
  87035. unsigned order;
  87036. /**< The FIR order. */
  87037. unsigned qlp_coeff_precision;
  87038. /**< Quantized FIR filter coefficient precision in bits. */
  87039. int quantization_level;
  87040. /**< The qlp coeff shift needed. */
  87041. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  87042. /**< FIR filter coefficients. */
  87043. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  87044. /**< Warmup samples to prime the predictor, length == order. */
  87045. const FLAC__int32 *residual;
  87046. /**< The residual signal, length == (blocksize minus order) samples. */
  87047. } FLAC__Subframe_LPC;
  87048. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  87049. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  87050. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  87051. */
  87052. typedef struct {
  87053. FLAC__SubframeType type;
  87054. union {
  87055. FLAC__Subframe_Constant constant;
  87056. FLAC__Subframe_Fixed fixed;
  87057. FLAC__Subframe_LPC lpc;
  87058. FLAC__Subframe_Verbatim verbatim;
  87059. } data;
  87060. unsigned wasted_bits;
  87061. } FLAC__Subframe;
  87062. /** == 1 (bit)
  87063. *
  87064. * This used to be a zero-padding bit (hence the name
  87065. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  87066. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  87067. * to mean something else.
  87068. */
  87069. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  87070. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  87071. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  87072. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  87073. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  87074. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  87075. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  87076. /*****************************************************************************/
  87077. /*****************************************************************************
  87078. *
  87079. * Frame structures
  87080. *
  87081. *****************************************************************************/
  87082. /** An enumeration of the available channel assignments. */
  87083. typedef enum {
  87084. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  87085. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  87086. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  87087. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  87088. } FLAC__ChannelAssignment;
  87089. /** Maps a FLAC__ChannelAssignment to a C string.
  87090. *
  87091. * Using a FLAC__ChannelAssignment as the index to this array will
  87092. * give the string equivalent. The contents should not be modified.
  87093. */
  87094. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  87095. /** An enumeration of the possible frame numbering methods. */
  87096. typedef enum {
  87097. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  87098. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  87099. } FLAC__FrameNumberType;
  87100. /** Maps a FLAC__FrameNumberType to a C string.
  87101. *
  87102. * Using a FLAC__FrameNumberType as the index to this array will
  87103. * give the string equivalent. The contents should not be modified.
  87104. */
  87105. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  87106. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  87107. */
  87108. typedef struct {
  87109. unsigned blocksize;
  87110. /**< The number of samples per subframe. */
  87111. unsigned sample_rate;
  87112. /**< The sample rate in Hz. */
  87113. unsigned channels;
  87114. /**< The number of channels (== number of subframes). */
  87115. FLAC__ChannelAssignment channel_assignment;
  87116. /**< The channel assignment for the frame. */
  87117. unsigned bits_per_sample;
  87118. /**< The sample resolution. */
  87119. FLAC__FrameNumberType number_type;
  87120. /**< The numbering scheme used for the frame. As a convenience, the
  87121. * decoder will always convert a frame number to a sample number because
  87122. * the rules are complex. */
  87123. union {
  87124. FLAC__uint32 frame_number;
  87125. FLAC__uint64 sample_number;
  87126. } number;
  87127. /**< The frame number or sample number of first sample in frame;
  87128. * use the \a number_type value to determine which to use. */
  87129. FLAC__uint8 crc;
  87130. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  87131. * of the raw frame header bytes, meaning everything before the CRC byte
  87132. * including the sync code.
  87133. */
  87134. } FLAC__FrameHeader;
  87135. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  87136. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  87137. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  87138. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  87139. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  87140. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  87141. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  87142. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  87143. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  87144. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  87145. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  87146. */
  87147. typedef struct {
  87148. FLAC__uint16 crc;
  87149. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  87150. * 0) of the bytes before the crc, back to and including the frame header
  87151. * sync code.
  87152. */
  87153. } FLAC__FrameFooter;
  87154. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  87155. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  87156. */
  87157. typedef struct {
  87158. FLAC__FrameHeader header;
  87159. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  87160. FLAC__FrameFooter footer;
  87161. } FLAC__Frame;
  87162. /*****************************************************************************/
  87163. /*****************************************************************************
  87164. *
  87165. * Meta-data structures
  87166. *
  87167. *****************************************************************************/
  87168. /** An enumeration of the available metadata block types. */
  87169. typedef enum {
  87170. FLAC__METADATA_TYPE_STREAMINFO = 0,
  87171. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  87172. FLAC__METADATA_TYPE_PADDING = 1,
  87173. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  87174. FLAC__METADATA_TYPE_APPLICATION = 2,
  87175. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  87176. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  87177. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  87178. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  87179. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  87180. FLAC__METADATA_TYPE_CUESHEET = 5,
  87181. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  87182. FLAC__METADATA_TYPE_PICTURE = 6,
  87183. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  87184. FLAC__METADATA_TYPE_UNDEFINED = 7
  87185. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  87186. } FLAC__MetadataType;
  87187. /** Maps a FLAC__MetadataType to a C string.
  87188. *
  87189. * Using a FLAC__MetadataType as the index to this array will
  87190. * give the string equivalent. The contents should not be modified.
  87191. */
  87192. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  87193. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  87194. */
  87195. typedef struct {
  87196. unsigned min_blocksize, max_blocksize;
  87197. unsigned min_framesize, max_framesize;
  87198. unsigned sample_rate;
  87199. unsigned channels;
  87200. unsigned bits_per_sample;
  87201. FLAC__uint64 total_samples;
  87202. FLAC__byte md5sum[16];
  87203. } FLAC__StreamMetadata_StreamInfo;
  87204. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87205. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87206. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87207. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87208. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87209. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87210. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87211. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87212. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87213. /** The total stream length of the STREAMINFO block in bytes. */
  87214. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87215. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87216. */
  87217. typedef struct {
  87218. int dummy;
  87219. /**< Conceptually this is an empty struct since we don't store the
  87220. * padding bytes. Empty structs are not allowed by some C compilers,
  87221. * hence the dummy.
  87222. */
  87223. } FLAC__StreamMetadata_Padding;
  87224. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87225. */
  87226. typedef struct {
  87227. FLAC__byte id[4];
  87228. FLAC__byte *data;
  87229. } FLAC__StreamMetadata_Application;
  87230. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87231. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87232. */
  87233. typedef struct {
  87234. FLAC__uint64 sample_number;
  87235. /**< The sample number of the target frame. */
  87236. FLAC__uint64 stream_offset;
  87237. /**< The offset, in bytes, of the target frame with respect to
  87238. * beginning of the first frame. */
  87239. unsigned frame_samples;
  87240. /**< The number of samples in the target frame. */
  87241. } FLAC__StreamMetadata_SeekPoint;
  87242. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87243. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87244. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87245. /** The total stream length of a seek point in bytes. */
  87246. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87247. /** The value used in the \a sample_number field of
  87248. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87249. * point (== 0xffffffffffffffff).
  87250. */
  87251. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87252. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87253. *
  87254. * \note From the format specification:
  87255. * - The seek points must be sorted by ascending sample number.
  87256. * - Each seek point's sample number must be the first sample of the
  87257. * target frame.
  87258. * - Each seek point's sample number must be unique within the table.
  87259. * - Existence of a SEEKTABLE block implies a correct setting of
  87260. * total_samples in the stream_info block.
  87261. * - Behavior is undefined when more than one SEEKTABLE block is
  87262. * present in a stream.
  87263. */
  87264. typedef struct {
  87265. unsigned num_points;
  87266. FLAC__StreamMetadata_SeekPoint *points;
  87267. } FLAC__StreamMetadata_SeekTable;
  87268. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87269. *
  87270. * For convenience, the APIs maintain a trailing NUL character at the end of
  87271. * \a entry which is not counted toward \a length, i.e.
  87272. * \code strlen(entry) == length \endcode
  87273. */
  87274. typedef struct {
  87275. FLAC__uint32 length;
  87276. FLAC__byte *entry;
  87277. } FLAC__StreamMetadata_VorbisComment_Entry;
  87278. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87279. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87280. */
  87281. typedef struct {
  87282. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87283. FLAC__uint32 num_comments;
  87284. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87285. } FLAC__StreamMetadata_VorbisComment;
  87286. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87287. /** FLAC CUESHEET track index structure. (See the
  87288. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87289. * the full description of each field.)
  87290. */
  87291. typedef struct {
  87292. FLAC__uint64 offset;
  87293. /**< Offset in samples, relative to the track offset, of the index
  87294. * point.
  87295. */
  87296. FLAC__byte number;
  87297. /**< The index point number. */
  87298. } FLAC__StreamMetadata_CueSheet_Index;
  87299. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87300. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87301. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87302. /** FLAC CUESHEET track structure. (See the
  87303. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87304. * the full description of each field.)
  87305. */
  87306. typedef struct {
  87307. FLAC__uint64 offset;
  87308. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87309. FLAC__byte number;
  87310. /**< The track number. */
  87311. char isrc[13];
  87312. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87313. unsigned type:1;
  87314. /**< The track type: 0 for audio, 1 for non-audio. */
  87315. unsigned pre_emphasis:1;
  87316. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87317. FLAC__byte num_indices;
  87318. /**< The number of track index points. */
  87319. FLAC__StreamMetadata_CueSheet_Index *indices;
  87320. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87321. } FLAC__StreamMetadata_CueSheet_Track;
  87322. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87323. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87324. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87325. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87326. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87327. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87328. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87329. /** FLAC CUESHEET structure. (See the
  87330. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87331. * for the full description of each field.)
  87332. */
  87333. typedef struct {
  87334. char media_catalog_number[129];
  87335. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87336. * general, the media catalog number may be 0 to 128 bytes long; any
  87337. * unused characters should be right-padded with NUL characters.
  87338. */
  87339. FLAC__uint64 lead_in;
  87340. /**< The number of lead-in samples. */
  87341. FLAC__bool is_cd;
  87342. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87343. unsigned num_tracks;
  87344. /**< The number of tracks. */
  87345. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87346. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87347. } FLAC__StreamMetadata_CueSheet;
  87348. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87349. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87350. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87351. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87352. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87353. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87354. typedef enum {
  87355. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87356. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87357. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87358. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87359. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87360. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87361. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87362. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87363. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87364. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87365. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87366. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87367. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87368. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87369. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87370. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87371. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87372. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87373. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87374. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87375. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87376. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87377. } FLAC__StreamMetadata_Picture_Type;
  87378. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87379. *
  87380. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87381. * will give the string equivalent. The contents should not be
  87382. * modified.
  87383. */
  87384. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87385. /** FLAC PICTURE structure. (See the
  87386. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87387. * for the full description of each field.)
  87388. */
  87389. typedef struct {
  87390. FLAC__StreamMetadata_Picture_Type type;
  87391. /**< The kind of picture stored. */
  87392. char *mime_type;
  87393. /**< Picture data's MIME type, in ASCII printable characters
  87394. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87395. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87396. * MIME type of '-->' is also allowed, in which case the picture
  87397. * data should be a complete URL. In file storage, the MIME type is
  87398. * stored as a 32-bit length followed by the ASCII string with no NUL
  87399. * terminator, but is converted to a plain C string in this structure
  87400. * for convenience.
  87401. */
  87402. FLAC__byte *description;
  87403. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87404. * the description is stored as a 32-bit length followed by the UTF-8
  87405. * string with no NUL terminator, but is converted to a plain C string
  87406. * in this structure for convenience.
  87407. */
  87408. FLAC__uint32 width;
  87409. /**< Picture's width in pixels. */
  87410. FLAC__uint32 height;
  87411. /**< Picture's height in pixels. */
  87412. FLAC__uint32 depth;
  87413. /**< Picture's color depth in bits-per-pixel. */
  87414. FLAC__uint32 colors;
  87415. /**< For indexed palettes (like GIF), picture's number of colors (the
  87416. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87417. */
  87418. FLAC__uint32 data_length;
  87419. /**< Length of binary picture data in bytes. */
  87420. FLAC__byte *data;
  87421. /**< Binary picture data. */
  87422. } FLAC__StreamMetadata_Picture;
  87423. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87424. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87425. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87426. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87427. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87428. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87429. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87430. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87431. /** Structure that is used when a metadata block of unknown type is loaded.
  87432. * The contents are opaque. The structure is used only internally to
  87433. * correctly handle unknown metadata.
  87434. */
  87435. typedef struct {
  87436. FLAC__byte *data;
  87437. } FLAC__StreamMetadata_Unknown;
  87438. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87439. */
  87440. typedef struct {
  87441. FLAC__MetadataType type;
  87442. /**< The type of the metadata block; used determine which member of the
  87443. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87444. * then \a data.unknown must be used. */
  87445. FLAC__bool is_last;
  87446. /**< \c true if this metadata block is the last, else \a false */
  87447. unsigned length;
  87448. /**< Length, in bytes, of the block data as it appears in the stream. */
  87449. union {
  87450. FLAC__StreamMetadata_StreamInfo stream_info;
  87451. FLAC__StreamMetadata_Padding padding;
  87452. FLAC__StreamMetadata_Application application;
  87453. FLAC__StreamMetadata_SeekTable seek_table;
  87454. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87455. FLAC__StreamMetadata_CueSheet cue_sheet;
  87456. FLAC__StreamMetadata_Picture picture;
  87457. FLAC__StreamMetadata_Unknown unknown;
  87458. } data;
  87459. /**< Polymorphic block data; use the \a type value to determine which
  87460. * to use. */
  87461. } FLAC__StreamMetadata;
  87462. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87463. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87464. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87465. /** The total stream length of a metadata block header in bytes. */
  87466. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87467. /*****************************************************************************/
  87468. /*****************************************************************************
  87469. *
  87470. * Utility functions
  87471. *
  87472. *****************************************************************************/
  87473. /** Tests that a sample rate is valid for FLAC.
  87474. *
  87475. * \param sample_rate The sample rate to test for compliance.
  87476. * \retval FLAC__bool
  87477. * \c true if the given sample rate conforms to the specification, else
  87478. * \c false.
  87479. */
  87480. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87481. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87482. * for valid sample rates are slightly more complex since the rate has to
  87483. * be expressible completely in the frame header.
  87484. *
  87485. * \param sample_rate The sample rate to test for compliance.
  87486. * \retval FLAC__bool
  87487. * \c true if the given sample rate conforms to the specification for the
  87488. * subset, else \c false.
  87489. */
  87490. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87491. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87492. * comment specification.
  87493. *
  87494. * Vorbis comment names must be composed only of characters from
  87495. * [0x20-0x3C,0x3E-0x7D].
  87496. *
  87497. * \param name A NUL-terminated string to be checked.
  87498. * \assert
  87499. * \code name != NULL \endcode
  87500. * \retval FLAC__bool
  87501. * \c false if entry name is illegal, else \c true.
  87502. */
  87503. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87504. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87505. * comment specification.
  87506. *
  87507. * Vorbis comment values must be valid UTF-8 sequences.
  87508. *
  87509. * \param value A string to be checked.
  87510. * \param length A the length of \a value in bytes. May be
  87511. * \c (unsigned)(-1) to indicate that \a value is a plain
  87512. * UTF-8 NUL-terminated string.
  87513. * \assert
  87514. * \code value != NULL \endcode
  87515. * \retval FLAC__bool
  87516. * \c false if entry name is illegal, else \c true.
  87517. */
  87518. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87519. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87520. * comment specification.
  87521. *
  87522. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87523. * 'value' must be legal according to
  87524. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87525. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87526. *
  87527. * \param entry An entry to be checked.
  87528. * \param length The length of \a entry in bytes.
  87529. * \assert
  87530. * \code value != NULL \endcode
  87531. * \retval FLAC__bool
  87532. * \c false if entry name is illegal, else \c true.
  87533. */
  87534. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87535. /** Check a seek table to see if it conforms to the FLAC specification.
  87536. * See the format specification for limits on the contents of the
  87537. * seek table.
  87538. *
  87539. * \param seek_table A pointer to a seek table to be checked.
  87540. * \assert
  87541. * \code seek_table != NULL \endcode
  87542. * \retval FLAC__bool
  87543. * \c false if seek table is illegal, else \c true.
  87544. */
  87545. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87546. /** Sort a seek table's seek points according to the format specification.
  87547. * This includes a "unique-ification" step to remove duplicates, i.e.
  87548. * seek points with identical \a sample_number values. Duplicate seek
  87549. * points are converted into placeholder points and sorted to the end of
  87550. * the table.
  87551. *
  87552. * \param seek_table A pointer to a seek table to be sorted.
  87553. * \assert
  87554. * \code seek_table != NULL \endcode
  87555. * \retval unsigned
  87556. * The number of duplicate seek points converted into placeholders.
  87557. */
  87558. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87559. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87560. * See the format specification for limits on the contents of the
  87561. * cue sheet.
  87562. *
  87563. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87564. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87565. * stringent requirements for a CD-DA (audio) disc.
  87566. * \param violation Address of a pointer to a string. If there is a
  87567. * violation, a pointer to a string explanation of the
  87568. * violation will be returned here. \a violation may be
  87569. * \c NULL if you don't need the returned string. Do not
  87570. * free the returned string; it will always point to static
  87571. * data.
  87572. * \assert
  87573. * \code cue_sheet != NULL \endcode
  87574. * \retval FLAC__bool
  87575. * \c false if cue sheet is illegal, else \c true.
  87576. */
  87577. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87578. /** Check picture data to see if it conforms to the FLAC specification.
  87579. * See the format specification for limits on the contents of the
  87580. * PICTURE block.
  87581. *
  87582. * \param picture A pointer to existing picture data to be checked.
  87583. * \param violation Address of a pointer to a string. If there is a
  87584. * violation, a pointer to a string explanation of the
  87585. * violation will be returned here. \a violation may be
  87586. * \c NULL if you don't need the returned string. Do not
  87587. * free the returned string; it will always point to static
  87588. * data.
  87589. * \assert
  87590. * \code picture != NULL \endcode
  87591. * \retval FLAC__bool
  87592. * \c false if picture data is illegal, else \c true.
  87593. */
  87594. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87595. /* \} */
  87596. #ifdef __cplusplus
  87597. }
  87598. #endif
  87599. #endif
  87600. /*** End of inlined file: format.h ***/
  87601. /*** Start of inlined file: metadata.h ***/
  87602. #ifndef FLAC__METADATA_H
  87603. #define FLAC__METADATA_H
  87604. #include <sys/types.h> /* for off_t */
  87605. /* --------------------------------------------------------------------
  87606. (For an example of how all these routines are used, see the source
  87607. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87608. metaflac in src/metaflac/)
  87609. ------------------------------------------------------------------*/
  87610. /** \file include/FLAC/metadata.h
  87611. *
  87612. * \brief
  87613. * This module provides functions for creating and manipulating FLAC
  87614. * metadata blocks in memory, and three progressively more powerful
  87615. * interfaces for traversing and editing metadata in FLAC files.
  87616. *
  87617. * See the detailed documentation for each interface in the
  87618. * \link flac_metadata metadata \endlink module.
  87619. */
  87620. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87621. * \ingroup flac
  87622. *
  87623. * \brief
  87624. * This module provides functions for creating and manipulating FLAC
  87625. * metadata blocks in memory, and three progressively more powerful
  87626. * interfaces for traversing and editing metadata in native FLAC files.
  87627. * Note that currently only the Chain interface (level 2) supports Ogg
  87628. * FLAC files, and it is read-only i.e. no writing back changed
  87629. * metadata to file.
  87630. *
  87631. * There are three metadata interfaces of increasing complexity:
  87632. *
  87633. * Level 0:
  87634. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87635. * PICTURE blocks.
  87636. *
  87637. * Level 1:
  87638. * Read-write access to all metadata blocks. This level is write-
  87639. * efficient in most cases (more on this below), and uses less memory
  87640. * than level 2.
  87641. *
  87642. * Level 2:
  87643. * Read-write access to all metadata blocks. This level is write-
  87644. * efficient in all cases, but uses more memory since all metadata for
  87645. * the whole file is read into memory and manipulated before writing
  87646. * out again.
  87647. *
  87648. * What do we mean by efficient? Since FLAC metadata appears at the
  87649. * beginning of the file, when writing metadata back to a FLAC file
  87650. * it is possible to grow or shrink the metadata such that the entire
  87651. * file must be rewritten. However, if the size remains the same during
  87652. * changes or PADDING blocks are utilized, only the metadata needs to be
  87653. * overwritten, which is much faster.
  87654. *
  87655. * Efficient means the whole file is rewritten at most one time, and only
  87656. * when necessary. Level 1 is not efficient only in the case that you
  87657. * cause more than one metadata block to grow or shrink beyond what can
  87658. * be accomodated by padding. In this case you should probably use level
  87659. * 2, which allows you to edit all the metadata for a file in memory and
  87660. * write it out all at once.
  87661. *
  87662. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87663. * front of the file.
  87664. *
  87665. * All levels access files via their filenames. In addition, level 2
  87666. * has additional alternative read and write functions that take an I/O
  87667. * handle and callbacks, for situations where access by filename is not
  87668. * possible.
  87669. *
  87670. * In addition to the three interfaces, this module defines functions for
  87671. * creating and manipulating various metadata objects in memory. As we see
  87672. * from the Format module, FLAC metadata blocks in memory are very primitive
  87673. * structures for storing information in an efficient way. Reading
  87674. * information from the structures is easy but creating or modifying them
  87675. * directly is more complex. The metadata object routines here facilitate
  87676. * this by taking care of the consistency and memory management drudgery.
  87677. *
  87678. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87679. * metadata however, you will not probably not need these.
  87680. *
  87681. * From a dependency standpoint, none of the encoders or decoders require
  87682. * the metadata module. This is so that embedded users can strip out the
  87683. * metadata module from libFLAC to reduce the size and complexity.
  87684. */
  87685. #ifdef __cplusplus
  87686. extern "C" {
  87687. #endif
  87688. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87689. * \ingroup flac_metadata
  87690. *
  87691. * \brief
  87692. * The level 0 interface consists of individual routines to read the
  87693. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87694. * only a filename.
  87695. *
  87696. * They try to skip any ID3v2 tag at the head of the file.
  87697. *
  87698. * \{
  87699. */
  87700. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87701. * will try to skip any ID3v2 tag at the head of the file.
  87702. *
  87703. * \param filename The path to the FLAC file to read.
  87704. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87705. * FLAC__StreamMetadata is a simple structure with no
  87706. * memory allocation involved, you pass the address of
  87707. * an existing structure. It need not be initialized.
  87708. * \assert
  87709. * \code filename != NULL \endcode
  87710. * \code streaminfo != NULL \endcode
  87711. * \retval FLAC__bool
  87712. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87713. * \c false if there was a memory allocation error, a file decoder error,
  87714. * or the file contained no STREAMINFO block. (A memory allocation error
  87715. * is possible because this function must set up a file decoder.)
  87716. */
  87717. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87718. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87719. * function will try to skip any ID3v2 tag at the head of the file.
  87720. *
  87721. * \param filename The path to the FLAC file to read.
  87722. * \param tags The address where the returned pointer will be
  87723. * stored. The \a tags object must be deleted by
  87724. * the caller using FLAC__metadata_object_delete().
  87725. * \assert
  87726. * \code filename != NULL \endcode
  87727. * \code tags != NULL \endcode
  87728. * \retval FLAC__bool
  87729. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87730. * and \a *tags will be set to the address of the metadata structure.
  87731. * Returns \c false if there was a memory allocation error, a file
  87732. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87733. * \a *tags will be set to \c NULL.
  87734. */
  87735. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87736. /** Read the CUESHEET metadata block of the given FLAC file. This
  87737. * function will try to skip any ID3v2 tag at the head of the file.
  87738. *
  87739. * \param filename The path to the FLAC file to read.
  87740. * \param cuesheet The address where the returned pointer will be
  87741. * stored. The \a cuesheet object must be deleted by
  87742. * the caller using FLAC__metadata_object_delete().
  87743. * \assert
  87744. * \code filename != NULL \endcode
  87745. * \code cuesheet != NULL \endcode
  87746. * \retval FLAC__bool
  87747. * \c true if a valid CUESHEET block was read from \a filename,
  87748. * and \a *cuesheet will be set to the address of the metadata
  87749. * structure. Returns \c false if there was a memory allocation
  87750. * error, a file decoder error, or the file contained no CUESHEET
  87751. * block, and \a *cuesheet will be set to \c NULL.
  87752. */
  87753. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87754. /** Read a PICTURE metadata block of the given FLAC file. This
  87755. * function will try to skip any ID3v2 tag at the head of the file.
  87756. * Since there can be more than one PICTURE block in a file, this
  87757. * function takes a number of parameters that act as constraints to
  87758. * the search. The PICTURE block with the largest area matching all
  87759. * the constraints will be returned, or \a *picture will be set to
  87760. * \c NULL if there was no such block.
  87761. *
  87762. * \param filename The path to the FLAC file to read.
  87763. * \param picture The address where the returned pointer will be
  87764. * stored. The \a picture object must be deleted by
  87765. * the caller using FLAC__metadata_object_delete().
  87766. * \param type The desired picture type. Use \c -1 to mean
  87767. * "any type".
  87768. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87769. * string will be matched exactly. Use \c NULL to
  87770. * mean "any MIME type".
  87771. * \param description The desired description. The string will be
  87772. * matched exactly. Use \c NULL to mean "any
  87773. * description".
  87774. * \param max_width The maximum width in pixels desired. Use
  87775. * \c (unsigned)(-1) to mean "any width".
  87776. * \param max_height The maximum height in pixels desired. Use
  87777. * \c (unsigned)(-1) to mean "any height".
  87778. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87779. * Use \c (unsigned)(-1) to mean "any depth".
  87780. * \param max_colors The maximum number of colors desired. Use
  87781. * \c (unsigned)(-1) to mean "any number of colors".
  87782. * \assert
  87783. * \code filename != NULL \endcode
  87784. * \code picture != NULL \endcode
  87785. * \retval FLAC__bool
  87786. * \c true if a valid PICTURE block was read from \a filename,
  87787. * and \a *picture will be set to the address of the metadata
  87788. * structure. Returns \c false if there was a memory allocation
  87789. * error, a file decoder error, or the file contained no PICTURE
  87790. * block, and \a *picture will be set to \c NULL.
  87791. */
  87792. 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);
  87793. /* \} */
  87794. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87795. * \ingroup flac_metadata
  87796. *
  87797. * \brief
  87798. * The level 1 interface provides read-write access to FLAC file metadata and
  87799. * operates directly on the FLAC file.
  87800. *
  87801. * The general usage of this interface is:
  87802. *
  87803. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87804. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87805. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87806. * see if the file is writable, or only read access is allowed.
  87807. * - Use FLAC__metadata_simple_iterator_next() and
  87808. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87809. * This is does not read the actual blocks themselves.
  87810. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87811. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87812. * forward from the front of the file.
  87813. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87814. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87815. * the current iterator position. The returned object is yours to modify
  87816. * and free.
  87817. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87818. * back. You must have write permission to the original file. Make sure to
  87819. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87820. * below.
  87821. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87822. * Use the object creation functions from
  87823. * \link flac_metadata_object here \endlink to generate new objects.
  87824. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87825. * currently referred to by the iterator, or replace it with padding.
  87826. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87827. * finished.
  87828. *
  87829. * \note
  87830. * The FLAC file remains open the whole time between
  87831. * FLAC__metadata_simple_iterator_init() and
  87832. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87833. * the file during this time.
  87834. *
  87835. * \note
  87836. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87837. * FLAC__StreamMetadata objects. These are managed automatically.
  87838. *
  87839. * \note
  87840. * If any of the modification functions
  87841. * (FLAC__metadata_simple_iterator_set_block(),
  87842. * FLAC__metadata_simple_iterator_delete_block(),
  87843. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87844. * you should delete the iterator as it may no longer be valid.
  87845. *
  87846. * \{
  87847. */
  87848. struct FLAC__Metadata_SimpleIterator;
  87849. /** The opaque structure definition for the level 1 iterator type.
  87850. * See the
  87851. * \link flac_metadata_level1 metadata level 1 module \endlink
  87852. * for a detailed description.
  87853. */
  87854. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87855. /** Status type for FLAC__Metadata_SimpleIterator.
  87856. *
  87857. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87858. */
  87859. typedef enum {
  87860. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87861. /**< The iterator is in the normal OK state */
  87862. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87863. /**< The data passed into a function violated the function's usage criteria */
  87864. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87865. /**< The iterator could not open the target file */
  87866. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87867. /**< The iterator could not find the FLAC signature at the start of the file */
  87868. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87869. /**< The iterator tried to write to a file that was not writable */
  87870. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87871. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87872. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87873. /**< The iterator encountered an error while reading the FLAC file */
  87874. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87875. /**< The iterator encountered an error while seeking in the FLAC file */
  87876. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87877. /**< The iterator encountered an error while writing the FLAC file */
  87878. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87879. /**< The iterator encountered an error renaming the FLAC file */
  87880. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87881. /**< The iterator encountered an error removing the temporary file */
  87882. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87883. /**< Memory allocation failed */
  87884. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87885. /**< The caller violated an assertion or an unexpected error occurred */
  87886. } FLAC__Metadata_SimpleIteratorStatus;
  87887. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87888. *
  87889. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87890. * will give the string equivalent. The contents should not be modified.
  87891. */
  87892. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87893. /** Create a new iterator instance.
  87894. *
  87895. * \retval FLAC__Metadata_SimpleIterator*
  87896. * \c NULL if there was an error allocating memory, else the new instance.
  87897. */
  87898. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87899. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87900. *
  87901. * \param iterator A pointer to an existing iterator.
  87902. * \assert
  87903. * \code iterator != NULL \endcode
  87904. */
  87905. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87906. /** Get the current status of the iterator. Call this after a function
  87907. * returns \c false to get the reason for the error. Also resets the status
  87908. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87909. *
  87910. * \param iterator A pointer to an existing iterator.
  87911. * \assert
  87912. * \code iterator != NULL \endcode
  87913. * \retval FLAC__Metadata_SimpleIteratorStatus
  87914. * The current status of the iterator.
  87915. */
  87916. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87917. /** Initialize the iterator to point to the first metadata block in the
  87918. * given FLAC file.
  87919. *
  87920. * \param iterator A pointer to an existing iterator.
  87921. * \param filename The path to the FLAC file.
  87922. * \param read_only If \c true, the FLAC file will be opened
  87923. * in read-only mode; if \c false, the FLAC
  87924. * file will be opened for edit even if no
  87925. * edits are performed.
  87926. * \param preserve_file_stats If \c true, the owner and modification
  87927. * time will be preserved even if the FLAC
  87928. * file is written to.
  87929. * \assert
  87930. * \code iterator != NULL \endcode
  87931. * \code filename != NULL \endcode
  87932. * \retval FLAC__bool
  87933. * \c false if a memory allocation error occurs, the file can't be
  87934. * opened, or another error occurs, else \c true.
  87935. */
  87936. 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);
  87937. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87938. * FLAC__metadata_simple_iterator_set_block() and
  87939. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87940. *
  87941. * \param iterator A pointer to an existing iterator.
  87942. * \assert
  87943. * \code iterator != NULL \endcode
  87944. * \retval FLAC__bool
  87945. * See above.
  87946. */
  87947. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87948. /** Moves the iterator forward one metadata block, returning \c false if
  87949. * already at the end.
  87950. *
  87951. * \param iterator A pointer to an existing initialized iterator.
  87952. * \assert
  87953. * \code iterator != NULL \endcode
  87954. * \a iterator has been successfully initialized with
  87955. * FLAC__metadata_simple_iterator_init()
  87956. * \retval FLAC__bool
  87957. * \c false if already at the last metadata block of the chain, else
  87958. * \c true.
  87959. */
  87960. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87961. /** Moves the iterator backward one metadata block, returning \c false if
  87962. * already at the beginning.
  87963. *
  87964. * \param iterator A pointer to an existing initialized iterator.
  87965. * \assert
  87966. * \code iterator != NULL \endcode
  87967. * \a iterator has been successfully initialized with
  87968. * FLAC__metadata_simple_iterator_init()
  87969. * \retval FLAC__bool
  87970. * \c false if already at the first metadata block of the chain, else
  87971. * \c true.
  87972. */
  87973. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87974. /** Returns a flag telling if the current metadata block is the last.
  87975. *
  87976. * \param iterator A pointer to an existing initialized iterator.
  87977. * \assert
  87978. * \code iterator != NULL \endcode
  87979. * \a iterator has been successfully initialized with
  87980. * FLAC__metadata_simple_iterator_init()
  87981. * \retval FLAC__bool
  87982. * \c true if the current metadata block is the last in the file,
  87983. * else \c false.
  87984. */
  87985. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87986. /** Get the offset of the metadata block at the current position. This
  87987. * avoids reading the actual block data which can save time for large
  87988. * blocks.
  87989. *
  87990. * \param iterator A pointer to an existing initialized iterator.
  87991. * \assert
  87992. * \code iterator != NULL \endcode
  87993. * \a iterator has been successfully initialized with
  87994. * FLAC__metadata_simple_iterator_init()
  87995. * \retval off_t
  87996. * The offset of the metadata block at the current iterator position.
  87997. * This is the byte offset relative to the beginning of the file of
  87998. * the current metadata block's header.
  87999. */
  88000. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  88001. /** Get the type of the metadata block at the current position. This
  88002. * avoids reading the actual block data which can save time for large
  88003. * blocks.
  88004. *
  88005. * \param iterator A pointer to an existing initialized iterator.
  88006. * \assert
  88007. * \code iterator != NULL \endcode
  88008. * \a iterator has been successfully initialized with
  88009. * FLAC__metadata_simple_iterator_init()
  88010. * \retval FLAC__MetadataType
  88011. * The type of the metadata block at the current iterator position.
  88012. */
  88013. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  88014. /** Get the length of the metadata block at the current position. This
  88015. * avoids reading the actual block data which can save time for large
  88016. * blocks.
  88017. *
  88018. * \param iterator A pointer to an existing initialized iterator.
  88019. * \assert
  88020. * \code iterator != NULL \endcode
  88021. * \a iterator has been successfully initialized with
  88022. * FLAC__metadata_simple_iterator_init()
  88023. * \retval unsigned
  88024. * The length of the metadata block at the current iterator position.
  88025. * The is same length as that in the
  88026. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  88027. * i.e. the length of the metadata body that follows the header.
  88028. */
  88029. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  88030. /** Get the application ID of the \c APPLICATION block at the current
  88031. * position. This avoids reading the actual block data which can save
  88032. * time for large blocks.
  88033. *
  88034. * \param iterator A pointer to an existing initialized iterator.
  88035. * \param id A pointer to a buffer of at least \c 4 bytes where
  88036. * the ID will be stored.
  88037. * \assert
  88038. * \code iterator != NULL \endcode
  88039. * \code id != NULL \endcode
  88040. * \a iterator has been successfully initialized with
  88041. * FLAC__metadata_simple_iterator_init()
  88042. * \retval FLAC__bool
  88043. * \c true if the ID was successfully read, else \c false, in which
  88044. * case you should check FLAC__metadata_simple_iterator_status() to
  88045. * find out why. If the status is
  88046. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  88047. * current metadata block is not an \c APPLICATION block. Otherwise
  88048. * if the status is
  88049. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  88050. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  88051. * occurred and the iterator can no longer be used.
  88052. */
  88053. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  88054. /** Get the metadata block at the current position. You can modify the
  88055. * block but must use FLAC__metadata_simple_iterator_set_block() to
  88056. * write it back to the FLAC file.
  88057. *
  88058. * You must call FLAC__metadata_object_delete() on the returned object
  88059. * when you are finished with it.
  88060. *
  88061. * \param iterator A pointer to an existing initialized iterator.
  88062. * \assert
  88063. * \code iterator != NULL \endcode
  88064. * \a iterator has been successfully initialized with
  88065. * FLAC__metadata_simple_iterator_init()
  88066. * \retval FLAC__StreamMetadata*
  88067. * The current metadata block, or \c NULL if there was a memory
  88068. * allocation error.
  88069. */
  88070. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  88071. /** Write a block back to the FLAC file. This function tries to be
  88072. * as efficient as possible; how the block is actually written is
  88073. * shown by the following:
  88074. *
  88075. * Existing block is a STREAMINFO block and the new block is a
  88076. * STREAMINFO block: the new block is written in place. Make sure
  88077. * you know what you're doing when changing the values of a
  88078. * STREAMINFO block.
  88079. *
  88080. * Existing block is a STREAMINFO block and the new block is a
  88081. * not a STREAMINFO block: this is an error since the first block
  88082. * must be a STREAMINFO block. Returns \c false without altering the
  88083. * file.
  88084. *
  88085. * Existing block is not a STREAMINFO block and the new block is a
  88086. * STREAMINFO block: this is an error since there may be only one
  88087. * STREAMINFO block. Returns \c false without altering the file.
  88088. *
  88089. * Existing block and new block are the same length: the existing
  88090. * block will be replaced by the new block, written in place.
  88091. *
  88092. * Existing block is longer than new block: if use_padding is \c true,
  88093. * the existing block will be overwritten in place with the new
  88094. * block followed by a PADDING block, if possible, to make the total
  88095. * size the same as the existing block. Remember that a padding
  88096. * block requires at least four bytes so if the difference in size
  88097. * between the new block and existing block is less than that, the
  88098. * entire file will have to be rewritten, using the new block's
  88099. * exact size. If use_padding is \c false, the entire file will be
  88100. * rewritten, replacing the existing block by the new block.
  88101. *
  88102. * Existing block is shorter than new block: if use_padding is \c true,
  88103. * the function will try and expand the new block into the following
  88104. * PADDING block, if it exists and doing so won't shrink the PADDING
  88105. * block to less than 4 bytes. If there is no following PADDING
  88106. * block, or it will shrink to less than 4 bytes, or use_padding is
  88107. * \c false, the entire file is rewritten, replacing the existing block
  88108. * with the new block. Note that in this case any following PADDING
  88109. * block is preserved as is.
  88110. *
  88111. * After writing the block, the iterator will remain in the same
  88112. * place, i.e. pointing to the new block.
  88113. *
  88114. * \param iterator A pointer to an existing initialized iterator.
  88115. * \param block The block to set.
  88116. * \param use_padding See above.
  88117. * \assert
  88118. * \code iterator != NULL \endcode
  88119. * \a iterator has been successfully initialized with
  88120. * FLAC__metadata_simple_iterator_init()
  88121. * \code block != NULL \endcode
  88122. * \retval FLAC__bool
  88123. * \c true if successful, else \c false.
  88124. */
  88125. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88126. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  88127. * except that instead of writing over an existing block, it appends
  88128. * a block after the existing block. \a use_padding is again used to
  88129. * tell the function to try an expand into following padding in an
  88130. * attempt to avoid rewriting the entire file.
  88131. *
  88132. * This function will fail and return \c false if given a STREAMINFO
  88133. * block.
  88134. *
  88135. * After writing the block, the iterator will be pointing to the
  88136. * new block.
  88137. *
  88138. * \param iterator A pointer to an existing initialized iterator.
  88139. * \param block The block to set.
  88140. * \param use_padding See above.
  88141. * \assert
  88142. * \code iterator != NULL \endcode
  88143. * \a iterator has been successfully initialized with
  88144. * FLAC__metadata_simple_iterator_init()
  88145. * \code block != NULL \endcode
  88146. * \retval FLAC__bool
  88147. * \c true if successful, else \c false.
  88148. */
  88149. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88150. /** Deletes the block at the current position. This will cause the
  88151. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  88152. * in which case the block will be replaced by an equal-sized PADDING
  88153. * block. The iterator will be left pointing to the block before the
  88154. * one just deleted.
  88155. *
  88156. * You may not delete the STREAMINFO block.
  88157. *
  88158. * \param iterator A pointer to an existing initialized iterator.
  88159. * \param use_padding See above.
  88160. * \assert
  88161. * \code iterator != NULL \endcode
  88162. * \a iterator has been successfully initialized with
  88163. * FLAC__metadata_simple_iterator_init()
  88164. * \retval FLAC__bool
  88165. * \c true if successful, else \c false.
  88166. */
  88167. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  88168. /* \} */
  88169. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  88170. * \ingroup flac_metadata
  88171. *
  88172. * \brief
  88173. * The level 2 interface provides read-write access to FLAC file metadata;
  88174. * all metadata is read into memory, operated on in memory, and then written
  88175. * to file, which is more efficient than level 1 when editing multiple blocks.
  88176. *
  88177. * Currently Ogg FLAC is supported for read only, via
  88178. * FLAC__metadata_chain_read_ogg() but a subsequent
  88179. * FLAC__metadata_chain_write() will fail.
  88180. *
  88181. * The general usage of this interface is:
  88182. *
  88183. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  88184. * linked list of FLAC metadata blocks.
  88185. * - Read all metadata into the the chain from a FLAC file using
  88186. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  88187. * check the status.
  88188. * - Optionally, consolidate the padding using
  88189. * FLAC__metadata_chain_merge_padding() or
  88190. * FLAC__metadata_chain_sort_padding().
  88191. * - Create a new iterator using FLAC__metadata_iterator_new()
  88192. * - Initialize the iterator to point to the first element in the chain
  88193. * using FLAC__metadata_iterator_init()
  88194. * - Traverse the chain using FLAC__metadata_iterator_next and
  88195. * FLAC__metadata_iterator_prev().
  88196. * - Get a block for reading or modification using
  88197. * FLAC__metadata_iterator_get_block(). The pointer to the object
  88198. * inside the chain is returned, so the block is yours to modify.
  88199. * Changes will be reflected in the FLAC file when you write the
  88200. * chain. You can also add and delete blocks (see functions below).
  88201. * - When done, write out the chain using FLAC__metadata_chain_write().
  88202. * Make sure to read the whole comment to the function below.
  88203. * - Delete the chain using FLAC__metadata_chain_delete().
  88204. *
  88205. * \note
  88206. * Even though the FLAC file is not open while the chain is being
  88207. * manipulated, you must not alter the file externally during
  88208. * this time. The chain assumes the FLAC file will not change
  88209. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88210. * and FLAC__metadata_chain_write().
  88211. *
  88212. * \note
  88213. * Do not modify the is_last, length, or type fields of returned
  88214. * FLAC__StreamMetadata objects. These are managed automatically.
  88215. *
  88216. * \note
  88217. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88218. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88219. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88220. * become owned by the chain and they will be deleted when the chain is
  88221. * deleted.
  88222. *
  88223. * \{
  88224. */
  88225. struct FLAC__Metadata_Chain;
  88226. /** The opaque structure definition for the level 2 chain type.
  88227. */
  88228. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88229. struct FLAC__Metadata_Iterator;
  88230. /** The opaque structure definition for the level 2 iterator type.
  88231. */
  88232. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88233. typedef enum {
  88234. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88235. /**< The chain is in the normal OK state */
  88236. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88237. /**< The data passed into a function violated the function's usage criteria */
  88238. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88239. /**< The chain could not open the target file */
  88240. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88241. /**< The chain could not find the FLAC signature at the start of the file */
  88242. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88243. /**< The chain tried to write to a file that was not writable */
  88244. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88245. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88246. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88247. /**< The chain encountered an error while reading the FLAC file */
  88248. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88249. /**< The chain encountered an error while seeking in the FLAC file */
  88250. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88251. /**< The chain encountered an error while writing the FLAC file */
  88252. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88253. /**< The chain encountered an error renaming the FLAC file */
  88254. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88255. /**< The chain encountered an error removing the temporary file */
  88256. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88257. /**< Memory allocation failed */
  88258. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88259. /**< The caller violated an assertion or an unexpected error occurred */
  88260. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88261. /**< One or more of the required callbacks was NULL */
  88262. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88263. /**< FLAC__metadata_chain_write() was called on a chain read by
  88264. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88265. * or
  88266. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88267. * was called on a chain read by
  88268. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88269. * Matching read/write methods must always be used. */
  88270. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88271. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88272. * chain write requires a tempfile; use
  88273. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88274. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88275. * called when the chain write does not require a tempfile; use
  88276. * FLAC__metadata_chain_write_with_callbacks() instead.
  88277. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88278. * before writing via callbacks. */
  88279. } FLAC__Metadata_ChainStatus;
  88280. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88281. *
  88282. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88283. * will give the string equivalent. The contents should not be modified.
  88284. */
  88285. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88286. /*********** FLAC__Metadata_Chain ***********/
  88287. /** Create a new chain instance.
  88288. *
  88289. * \retval FLAC__Metadata_Chain*
  88290. * \c NULL if there was an error allocating memory, else the new instance.
  88291. */
  88292. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88293. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88294. *
  88295. * \param chain A pointer to an existing chain.
  88296. * \assert
  88297. * \code chain != NULL \endcode
  88298. */
  88299. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88300. /** Get the current status of the chain. Call this after a function
  88301. * returns \c false to get the reason for the error. Also resets the
  88302. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88303. *
  88304. * \param chain A pointer to an existing chain.
  88305. * \assert
  88306. * \code chain != NULL \endcode
  88307. * \retval FLAC__Metadata_ChainStatus
  88308. * The current status of the chain.
  88309. */
  88310. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88311. /** Read all metadata from a FLAC file into the chain.
  88312. *
  88313. * \param chain A pointer to an existing chain.
  88314. * \param filename The path to the FLAC file to read.
  88315. * \assert
  88316. * \code chain != NULL \endcode
  88317. * \code filename != NULL \endcode
  88318. * \retval FLAC__bool
  88319. * \c true if a valid list of metadata blocks was read from
  88320. * \a filename, else \c false. On failure, check the status with
  88321. * FLAC__metadata_chain_status().
  88322. */
  88323. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88324. /** Read all metadata from an Ogg FLAC file into the chain.
  88325. *
  88326. * \note Ogg FLAC metadata data writing is not supported yet and
  88327. * FLAC__metadata_chain_write() will fail.
  88328. *
  88329. * \param chain A pointer to an existing chain.
  88330. * \param filename The path to the Ogg FLAC file to read.
  88331. * \assert
  88332. * \code chain != NULL \endcode
  88333. * \code filename != NULL \endcode
  88334. * \retval FLAC__bool
  88335. * \c true if a valid list of metadata blocks was read from
  88336. * \a filename, else \c false. On failure, check the status with
  88337. * FLAC__metadata_chain_status().
  88338. */
  88339. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88340. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88341. *
  88342. * The \a handle need only be open for reading, but must be seekable.
  88343. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88344. * for Windows).
  88345. *
  88346. * \param chain A pointer to an existing chain.
  88347. * \param handle The I/O handle of the FLAC stream to read. The
  88348. * handle will NOT be closed after the metadata is read;
  88349. * that is the duty of the caller.
  88350. * \param callbacks
  88351. * A set of callbacks to use for I/O. The mandatory
  88352. * callbacks are \a read, \a seek, and \a tell.
  88353. * \assert
  88354. * \code chain != NULL \endcode
  88355. * \retval FLAC__bool
  88356. * \c true if a valid list of metadata blocks was read from
  88357. * \a handle, else \c false. On failure, check the status with
  88358. * FLAC__metadata_chain_status().
  88359. */
  88360. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88361. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88362. *
  88363. * The \a handle need only be open for reading, but must be seekable.
  88364. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88365. * for Windows).
  88366. *
  88367. * \note Ogg FLAC metadata data writing is not supported yet and
  88368. * FLAC__metadata_chain_write() will fail.
  88369. *
  88370. * \param chain A pointer to an existing chain.
  88371. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88372. * handle will NOT be closed after the metadata is read;
  88373. * that is the duty of the caller.
  88374. * \param callbacks
  88375. * A set of callbacks to use for I/O. The mandatory
  88376. * callbacks are \a read, \a seek, and \a tell.
  88377. * \assert
  88378. * \code chain != NULL \endcode
  88379. * \retval FLAC__bool
  88380. * \c true if a valid list of metadata blocks was read from
  88381. * \a handle, else \c false. On failure, check the status with
  88382. * FLAC__metadata_chain_status().
  88383. */
  88384. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88385. /** Checks if writing the given chain would require the use of a
  88386. * temporary file, or if it could be written in place.
  88387. *
  88388. * Under certain conditions, padding can be utilized so that writing
  88389. * edited metadata back to the FLAC file does not require rewriting the
  88390. * entire file. If rewriting is required, then a temporary workfile is
  88391. * required. When writing metadata using callbacks, you must check
  88392. * this function to know whether to call
  88393. * FLAC__metadata_chain_write_with_callbacks() or
  88394. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88395. * writing with FLAC__metadata_chain_write(), the temporary file is
  88396. * handled internally.
  88397. *
  88398. * \param chain A pointer to an existing chain.
  88399. * \param use_padding
  88400. * Whether or not padding will be allowed to be used
  88401. * during the write. The value of \a use_padding given
  88402. * here must match the value later passed to
  88403. * FLAC__metadata_chain_write_with_callbacks() or
  88404. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88405. * \assert
  88406. * \code chain != NULL \endcode
  88407. * \retval FLAC__bool
  88408. * \c true if writing the current chain would require a tempfile, or
  88409. * \c false if metadata can be written in place.
  88410. */
  88411. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88412. /** Write all metadata out to the FLAC file. This function tries to be as
  88413. * efficient as possible; how the metadata is actually written is shown by
  88414. * the following:
  88415. *
  88416. * If the current chain is the same size as the existing metadata, the new
  88417. * data is written in place.
  88418. *
  88419. * If the current chain is longer than the existing metadata, and
  88420. * \a use_padding is \c true, and the last block is a PADDING block of
  88421. * sufficient length, the function will truncate the final padding block
  88422. * so that the overall size of the metadata is the same as the existing
  88423. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88424. * the above conditions are met, the entire FLAC file must be rewritten.
  88425. * If you want to use padding this way it is a good idea to call
  88426. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88427. * amount of padding to work with, unless you need to preserve ordering
  88428. * of the PADDING blocks for some reason.
  88429. *
  88430. * If the current chain is shorter than the existing metadata, and
  88431. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88432. * is extended to make the overall size the same as the existing data. If
  88433. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88434. * PADDING block is added to the end of the new data to make it the same
  88435. * size as the existing data (if possible, see the note to
  88436. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88437. * and the new data is written in place. If none of the above apply or
  88438. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88439. *
  88440. * If \a preserve_file_stats is \c true, the owner and modification time will
  88441. * be preserved even if the FLAC file is written.
  88442. *
  88443. * For this write function to be used, the chain must have been read with
  88444. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88445. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88446. *
  88447. * \param chain A pointer to an existing chain.
  88448. * \param use_padding See above.
  88449. * \param preserve_file_stats See above.
  88450. * \assert
  88451. * \code chain != NULL \endcode
  88452. * \retval FLAC__bool
  88453. * \c true if the write succeeded, else \c false. On failure,
  88454. * check the status with FLAC__metadata_chain_status().
  88455. */
  88456. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88457. /** Write all metadata out to a FLAC stream via callbacks.
  88458. *
  88459. * (See FLAC__metadata_chain_write() for the details on how padding is
  88460. * used to write metadata in place if possible.)
  88461. *
  88462. * The \a handle must be open for updating and be seekable. The
  88463. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88464. * for Windows).
  88465. *
  88466. * For this write function to be used, the chain must have been read with
  88467. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88468. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88469. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88470. * \c false.
  88471. *
  88472. * \param chain A pointer to an existing chain.
  88473. * \param use_padding See FLAC__metadata_chain_write()
  88474. * \param handle The I/O handle of the FLAC stream to write. The
  88475. * handle will NOT be closed after the metadata is
  88476. * written; that is the duty of the caller.
  88477. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88478. * callbacks are \a write and \a seek.
  88479. * \assert
  88480. * \code chain != NULL \endcode
  88481. * \retval FLAC__bool
  88482. * \c true if the write succeeded, else \c false. On failure,
  88483. * check the status with FLAC__metadata_chain_status().
  88484. */
  88485. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88486. /** Write all metadata out to a FLAC stream via callbacks.
  88487. *
  88488. * (See FLAC__metadata_chain_write() for the details on how padding is
  88489. * used to write metadata in place if possible.)
  88490. *
  88491. * This version of the write-with-callbacks function must be used when
  88492. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88493. * this function, you must supply an I/O handle corresponding to the
  88494. * FLAC file to edit, and a temporary handle to which the new FLAC
  88495. * file will be written. It is the caller's job to move this temporary
  88496. * FLAC file on top of the original FLAC file to complete the metadata
  88497. * edit.
  88498. *
  88499. * The \a handle must be open for reading and be seekable. The
  88500. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88501. * for Windows).
  88502. *
  88503. * The \a temp_handle must be open for writing. The
  88504. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88505. * for Windows). It should be an empty stream, or at least positioned
  88506. * at the start-of-file (in which case it is the caller's duty to
  88507. * truncate it on return).
  88508. *
  88509. * For this write function to be used, the chain must have been read with
  88510. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88511. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88512. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88513. * \c true.
  88514. *
  88515. * \param chain A pointer to an existing chain.
  88516. * \param use_padding See FLAC__metadata_chain_write()
  88517. * \param handle The I/O handle of the original FLAC stream to read.
  88518. * The handle will NOT be closed after the metadata is
  88519. * written; that is the duty of the caller.
  88520. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88521. * The mandatory callbacks are \a read, \a seek, and
  88522. * \a eof.
  88523. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88524. * handle will NOT be closed after the metadata is
  88525. * written; that is the duty of the caller.
  88526. * \param temp_callbacks
  88527. * A set of callbacks to use for I/O on temp_handle.
  88528. * The only mandatory callback is \a write.
  88529. * \assert
  88530. * \code chain != NULL \endcode
  88531. * \retval FLAC__bool
  88532. * \c true if the write succeeded, else \c false. On failure,
  88533. * check the status with FLAC__metadata_chain_status().
  88534. */
  88535. 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);
  88536. /** Merge adjacent PADDING blocks into a single block.
  88537. *
  88538. * \note This function does not write to the FLAC file, it only
  88539. * modifies the chain.
  88540. *
  88541. * \warning Any iterator on the current chain will become invalid after this
  88542. * call. You should delete the iterator and get a new one.
  88543. *
  88544. * \param chain A pointer to an existing chain.
  88545. * \assert
  88546. * \code chain != NULL \endcode
  88547. */
  88548. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88549. /** This function will move all PADDING blocks to the end on the metadata,
  88550. * then merge them into a single block.
  88551. *
  88552. * \note This function does not write to the FLAC file, it only
  88553. * modifies the chain.
  88554. *
  88555. * \warning Any iterator on the current chain will become invalid after this
  88556. * call. You should delete the iterator and get a new one.
  88557. *
  88558. * \param chain A pointer to an existing chain.
  88559. * \assert
  88560. * \code chain != NULL \endcode
  88561. */
  88562. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88563. /*********** FLAC__Metadata_Iterator ***********/
  88564. /** Create a new iterator instance.
  88565. *
  88566. * \retval FLAC__Metadata_Iterator*
  88567. * \c NULL if there was an error allocating memory, else the new instance.
  88568. */
  88569. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88570. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88571. *
  88572. * \param iterator A pointer to an existing iterator.
  88573. * \assert
  88574. * \code iterator != NULL \endcode
  88575. */
  88576. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88577. /** Initialize the iterator to point to the first metadata block in the
  88578. * given chain.
  88579. *
  88580. * \param iterator A pointer to an existing iterator.
  88581. * \param chain A pointer to an existing and initialized (read) chain.
  88582. * \assert
  88583. * \code iterator != NULL \endcode
  88584. * \code chain != NULL \endcode
  88585. */
  88586. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88587. /** Moves the iterator forward one metadata block, returning \c false if
  88588. * already at the end.
  88589. *
  88590. * \param iterator A pointer to an existing initialized iterator.
  88591. * \assert
  88592. * \code iterator != NULL \endcode
  88593. * \a iterator has been successfully initialized with
  88594. * FLAC__metadata_iterator_init()
  88595. * \retval FLAC__bool
  88596. * \c false if already at the last metadata block of the chain, else
  88597. * \c true.
  88598. */
  88599. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88600. /** Moves the iterator backward one metadata block, returning \c false if
  88601. * already at the beginning.
  88602. *
  88603. * \param iterator A pointer to an existing initialized iterator.
  88604. * \assert
  88605. * \code iterator != NULL \endcode
  88606. * \a iterator has been successfully initialized with
  88607. * FLAC__metadata_iterator_init()
  88608. * \retval FLAC__bool
  88609. * \c false if already at the first metadata block of the chain, else
  88610. * \c true.
  88611. */
  88612. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88613. /** Get the type of the metadata block at the current position.
  88614. *
  88615. * \param iterator A pointer to an existing initialized iterator.
  88616. * \assert
  88617. * \code iterator != NULL \endcode
  88618. * \a iterator has been successfully initialized with
  88619. * FLAC__metadata_iterator_init()
  88620. * \retval FLAC__MetadataType
  88621. * The type of the metadata block at the current iterator position.
  88622. */
  88623. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88624. /** Get the metadata block at the current position. You can modify
  88625. * the block in place but must write the chain before the changes
  88626. * are reflected to the FLAC file. You do not need to call
  88627. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88628. * the pointer returned by FLAC__metadata_iterator_get_block()
  88629. * points directly into the chain.
  88630. *
  88631. * \warning
  88632. * Do not call FLAC__metadata_object_delete() on the returned object;
  88633. * to delete a block use FLAC__metadata_iterator_delete_block().
  88634. *
  88635. * \param iterator A pointer to an existing initialized iterator.
  88636. * \assert
  88637. * \code iterator != NULL \endcode
  88638. * \a iterator has been successfully initialized with
  88639. * FLAC__metadata_iterator_init()
  88640. * \retval FLAC__StreamMetadata*
  88641. * The current metadata block.
  88642. */
  88643. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88644. /** Set the metadata block at the current position, replacing the existing
  88645. * block. The new block passed in becomes owned by the chain and it will be
  88646. * deleted when the chain is deleted.
  88647. *
  88648. * \param iterator A pointer to an existing initialized iterator.
  88649. * \param block A pointer to a metadata block.
  88650. * \assert
  88651. * \code iterator != NULL \endcode
  88652. * \a iterator has been successfully initialized with
  88653. * FLAC__metadata_iterator_init()
  88654. * \code block != NULL \endcode
  88655. * \retval FLAC__bool
  88656. * \c false if the conditions in the above description are not met, or
  88657. * a memory allocation error occurs, otherwise \c true.
  88658. */
  88659. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88660. /** Removes the current block from the chain. If \a replace_with_padding is
  88661. * \c true, the block will instead be replaced with a padding block of equal
  88662. * size. You can not delete the STREAMINFO block. The iterator will be
  88663. * left pointing to the block before the one just "deleted", even if
  88664. * \a replace_with_padding is \c true.
  88665. *
  88666. * \param iterator A pointer to an existing initialized iterator.
  88667. * \param replace_with_padding See above.
  88668. * \assert
  88669. * \code iterator != NULL \endcode
  88670. * \a iterator has been successfully initialized with
  88671. * FLAC__metadata_iterator_init()
  88672. * \retval FLAC__bool
  88673. * \c false if the conditions in the above description are not met,
  88674. * otherwise \c true.
  88675. */
  88676. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88677. /** Insert a new block before the current block. You cannot insert a block
  88678. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88679. * as there can be only one, the one that already exists at the head when you
  88680. * read in a chain. The chain takes ownership of the new block and it will be
  88681. * deleted when the chain is deleted. The iterator will be left pointing to
  88682. * the new block.
  88683. *
  88684. * \param iterator A pointer to an existing initialized iterator.
  88685. * \param block A pointer to a metadata block to insert.
  88686. * \assert
  88687. * \code iterator != NULL \endcode
  88688. * \a iterator has been successfully initialized with
  88689. * FLAC__metadata_iterator_init()
  88690. * \retval FLAC__bool
  88691. * \c false if the conditions in the above description are not met, or
  88692. * a memory allocation error occurs, otherwise \c true.
  88693. */
  88694. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88695. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88696. * block as there can be only one, the one that already exists at the head when
  88697. * you read in a chain. The chain takes ownership of the new block and it will
  88698. * be deleted when the chain is deleted. The iterator will be left pointing to
  88699. * the new block.
  88700. *
  88701. * \param iterator A pointer to an existing initialized iterator.
  88702. * \param block A pointer to a metadata block to insert.
  88703. * \assert
  88704. * \code iterator != NULL \endcode
  88705. * \a iterator has been successfully initialized with
  88706. * FLAC__metadata_iterator_init()
  88707. * \retval FLAC__bool
  88708. * \c false if the conditions in the above description are not met, or
  88709. * a memory allocation error occurs, otherwise \c true.
  88710. */
  88711. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88712. /* \} */
  88713. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88714. * \ingroup flac_metadata
  88715. *
  88716. * \brief
  88717. * This module contains methods for manipulating FLAC metadata objects.
  88718. *
  88719. * Since many are variable length we have to be careful about the memory
  88720. * management. We decree that all pointers to data in the object are
  88721. * owned by the object and memory-managed by the object.
  88722. *
  88723. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88724. * functions to create all instances. When using the
  88725. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88726. * \a copy to \c true to have the function make it's own copy of the data, or
  88727. * to \c false to give the object ownership of your data. In the latter case
  88728. * your pointer must be freeable by free() and will be free()d when the object
  88729. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88730. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88731. * the length argument is 0 and the \a copy argument is \c false.
  88732. *
  88733. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88734. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88735. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88736. * case of a memory allocation error.
  88737. *
  88738. * We don't have the convenience of C++ here, so note that the library relies
  88739. * on you to keep the types straight. In other words, if you pass, for
  88740. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88741. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88742. * failure.
  88743. *
  88744. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88745. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88746. * toward the length or stored in the stream, but it can make working with plain
  88747. * comments (those that don't contain embedded-NULs in the value) easier.
  88748. * Entries passed into these functions have trailing NULs added if missing, and
  88749. * returned entries are guaranteed to have a trailing NUL.
  88750. *
  88751. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88752. * comment entry/name/value will first validate that it complies with the Vorbis
  88753. * comment specification and return false if it does not.
  88754. *
  88755. * There is no need to recalculate the length field on metadata blocks you
  88756. * have modified. They will be calculated automatically before they are
  88757. * written back to a file.
  88758. *
  88759. * \{
  88760. */
  88761. /** Create a new metadata object instance of the given type.
  88762. *
  88763. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88764. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88765. * the vendor string set (but zero comments).
  88766. *
  88767. * Do not pass in a value greater than or equal to
  88768. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88769. * doing.
  88770. *
  88771. * \param type Type of object to create
  88772. * \retval FLAC__StreamMetadata*
  88773. * \c NULL if there was an error allocating memory or the type code is
  88774. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88775. */
  88776. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88777. /** Create a copy of an existing metadata object.
  88778. *
  88779. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88780. * object is also copied. The caller takes ownership of the new block and
  88781. * is responsible for freeing it with FLAC__metadata_object_delete().
  88782. *
  88783. * \param object Pointer to object to copy.
  88784. * \assert
  88785. * \code object != NULL \endcode
  88786. * \retval FLAC__StreamMetadata*
  88787. * \c NULL if there was an error allocating memory, else the new instance.
  88788. */
  88789. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88790. /** Free a metadata object. Deletes the object pointed to by \a object.
  88791. *
  88792. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88793. * object is also deleted.
  88794. *
  88795. * \param object A pointer to an existing object.
  88796. * \assert
  88797. * \code object != NULL \endcode
  88798. */
  88799. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88800. /** Compares two metadata objects.
  88801. *
  88802. * The compare is "deep", i.e. dynamically allocated data within the
  88803. * object is also compared.
  88804. *
  88805. * \param block1 A pointer to an existing object.
  88806. * \param block2 A pointer to an existing object.
  88807. * \assert
  88808. * \code block1 != NULL \endcode
  88809. * \code block2 != NULL \endcode
  88810. * \retval FLAC__bool
  88811. * \c true if objects are identical, else \c false.
  88812. */
  88813. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88814. /** Sets the application data of an APPLICATION block.
  88815. *
  88816. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88817. * takes ownership of the pointer. The existing data will be freed if this
  88818. * function is successful, otherwise the original data will remain if \a copy
  88819. * is \c true and malloc() fails.
  88820. *
  88821. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88822. *
  88823. * \param object A pointer to an existing APPLICATION object.
  88824. * \param data A pointer to the data to set.
  88825. * \param length The length of \a data in bytes.
  88826. * \param copy See above.
  88827. * \assert
  88828. * \code object != NULL \endcode
  88829. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88830. * \code (data != NULL && length > 0) ||
  88831. * (data == NULL && length == 0 && copy == false) \endcode
  88832. * \retval FLAC__bool
  88833. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88834. */
  88835. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88836. /** Resize the seekpoint array.
  88837. *
  88838. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88839. * points will be added to the end.
  88840. *
  88841. * \param object A pointer to an existing SEEKTABLE object.
  88842. * \param new_num_points The desired length of the array; may be \c 0.
  88843. * \assert
  88844. * \code object != NULL \endcode
  88845. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88846. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88847. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88848. * \retval FLAC__bool
  88849. * \c false if memory allocation error, else \c true.
  88850. */
  88851. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88852. /** Set a seekpoint in a seektable.
  88853. *
  88854. * \param object A pointer to an existing SEEKTABLE object.
  88855. * \param point_num Index into seekpoint array to set.
  88856. * \param point The point to set.
  88857. * \assert
  88858. * \code object != NULL \endcode
  88859. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88860. * \code object->data.seek_table.num_points > point_num \endcode
  88861. */
  88862. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88863. /** Insert a seekpoint into a seektable.
  88864. *
  88865. * \param object A pointer to an existing SEEKTABLE object.
  88866. * \param point_num Index into seekpoint array to set.
  88867. * \param point The point to set.
  88868. * \assert
  88869. * \code object != NULL \endcode
  88870. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88871. * \code object->data.seek_table.num_points >= point_num \endcode
  88872. * \retval FLAC__bool
  88873. * \c false if memory allocation error, else \c true.
  88874. */
  88875. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88876. /** Delete a seekpoint from a seektable.
  88877. *
  88878. * \param object A pointer to an existing SEEKTABLE object.
  88879. * \param point_num Index into seekpoint array to set.
  88880. * \assert
  88881. * \code object != NULL \endcode
  88882. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88883. * \code object->data.seek_table.num_points > point_num \endcode
  88884. * \retval FLAC__bool
  88885. * \c false if memory allocation error, else \c true.
  88886. */
  88887. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88888. /** Check a seektable to see if it conforms to the FLAC specification.
  88889. * See the format specification for limits on the contents of the
  88890. * seektable.
  88891. *
  88892. * \param object A pointer to an existing SEEKTABLE object.
  88893. * \assert
  88894. * \code object != NULL \endcode
  88895. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88896. * \retval FLAC__bool
  88897. * \c false if seek table is illegal, else \c true.
  88898. */
  88899. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88900. /** Append a number of placeholder points to the end of a seek table.
  88901. *
  88902. * \note
  88903. * As with the other ..._seektable_template_... functions, you should
  88904. * call FLAC__metadata_object_seektable_template_sort() when finished
  88905. * to make the seek table legal.
  88906. *
  88907. * \param object A pointer to an existing SEEKTABLE object.
  88908. * \param num The number of placeholder points to append.
  88909. * \assert
  88910. * \code object != NULL \endcode
  88911. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88912. * \retval FLAC__bool
  88913. * \c false if memory allocation fails, else \c true.
  88914. */
  88915. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88916. /** Append a specific seek point template to the end of a seek table.
  88917. *
  88918. * \note
  88919. * As with the other ..._seektable_template_... functions, you should
  88920. * call FLAC__metadata_object_seektable_template_sort() when finished
  88921. * to make the seek table legal.
  88922. *
  88923. * \param object A pointer to an existing SEEKTABLE object.
  88924. * \param sample_number The sample number of the seek point template.
  88925. * \assert
  88926. * \code object != NULL \endcode
  88927. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88928. * \retval FLAC__bool
  88929. * \c false if memory allocation fails, else \c true.
  88930. */
  88931. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88932. /** Append specific seek point templates to the end of a seek table.
  88933. *
  88934. * \note
  88935. * As with the other ..._seektable_template_... functions, you should
  88936. * call FLAC__metadata_object_seektable_template_sort() when finished
  88937. * to make the seek table legal.
  88938. *
  88939. * \param object A pointer to an existing SEEKTABLE object.
  88940. * \param sample_numbers An array of sample numbers for the seek points.
  88941. * \param num The number of seek point templates to append.
  88942. * \assert
  88943. * \code object != NULL \endcode
  88944. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88945. * \retval FLAC__bool
  88946. * \c false if memory allocation fails, else \c true.
  88947. */
  88948. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88949. /** Append a set of evenly-spaced seek point templates to the end of a
  88950. * seek table.
  88951. *
  88952. * \note
  88953. * As with the other ..._seektable_template_... functions, you should
  88954. * call FLAC__metadata_object_seektable_template_sort() when finished
  88955. * to make the seek table legal.
  88956. *
  88957. * \param object A pointer to an existing SEEKTABLE object.
  88958. * \param num The number of placeholder points to append.
  88959. * \param total_samples The total number of samples to be encoded;
  88960. * the seekpoints will be spaced approximately
  88961. * \a total_samples / \a num samples apart.
  88962. * \assert
  88963. * \code object != NULL \endcode
  88964. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88965. * \code total_samples > 0 \endcode
  88966. * \retval FLAC__bool
  88967. * \c false if memory allocation fails, else \c true.
  88968. */
  88969. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88970. /** Append a set of evenly-spaced seek point templates to the end of a
  88971. * seek table.
  88972. *
  88973. * \note
  88974. * As with the other ..._seektable_template_... functions, you should
  88975. * call FLAC__metadata_object_seektable_template_sort() when finished
  88976. * to make the seek table legal.
  88977. *
  88978. * \param object A pointer to an existing SEEKTABLE object.
  88979. * \param samples The number of samples apart to space the placeholder
  88980. * points. The first point will be at sample \c 0, the
  88981. * second at sample \a samples, then 2*\a samples, and
  88982. * so on. As long as \a samples and \a total_samples
  88983. * are greater than \c 0, there will always be at least
  88984. * one seekpoint at sample \c 0.
  88985. * \param total_samples The total number of samples to be encoded;
  88986. * the seekpoints will be spaced
  88987. * \a samples samples apart.
  88988. * \assert
  88989. * \code object != NULL \endcode
  88990. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88991. * \code samples > 0 \endcode
  88992. * \code total_samples > 0 \endcode
  88993. * \retval FLAC__bool
  88994. * \c false if memory allocation fails, else \c true.
  88995. */
  88996. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88997. /** Sort a seek table's seek points according to the format specification,
  88998. * removing duplicates.
  88999. *
  89000. * \param object A pointer to a seek table to be sorted.
  89001. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  89002. * If \c true, duplicates are deleted and the seek table is
  89003. * shrunk appropriately; the number of placeholder points
  89004. * present in the seek table will be the same after the call
  89005. * as before.
  89006. * \assert
  89007. * \code object != NULL \endcode
  89008. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  89009. * \retval FLAC__bool
  89010. * \c false if realloc() fails, else \c true.
  89011. */
  89012. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  89013. /** Sets the vendor string in a VORBIS_COMMENT block.
  89014. *
  89015. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89016. * one already.
  89017. *
  89018. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89019. * takes ownership of the \c entry.entry pointer.
  89020. *
  89021. * \note If this function returns \c false, the caller still owns the
  89022. * pointer.
  89023. *
  89024. * \param object A pointer to an existing VORBIS_COMMENT object.
  89025. * \param entry The entry to set the vendor string to.
  89026. * \param copy See above.
  89027. * \assert
  89028. * \code object != NULL \endcode
  89029. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89030. * \code (entry.entry != NULL && entry.length > 0) ||
  89031. * (entry.entry == NULL && entry.length == 0) \endcode
  89032. * \retval FLAC__bool
  89033. * \c false if memory allocation fails or \a entry does not comply with the
  89034. * Vorbis comment specification, else \c true.
  89035. */
  89036. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89037. /** Resize the comment array.
  89038. *
  89039. * If the size shrinks, elements will truncated; if it grows, new empty
  89040. * fields will be added to the end.
  89041. *
  89042. * \param object A pointer to an existing VORBIS_COMMENT object.
  89043. * \param new_num_comments The desired length of the array; may be \c 0.
  89044. * \assert
  89045. * \code object != NULL \endcode
  89046. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89047. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  89048. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  89049. * \retval FLAC__bool
  89050. * \c false if memory allocation fails, else \c true.
  89051. */
  89052. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  89053. /** Sets a comment in a VORBIS_COMMENT block.
  89054. *
  89055. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89056. * one already.
  89057. *
  89058. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89059. * takes ownership of the \c entry.entry pointer.
  89060. *
  89061. * \note If this function returns \c false, the caller still owns the
  89062. * pointer.
  89063. *
  89064. * \param object A pointer to an existing VORBIS_COMMENT object.
  89065. * \param comment_num Index into comment array to set.
  89066. * \param entry The entry to set the comment to.
  89067. * \param copy See above.
  89068. * \assert
  89069. * \code object != NULL \endcode
  89070. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89071. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  89072. * \code (entry.entry != NULL && entry.length > 0) ||
  89073. * (entry.entry == NULL && entry.length == 0) \endcode
  89074. * \retval FLAC__bool
  89075. * \c false if memory allocation fails or \a entry does not comply with the
  89076. * Vorbis comment specification, else \c true.
  89077. */
  89078. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89079. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  89080. *
  89081. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89082. * one already.
  89083. *
  89084. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89085. * takes ownership of the \c entry.entry pointer.
  89086. *
  89087. * \note If this function returns \c false, the caller still owns the
  89088. * pointer.
  89089. *
  89090. * \param object A pointer to an existing VORBIS_COMMENT object.
  89091. * \param comment_num The index at which to insert the comment. The comments
  89092. * at and after \a comment_num move right one position.
  89093. * To append a comment to the end, set \a comment_num to
  89094. * \c object->data.vorbis_comment.num_comments .
  89095. * \param entry The comment to insert.
  89096. * \param copy See above.
  89097. * \assert
  89098. * \code object != NULL \endcode
  89099. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89100. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  89101. * \code (entry.entry != NULL && entry.length > 0) ||
  89102. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89103. * \retval FLAC__bool
  89104. * \c false if memory allocation fails or \a entry does not comply with the
  89105. * Vorbis comment specification, else \c true.
  89106. */
  89107. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89108. /** Appends a comment to a VORBIS_COMMENT block.
  89109. *
  89110. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89111. * one already.
  89112. *
  89113. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89114. * takes ownership of the \c entry.entry pointer.
  89115. *
  89116. * \note If this function returns \c false, the caller still owns the
  89117. * pointer.
  89118. *
  89119. * \param object A pointer to an existing VORBIS_COMMENT object.
  89120. * \param entry The comment to insert.
  89121. * \param copy See above.
  89122. * \assert
  89123. * \code object != NULL \endcode
  89124. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89125. * \code (entry.entry != NULL && entry.length > 0) ||
  89126. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89127. * \retval FLAC__bool
  89128. * \c false if memory allocation fails or \a entry does not comply with the
  89129. * Vorbis comment specification, else \c true.
  89130. */
  89131. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89132. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  89133. *
  89134. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89135. * one already.
  89136. *
  89137. * Depending on the the value of \a all, either all or just the first comment
  89138. * whose field name(s) match the given entry's name will be replaced by the
  89139. * given entry. If no comments match, \a entry will simply be appended.
  89140. *
  89141. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89142. * takes ownership of the \c entry.entry pointer.
  89143. *
  89144. * \note If this function returns \c false, the caller still owns the
  89145. * pointer.
  89146. *
  89147. * \param object A pointer to an existing VORBIS_COMMENT object.
  89148. * \param entry The comment to insert.
  89149. * \param all If \c true, all comments whose field name matches
  89150. * \a entry's field name will be removed, and \a entry will
  89151. * be inserted at the position of the first matching
  89152. * comment. If \c false, only the first comment whose
  89153. * field name matches \a entry's field name will be
  89154. * replaced with \a entry.
  89155. * \param copy See above.
  89156. * \assert
  89157. * \code object != NULL \endcode
  89158. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89159. * \code (entry.entry != NULL && entry.length > 0) ||
  89160. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89161. * \retval FLAC__bool
  89162. * \c false if memory allocation fails or \a entry does not comply with the
  89163. * Vorbis comment specification, else \c true.
  89164. */
  89165. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  89166. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  89167. *
  89168. * \param object A pointer to an existing VORBIS_COMMENT object.
  89169. * \param comment_num The index of the comment to delete.
  89170. * \assert
  89171. * \code object != NULL \endcode
  89172. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89173. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  89174. * \retval FLAC__bool
  89175. * \c false if realloc() fails, else \c true.
  89176. */
  89177. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  89178. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  89179. *
  89180. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  89181. * memory and shall be owned by the caller. For convenience the entry will
  89182. * have a terminating NUL.
  89183. *
  89184. * \param entry A pointer to a Vorbis comment entry. The entry's
  89185. * \c entry pointer should not point to allocated
  89186. * memory as it will be overwritten.
  89187. * \param field_name The field name in ASCII, \c NUL terminated.
  89188. * \param field_value The field value in UTF-8, \c NUL terminated.
  89189. * \assert
  89190. * \code entry != NULL \endcode
  89191. * \code field_name != NULL \endcode
  89192. * \code field_value != NULL \endcode
  89193. * \retval FLAC__bool
  89194. * \c false if malloc() fails, or if \a field_name or \a field_value does
  89195. * not comply with the Vorbis comment specification, else \c true.
  89196. */
  89197. 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);
  89198. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  89199. *
  89200. * The returned pointers to name and value will be allocated by malloc()
  89201. * and shall be owned by the caller.
  89202. *
  89203. * \param entry An existing Vorbis comment entry.
  89204. * \param field_name The address of where the returned pointer to the
  89205. * field name will be stored.
  89206. * \param field_value The address of where the returned pointer to the
  89207. * field value will be stored.
  89208. * \assert
  89209. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89210. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89211. * \code field_name != NULL \endcode
  89212. * \code field_value != NULL \endcode
  89213. * \retval FLAC__bool
  89214. * \c false if memory allocation fails or \a entry does not comply with the
  89215. * Vorbis comment specification, else \c true.
  89216. */
  89217. 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);
  89218. /** Check if the given Vorbis comment entry's field name matches the given
  89219. * field name.
  89220. *
  89221. * \param entry An existing Vorbis comment entry.
  89222. * \param field_name The field name to check.
  89223. * \param field_name_length The length of \a field_name, not including the
  89224. * terminating \c NUL.
  89225. * \assert
  89226. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89227. * \retval FLAC__bool
  89228. * \c true if the field names match, else \c false
  89229. */
  89230. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89231. /** Find a Vorbis comment with the given field name.
  89232. *
  89233. * The search begins at entry number \a offset; use an offset of 0 to
  89234. * search from the beginning of the comment array.
  89235. *
  89236. * \param object A pointer to an existing VORBIS_COMMENT object.
  89237. * \param offset The offset into the comment array from where to start
  89238. * the search.
  89239. * \param field_name The field name of the comment to find.
  89240. * \assert
  89241. * \code object != NULL \endcode
  89242. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89243. * \code field_name != NULL \endcode
  89244. * \retval int
  89245. * The offset in the comment array of the first comment whose field
  89246. * name matches \a field_name, or \c -1 if no match was found.
  89247. */
  89248. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89249. /** Remove first Vorbis comment matching the given field name.
  89250. *
  89251. * \param object A pointer to an existing VORBIS_COMMENT object.
  89252. * \param field_name The field name of comment to delete.
  89253. * \assert
  89254. * \code object != NULL \endcode
  89255. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89256. * \retval int
  89257. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89258. * \c 1 for one matching entry deleted.
  89259. */
  89260. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89261. /** Remove all Vorbis comments matching the given field name.
  89262. *
  89263. * \param object A pointer to an existing VORBIS_COMMENT object.
  89264. * \param field_name The field name of comments to delete.
  89265. * \assert
  89266. * \code object != NULL \endcode
  89267. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89268. * \retval int
  89269. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89270. * else the number of matching entries deleted.
  89271. */
  89272. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89273. /** Create a new CUESHEET track instance.
  89274. *
  89275. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89276. *
  89277. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89278. * \c NULL if there was an error allocating memory, else the new instance.
  89279. */
  89280. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89281. /** Create a copy of an existing CUESHEET track object.
  89282. *
  89283. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89284. * object is also copied. The caller takes ownership of the new object and
  89285. * is responsible for freeing it with
  89286. * FLAC__metadata_object_cuesheet_track_delete().
  89287. *
  89288. * \param object Pointer to object to copy.
  89289. * \assert
  89290. * \code object != NULL \endcode
  89291. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89292. * \c NULL if there was an error allocating memory, else the new instance.
  89293. */
  89294. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89295. /** Delete a CUESHEET track object
  89296. *
  89297. * \param object A pointer to an existing CUESHEET track object.
  89298. * \assert
  89299. * \code object != NULL \endcode
  89300. */
  89301. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89302. /** Resize a track's index point array.
  89303. *
  89304. * If the size shrinks, elements will truncated; if it grows, new blank
  89305. * indices will be added to the end.
  89306. *
  89307. * \param object A pointer to an existing CUESHEET object.
  89308. * \param track_num The index of the track to modify. NOTE: this is not
  89309. * necessarily the same as the track's \a number field.
  89310. * \param new_num_indices The desired length of the array; may be \c 0.
  89311. * \assert
  89312. * \code object != NULL \endcode
  89313. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89314. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89315. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89316. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89317. * \retval FLAC__bool
  89318. * \c false if memory allocation error, else \c true.
  89319. */
  89320. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89321. /** Insert an index point in a CUESHEET track at the given index.
  89322. *
  89323. * \param object A pointer to an existing CUESHEET object.
  89324. * \param track_num The index of the track to modify. NOTE: this is not
  89325. * necessarily the same as the track's \a number field.
  89326. * \param index_num The index into the track's index array at which to
  89327. * insert the index point. NOTE: this is not necessarily
  89328. * the same as the index point's \a number field. The
  89329. * indices at and after \a index_num move right one
  89330. * position. To append an index point to the end, set
  89331. * \a index_num to
  89332. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89333. * \param index The index point to insert.
  89334. * \assert
  89335. * \code object != NULL \endcode
  89336. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89337. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89338. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89339. * \retval FLAC__bool
  89340. * \c false if realloc() fails, else \c true.
  89341. */
  89342. 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);
  89343. /** Insert a blank index point in a CUESHEET track at the given index.
  89344. *
  89345. * A blank index point is one in which all field values are zero.
  89346. *
  89347. * \param object A pointer to an existing CUESHEET object.
  89348. * \param track_num The index of the track to modify. NOTE: this is not
  89349. * necessarily the same as the track's \a number field.
  89350. * \param index_num The index into the track's index array at which to
  89351. * insert the index point. NOTE: this is not necessarily
  89352. * the same as the index point's \a number field. The
  89353. * indices at and after \a index_num move right one
  89354. * position. To append an index point to the end, set
  89355. * \a index_num to
  89356. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89357. * \assert
  89358. * \code object != NULL \endcode
  89359. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89360. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89361. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89362. * \retval FLAC__bool
  89363. * \c false if realloc() fails, else \c true.
  89364. */
  89365. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89366. /** Delete an index point in a CUESHEET track at the given index.
  89367. *
  89368. * \param object A pointer to an existing CUESHEET object.
  89369. * \param track_num The index into the track array of the track to
  89370. * modify. NOTE: this is not necessarily the same
  89371. * as the track's \a number field.
  89372. * \param index_num The index into the track's index array of the index
  89373. * to delete. NOTE: this is not necessarily the same
  89374. * as the index's \a number field.
  89375. * \assert
  89376. * \code object != NULL \endcode
  89377. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89378. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89379. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89380. * \retval FLAC__bool
  89381. * \c false if realloc() fails, else \c true.
  89382. */
  89383. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89384. /** Resize the track array.
  89385. *
  89386. * If the size shrinks, elements will truncated; if it grows, new blank
  89387. * tracks will be added to the end.
  89388. *
  89389. * \param object A pointer to an existing CUESHEET object.
  89390. * \param new_num_tracks The desired length of the array; may be \c 0.
  89391. * \assert
  89392. * \code object != NULL \endcode
  89393. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89394. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89395. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89396. * \retval FLAC__bool
  89397. * \c false if memory allocation error, else \c true.
  89398. */
  89399. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89400. /** Sets a track in a CUESHEET block.
  89401. *
  89402. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89403. * takes ownership of the \a track pointer.
  89404. *
  89405. * \param object A pointer to an existing CUESHEET object.
  89406. * \param track_num Index into track array to set. NOTE: this is not
  89407. * necessarily the same as the track's \a number field.
  89408. * \param track The track to set the track to. You may safely pass in
  89409. * a const pointer if \a copy is \c true.
  89410. * \param copy See above.
  89411. * \assert
  89412. * \code object != NULL \endcode
  89413. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89414. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89415. * \code (track->indices != NULL && track->num_indices > 0) ||
  89416. * (track->indices == NULL && track->num_indices == 0)
  89417. * \retval FLAC__bool
  89418. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89419. */
  89420. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89421. /** Insert a track in a CUESHEET block at the given index.
  89422. *
  89423. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89424. * takes ownership of the \a track pointer.
  89425. *
  89426. * \param object A pointer to an existing CUESHEET object.
  89427. * \param track_num The index at which to insert the track. NOTE: this
  89428. * is not necessarily the same as the track's \a number
  89429. * field. The tracks at and after \a track_num move right
  89430. * one position. To append a track to the end, set
  89431. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89432. * \param track The track to insert. You may safely pass in a const
  89433. * pointer if \a copy is \c true.
  89434. * \param copy See above.
  89435. * \assert
  89436. * \code object != NULL \endcode
  89437. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89438. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89439. * \retval FLAC__bool
  89440. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89441. */
  89442. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89443. /** Insert a blank track in a CUESHEET block at the given index.
  89444. *
  89445. * A blank track is one in which all field values are zero.
  89446. *
  89447. * \param object A pointer to an existing CUESHEET object.
  89448. * \param track_num The index at which to insert the track. NOTE: this
  89449. * is not necessarily the same as the track's \a number
  89450. * field. The tracks at and after \a track_num move right
  89451. * one position. To append a track to the end, set
  89452. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89453. * \assert
  89454. * \code object != NULL \endcode
  89455. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89456. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89457. * \retval FLAC__bool
  89458. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89459. */
  89460. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89461. /** Delete a track in a CUESHEET block at the given index.
  89462. *
  89463. * \param object A pointer to an existing CUESHEET object.
  89464. * \param track_num The index into the track array of the track to
  89465. * delete. NOTE: this is not necessarily the same
  89466. * as the track's \a number field.
  89467. * \assert
  89468. * \code object != NULL \endcode
  89469. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89470. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89471. * \retval FLAC__bool
  89472. * \c false if realloc() fails, else \c true.
  89473. */
  89474. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89475. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89476. * See the format specification for limits on the contents of the
  89477. * cue sheet.
  89478. *
  89479. * \param object A pointer to an existing CUESHEET object.
  89480. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89481. * stringent requirements for a CD-DA (audio) disc.
  89482. * \param violation Address of a pointer to a string. If there is a
  89483. * violation, a pointer to a string explanation of the
  89484. * violation will be returned here. \a violation may be
  89485. * \c NULL if you don't need the returned string. Do not
  89486. * free the returned string; it will always point to static
  89487. * data.
  89488. * \assert
  89489. * \code object != NULL \endcode
  89490. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89491. * \retval FLAC__bool
  89492. * \c false if cue sheet is illegal, else \c true.
  89493. */
  89494. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89495. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89496. * assumes the cue sheet corresponds to a CD; the result is undefined
  89497. * if the cuesheet's is_cd bit is not set.
  89498. *
  89499. * \param object A pointer to an existing CUESHEET object.
  89500. * \assert
  89501. * \code object != NULL \endcode
  89502. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89503. * \retval FLAC__uint32
  89504. * The unsigned integer representation of the CDDB/freedb ID
  89505. */
  89506. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89507. /** Sets the MIME type of a PICTURE block.
  89508. *
  89509. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89510. * takes ownership of the pointer. The existing string will be freed if this
  89511. * function is successful, otherwise the original string will remain if \a copy
  89512. * is \c true and malloc() fails.
  89513. *
  89514. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89515. *
  89516. * \param object A pointer to an existing PICTURE object.
  89517. * \param mime_type A pointer to the MIME type string. The string must be
  89518. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89519. * is done.
  89520. * \param copy See above.
  89521. * \assert
  89522. * \code object != NULL \endcode
  89523. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89524. * \code (mime_type != NULL) \endcode
  89525. * \retval FLAC__bool
  89526. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89527. */
  89528. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89529. /** Sets the description of a PICTURE block.
  89530. *
  89531. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89532. * takes ownership of the pointer. The existing string will be freed if this
  89533. * function is successful, otherwise the original string will remain if \a copy
  89534. * is \c true and malloc() fails.
  89535. *
  89536. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89537. *
  89538. * \param object A pointer to an existing PICTURE object.
  89539. * \param description A pointer to the description string. The string must be
  89540. * valid UTF-8, NUL-terminated. No validation is done.
  89541. * \param copy See above.
  89542. * \assert
  89543. * \code object != NULL \endcode
  89544. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89545. * \code (description != NULL) \endcode
  89546. * \retval FLAC__bool
  89547. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89548. */
  89549. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89550. /** Sets the picture data of a PICTURE block.
  89551. *
  89552. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89553. * takes ownership of the pointer. Also sets the \a data_length field of the
  89554. * metadata object to what is passed in as the \a length parameter. The
  89555. * existing data will be freed if this function is successful, otherwise the
  89556. * original data and data_length will remain if \a copy is \c true and
  89557. * malloc() fails.
  89558. *
  89559. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89560. *
  89561. * \param object A pointer to an existing PICTURE object.
  89562. * \param data A pointer to the data to set.
  89563. * \param length The length of \a data in bytes.
  89564. * \param copy See above.
  89565. * \assert
  89566. * \code object != NULL \endcode
  89567. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89568. * \code (data != NULL && length > 0) ||
  89569. * (data == NULL && length == 0 && copy == false) \endcode
  89570. * \retval FLAC__bool
  89571. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89572. */
  89573. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89574. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89575. * See the format specification for limits on the contents of the
  89576. * PICTURE block.
  89577. *
  89578. * \param object A pointer to existing PICTURE block to be checked.
  89579. * \param violation Address of a pointer to a string. If there is a
  89580. * violation, a pointer to a string explanation of the
  89581. * violation will be returned here. \a violation may be
  89582. * \c NULL if you don't need the returned string. Do not
  89583. * free the returned string; it will always point to static
  89584. * data.
  89585. * \assert
  89586. * \code object != NULL \endcode
  89587. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89588. * \retval FLAC__bool
  89589. * \c false if PICTURE block is illegal, else \c true.
  89590. */
  89591. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89592. /* \} */
  89593. #ifdef __cplusplus
  89594. }
  89595. #endif
  89596. #endif
  89597. /*** End of inlined file: metadata.h ***/
  89598. /*** Start of inlined file: stream_decoder.h ***/
  89599. #ifndef FLAC__STREAM_DECODER_H
  89600. #define FLAC__STREAM_DECODER_H
  89601. #include <stdio.h> /* for FILE */
  89602. #ifdef __cplusplus
  89603. extern "C" {
  89604. #endif
  89605. /** \file include/FLAC/stream_decoder.h
  89606. *
  89607. * \brief
  89608. * This module contains the functions which implement the stream
  89609. * decoder.
  89610. *
  89611. * See the detailed documentation in the
  89612. * \link flac_stream_decoder stream decoder \endlink module.
  89613. */
  89614. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89615. * \ingroup flac
  89616. *
  89617. * \brief
  89618. * This module describes the decoder layers provided by libFLAC.
  89619. *
  89620. * The stream decoder can be used to decode complete streams either from
  89621. * the client via callbacks, or directly from a file, depending on how
  89622. * it is initialized. When decoding via callbacks, the client provides
  89623. * callbacks for reading FLAC data and writing decoded samples, and
  89624. * handling metadata and errors. If the client also supplies seek-related
  89625. * callback, the decoder function for sample-accurate seeking within the
  89626. * FLAC input is also available. When decoding from a file, the client
  89627. * needs only supply a filename or open \c FILE* and write/metadata/error
  89628. * callbacks; the rest of the callbacks are supplied internally. For more
  89629. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89630. */
  89631. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89632. * \ingroup flac_decoder
  89633. *
  89634. * \brief
  89635. * This module contains the functions which implement the stream
  89636. * decoder.
  89637. *
  89638. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89639. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89640. *
  89641. * The basic usage of this decoder is as follows:
  89642. * - The program creates an instance of a decoder using
  89643. * FLAC__stream_decoder_new().
  89644. * - The program overrides the default settings using
  89645. * FLAC__stream_decoder_set_*() functions.
  89646. * - The program initializes the instance to validate the settings and
  89647. * prepare for decoding using
  89648. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89649. * or FLAC__stream_decoder_init_file() for native FLAC,
  89650. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89651. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89652. * - The program calls the FLAC__stream_decoder_process_*() functions
  89653. * to decode data, which subsequently calls the callbacks.
  89654. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89655. * which flushes the input and output and resets the decoder to the
  89656. * uninitialized state.
  89657. * - The instance may be used again or deleted with
  89658. * FLAC__stream_decoder_delete().
  89659. *
  89660. * In more detail, the program will create a new instance by calling
  89661. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89662. * functions to override the default decoder options, and call
  89663. * one of the FLAC__stream_decoder_init_*() functions.
  89664. *
  89665. * There are three initialization functions for native FLAC, one for
  89666. * setting up the decoder to decode FLAC data from the client via
  89667. * callbacks, and two for decoding directly from a FLAC file.
  89668. *
  89669. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89670. * You must also supply several callbacks for handling I/O. Some (like
  89671. * seeking) are optional, depending on the capabilities of the input.
  89672. *
  89673. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89674. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89675. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89676. * the other callbacks internally.
  89677. *
  89678. * There are three similarly-named init functions for decoding from Ogg
  89679. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89680. * library has been built with Ogg support.
  89681. *
  89682. * Once the decoder is initialized, your program will call one of several
  89683. * functions to start the decoding process:
  89684. *
  89685. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89686. * most one metadata block or audio frame and return, calling either the
  89687. * metadata callback or write callback, respectively, once. If the decoder
  89688. * loses sync it will return with only the error callback being called.
  89689. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89690. * to process the stream from the current location and stop upon reaching
  89691. * the first audio frame. The client will get one metadata, write, or error
  89692. * callback per metadata block, audio frame, or sync error, respectively.
  89693. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89694. * to process the stream from the current location until the read callback
  89695. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89696. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89697. * write, or error callback per metadata block, audio frame, or sync error,
  89698. * respectively.
  89699. *
  89700. * When the decoder has finished decoding (normally or through an abort),
  89701. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89702. * ensures the decoder is in the correct state and frees memory. Then the
  89703. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89704. * again to decode another stream.
  89705. *
  89706. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89707. * At any point after the stream decoder has been initialized, the client can
  89708. * call this function to seek to an exact sample within the stream.
  89709. * Subsequently, the first time the write callback is called it will be
  89710. * passed a (possibly partial) block starting at that sample.
  89711. *
  89712. * If the client cannot seek via the callback interface provided, but still
  89713. * has another way of seeking, it can flush the decoder using
  89714. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89715. * through the read callback.
  89716. *
  89717. * The stream decoder also provides MD5 signature checking. If this is
  89718. * turned on before initialization, FLAC__stream_decoder_finish() will
  89719. * report when the decoded MD5 signature does not match the one stored
  89720. * in the STREAMINFO block. MD5 checking is automatically turned off
  89721. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89722. * in the STREAMINFO block or when a seek is attempted.
  89723. *
  89724. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89725. * attention. By default, the decoder only calls the metadata_callback for
  89726. * the STREAMINFO block. These functions allow you to tell the decoder
  89727. * explicitly which blocks to parse and return via the metadata_callback
  89728. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89729. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89730. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89731. * which blocks to return. Remember that metadata blocks can potentially
  89732. * be big (for example, cover art) so filtering out the ones you don't
  89733. * use can reduce the memory requirements of the decoder. Also note the
  89734. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89735. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89736. * filtering APPLICATION blocks based on the application ID.
  89737. *
  89738. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89739. * they still can legally be filtered from the metadata_callback.
  89740. *
  89741. * \note
  89742. * The "set" functions may only be called when the decoder is in the
  89743. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89744. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89745. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89746. * return \c true, otherwise \c false.
  89747. *
  89748. * \note
  89749. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89750. * defaults, including the callbacks.
  89751. *
  89752. * \{
  89753. */
  89754. /** State values for a FLAC__StreamDecoder
  89755. *
  89756. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89757. */
  89758. typedef enum {
  89759. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89760. /**< The decoder is ready to search for metadata. */
  89761. FLAC__STREAM_DECODER_READ_METADATA,
  89762. /**< The decoder is ready to or is in the process of reading metadata. */
  89763. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89764. /**< The decoder is ready to or is in the process of searching for the
  89765. * frame sync code.
  89766. */
  89767. FLAC__STREAM_DECODER_READ_FRAME,
  89768. /**< The decoder is ready to or is in the process of reading a frame. */
  89769. FLAC__STREAM_DECODER_END_OF_STREAM,
  89770. /**< The decoder has reached the end of the stream. */
  89771. FLAC__STREAM_DECODER_OGG_ERROR,
  89772. /**< An error occurred in the underlying Ogg layer. */
  89773. FLAC__STREAM_DECODER_SEEK_ERROR,
  89774. /**< An error occurred while seeking. The decoder must be flushed
  89775. * with FLAC__stream_decoder_flush() or reset with
  89776. * FLAC__stream_decoder_reset() before decoding can continue.
  89777. */
  89778. FLAC__STREAM_DECODER_ABORTED,
  89779. /**< The decoder was aborted by the read callback. */
  89780. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89781. /**< An error occurred allocating memory. The decoder is in an invalid
  89782. * state and can no longer be used.
  89783. */
  89784. FLAC__STREAM_DECODER_UNINITIALIZED
  89785. /**< The decoder is in the uninitialized state; one of the
  89786. * FLAC__stream_decoder_init_*() functions must be called before samples
  89787. * can be processed.
  89788. */
  89789. } FLAC__StreamDecoderState;
  89790. /** Maps a FLAC__StreamDecoderState to a C string.
  89791. *
  89792. * Using a FLAC__StreamDecoderState as the index to this array
  89793. * will give the string equivalent. The contents should not be modified.
  89794. */
  89795. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89796. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89797. */
  89798. typedef enum {
  89799. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89800. /**< Initialization was successful. */
  89801. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89802. /**< The library was not compiled with support for the given container
  89803. * format.
  89804. */
  89805. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89806. /**< A required callback was not supplied. */
  89807. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89808. /**< An error occurred allocating memory. */
  89809. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89810. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89811. * FLAC__stream_decoder_init_ogg_file(). */
  89812. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89813. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89814. * already initialized, usually because
  89815. * FLAC__stream_decoder_finish() was not called.
  89816. */
  89817. } FLAC__StreamDecoderInitStatus;
  89818. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89819. *
  89820. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89821. * will give the string equivalent. The contents should not be modified.
  89822. */
  89823. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89824. /** Return values for the FLAC__StreamDecoder read callback.
  89825. */
  89826. typedef enum {
  89827. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89828. /**< The read was OK and decoding can continue. */
  89829. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89830. /**< The read was attempted while at the end of the stream. Note that
  89831. * the client must only return this value when the read callback was
  89832. * called when already at the end of the stream. Otherwise, if the read
  89833. * itself moves to the end of the stream, the client should still return
  89834. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89835. * the next read callback it should return
  89836. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89837. * of \c 0.
  89838. */
  89839. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89840. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89841. } FLAC__StreamDecoderReadStatus;
  89842. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89843. *
  89844. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89845. * will give the string equivalent. The contents should not be modified.
  89846. */
  89847. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89848. /** Return values for the FLAC__StreamDecoder seek callback.
  89849. */
  89850. typedef enum {
  89851. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89852. /**< The seek was OK and decoding can continue. */
  89853. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89854. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89855. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89856. /**< Client does not support seeking. */
  89857. } FLAC__StreamDecoderSeekStatus;
  89858. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89859. *
  89860. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89861. * will give the string equivalent. The contents should not be modified.
  89862. */
  89863. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89864. /** Return values for the FLAC__StreamDecoder tell callback.
  89865. */
  89866. typedef enum {
  89867. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89868. /**< The tell was OK and decoding can continue. */
  89869. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89870. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89871. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89872. /**< Client does not support telling the position. */
  89873. } FLAC__StreamDecoderTellStatus;
  89874. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89875. *
  89876. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89877. * will give the string equivalent. The contents should not be modified.
  89878. */
  89879. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89880. /** Return values for the FLAC__StreamDecoder length callback.
  89881. */
  89882. typedef enum {
  89883. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89884. /**< The length call was OK and decoding can continue. */
  89885. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89886. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89887. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89888. /**< Client does not support reporting the length. */
  89889. } FLAC__StreamDecoderLengthStatus;
  89890. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89891. *
  89892. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89893. * will give the string equivalent. The contents should not be modified.
  89894. */
  89895. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89896. /** Return values for the FLAC__StreamDecoder write callback.
  89897. */
  89898. typedef enum {
  89899. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89900. /**< The write was OK and decoding can continue. */
  89901. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89902. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89903. } FLAC__StreamDecoderWriteStatus;
  89904. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89905. *
  89906. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89907. * will give the string equivalent. The contents should not be modified.
  89908. */
  89909. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89910. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89911. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89912. * all. The rest could be caused by bad sync (false synchronization on
  89913. * data that is not the start of a frame) or corrupted data. The error
  89914. * itself is the decoder's best guess at what happened assuming a correct
  89915. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89916. * could be caused by a correct sync on the start of a frame, but some
  89917. * data in the frame header was corrupted. Or it could be the result of
  89918. * syncing on a point the stream that looked like the starting of a frame
  89919. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89920. * could be because the decoder encountered a valid frame made by a future
  89921. * version of the encoder which it cannot parse, or because of a false
  89922. * sync making it appear as though an encountered frame was generated by
  89923. * a future encoder.
  89924. */
  89925. typedef enum {
  89926. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89927. /**< An error in the stream caused the decoder to lose synchronization. */
  89928. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89929. /**< The decoder encountered a corrupted frame header. */
  89930. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89931. /**< The frame's data did not match the CRC in the footer. */
  89932. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89933. /**< The decoder encountered reserved fields in use in the stream. */
  89934. } FLAC__StreamDecoderErrorStatus;
  89935. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89936. *
  89937. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89938. * will give the string equivalent. The contents should not be modified.
  89939. */
  89940. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89941. /***********************************************************************
  89942. *
  89943. * class FLAC__StreamDecoder
  89944. *
  89945. ***********************************************************************/
  89946. struct FLAC__StreamDecoderProtected;
  89947. struct FLAC__StreamDecoderPrivate;
  89948. /** The opaque structure definition for the stream decoder type.
  89949. * See the \link flac_stream_decoder stream decoder module \endlink
  89950. * for a detailed description.
  89951. */
  89952. typedef struct {
  89953. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89954. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89955. } FLAC__StreamDecoder;
  89956. /** Signature for the read callback.
  89957. *
  89958. * A function pointer matching this signature must be passed to
  89959. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89960. * called when the decoder needs more input data. The address of the
  89961. * buffer to be filled is supplied, along with the number of bytes the
  89962. * buffer can hold. The callback may choose to supply less data and
  89963. * modify the byte count but must be careful not to overflow the buffer.
  89964. * The callback then returns a status code chosen from
  89965. * FLAC__StreamDecoderReadStatus.
  89966. *
  89967. * Here is an example of a read callback for stdio streams:
  89968. * \code
  89969. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89970. * {
  89971. * FILE *file = ((MyClientData*)client_data)->file;
  89972. * if(*bytes > 0) {
  89973. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89974. * if(ferror(file))
  89975. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89976. * else if(*bytes == 0)
  89977. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89978. * else
  89979. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89980. * }
  89981. * else
  89982. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89983. * }
  89984. * \endcode
  89985. *
  89986. * \note In general, FLAC__StreamDecoder functions which change the
  89987. * state should not be called on the \a decoder while in the callback.
  89988. *
  89989. * \param decoder The decoder instance calling the callback.
  89990. * \param buffer A pointer to a location for the callee to store
  89991. * data to be decoded.
  89992. * \param bytes A pointer to the size of the buffer. On entry
  89993. * to the callback, it contains the maximum number
  89994. * of bytes that may be stored in \a buffer. The
  89995. * callee must set it to the actual number of bytes
  89996. * stored (0 in case of error or end-of-stream) before
  89997. * returning.
  89998. * \param client_data The callee's client data set through
  89999. * FLAC__stream_decoder_init_*().
  90000. * \retval FLAC__StreamDecoderReadStatus
  90001. * The callee's return status. Note that the callback should return
  90002. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  90003. * zero bytes were read and there is no more data to be read.
  90004. */
  90005. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90006. /** Signature for the seek callback.
  90007. *
  90008. * A function pointer matching this signature may be passed to
  90009. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90010. * called when the decoder needs to seek the input stream. The decoder
  90011. * will pass the absolute byte offset to seek to, 0 meaning the
  90012. * beginning of the stream.
  90013. *
  90014. * Here is an example of a seek callback for stdio streams:
  90015. * \code
  90016. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90017. * {
  90018. * FILE *file = ((MyClientData*)client_data)->file;
  90019. * if(file == stdin)
  90020. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  90021. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90022. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  90023. * else
  90024. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  90025. * }
  90026. * \endcode
  90027. *
  90028. * \note In general, FLAC__StreamDecoder functions which change the
  90029. * state should not be called on the \a decoder while in the callback.
  90030. *
  90031. * \param decoder The decoder instance calling the callback.
  90032. * \param absolute_byte_offset The offset from the beginning of the stream
  90033. * to seek to.
  90034. * \param client_data The callee's client data set through
  90035. * FLAC__stream_decoder_init_*().
  90036. * \retval FLAC__StreamDecoderSeekStatus
  90037. * The callee's return status.
  90038. */
  90039. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90040. /** Signature for the tell callback.
  90041. *
  90042. * A function pointer matching this signature may be passed to
  90043. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90044. * called when the decoder wants to know the current position of the
  90045. * stream. The callback should return the byte offset from the
  90046. * beginning of the stream.
  90047. *
  90048. * Here is an example of a tell callback for stdio streams:
  90049. * \code
  90050. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90051. * {
  90052. * FILE *file = ((MyClientData*)client_data)->file;
  90053. * off_t pos;
  90054. * if(file == stdin)
  90055. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  90056. * else if((pos = ftello(file)) < 0)
  90057. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  90058. * else {
  90059. * *absolute_byte_offset = (FLAC__uint64)pos;
  90060. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  90061. * }
  90062. * }
  90063. * \endcode
  90064. *
  90065. * \note In general, FLAC__StreamDecoder functions which change the
  90066. * state should not be called on the \a decoder while in the callback.
  90067. *
  90068. * \param decoder The decoder instance calling the callback.
  90069. * \param absolute_byte_offset A pointer to storage for the current offset
  90070. * from the beginning of the stream.
  90071. * \param client_data The callee's client data set through
  90072. * FLAC__stream_decoder_init_*().
  90073. * \retval FLAC__StreamDecoderTellStatus
  90074. * The callee's return status.
  90075. */
  90076. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90077. /** Signature for the length callback.
  90078. *
  90079. * A function pointer matching this signature may be passed to
  90080. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90081. * called when the decoder wants to know the total length of the stream
  90082. * in bytes.
  90083. *
  90084. * Here is an example of a length callback for stdio streams:
  90085. * \code
  90086. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  90087. * {
  90088. * FILE *file = ((MyClientData*)client_data)->file;
  90089. * struct stat filestats;
  90090. *
  90091. * if(file == stdin)
  90092. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  90093. * else if(fstat(fileno(file), &filestats) != 0)
  90094. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  90095. * else {
  90096. * *stream_length = (FLAC__uint64)filestats.st_size;
  90097. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  90098. * }
  90099. * }
  90100. * \endcode
  90101. *
  90102. * \note In general, FLAC__StreamDecoder functions which change the
  90103. * state should not be called on the \a decoder while in the callback.
  90104. *
  90105. * \param decoder The decoder instance calling the callback.
  90106. * \param stream_length A pointer to storage for the length of the stream
  90107. * in bytes.
  90108. * \param client_data The callee's client data set through
  90109. * FLAC__stream_decoder_init_*().
  90110. * \retval FLAC__StreamDecoderLengthStatus
  90111. * The callee's return status.
  90112. */
  90113. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  90114. /** Signature for the EOF callback.
  90115. *
  90116. * A function pointer matching this signature may be passed to
  90117. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90118. * called when the decoder needs to know if the end of the stream has
  90119. * been reached.
  90120. *
  90121. * Here is an example of a EOF callback for stdio streams:
  90122. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  90123. * \code
  90124. * {
  90125. * FILE *file = ((MyClientData*)client_data)->file;
  90126. * return feof(file)? true : false;
  90127. * }
  90128. * \endcode
  90129. *
  90130. * \note In general, FLAC__StreamDecoder functions which change the
  90131. * state should not be called on the \a decoder while in the callback.
  90132. *
  90133. * \param decoder The decoder instance calling the callback.
  90134. * \param client_data The callee's client data set through
  90135. * FLAC__stream_decoder_init_*().
  90136. * \retval FLAC__bool
  90137. * \c true if the currently at the end of the stream, else \c false.
  90138. */
  90139. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  90140. /** Signature for the write callback.
  90141. *
  90142. * A function pointer matching this signature must be passed to one of
  90143. * the FLAC__stream_decoder_init_*() functions.
  90144. * The supplied function will be called when the decoder has decoded a
  90145. * single audio frame. The decoder will pass the frame metadata as well
  90146. * as an array of pointers (one for each channel) pointing to the
  90147. * decoded audio.
  90148. *
  90149. * \note In general, FLAC__StreamDecoder functions which change the
  90150. * state should not be called on the \a decoder while in the callback.
  90151. *
  90152. * \param decoder The decoder instance calling the callback.
  90153. * \param frame The description of the decoded frame. See
  90154. * FLAC__Frame.
  90155. * \param buffer An array of pointers to decoded channels of data.
  90156. * Each pointer will point to an array of signed
  90157. * samples of length \a frame->header.blocksize.
  90158. * Channels will be ordered according to the FLAC
  90159. * specification; see the documentation for the
  90160. * <A HREF="../format.html#frame_header">frame header</A>.
  90161. * \param client_data The callee's client data set through
  90162. * FLAC__stream_decoder_init_*().
  90163. * \retval FLAC__StreamDecoderWriteStatus
  90164. * The callee's return status.
  90165. */
  90166. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  90167. /** Signature for the metadata callback.
  90168. *
  90169. * A function pointer matching this signature must be passed to one of
  90170. * the FLAC__stream_decoder_init_*() functions.
  90171. * The supplied function will be called when the decoder has decoded a
  90172. * metadata block. In a valid FLAC file there will always be one
  90173. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  90174. * These will be supplied by the decoder in the same order as they
  90175. * appear in the stream and always before the first audio frame (i.e.
  90176. * write callback). The metadata block that is passed in must not be
  90177. * modified, and it doesn't live beyond the callback, so you should make
  90178. * a copy of it with FLAC__metadata_object_clone() if you will need it
  90179. * elsewhere. Since metadata blocks can potentially be large, by
  90180. * default the decoder only calls the metadata callback for the
  90181. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  90182. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  90183. *
  90184. * \note In general, FLAC__StreamDecoder functions which change the
  90185. * state should not be called on the \a decoder while in the callback.
  90186. *
  90187. * \param decoder The decoder instance calling the callback.
  90188. * \param metadata The decoded metadata block.
  90189. * \param client_data The callee's client data set through
  90190. * FLAC__stream_decoder_init_*().
  90191. */
  90192. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90193. /** Signature for the error callback.
  90194. *
  90195. * A function pointer matching this signature must be passed to one of
  90196. * the FLAC__stream_decoder_init_*() functions.
  90197. * The supplied function will be called whenever an error occurs during
  90198. * decoding.
  90199. *
  90200. * \note In general, FLAC__StreamDecoder functions which change the
  90201. * state should not be called on the \a decoder while in the callback.
  90202. *
  90203. * \param decoder The decoder instance calling the callback.
  90204. * \param status The error encountered by the decoder.
  90205. * \param client_data The callee's client data set through
  90206. * FLAC__stream_decoder_init_*().
  90207. */
  90208. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90209. /***********************************************************************
  90210. *
  90211. * Class constructor/destructor
  90212. *
  90213. ***********************************************************************/
  90214. /** Create a new stream decoder instance. The instance is created with
  90215. * default settings; see the individual FLAC__stream_decoder_set_*()
  90216. * functions for each setting's default.
  90217. *
  90218. * \retval FLAC__StreamDecoder*
  90219. * \c NULL if there was an error allocating memory, else the new instance.
  90220. */
  90221. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90222. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90223. *
  90224. * \param decoder A pointer to an existing decoder.
  90225. * \assert
  90226. * \code decoder != NULL \endcode
  90227. */
  90228. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90229. /***********************************************************************
  90230. *
  90231. * Public class method prototypes
  90232. *
  90233. ***********************************************************************/
  90234. /** Set the serial number for the FLAC stream within the Ogg container.
  90235. * The default behavior is to use the serial number of the first Ogg
  90236. * page. Setting a serial number here will explicitly specify which
  90237. * stream is to be decoded.
  90238. *
  90239. * \note
  90240. * This does not need to be set for native FLAC decoding.
  90241. *
  90242. * \default \c use serial number of first page
  90243. * \param decoder A decoder instance to set.
  90244. * \param serial_number See above.
  90245. * \assert
  90246. * \code decoder != NULL \endcode
  90247. * \retval FLAC__bool
  90248. * \c false if the decoder is already initialized, else \c true.
  90249. */
  90250. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90251. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90252. * compute the MD5 signature of the unencoded audio data while decoding
  90253. * and compare it to the signature from the STREAMINFO block, if it
  90254. * exists, during FLAC__stream_decoder_finish().
  90255. *
  90256. * MD5 signature checking will be turned off (until the next
  90257. * FLAC__stream_decoder_reset()) if there is no signature in the
  90258. * STREAMINFO block or when a seek is attempted.
  90259. *
  90260. * Clients that do not use the MD5 check should leave this off to speed
  90261. * up decoding.
  90262. *
  90263. * \default \c false
  90264. * \param decoder A decoder instance to set.
  90265. * \param value Flag value (see above).
  90266. * \assert
  90267. * \code decoder != NULL \endcode
  90268. * \retval FLAC__bool
  90269. * \c false if the decoder is already initialized, else \c true.
  90270. */
  90271. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90272. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90273. *
  90274. * \default By default, only the \c STREAMINFO block is returned via the
  90275. * metadata callback.
  90276. * \param decoder A decoder instance to set.
  90277. * \param type See above.
  90278. * \assert
  90279. * \code decoder != NULL \endcode
  90280. * \a type is valid
  90281. * \retval FLAC__bool
  90282. * \c false if the decoder is already initialized, else \c true.
  90283. */
  90284. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90285. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90286. * given \a id.
  90287. *
  90288. * \default By default, only the \c STREAMINFO block is returned via the
  90289. * metadata callback.
  90290. * \param decoder A decoder instance to set.
  90291. * \param id See above.
  90292. * \assert
  90293. * \code decoder != NULL \endcode
  90294. * \code id != NULL \endcode
  90295. * \retval FLAC__bool
  90296. * \c false if the decoder is already initialized, else \c true.
  90297. */
  90298. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90299. /** Direct the decoder to pass on all metadata blocks of any type.
  90300. *
  90301. * \default By default, only the \c STREAMINFO block is returned via the
  90302. * metadata callback.
  90303. * \param decoder A decoder instance to set.
  90304. * \assert
  90305. * \code decoder != NULL \endcode
  90306. * \retval FLAC__bool
  90307. * \c false if the decoder is already initialized, else \c true.
  90308. */
  90309. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90310. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90311. *
  90312. * \default By default, only the \c STREAMINFO block is returned via the
  90313. * metadata callback.
  90314. * \param decoder A decoder instance to set.
  90315. * \param type See above.
  90316. * \assert
  90317. * \code decoder != NULL \endcode
  90318. * \a type is valid
  90319. * \retval FLAC__bool
  90320. * \c false if the decoder is already initialized, else \c true.
  90321. */
  90322. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90323. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90324. * the given \a id.
  90325. *
  90326. * \default By default, only the \c STREAMINFO block is returned via the
  90327. * metadata callback.
  90328. * \param decoder A decoder instance to set.
  90329. * \param id See above.
  90330. * \assert
  90331. * \code decoder != NULL \endcode
  90332. * \code id != NULL \endcode
  90333. * \retval FLAC__bool
  90334. * \c false if the decoder is already initialized, else \c true.
  90335. */
  90336. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90337. /** Direct the decoder to filter out all metadata blocks of any type.
  90338. *
  90339. * \default By default, only the \c STREAMINFO block is returned via the
  90340. * metadata callback.
  90341. * \param decoder A decoder instance to set.
  90342. * \assert
  90343. * \code decoder != NULL \endcode
  90344. * \retval FLAC__bool
  90345. * \c false if the decoder is already initialized, else \c true.
  90346. */
  90347. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90348. /** Get the current decoder state.
  90349. *
  90350. * \param decoder A decoder instance to query.
  90351. * \assert
  90352. * \code decoder != NULL \endcode
  90353. * \retval FLAC__StreamDecoderState
  90354. * The current decoder state.
  90355. */
  90356. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90357. /** Get the current decoder state as a C string.
  90358. *
  90359. * \param decoder A decoder instance to query.
  90360. * \assert
  90361. * \code decoder != NULL \endcode
  90362. * \retval const char *
  90363. * The decoder state as a C string. Do not modify the contents.
  90364. */
  90365. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90366. /** Get the "MD5 signature checking" flag.
  90367. * This is the value of the setting, not whether or not the decoder is
  90368. * currently checking the MD5 (remember, it can be turned off automatically
  90369. * by a seek). When the decoder is reset the flag will be restored to the
  90370. * value returned by this function.
  90371. *
  90372. * \param decoder A decoder instance to query.
  90373. * \assert
  90374. * \code decoder != NULL \endcode
  90375. * \retval FLAC__bool
  90376. * See above.
  90377. */
  90378. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90379. /** Get the total number of samples in the stream being decoded.
  90380. * Will only be valid after decoding has started and will contain the
  90381. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90382. *
  90383. * \param decoder A decoder instance to query.
  90384. * \assert
  90385. * \code decoder != NULL \endcode
  90386. * \retval unsigned
  90387. * See above.
  90388. */
  90389. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90390. /** Get the current number of channels in the stream being decoded.
  90391. * Will only be valid after decoding has started and will contain the
  90392. * value from the most recently decoded frame header.
  90393. *
  90394. * \param decoder A decoder instance to query.
  90395. * \assert
  90396. * \code decoder != NULL \endcode
  90397. * \retval unsigned
  90398. * See above.
  90399. */
  90400. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90401. /** Get the current channel assignment in the stream being decoded.
  90402. * Will only be valid after decoding has started and will contain the
  90403. * value from the most recently decoded frame header.
  90404. *
  90405. * \param decoder A decoder instance to query.
  90406. * \assert
  90407. * \code decoder != NULL \endcode
  90408. * \retval FLAC__ChannelAssignment
  90409. * See above.
  90410. */
  90411. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90412. /** Get the current sample resolution in the stream being decoded.
  90413. * Will only be valid after decoding has started and will contain the
  90414. * value from the most recently decoded frame header.
  90415. *
  90416. * \param decoder A decoder instance to query.
  90417. * \assert
  90418. * \code decoder != NULL \endcode
  90419. * \retval unsigned
  90420. * See above.
  90421. */
  90422. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90423. /** Get the current sample rate in Hz of the stream being decoded.
  90424. * Will only be valid after decoding has started and will contain the
  90425. * value from the most recently decoded frame header.
  90426. *
  90427. * \param decoder A decoder instance to query.
  90428. * \assert
  90429. * \code decoder != NULL \endcode
  90430. * \retval unsigned
  90431. * See above.
  90432. */
  90433. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90434. /** Get the current blocksize of the stream being decoded.
  90435. * Will only be valid after decoding has started and will contain the
  90436. * value from the most recently decoded frame header.
  90437. *
  90438. * \param decoder A decoder instance to query.
  90439. * \assert
  90440. * \code decoder != NULL \endcode
  90441. * \retval unsigned
  90442. * See above.
  90443. */
  90444. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90445. /** Returns the decoder's current read position within the stream.
  90446. * The position is the byte offset from the start of the stream.
  90447. * Bytes before this position have been fully decoded. Note that
  90448. * there may still be undecoded bytes in the decoder's read FIFO.
  90449. * The returned position is correct even after a seek.
  90450. *
  90451. * \warning This function currently only works for native FLAC,
  90452. * not Ogg FLAC streams.
  90453. *
  90454. * \param decoder A decoder instance to query.
  90455. * \param position Address at which to return the desired position.
  90456. * \assert
  90457. * \code decoder != NULL \endcode
  90458. * \code position != NULL \endcode
  90459. * \retval FLAC__bool
  90460. * \c true if successful, \c false if the stream is not native FLAC,
  90461. * or there was an error from the 'tell' callback or it returned
  90462. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90463. */
  90464. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90465. /** Initialize the decoder instance to decode native FLAC streams.
  90466. *
  90467. * This flavor of initialization sets up the decoder to decode from a
  90468. * native FLAC stream. I/O is performed via callbacks to the client.
  90469. * For decoding from a plain file via filename or open FILE*,
  90470. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90471. * provide a simpler interface.
  90472. *
  90473. * This function should be called after FLAC__stream_decoder_new() and
  90474. * FLAC__stream_decoder_set_*() but before any of the
  90475. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90476. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90477. * if initialization succeeded.
  90478. *
  90479. * \param decoder An uninitialized decoder instance.
  90480. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90481. * pointer must not be \c NULL.
  90482. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90483. * pointer may be \c NULL if seeking is not
  90484. * supported. If \a seek_callback is not \c NULL then a
  90485. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90486. * Alternatively, a dummy seek callback that just
  90487. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90488. * may also be supplied, all though this is slightly
  90489. * less efficient for the decoder.
  90490. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90491. * pointer may be \c NULL if not supported by the client. If
  90492. * \a seek_callback is not \c NULL then a
  90493. * \a tell_callback must also be supplied.
  90494. * Alternatively, a dummy tell callback that just
  90495. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90496. * may also be supplied, all though this is slightly
  90497. * less efficient for the decoder.
  90498. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90499. * pointer may be \c NULL if not supported by the client. If
  90500. * \a seek_callback is not \c NULL then a
  90501. * \a length_callback must also be supplied.
  90502. * Alternatively, a dummy length callback that just
  90503. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90504. * may also be supplied, all though this is slightly
  90505. * less efficient for the decoder.
  90506. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90507. * pointer may be \c NULL if not supported by the client. If
  90508. * \a seek_callback is not \c NULL then a
  90509. * \a eof_callback must also be supplied.
  90510. * Alternatively, a dummy length callback that just
  90511. * returns \c false
  90512. * may also be supplied, all though this is slightly
  90513. * less efficient for the decoder.
  90514. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90515. * pointer must not be \c NULL.
  90516. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90517. * pointer may be \c NULL if the callback is not
  90518. * desired.
  90519. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90520. * pointer must not be \c NULL.
  90521. * \param client_data This value will be supplied to callbacks in their
  90522. * \a client_data argument.
  90523. * \assert
  90524. * \code decoder != NULL \endcode
  90525. * \retval FLAC__StreamDecoderInitStatus
  90526. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90527. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90528. */
  90529. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90530. FLAC__StreamDecoder *decoder,
  90531. FLAC__StreamDecoderReadCallback read_callback,
  90532. FLAC__StreamDecoderSeekCallback seek_callback,
  90533. FLAC__StreamDecoderTellCallback tell_callback,
  90534. FLAC__StreamDecoderLengthCallback length_callback,
  90535. FLAC__StreamDecoderEofCallback eof_callback,
  90536. FLAC__StreamDecoderWriteCallback write_callback,
  90537. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90538. FLAC__StreamDecoderErrorCallback error_callback,
  90539. void *client_data
  90540. );
  90541. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90542. *
  90543. * This flavor of initialization sets up the decoder to decode from a
  90544. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90545. * client. For decoding from a plain file via filename or open FILE*,
  90546. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90547. * provide a simpler interface.
  90548. *
  90549. * This function should be called after FLAC__stream_decoder_new() and
  90550. * FLAC__stream_decoder_set_*() but before any of the
  90551. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90552. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90553. * if initialization succeeded.
  90554. *
  90555. * \note Support for Ogg FLAC in the library is optional. If this
  90556. * library has been built without support for Ogg FLAC, this function
  90557. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90558. *
  90559. * \param decoder An uninitialized decoder instance.
  90560. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90561. * pointer must not be \c NULL.
  90562. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90563. * pointer may be \c NULL if seeking is not
  90564. * supported. If \a seek_callback is not \c NULL then a
  90565. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90566. * Alternatively, a dummy seek callback that just
  90567. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90568. * may also be supplied, all though this is slightly
  90569. * less efficient for the decoder.
  90570. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90571. * pointer may be \c NULL if not supported by the client. If
  90572. * \a seek_callback is not \c NULL then a
  90573. * \a tell_callback must also be supplied.
  90574. * Alternatively, a dummy tell callback that just
  90575. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90576. * may also be supplied, all though this is slightly
  90577. * less efficient for the decoder.
  90578. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90579. * pointer may be \c NULL if not supported by the client. If
  90580. * \a seek_callback is not \c NULL then a
  90581. * \a length_callback must also be supplied.
  90582. * Alternatively, a dummy length callback that just
  90583. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90584. * may also be supplied, all though this is slightly
  90585. * less efficient for the decoder.
  90586. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90587. * pointer may be \c NULL if not supported by the client. If
  90588. * \a seek_callback is not \c NULL then a
  90589. * \a eof_callback must also be supplied.
  90590. * Alternatively, a dummy length callback that just
  90591. * returns \c false
  90592. * may also be supplied, all though this is slightly
  90593. * less efficient for the decoder.
  90594. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90595. * pointer must not be \c NULL.
  90596. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90597. * pointer may be \c NULL if the callback is not
  90598. * desired.
  90599. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90600. * pointer must not be \c NULL.
  90601. * \param client_data This value will be supplied to callbacks in their
  90602. * \a client_data argument.
  90603. * \assert
  90604. * \code decoder != NULL \endcode
  90605. * \retval FLAC__StreamDecoderInitStatus
  90606. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90607. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90608. */
  90609. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90610. FLAC__StreamDecoder *decoder,
  90611. FLAC__StreamDecoderReadCallback read_callback,
  90612. FLAC__StreamDecoderSeekCallback seek_callback,
  90613. FLAC__StreamDecoderTellCallback tell_callback,
  90614. FLAC__StreamDecoderLengthCallback length_callback,
  90615. FLAC__StreamDecoderEofCallback eof_callback,
  90616. FLAC__StreamDecoderWriteCallback write_callback,
  90617. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90618. FLAC__StreamDecoderErrorCallback error_callback,
  90619. void *client_data
  90620. );
  90621. /** Initialize the decoder instance to decode native FLAC files.
  90622. *
  90623. * This flavor of initialization sets up the decoder to decode from a
  90624. * plain native FLAC file. For non-stdio streams, you must use
  90625. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90626. *
  90627. * This function should be called after FLAC__stream_decoder_new() and
  90628. * FLAC__stream_decoder_set_*() but before any of the
  90629. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90630. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90631. * if initialization succeeded.
  90632. *
  90633. * \param decoder An uninitialized decoder instance.
  90634. * \param file An open FLAC file. The file should have been
  90635. * opened with mode \c "rb" and rewound. The file
  90636. * becomes owned by the decoder and should not be
  90637. * manipulated by the client while decoding.
  90638. * Unless \a file is \c stdin, it will be closed
  90639. * when FLAC__stream_decoder_finish() is called.
  90640. * Note however that seeking will not work when
  90641. * decoding from \c stdout since it is not seekable.
  90642. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90643. * pointer must not be \c NULL.
  90644. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90645. * pointer may be \c NULL if the callback is not
  90646. * desired.
  90647. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90648. * pointer must not be \c NULL.
  90649. * \param client_data This value will be supplied to callbacks in their
  90650. * \a client_data argument.
  90651. * \assert
  90652. * \code decoder != NULL \endcode
  90653. * \code file != NULL \endcode
  90654. * \retval FLAC__StreamDecoderInitStatus
  90655. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90656. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90657. */
  90658. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90659. FLAC__StreamDecoder *decoder,
  90660. FILE *file,
  90661. FLAC__StreamDecoderWriteCallback write_callback,
  90662. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90663. FLAC__StreamDecoderErrorCallback error_callback,
  90664. void *client_data
  90665. );
  90666. /** Initialize the decoder instance to decode Ogg FLAC files.
  90667. *
  90668. * This flavor of initialization sets up the decoder to decode from a
  90669. * plain Ogg FLAC file. For non-stdio streams, you must use
  90670. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90671. *
  90672. * This function should be called after FLAC__stream_decoder_new() and
  90673. * FLAC__stream_decoder_set_*() but before any of the
  90674. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90675. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90676. * if initialization succeeded.
  90677. *
  90678. * \note Support for Ogg FLAC in the library is optional. If this
  90679. * library has been built without support for Ogg FLAC, this function
  90680. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90681. *
  90682. * \param decoder An uninitialized decoder instance.
  90683. * \param file An open FLAC file. The file should have been
  90684. * opened with mode \c "rb" and rewound. The file
  90685. * becomes owned by the decoder and should not be
  90686. * manipulated by the client while decoding.
  90687. * Unless \a file is \c stdin, it will be closed
  90688. * when FLAC__stream_decoder_finish() is called.
  90689. * Note however that seeking will not work when
  90690. * decoding from \c stdout since it is not seekable.
  90691. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90692. * pointer must not be \c NULL.
  90693. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90694. * pointer may be \c NULL if the callback is not
  90695. * desired.
  90696. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90697. * pointer must not be \c NULL.
  90698. * \param client_data This value will be supplied to callbacks in their
  90699. * \a client_data argument.
  90700. * \assert
  90701. * \code decoder != NULL \endcode
  90702. * \code file != NULL \endcode
  90703. * \retval FLAC__StreamDecoderInitStatus
  90704. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90705. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90706. */
  90707. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90708. FLAC__StreamDecoder *decoder,
  90709. FILE *file,
  90710. FLAC__StreamDecoderWriteCallback write_callback,
  90711. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90712. FLAC__StreamDecoderErrorCallback error_callback,
  90713. void *client_data
  90714. );
  90715. /** Initialize the decoder instance to decode native FLAC files.
  90716. *
  90717. * This flavor of initialization sets up the decoder to decode from a plain
  90718. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90719. * example, with Unicode filenames on Windows), you must use
  90720. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90721. * and provide callbacks for the I/O.
  90722. *
  90723. * This function should be called after FLAC__stream_decoder_new() and
  90724. * FLAC__stream_decoder_set_*() but before any of the
  90725. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90726. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90727. * if initialization succeeded.
  90728. *
  90729. * \param decoder An uninitialized decoder instance.
  90730. * \param filename The name of the file to decode from. The file will
  90731. * be opened with fopen(). Use \c NULL to decode from
  90732. * \c stdin. Note that \c stdin is not seekable.
  90733. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90734. * pointer must not be \c NULL.
  90735. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90736. * pointer may be \c NULL if the callback is not
  90737. * desired.
  90738. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90739. * pointer must not be \c NULL.
  90740. * \param client_data This value will be supplied to callbacks in their
  90741. * \a client_data argument.
  90742. * \assert
  90743. * \code decoder != NULL \endcode
  90744. * \retval FLAC__StreamDecoderInitStatus
  90745. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90746. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90747. */
  90748. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90749. FLAC__StreamDecoder *decoder,
  90750. const char *filename,
  90751. FLAC__StreamDecoderWriteCallback write_callback,
  90752. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90753. FLAC__StreamDecoderErrorCallback error_callback,
  90754. void *client_data
  90755. );
  90756. /** Initialize the decoder instance to decode Ogg FLAC files.
  90757. *
  90758. * This flavor of initialization sets up the decoder to decode from a plain
  90759. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90760. * example, with Unicode filenames on Windows), you must use
  90761. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90762. * and provide callbacks for the I/O.
  90763. *
  90764. * This function should be called after FLAC__stream_decoder_new() and
  90765. * FLAC__stream_decoder_set_*() but before any of the
  90766. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90767. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90768. * if initialization succeeded.
  90769. *
  90770. * \note Support for Ogg FLAC in the library is optional. If this
  90771. * library has been built without support for Ogg FLAC, this function
  90772. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90773. *
  90774. * \param decoder An uninitialized decoder instance.
  90775. * \param filename The name of the file to decode from. The file will
  90776. * be opened with fopen(). Use \c NULL to decode from
  90777. * \c stdin. Note that \c stdin is not seekable.
  90778. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90779. * pointer must not be \c NULL.
  90780. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90781. * pointer may be \c NULL if the callback is not
  90782. * desired.
  90783. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90784. * pointer must not be \c NULL.
  90785. * \param client_data This value will be supplied to callbacks in their
  90786. * \a client_data argument.
  90787. * \assert
  90788. * \code decoder != NULL \endcode
  90789. * \retval FLAC__StreamDecoderInitStatus
  90790. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90791. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90792. */
  90793. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90794. FLAC__StreamDecoder *decoder,
  90795. const char *filename,
  90796. FLAC__StreamDecoderWriteCallback write_callback,
  90797. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90798. FLAC__StreamDecoderErrorCallback error_callback,
  90799. void *client_data
  90800. );
  90801. /** Finish the decoding process.
  90802. * Flushes the decoding buffer, releases resources, resets the decoder
  90803. * settings to their defaults, and returns the decoder state to
  90804. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90805. *
  90806. * In the event of a prematurely-terminated decode, it is not strictly
  90807. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90808. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90809. * with a FLAC__stream_decoder_finish().
  90810. *
  90811. * \param decoder An uninitialized decoder instance.
  90812. * \assert
  90813. * \code decoder != NULL \endcode
  90814. * \retval FLAC__bool
  90815. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90816. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90817. * signature does not match the one computed by the decoder; else
  90818. * \c true.
  90819. */
  90820. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90821. /** Flush the stream input.
  90822. * The decoder's input buffer will be cleared and the state set to
  90823. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90824. * off MD5 checking.
  90825. *
  90826. * \param decoder A decoder instance.
  90827. * \assert
  90828. * \code decoder != NULL \endcode
  90829. * \retval FLAC__bool
  90830. * \c true if successful, else \c false if a memory allocation
  90831. * error occurs (in which case the state will be set to
  90832. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90833. */
  90834. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90835. /** Reset the decoding process.
  90836. * The decoder's input buffer will be cleared and the state set to
  90837. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90838. * FLAC__stream_decoder_finish() except that the settings are
  90839. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90840. * before decoding again. MD5 checking will be restored to its original
  90841. * setting.
  90842. *
  90843. * If the decoder is seekable, or was initialized with
  90844. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90845. * the decoder will also attempt to seek to the beginning of the file.
  90846. * If this rewind fails, this function will return \c false. It follows
  90847. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90848. * \c stdin.
  90849. *
  90850. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90851. * and is not seekable (i.e. no seek callback was provided or the seek
  90852. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90853. * is the duty of the client to start feeding data from the beginning of
  90854. * the stream on the next FLAC__stream_decoder_process() or
  90855. * FLAC__stream_decoder_process_interleaved() call.
  90856. *
  90857. * \param decoder A decoder instance.
  90858. * \assert
  90859. * \code decoder != NULL \endcode
  90860. * \retval FLAC__bool
  90861. * \c true if successful, else \c false if a memory allocation occurs
  90862. * (in which case the state will be set to
  90863. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90864. * occurs (the state will be unchanged).
  90865. */
  90866. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90867. /** Decode one metadata block or audio frame.
  90868. * This version instructs the decoder to decode a either a single metadata
  90869. * block or a single frame and stop, unless the callbacks return a fatal
  90870. * error or the read callback returns
  90871. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90872. *
  90873. * As the decoder needs more input it will call the read callback.
  90874. * Depending on what was decoded, the metadata or write callback will be
  90875. * called with the decoded metadata block or audio frame.
  90876. *
  90877. * Unless there is a fatal read error or end of stream, this function
  90878. * will return once one whole frame is decoded. In other words, if the
  90879. * stream is not synchronized or points to a corrupt frame header, the
  90880. * decoder will continue to try and resync until it gets to a valid
  90881. * frame, then decode one frame, then return. If the decoder points to
  90882. * a frame whose frame CRC in the frame footer does not match the
  90883. * computed frame CRC, this function will issue a
  90884. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90885. * error callback, and return, having decoded one complete, although
  90886. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90887. * correct length to the write callback.)
  90888. *
  90889. * \param decoder An initialized decoder instance.
  90890. * \assert
  90891. * \code decoder != NULL \endcode
  90892. * \retval FLAC__bool
  90893. * \c false if any fatal read, write, or memory allocation error
  90894. * occurred (meaning decoding must stop), else \c true; for more
  90895. * information about the decoder, check the decoder state with
  90896. * FLAC__stream_decoder_get_state().
  90897. */
  90898. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90899. /** Decode until the end of the metadata.
  90900. * This version instructs the decoder to decode from the current position
  90901. * and continue until all the metadata has been read, or until the
  90902. * callbacks return a fatal error or the read callback returns
  90903. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90904. *
  90905. * As the decoder needs more input it will call the read callback.
  90906. * As each metadata block is decoded, the metadata callback will be called
  90907. * with the decoded metadata.
  90908. *
  90909. * \param decoder An initialized decoder instance.
  90910. * \assert
  90911. * \code decoder != NULL \endcode
  90912. * \retval FLAC__bool
  90913. * \c false if any fatal read, write, or memory allocation error
  90914. * occurred (meaning decoding must stop), else \c true; for more
  90915. * information about the decoder, check the decoder state with
  90916. * FLAC__stream_decoder_get_state().
  90917. */
  90918. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90919. /** Decode until the end of the stream.
  90920. * This version instructs the decoder to decode from the current position
  90921. * and continue until the end of stream (the read callback returns
  90922. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90923. * callbacks return a fatal error.
  90924. *
  90925. * As the decoder needs more input it will call the read callback.
  90926. * As each metadata block and frame is decoded, the metadata or write
  90927. * callback will be called with the decoded metadata or frame.
  90928. *
  90929. * \param decoder An initialized decoder instance.
  90930. * \assert
  90931. * \code decoder != NULL \endcode
  90932. * \retval FLAC__bool
  90933. * \c false if any fatal read, write, or memory allocation error
  90934. * occurred (meaning decoding must stop), else \c true; for more
  90935. * information about the decoder, check the decoder state with
  90936. * FLAC__stream_decoder_get_state().
  90937. */
  90938. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90939. /** Skip one audio frame.
  90940. * This version instructs the decoder to 'skip' a single frame and stop,
  90941. * unless the callbacks return a fatal error or the read callback returns
  90942. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90943. *
  90944. * The decoding flow is the same as what occurs when
  90945. * FLAC__stream_decoder_process_single() is called to process an audio
  90946. * frame, except that this function does not decode the parsed data into
  90947. * PCM or call the write callback. The integrity of the frame is still
  90948. * checked the same way as in the other process functions.
  90949. *
  90950. * This function will return once one whole frame is skipped, in the
  90951. * same way that FLAC__stream_decoder_process_single() will return once
  90952. * one whole frame is decoded.
  90953. *
  90954. * This function can be used in more quickly determining FLAC frame
  90955. * boundaries when decoding of the actual data is not needed, for
  90956. * example when an application is separating a FLAC stream into frames
  90957. * for editing or storing in a container. To do this, the application
  90958. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90959. * to the next frame, then use
  90960. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90961. * boundary.
  90962. *
  90963. * This function should only be called when the stream has advanced
  90964. * past all the metadata, otherwise it will return \c false.
  90965. *
  90966. * \param decoder An initialized decoder instance not in a metadata
  90967. * state.
  90968. * \assert
  90969. * \code decoder != NULL \endcode
  90970. * \retval FLAC__bool
  90971. * \c false if any fatal read, write, or memory allocation error
  90972. * occurred (meaning decoding must stop), or if the decoder
  90973. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90974. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90975. * information about the decoder, check the decoder state with
  90976. * FLAC__stream_decoder_get_state().
  90977. */
  90978. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90979. /** Flush the input and seek to an absolute sample.
  90980. * Decoding will resume at the given sample. Note that because of
  90981. * this, the next write callback may contain a partial block. The
  90982. * client must support seeking the input or this function will fail
  90983. * and return \c false. Furthermore, if the decoder state is
  90984. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90985. * with FLAC__stream_decoder_flush() or reset with
  90986. * FLAC__stream_decoder_reset() before decoding can continue.
  90987. *
  90988. * \param decoder A decoder instance.
  90989. * \param sample The target sample number to seek to.
  90990. * \assert
  90991. * \code decoder != NULL \endcode
  90992. * \retval FLAC__bool
  90993. * \c true if successful, else \c false.
  90994. */
  90995. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90996. /* \} */
  90997. #ifdef __cplusplus
  90998. }
  90999. #endif
  91000. #endif
  91001. /*** End of inlined file: stream_decoder.h ***/
  91002. /*** Start of inlined file: stream_encoder.h ***/
  91003. #ifndef FLAC__STREAM_ENCODER_H
  91004. #define FLAC__STREAM_ENCODER_H
  91005. #include <stdio.h> /* for FILE */
  91006. #ifdef __cplusplus
  91007. extern "C" {
  91008. #endif
  91009. /** \file include/FLAC/stream_encoder.h
  91010. *
  91011. * \brief
  91012. * This module contains the functions which implement the stream
  91013. * encoder.
  91014. *
  91015. * See the detailed documentation in the
  91016. * \link flac_stream_encoder stream encoder \endlink module.
  91017. */
  91018. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  91019. * \ingroup flac
  91020. *
  91021. * \brief
  91022. * This module describes the encoder layers provided by libFLAC.
  91023. *
  91024. * The stream encoder can be used to encode complete streams either to the
  91025. * client via callbacks, or directly to a file, depending on how it is
  91026. * initialized. When encoding via callbacks, the client provides a write
  91027. * callback which will be called whenever FLAC data is ready to be written.
  91028. * If the client also supplies a seek callback, the encoder will also
  91029. * automatically handle the writing back of metadata discovered while
  91030. * encoding, like stream info, seek points offsets, etc. When encoding to
  91031. * a file, the client needs only supply a filename or open \c FILE* and an
  91032. * optional progress callback for periodic notification of progress; the
  91033. * write and seek callbacks are supplied internally. For more info see the
  91034. * \link flac_stream_encoder stream encoder \endlink module.
  91035. */
  91036. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  91037. * \ingroup flac_encoder
  91038. *
  91039. * \brief
  91040. * This module contains the functions which implement the stream
  91041. * encoder.
  91042. *
  91043. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  91044. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  91045. *
  91046. * The basic usage of this encoder is as follows:
  91047. * - The program creates an instance of an encoder using
  91048. * FLAC__stream_encoder_new().
  91049. * - The program overrides the default settings using
  91050. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  91051. * functions should be called:
  91052. * - FLAC__stream_encoder_set_channels()
  91053. * - FLAC__stream_encoder_set_bits_per_sample()
  91054. * - FLAC__stream_encoder_set_sample_rate()
  91055. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  91056. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  91057. * - If the application wants to control the compression level or set its own
  91058. * metadata, then the following should also be called:
  91059. * - FLAC__stream_encoder_set_compression_level()
  91060. * - FLAC__stream_encoder_set_verify()
  91061. * - FLAC__stream_encoder_set_metadata()
  91062. * - The rest of the set functions should only be called if the client needs
  91063. * exact control over how the audio is compressed; thorough understanding
  91064. * of the FLAC format is necessary to achieve good results.
  91065. * - The program initializes the instance to validate the settings and
  91066. * prepare for encoding using
  91067. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  91068. * or FLAC__stream_encoder_init_file() for native FLAC
  91069. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  91070. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  91071. * - The program calls FLAC__stream_encoder_process() or
  91072. * FLAC__stream_encoder_process_interleaved() to encode data, which
  91073. * subsequently calls the callbacks when there is encoder data ready
  91074. * to be written.
  91075. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  91076. * which causes the encoder to encode any data still in its input pipe,
  91077. * update the metadata with the final encoding statistics if output
  91078. * seeking is possible, and finally reset the encoder to the
  91079. * uninitialized state.
  91080. * - The instance may be used again or deleted with
  91081. * FLAC__stream_encoder_delete().
  91082. *
  91083. * In more detail, the stream encoder functions similarly to the
  91084. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  91085. * callbacks and more options. Typically the client will create a new
  91086. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  91087. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  91088. * calling one of the FLAC__stream_encoder_init_*() functions.
  91089. *
  91090. * Unlike the decoders, the stream encoder has many options that can
  91091. * affect the speed and compression ratio. When setting these parameters
  91092. * you should have some basic knowledge of the format (see the
  91093. * <A HREF="../documentation.html#format">user-level documentation</A>
  91094. * or the <A HREF="../format.html">formal description</A>). The
  91095. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  91096. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  91097. * functions will do this, so make sure to pay attention to the state
  91098. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  91099. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  91100. * before FLAC__stream_encoder_init_*() will take on the defaults from
  91101. * the constructor.
  91102. *
  91103. * There are three initialization functions for native FLAC, one for
  91104. * setting up the encoder to encode FLAC data to the client via
  91105. * callbacks, and two for encoding directly to a file.
  91106. *
  91107. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  91108. * You must also supply a write callback which will be called anytime
  91109. * there is raw encoded data to write. If the client can seek the output
  91110. * it is best to also supply seek and tell callbacks, as this allows the
  91111. * encoder to go back after encoding is finished to write back
  91112. * information that was collected while encoding, like seek point offsets,
  91113. * frame sizes, etc.
  91114. *
  91115. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  91116. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  91117. * filename or open \c FILE*; the encoder will handle all the callbacks
  91118. * internally. You may also supply a progress callback for periodic
  91119. * notification of the encoding progress.
  91120. *
  91121. * There are three similarly-named init functions for encoding to Ogg
  91122. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  91123. * library has been built with Ogg support.
  91124. *
  91125. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  91126. * call the write callback several times, once with the \c fLaC signature,
  91127. * and once for each encoded metadata block. Note that for Ogg FLAC
  91128. * encoding you will usually get at least twice the number of callbacks than
  91129. * with native FLAC, one for the Ogg page header and one for the page body.
  91130. *
  91131. * After initializing the instance, the client may feed audio data to the
  91132. * encoder in one of two ways:
  91133. *
  91134. * - Channel separate, through FLAC__stream_encoder_process() - The client
  91135. * will pass an array of pointers to buffers, one for each channel, to
  91136. * the encoder, each of the same length. The samples need not be
  91137. * block-aligned, but each channel should have the same number of samples.
  91138. * - Channel interleaved, through
  91139. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  91140. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  91141. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91142. * Again, the samples need not be block-aligned but they must be
  91143. * sample-aligned, i.e. the first value should be channel0_sample0 and
  91144. * the last value channelN_sampleM.
  91145. *
  91146. * Note that for either process call, each sample in the buffers should be a
  91147. * signed integer, right-justified to the resolution set by
  91148. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  91149. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  91150. *
  91151. * When the client is finished encoding data, it calls
  91152. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  91153. * data still in its input pipe, and call the metadata callback with the
  91154. * final encoding statistics. Then the instance may be deleted with
  91155. * FLAC__stream_encoder_delete() or initialized again to encode another
  91156. * stream.
  91157. *
  91158. * For programs that write their own metadata, but that do not know the
  91159. * actual metadata until after encoding, it is advantageous to instruct
  91160. * the encoder to write a PADDING block of the correct size, so that
  91161. * instead of rewriting the whole stream after encoding, the program can
  91162. * just overwrite the PADDING block. If only the maximum size of the
  91163. * metadata is known, the program can write a slightly larger padding
  91164. * block, then split it after encoding.
  91165. *
  91166. * Make sure you understand how lengths are calculated. All FLAC metadata
  91167. * blocks have a 4 byte header which contains the type and length. This
  91168. * length does not include the 4 bytes of the header. See the format page
  91169. * for the specification of metadata blocks and their lengths.
  91170. *
  91171. * \note
  91172. * If you are writing the FLAC data to a file via callbacks, make sure it
  91173. * is open for update (e.g. mode "w+" for stdio streams). This is because
  91174. * after the first encoding pass, the encoder will try to seek back to the
  91175. * beginning of the stream, to the STREAMINFO block, to write some data
  91176. * there. (If using FLAC__stream_encoder_init*_file() or
  91177. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  91178. *
  91179. * \note
  91180. * The "set" functions may only be called when the encoder is in the
  91181. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  91182. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  91183. * before FLAC__stream_encoder_init_*(). If this is the case they will
  91184. * return \c true, otherwise \c false.
  91185. *
  91186. * \note
  91187. * FLAC__stream_encoder_finish() resets all settings to the constructor
  91188. * defaults.
  91189. *
  91190. * \{
  91191. */
  91192. /** State values for a FLAC__StreamEncoder.
  91193. *
  91194. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  91195. *
  91196. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  91197. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  91198. * must be deleted with FLAC__stream_encoder_delete().
  91199. */
  91200. typedef enum {
  91201. FLAC__STREAM_ENCODER_OK = 0,
  91202. /**< The encoder is in the normal OK state and samples can be processed. */
  91203. FLAC__STREAM_ENCODER_UNINITIALIZED,
  91204. /**< The encoder is in the uninitialized state; one of the
  91205. * FLAC__stream_encoder_init_*() functions must be called before samples
  91206. * can be processed.
  91207. */
  91208. FLAC__STREAM_ENCODER_OGG_ERROR,
  91209. /**< An error occurred in the underlying Ogg layer. */
  91210. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91211. /**< An error occurred in the underlying verify stream decoder;
  91212. * check FLAC__stream_encoder_get_verify_decoder_state().
  91213. */
  91214. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91215. /**< The verify decoder detected a mismatch between the original
  91216. * audio signal and the decoded audio signal.
  91217. */
  91218. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91219. /**< One of the callbacks returned a fatal error. */
  91220. FLAC__STREAM_ENCODER_IO_ERROR,
  91221. /**< An I/O error occurred while opening/reading/writing a file.
  91222. * Check \c errno.
  91223. */
  91224. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91225. /**< An error occurred while writing the stream; usually, the
  91226. * write_callback returned an error.
  91227. */
  91228. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91229. /**< Memory allocation failed. */
  91230. } FLAC__StreamEncoderState;
  91231. /** Maps a FLAC__StreamEncoderState to a C string.
  91232. *
  91233. * Using a FLAC__StreamEncoderState as the index to this array
  91234. * will give the string equivalent. The contents should not be modified.
  91235. */
  91236. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91237. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91238. */
  91239. typedef enum {
  91240. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91241. /**< Initialization was successful. */
  91242. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91243. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91244. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91245. /**< The library was not compiled with support for the given container
  91246. * format.
  91247. */
  91248. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91249. /**< A required callback was not supplied. */
  91250. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91251. /**< The encoder has an invalid setting for number of channels. */
  91252. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91253. /**< The encoder has an invalid setting for bits-per-sample.
  91254. * FLAC supports 4-32 bps but the reference encoder currently supports
  91255. * only up to 24 bps.
  91256. */
  91257. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91258. /**< The encoder has an invalid setting for the input sample rate. */
  91259. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91260. /**< The encoder has an invalid setting for the block size. */
  91261. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91262. /**< The encoder has an invalid setting for the maximum LPC order. */
  91263. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91264. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91265. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91266. /**< The specified block size is less than the maximum LPC order. */
  91267. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91268. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91269. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91270. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91271. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91272. * - One of the metadata blocks contains an undefined type
  91273. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91274. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91275. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91276. */
  91277. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91278. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91279. * already initialized, usually because
  91280. * FLAC__stream_encoder_finish() was not called.
  91281. */
  91282. } FLAC__StreamEncoderInitStatus;
  91283. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91284. *
  91285. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91286. * will give the string equivalent. The contents should not be modified.
  91287. */
  91288. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91289. /** Return values for the FLAC__StreamEncoder read callback.
  91290. */
  91291. typedef enum {
  91292. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91293. /**< The read was OK and decoding can continue. */
  91294. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91295. /**< The read was attempted at the end of the stream. */
  91296. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91297. /**< An unrecoverable error occurred. */
  91298. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91299. /**< Client does not support reading back from the output. */
  91300. } FLAC__StreamEncoderReadStatus;
  91301. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91302. *
  91303. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91304. * will give the string equivalent. The contents should not be modified.
  91305. */
  91306. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91307. /** Return values for the FLAC__StreamEncoder write callback.
  91308. */
  91309. typedef enum {
  91310. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91311. /**< The write was OK and encoding can continue. */
  91312. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91313. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91314. } FLAC__StreamEncoderWriteStatus;
  91315. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91316. *
  91317. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91318. * will give the string equivalent. The contents should not be modified.
  91319. */
  91320. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91321. /** Return values for the FLAC__StreamEncoder seek callback.
  91322. */
  91323. typedef enum {
  91324. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91325. /**< The seek was OK and encoding can continue. */
  91326. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91327. /**< An unrecoverable error occurred. */
  91328. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91329. /**< Client does not support seeking. */
  91330. } FLAC__StreamEncoderSeekStatus;
  91331. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91332. *
  91333. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91334. * will give the string equivalent. The contents should not be modified.
  91335. */
  91336. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91337. /** Return values for the FLAC__StreamEncoder tell callback.
  91338. */
  91339. typedef enum {
  91340. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91341. /**< The tell was OK and encoding can continue. */
  91342. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91343. /**< An unrecoverable error occurred. */
  91344. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91345. /**< Client does not support seeking. */
  91346. } FLAC__StreamEncoderTellStatus;
  91347. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91348. *
  91349. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91350. * will give the string equivalent. The contents should not be modified.
  91351. */
  91352. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91353. /***********************************************************************
  91354. *
  91355. * class FLAC__StreamEncoder
  91356. *
  91357. ***********************************************************************/
  91358. struct FLAC__StreamEncoderProtected;
  91359. struct FLAC__StreamEncoderPrivate;
  91360. /** The opaque structure definition for the stream encoder type.
  91361. * See the \link flac_stream_encoder stream encoder module \endlink
  91362. * for a detailed description.
  91363. */
  91364. typedef struct {
  91365. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91366. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91367. } FLAC__StreamEncoder;
  91368. /** Signature for the read callback.
  91369. *
  91370. * A function pointer matching this signature must be passed to
  91371. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91372. * The supplied function will be called when the encoder needs to read back
  91373. * encoded data. This happens during the metadata callback, when the encoder
  91374. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91375. * while encoding. The address of the buffer to be filled is supplied, along
  91376. * with the number of bytes the buffer can hold. The callback may choose to
  91377. * supply less data and modify the byte count but must be careful not to
  91378. * overflow the buffer. The callback then returns a status code chosen from
  91379. * FLAC__StreamEncoderReadStatus.
  91380. *
  91381. * Here is an example of a read callback for stdio streams:
  91382. * \code
  91383. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91384. * {
  91385. * FILE *file = ((MyClientData*)client_data)->file;
  91386. * if(*bytes > 0) {
  91387. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91388. * if(ferror(file))
  91389. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91390. * else if(*bytes == 0)
  91391. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91392. * else
  91393. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91394. * }
  91395. * else
  91396. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91397. * }
  91398. * \endcode
  91399. *
  91400. * \note In general, FLAC__StreamEncoder functions which change the
  91401. * state should not be called on the \a encoder while in the callback.
  91402. *
  91403. * \param encoder The encoder instance calling the callback.
  91404. * \param buffer A pointer to a location for the callee to store
  91405. * data to be encoded.
  91406. * \param bytes A pointer to the size of the buffer. On entry
  91407. * to the callback, it contains the maximum number
  91408. * of bytes that may be stored in \a buffer. The
  91409. * callee must set it to the actual number of bytes
  91410. * stored (0 in case of error or end-of-stream) before
  91411. * returning.
  91412. * \param client_data The callee's client data set through
  91413. * FLAC__stream_encoder_set_client_data().
  91414. * \retval FLAC__StreamEncoderReadStatus
  91415. * The callee's return status.
  91416. */
  91417. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91418. /** Signature for the write callback.
  91419. *
  91420. * A function pointer matching this signature must be passed to
  91421. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91422. * by the encoder anytime there is raw encoded data ready to write. It may
  91423. * include metadata mixed with encoded audio frames and the data is not
  91424. * guaranteed to be aligned on frame or metadata block boundaries.
  91425. *
  91426. * The only duty of the callback is to write out the \a bytes worth of data
  91427. * in \a buffer to the current position in the output stream. The arguments
  91428. * \a samples and \a current_frame are purely informational. If \a samples
  91429. * is greater than \c 0, then \a current_frame will hold the current frame
  91430. * number that is being written; otherwise it indicates that the write
  91431. * callback is being called to write metadata.
  91432. *
  91433. * \note
  91434. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91435. * write callback will be called twice when writing each audio
  91436. * frame; once for the page header, and once for the page body.
  91437. * When writing the page header, the \a samples argument to the
  91438. * write callback will be \c 0.
  91439. *
  91440. * \note In general, FLAC__StreamEncoder functions which change the
  91441. * state should not be called on the \a encoder while in the callback.
  91442. *
  91443. * \param encoder The encoder instance calling the callback.
  91444. * \param buffer An array of encoded data of length \a bytes.
  91445. * \param bytes The byte length of \a buffer.
  91446. * \param samples The number of samples encoded by \a buffer.
  91447. * \c 0 has a special meaning; see above.
  91448. * \param current_frame The number of the current frame being encoded.
  91449. * \param client_data The callee's client data set through
  91450. * FLAC__stream_encoder_init_*().
  91451. * \retval FLAC__StreamEncoderWriteStatus
  91452. * The callee's return status.
  91453. */
  91454. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91455. /** Signature for the seek callback.
  91456. *
  91457. * A function pointer matching this signature may be passed to
  91458. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91459. * when the encoder needs to seek the output stream. The encoder will pass
  91460. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91461. *
  91462. * Here is an example of a seek callback for stdio streams:
  91463. * \code
  91464. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91465. * {
  91466. * FILE *file = ((MyClientData*)client_data)->file;
  91467. * if(file == stdin)
  91468. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91469. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91470. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91471. * else
  91472. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91473. * }
  91474. * \endcode
  91475. *
  91476. * \note In general, FLAC__StreamEncoder functions which change the
  91477. * state should not be called on the \a encoder while in the callback.
  91478. *
  91479. * \param encoder The encoder instance calling the callback.
  91480. * \param absolute_byte_offset The offset from the beginning of the stream
  91481. * to seek to.
  91482. * \param client_data The callee's client data set through
  91483. * FLAC__stream_encoder_init_*().
  91484. * \retval FLAC__StreamEncoderSeekStatus
  91485. * The callee's return status.
  91486. */
  91487. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91488. /** Signature for the tell callback.
  91489. *
  91490. * A function pointer matching this signature may be passed to
  91491. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91492. * when the encoder needs to know the current position of the output stream.
  91493. *
  91494. * \warning
  91495. * The callback must return the true current byte offset of the output to
  91496. * which the encoder is writing. If you are buffering the output, make
  91497. * sure and take this into account. If you are writing directly to a
  91498. * FILE* from your write callback, ftell() is sufficient. If you are
  91499. * writing directly to a file descriptor from your write callback, you
  91500. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91501. * these points to rewrite metadata after encoding.
  91502. *
  91503. * Here is an example of a tell callback for stdio streams:
  91504. * \code
  91505. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91506. * {
  91507. * FILE *file = ((MyClientData*)client_data)->file;
  91508. * off_t pos;
  91509. * if(file == stdin)
  91510. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91511. * else if((pos = ftello(file)) < 0)
  91512. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91513. * else {
  91514. * *absolute_byte_offset = (FLAC__uint64)pos;
  91515. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91516. * }
  91517. * }
  91518. * \endcode
  91519. *
  91520. * \note In general, FLAC__StreamEncoder functions which change the
  91521. * state should not be called on the \a encoder while in the callback.
  91522. *
  91523. * \param encoder The encoder instance calling the callback.
  91524. * \param absolute_byte_offset The address at which to store the current
  91525. * position of the output.
  91526. * \param client_data The callee's client data set through
  91527. * FLAC__stream_encoder_init_*().
  91528. * \retval FLAC__StreamEncoderTellStatus
  91529. * The callee's return status.
  91530. */
  91531. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91532. /** Signature for the metadata callback.
  91533. *
  91534. * A function pointer matching this signature may be passed to
  91535. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91536. * once at the end of encoding with the populated STREAMINFO structure. This
  91537. * is so the client can seek back to the beginning of the file and write the
  91538. * STREAMINFO block with the correct statistics after encoding (like
  91539. * minimum/maximum frame size and total samples).
  91540. *
  91541. * \note In general, FLAC__StreamEncoder functions which change the
  91542. * state should not be called on the \a encoder while in the callback.
  91543. *
  91544. * \param encoder The encoder instance calling the callback.
  91545. * \param metadata The final populated STREAMINFO block.
  91546. * \param client_data The callee's client data set through
  91547. * FLAC__stream_encoder_init_*().
  91548. */
  91549. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91550. /** Signature for the progress callback.
  91551. *
  91552. * A function pointer matching this signature may be passed to
  91553. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91554. * The supplied function will be called when the encoder has finished
  91555. * writing a frame. The \c total_frames_estimate argument to the
  91556. * callback will be based on the value from
  91557. * FLAC__stream_encoder_set_total_samples_estimate().
  91558. *
  91559. * \note In general, FLAC__StreamEncoder functions which change the
  91560. * state should not be called on the \a encoder while in the callback.
  91561. *
  91562. * \param encoder The encoder instance calling the callback.
  91563. * \param bytes_written Bytes written so far.
  91564. * \param samples_written Samples written so far.
  91565. * \param frames_written Frames written so far.
  91566. * \param total_frames_estimate The estimate of the total number of
  91567. * frames to be written.
  91568. * \param client_data The callee's client data set through
  91569. * FLAC__stream_encoder_init_*().
  91570. */
  91571. 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);
  91572. /***********************************************************************
  91573. *
  91574. * Class constructor/destructor
  91575. *
  91576. ***********************************************************************/
  91577. /** Create a new stream encoder instance. The instance is created with
  91578. * default settings; see the individual FLAC__stream_encoder_set_*()
  91579. * functions for each setting's default.
  91580. *
  91581. * \retval FLAC__StreamEncoder*
  91582. * \c NULL if there was an error allocating memory, else the new instance.
  91583. */
  91584. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91585. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91586. *
  91587. * \param encoder A pointer to an existing encoder.
  91588. * \assert
  91589. * \code encoder != NULL \endcode
  91590. */
  91591. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91592. /***********************************************************************
  91593. *
  91594. * Public class method prototypes
  91595. *
  91596. ***********************************************************************/
  91597. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91598. *
  91599. * \note
  91600. * This does not need to be set for native FLAC encoding.
  91601. *
  91602. * \note
  91603. * It is recommended to set a serial number explicitly as the default of '0'
  91604. * may collide with other streams.
  91605. *
  91606. * \default \c 0
  91607. * \param encoder An encoder instance to set.
  91608. * \param serial_number See above.
  91609. * \assert
  91610. * \code encoder != NULL \endcode
  91611. * \retval FLAC__bool
  91612. * \c false if the encoder is already initialized, else \c true.
  91613. */
  91614. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91615. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91616. * encoded output by feeding it through an internal decoder and comparing
  91617. * the original signal against the decoded signal. If a mismatch occurs,
  91618. * the process call will return \c false. Note that this will slow the
  91619. * encoding process by the extra time required for decoding and comparison.
  91620. *
  91621. * \default \c false
  91622. * \param encoder An encoder instance to set.
  91623. * \param value Flag value (see above).
  91624. * \assert
  91625. * \code encoder != NULL \endcode
  91626. * \retval FLAC__bool
  91627. * \c false if the encoder is already initialized, else \c true.
  91628. */
  91629. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91630. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91631. * the encoder will comply with the Subset and will check the
  91632. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91633. * comply. If \c false, the settings may take advantage of the full
  91634. * range that the format allows.
  91635. *
  91636. * Make sure you know what it entails before setting this to \c false.
  91637. *
  91638. * \default \c true
  91639. * \param encoder An encoder instance to set.
  91640. * \param value Flag value (see above).
  91641. * \assert
  91642. * \code encoder != NULL \endcode
  91643. * \retval FLAC__bool
  91644. * \c false if the encoder is already initialized, else \c true.
  91645. */
  91646. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91647. /** Set the number of channels to be encoded.
  91648. *
  91649. * \default \c 2
  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_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91658. /** Set the sample resolution of the input to be encoded.
  91659. *
  91660. * \warning
  91661. * Do not feed the encoder data that is wider than the value you
  91662. * set here or you will generate an invalid stream.
  91663. *
  91664. * \default \c 16
  91665. * \param encoder An encoder instance to set.
  91666. * \param value See above.
  91667. * \assert
  91668. * \code encoder != NULL \endcode
  91669. * \retval FLAC__bool
  91670. * \c false if the encoder is already initialized, else \c true.
  91671. */
  91672. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91673. /** Set the sample rate (in Hz) of the input to be encoded.
  91674. *
  91675. * \default \c 44100
  91676. * \param encoder An encoder instance to set.
  91677. * \param value See above.
  91678. * \assert
  91679. * \code encoder != NULL \endcode
  91680. * \retval FLAC__bool
  91681. * \c false if the encoder is already initialized, else \c true.
  91682. */
  91683. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91684. /** Set the compression level
  91685. *
  91686. * The compression level is roughly proportional to the amount of effort
  91687. * the encoder expends to compress the file. A higher level usually
  91688. * means more computation but higher compression. The default level is
  91689. * suitable for most applications.
  91690. *
  91691. * Currently the levels range from \c 0 (fastest, least compression) to
  91692. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91693. * treated as \c 8.
  91694. *
  91695. * This function automatically calls the following other \c _set_
  91696. * functions with appropriate values, so the client does not need to
  91697. * unless it specifically wants to override them:
  91698. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91699. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91700. * - FLAC__stream_encoder_set_apodization()
  91701. * - FLAC__stream_encoder_set_max_lpc_order()
  91702. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91703. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91704. * - FLAC__stream_encoder_set_do_escape_coding()
  91705. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91706. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91707. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91708. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91709. *
  91710. * The actual values set for each level are:
  91711. * <table>
  91712. * <tr>
  91713. * <td><b>level</b><td>
  91714. * <td>do mid-side stereo<td>
  91715. * <td>loose mid-side stereo<td>
  91716. * <td>apodization<td>
  91717. * <td>max lpc order<td>
  91718. * <td>qlp coeff precision<td>
  91719. * <td>qlp coeff prec search<td>
  91720. * <td>escape coding<td>
  91721. * <td>exhaustive model search<td>
  91722. * <td>min residual partition order<td>
  91723. * <td>max residual partition order<td>
  91724. * <td>rice parameter search dist<td>
  91725. * </tr>
  91726. * <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>
  91727. * <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>
  91728. * <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>
  91729. * <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>
  91730. * <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>
  91731. * <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>
  91732. * <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>
  91733. * <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>
  91734. * <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>
  91735. * </table>
  91736. *
  91737. * \default \c 5
  91738. * \param encoder An encoder instance to set.
  91739. * \param value See above.
  91740. * \assert
  91741. * \code encoder != NULL \endcode
  91742. * \retval FLAC__bool
  91743. * \c false if the encoder is already initialized, else \c true.
  91744. */
  91745. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91746. /** Set the blocksize to use while encoding.
  91747. *
  91748. * The number of samples to use per frame. Use \c 0 to let the encoder
  91749. * estimate a blocksize; this is usually best.
  91750. *
  91751. * \default \c 0
  91752. * \param encoder An encoder instance to set.
  91753. * \param value See above.
  91754. * \assert
  91755. * \code encoder != NULL \endcode
  91756. * \retval FLAC__bool
  91757. * \c false if the encoder is already initialized, else \c true.
  91758. */
  91759. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91760. /** Set to \c true to enable mid-side encoding on stereo input. The
  91761. * number of channels must be 2 for this to have any effect. Set to
  91762. * \c false to use only independent channel coding.
  91763. *
  91764. * \default \c false
  91765. * \param encoder An encoder instance to set.
  91766. * \param value Flag value (see above).
  91767. * \assert
  91768. * \code encoder != NULL \endcode
  91769. * \retval FLAC__bool
  91770. * \c false if the encoder is already initialized, else \c true.
  91771. */
  91772. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91773. /** Set to \c true to enable adaptive switching between mid-side and
  91774. * left-right encoding on stereo input. Set to \c false to use
  91775. * exhaustive searching. Setting this to \c true requires
  91776. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91777. * \c true in order to have any effect.
  91778. *
  91779. * \default \c false
  91780. * \param encoder An encoder instance to set.
  91781. * \param value Flag value (see above).
  91782. * \assert
  91783. * \code encoder != NULL \endcode
  91784. * \retval FLAC__bool
  91785. * \c false if the encoder is already initialized, else \c true.
  91786. */
  91787. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91788. /** Sets the apodization function(s) the encoder will use when windowing
  91789. * audio data for LPC analysis.
  91790. *
  91791. * The \a specification is a plain ASCII string which specifies exactly
  91792. * which functions to use. There may be more than one (up to 32),
  91793. * separated by \c ';' characters. Some functions take one or more
  91794. * comma-separated arguments in parentheses.
  91795. *
  91796. * The available functions are \c bartlett, \c bartlett_hann,
  91797. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91798. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91799. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91800. *
  91801. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91802. * (0<STDDEV<=0.5).
  91803. *
  91804. * For \c tukey(P), P specifies the fraction of the window that is
  91805. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91806. * corresponds to \c hann.
  91807. *
  91808. * Example specifications are \c "blackman" or
  91809. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91810. *
  91811. * Any function that is specified erroneously is silently dropped. Up
  91812. * to 32 functions are kept, the rest are dropped. If the specification
  91813. * is empty the encoder defaults to \c "tukey(0.5)".
  91814. *
  91815. * When more than one function is specified, then for every subframe the
  91816. * encoder will try each of them separately and choose the window that
  91817. * results in the smallest compressed subframe.
  91818. *
  91819. * Note that each function specified causes the encoder to occupy a
  91820. * floating point array in which to store the window.
  91821. *
  91822. * \default \c "tukey(0.5)"
  91823. * \param encoder An encoder instance to set.
  91824. * \param specification See above.
  91825. * \assert
  91826. * \code encoder != NULL \endcode
  91827. * \code specification != NULL \endcode
  91828. * \retval FLAC__bool
  91829. * \c false if the encoder is already initialized, else \c true.
  91830. */
  91831. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91832. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91833. *
  91834. * \default \c 0
  91835. * \param encoder An encoder instance to set.
  91836. * \param value See above.
  91837. * \assert
  91838. * \code encoder != NULL \endcode
  91839. * \retval FLAC__bool
  91840. * \c false if the encoder is already initialized, else \c true.
  91841. */
  91842. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91843. /** Set the precision, in bits, of the quantized linear predictor
  91844. * coefficients, or \c 0 to let the encoder select it based on the
  91845. * blocksize.
  91846. *
  91847. * \note
  91848. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91849. * be less than 32.
  91850. *
  91851. * \default \c 0
  91852. * \param encoder An encoder instance to set.
  91853. * \param value See above.
  91854. * \assert
  91855. * \code encoder != NULL \endcode
  91856. * \retval FLAC__bool
  91857. * \c false if the encoder is already initialized, else \c true.
  91858. */
  91859. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91860. /** Set to \c false to use only the specified quantized linear predictor
  91861. * coefficient precision, or \c true to search neighboring precision
  91862. * values and use the best one.
  91863. *
  91864. * \default \c false
  91865. * \param encoder An encoder instance to set.
  91866. * \param value See above.
  91867. * \assert
  91868. * \code encoder != NULL \endcode
  91869. * \retval FLAC__bool
  91870. * \c false if the encoder is already initialized, else \c true.
  91871. */
  91872. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91873. /** Deprecated. Setting this value has no effect.
  91874. *
  91875. * \default \c false
  91876. * \param encoder An encoder instance to set.
  91877. * \param value See above.
  91878. * \assert
  91879. * \code encoder != NULL \endcode
  91880. * \retval FLAC__bool
  91881. * \c false if the encoder is already initialized, else \c true.
  91882. */
  91883. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91884. /** Set to \c false to let the encoder estimate the best model order
  91885. * based on the residual signal energy, or \c true to force the
  91886. * encoder to evaluate all order models and select the best.
  91887. *
  91888. * \default \c false
  91889. * \param encoder An encoder instance to set.
  91890. * \param value See above.
  91891. * \assert
  91892. * \code encoder != NULL \endcode
  91893. * \retval FLAC__bool
  91894. * \c false if the encoder is already initialized, else \c true.
  91895. */
  91896. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91897. /** Set the minimum partition order to search when coding the residual.
  91898. * This is used in tandem with
  91899. * FLAC__stream_encoder_set_max_residual_partition_order().
  91900. *
  91901. * The partition order determines the context size in the residual.
  91902. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91903. *
  91904. * Set both min and max values to \c 0 to force a single context,
  91905. * whose Rice parameter is based on the residual signal variance.
  91906. * Otherwise, set a min and max order, and the encoder will search
  91907. * all orders, using the mean of each context for its Rice parameter,
  91908. * and use the best.
  91909. *
  91910. * \default \c 0
  91911. * \param encoder An encoder instance to set.
  91912. * \param value See above.
  91913. * \assert
  91914. * \code encoder != NULL \endcode
  91915. * \retval FLAC__bool
  91916. * \c false if the encoder is already initialized, else \c true.
  91917. */
  91918. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91919. /** Set the maximum partition order to search when coding the residual.
  91920. * This is used in tandem with
  91921. * FLAC__stream_encoder_set_min_residual_partition_order().
  91922. *
  91923. * The partition order determines the context size in the residual.
  91924. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91925. *
  91926. * Set both min and max values to \c 0 to force a single context,
  91927. * whose Rice parameter is based on the residual signal variance.
  91928. * Otherwise, set a min and max order, and the encoder will search
  91929. * all orders, using the mean of each context for its Rice parameter,
  91930. * and use the best.
  91931. *
  91932. * \default \c 0
  91933. * \param encoder An encoder instance to set.
  91934. * \param value See above.
  91935. * \assert
  91936. * \code encoder != NULL \endcode
  91937. * \retval FLAC__bool
  91938. * \c false if the encoder is already initialized, else \c true.
  91939. */
  91940. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91941. /** Deprecated. Setting this value has no effect.
  91942. *
  91943. * \default \c 0
  91944. * \param encoder An encoder instance to set.
  91945. * \param value See above.
  91946. * \assert
  91947. * \code encoder != NULL \endcode
  91948. * \retval FLAC__bool
  91949. * \c false if the encoder is already initialized, else \c true.
  91950. */
  91951. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91952. /** Set an estimate of the total samples that will be encoded.
  91953. * This is merely an estimate and may be set to \c 0 if unknown.
  91954. * This value will be written to the STREAMINFO block before encoding,
  91955. * and can remove the need for the caller to rewrite the value later
  91956. * if the value is known before encoding.
  91957. *
  91958. * \default \c 0
  91959. * \param encoder An encoder instance to set.
  91960. * \param value See above.
  91961. * \assert
  91962. * \code encoder != NULL \endcode
  91963. * \retval FLAC__bool
  91964. * \c false if the encoder is already initialized, else \c true.
  91965. */
  91966. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91967. /** Set the metadata blocks to be emitted to the stream before encoding.
  91968. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91969. * array of pointers to metadata blocks. The array is non-const since
  91970. * the encoder may need to change the \a is_last flag inside them, and
  91971. * in some cases update seek point offsets. Otherwise, the encoder will
  91972. * not modify or free the blocks. It is up to the caller to free the
  91973. * metadata blocks after encoding finishes.
  91974. *
  91975. * \note
  91976. * The encoder stores only copies of the pointers in the \a metadata array;
  91977. * the metadata blocks themselves must survive at least until after
  91978. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91979. *
  91980. * \note
  91981. * The STREAMINFO block is always written and no STREAMINFO block may
  91982. * occur in the supplied array.
  91983. *
  91984. * \note
  91985. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91986. * in the \a metadata array, but the client has specified that it does not
  91987. * support seeking, then the SEEKTABLE will be written verbatim. However
  91988. * by itself this is not very useful as the client will not know the stream
  91989. * offsets for the seekpoints ahead of time. In order to get a proper
  91990. * seektable the client must support seeking. See next note.
  91991. *
  91992. * \note
  91993. * SEEKTABLE blocks are handled specially. Since you will not know
  91994. * the values for the seek point stream offsets, you should pass in
  91995. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91996. * required sample numbers (or placeholder points), with \c 0 for the
  91997. * \a frame_samples and \a stream_offset fields for each point. If the
  91998. * client has specified that it supports seeking by providing a seek
  91999. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  92000. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  92001. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  92002. * then while it is encoding the encoder will fill the stream offsets in
  92003. * for you and when encoding is finished, it will seek back and write the
  92004. * real values into the SEEKTABLE block in the stream. There are helper
  92005. * routines for manipulating seektable template blocks; see metadata.h:
  92006. * FLAC__metadata_object_seektable_template_*(). If the client does
  92007. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  92008. * will slow down or remove the ability to seek in the FLAC stream.
  92009. *
  92010. * \note
  92011. * The encoder instance \b will modify the first \c SEEKTABLE block
  92012. * as it transforms the template to a valid seektable while encoding,
  92013. * but it is still up to the caller to free all metadata blocks after
  92014. * encoding.
  92015. *
  92016. * \note
  92017. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  92018. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  92019. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  92020. * will simply write it's own into the stream. If no VORBIS_COMMENT
  92021. * block is present in the \a metadata array, libFLAC will write an
  92022. * empty one, containing only the vendor string.
  92023. *
  92024. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  92025. * the second metadata block of the stream. The encoder already supplies
  92026. * the STREAMINFO block automatically. If \a metadata does not contain a
  92027. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  92028. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  92029. * first, the init function will reorder \a metadata by moving the
  92030. * VORBIS_COMMENT block to the front; the relative ordering of the other
  92031. * blocks will remain as they were.
  92032. *
  92033. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  92034. * stream to \c 65535. If \a num_blocks exceeds this the function will
  92035. * return \c false.
  92036. *
  92037. * \default \c NULL, 0
  92038. * \param encoder An encoder instance to set.
  92039. * \param metadata See above.
  92040. * \param num_blocks See above.
  92041. * \assert
  92042. * \code encoder != NULL \endcode
  92043. * \retval FLAC__bool
  92044. * \c false if the encoder is already initialized, else \c true.
  92045. * \c false if the encoder is already initialized, or if
  92046. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  92047. */
  92048. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  92049. /** Get the current encoder state.
  92050. *
  92051. * \param encoder An encoder instance to query.
  92052. * \assert
  92053. * \code encoder != NULL \endcode
  92054. * \retval FLAC__StreamEncoderState
  92055. * The current encoder state.
  92056. */
  92057. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  92058. /** Get the state of the verify stream decoder.
  92059. * Useful when the stream encoder state is
  92060. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  92061. *
  92062. * \param encoder An encoder instance to query.
  92063. * \assert
  92064. * \code encoder != NULL \endcode
  92065. * \retval FLAC__StreamDecoderState
  92066. * The verify stream decoder state.
  92067. */
  92068. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  92069. /** Get the current encoder state as a C string.
  92070. * This version automatically resolves
  92071. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  92072. * verify decoder's state.
  92073. *
  92074. * \param encoder A encoder instance to query.
  92075. * \assert
  92076. * \code encoder != NULL \endcode
  92077. * \retval const char *
  92078. * The encoder state as a C string. Do not modify the contents.
  92079. */
  92080. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  92081. /** Get relevant values about the nature of a verify decoder error.
  92082. * Useful when the stream encoder state is
  92083. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  92084. * be addresses in which the stats will be returned, or NULL if value
  92085. * is not desired.
  92086. *
  92087. * \param encoder An encoder instance to query.
  92088. * \param absolute_sample The absolute sample number of the mismatch.
  92089. * \param frame_number The number of the frame in which the mismatch occurred.
  92090. * \param channel The channel in which the mismatch occurred.
  92091. * \param sample The number of the sample (relative to the frame) in
  92092. * which the mismatch occurred.
  92093. * \param expected The expected value for the sample in question.
  92094. * \param got The actual value returned by the decoder.
  92095. * \assert
  92096. * \code encoder != NULL \endcode
  92097. */
  92098. 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);
  92099. /** Get the "verify" flag.
  92100. *
  92101. * \param encoder An encoder instance to query.
  92102. * \assert
  92103. * \code encoder != NULL \endcode
  92104. * \retval FLAC__bool
  92105. * See FLAC__stream_encoder_set_verify().
  92106. */
  92107. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  92108. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  92109. *
  92110. * \param encoder An encoder instance to query.
  92111. * \assert
  92112. * \code encoder != NULL \endcode
  92113. * \retval FLAC__bool
  92114. * See FLAC__stream_encoder_set_streamable_subset().
  92115. */
  92116. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  92117. /** Get the number of input channels being processed.
  92118. *
  92119. * \param encoder An encoder instance to query.
  92120. * \assert
  92121. * \code encoder != NULL \endcode
  92122. * \retval unsigned
  92123. * See FLAC__stream_encoder_set_channels().
  92124. */
  92125. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  92126. /** Get the input sample resolution setting.
  92127. *
  92128. * \param encoder An encoder instance to query.
  92129. * \assert
  92130. * \code encoder != NULL \endcode
  92131. * \retval unsigned
  92132. * See FLAC__stream_encoder_set_bits_per_sample().
  92133. */
  92134. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  92135. /** Get the input sample rate setting.
  92136. *
  92137. * \param encoder An encoder instance to query.
  92138. * \assert
  92139. * \code encoder != NULL \endcode
  92140. * \retval unsigned
  92141. * See FLAC__stream_encoder_set_sample_rate().
  92142. */
  92143. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  92144. /** Get the blocksize setting.
  92145. *
  92146. * \param encoder An encoder instance to query.
  92147. * \assert
  92148. * \code encoder != NULL \endcode
  92149. * \retval unsigned
  92150. * See FLAC__stream_encoder_set_blocksize().
  92151. */
  92152. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  92153. /** Get the "mid/side stereo coding" flag.
  92154. *
  92155. * \param encoder An encoder instance to query.
  92156. * \assert
  92157. * \code encoder != NULL \endcode
  92158. * \retval FLAC__bool
  92159. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  92160. */
  92161. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92162. /** Get the "adaptive mid/side switching" flag.
  92163. *
  92164. * \param encoder An encoder instance to query.
  92165. * \assert
  92166. * \code encoder != NULL \endcode
  92167. * \retval FLAC__bool
  92168. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  92169. */
  92170. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92171. /** Get the maximum LPC order setting.
  92172. *
  92173. * \param encoder An encoder instance to query.
  92174. * \assert
  92175. * \code encoder != NULL \endcode
  92176. * \retval unsigned
  92177. * See FLAC__stream_encoder_set_max_lpc_order().
  92178. */
  92179. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  92180. /** Get the quantized linear predictor coefficient precision setting.
  92181. *
  92182. * \param encoder An encoder instance to query.
  92183. * \assert
  92184. * \code encoder != NULL \endcode
  92185. * \retval unsigned
  92186. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  92187. */
  92188. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  92189. /** Get the qlp coefficient precision search flag.
  92190. *
  92191. * \param encoder An encoder instance to query.
  92192. * \assert
  92193. * \code encoder != NULL \endcode
  92194. * \retval FLAC__bool
  92195. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  92196. */
  92197. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  92198. /** Get the "escape coding" flag.
  92199. *
  92200. * \param encoder An encoder instance to query.
  92201. * \assert
  92202. * \code encoder != NULL \endcode
  92203. * \retval FLAC__bool
  92204. * See FLAC__stream_encoder_set_do_escape_coding().
  92205. */
  92206. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  92207. /** Get the exhaustive model search flag.
  92208. *
  92209. * \param encoder An encoder instance to query.
  92210. * \assert
  92211. * \code encoder != NULL \endcode
  92212. * \retval FLAC__bool
  92213. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92214. */
  92215. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92216. /** Get the minimum residual partition order setting.
  92217. *
  92218. * \param encoder An encoder instance to query.
  92219. * \assert
  92220. * \code encoder != NULL \endcode
  92221. * \retval unsigned
  92222. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92223. */
  92224. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92225. /** Get maximum residual partition order setting.
  92226. *
  92227. * \param encoder An encoder instance to query.
  92228. * \assert
  92229. * \code encoder != NULL \endcode
  92230. * \retval unsigned
  92231. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92232. */
  92233. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92234. /** Get the Rice parameter search distance setting.
  92235. *
  92236. * \param encoder An encoder instance to query.
  92237. * \assert
  92238. * \code encoder != NULL \endcode
  92239. * \retval unsigned
  92240. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92241. */
  92242. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92243. /** Get the previously set estimate of the total samples to be encoded.
  92244. * The encoder merely mimics back the value given to
  92245. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92246. * other way of knowing how many samples the client will encode.
  92247. *
  92248. * \param encoder An encoder instance to set.
  92249. * \assert
  92250. * \code encoder != NULL \endcode
  92251. * \retval FLAC__uint64
  92252. * See FLAC__stream_encoder_get_total_samples_estimate().
  92253. */
  92254. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92255. /** Initialize the encoder instance to encode native FLAC streams.
  92256. *
  92257. * This flavor of initialization sets up the encoder to encode to a
  92258. * native FLAC stream. I/O is performed via callbacks to the client.
  92259. * For encoding to a plain file via filename or open \c FILE*,
  92260. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92261. * provide a simpler interface.
  92262. *
  92263. * This function should be called after FLAC__stream_encoder_new() and
  92264. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92265. * or FLAC__stream_encoder_process_interleaved().
  92266. * initialization succeeded.
  92267. *
  92268. * The call to FLAC__stream_encoder_init_stream() currently will also
  92269. * immediately call the write callback several times, once with the \c fLaC
  92270. * signature, and once for each encoded metadata block.
  92271. *
  92272. * \param encoder An uninitialized encoder instance.
  92273. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92274. * pointer must not be \c NULL.
  92275. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92276. * pointer may be \c NULL if seeking is not
  92277. * supported. The encoder uses seeking to go back
  92278. * and write some some stream statistics to the
  92279. * STREAMINFO block; this is recommended but not
  92280. * necessary to create a valid FLAC stream. If
  92281. * \a seek_callback is not \c NULL then a
  92282. * \a tell_callback must also be supplied.
  92283. * Alternatively, a dummy seek callback that just
  92284. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92285. * may also be supplied, all though this is slightly
  92286. * less efficient for the encoder.
  92287. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92288. * pointer may be \c NULL if seeking is not
  92289. * supported. If \a seek_callback is \c NULL then
  92290. * this argument will be ignored. If
  92291. * \a seek_callback is not \c NULL then a
  92292. * \a tell_callback must also be supplied.
  92293. * Alternatively, a dummy tell callback that just
  92294. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92295. * may also be supplied, all though this is slightly
  92296. * less efficient for the encoder.
  92297. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92298. * pointer may be \c NULL if the callback is not
  92299. * desired. If the client provides a seek callback,
  92300. * this function is not necessary as the encoder
  92301. * will automatically seek back and update the
  92302. * STREAMINFO block. It may also be \c NULL if the
  92303. * client does not support seeking, since it will
  92304. * have no way of going back to update the
  92305. * STREAMINFO. However the client can still supply
  92306. * a callback if it would like to know the details
  92307. * from the STREAMINFO.
  92308. * \param client_data This value will be supplied to callbacks in their
  92309. * \a client_data argument.
  92310. * \assert
  92311. * \code encoder != NULL \endcode
  92312. * \retval FLAC__StreamEncoderInitStatus
  92313. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92314. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92315. */
  92316. 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);
  92317. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92318. *
  92319. * This flavor of initialization sets up the encoder to encode to a FLAC
  92320. * stream in an Ogg container. I/O is performed via callbacks to the
  92321. * client. For encoding to a plain file via filename or open \c FILE*,
  92322. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92323. * provide a simpler interface.
  92324. *
  92325. * This function should be called after FLAC__stream_encoder_new() and
  92326. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92327. * or FLAC__stream_encoder_process_interleaved().
  92328. * initialization succeeded.
  92329. *
  92330. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92331. * immediately call the write callback several times to write the metadata
  92332. * packets.
  92333. *
  92334. * \param encoder An uninitialized encoder instance.
  92335. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92336. * pointer must not be \c NULL if \a seek_callback
  92337. * is non-NULL since they are both needed to be
  92338. * able to write data back to the Ogg FLAC stream
  92339. * in the post-encode phase.
  92340. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92341. * pointer must not be \c NULL.
  92342. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92343. * pointer may be \c NULL if seeking is not
  92344. * supported. The encoder uses seeking to go back
  92345. * and write some some stream statistics to the
  92346. * STREAMINFO block; this is recommended but not
  92347. * necessary to create a valid FLAC stream. If
  92348. * \a seek_callback is not \c NULL then a
  92349. * \a tell_callback must also be supplied.
  92350. * Alternatively, a dummy seek callback that just
  92351. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92352. * may also be supplied, all though this is slightly
  92353. * less efficient for the encoder.
  92354. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92355. * pointer may be \c NULL if seeking is not
  92356. * supported. If \a seek_callback is \c NULL then
  92357. * this argument will be ignored. If
  92358. * \a seek_callback is not \c NULL then a
  92359. * \a tell_callback must also be supplied.
  92360. * Alternatively, a dummy tell callback that just
  92361. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92362. * may also be supplied, all though this is slightly
  92363. * less efficient for the encoder.
  92364. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92365. * pointer may be \c NULL if the callback is not
  92366. * desired. If the client provides a seek callback,
  92367. * this function is not necessary as the encoder
  92368. * will automatically seek back and update the
  92369. * STREAMINFO block. It may also be \c NULL if the
  92370. * client does not support seeking, since it will
  92371. * have no way of going back to update the
  92372. * STREAMINFO. However the client can still supply
  92373. * a callback if it would like to know the details
  92374. * from the STREAMINFO.
  92375. * \param client_data This value will be supplied to callbacks in their
  92376. * \a client_data argument.
  92377. * \assert
  92378. * \code encoder != NULL \endcode
  92379. * \retval FLAC__StreamEncoderInitStatus
  92380. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92381. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92382. */
  92383. 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);
  92384. /** Initialize the encoder instance to encode native FLAC files.
  92385. *
  92386. * This flavor of initialization sets up the encoder to encode to a
  92387. * plain native FLAC file. For non-stdio streams, you must use
  92388. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92389. *
  92390. * This function should be called after FLAC__stream_encoder_new() and
  92391. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92392. * or FLAC__stream_encoder_process_interleaved().
  92393. * initialization succeeded.
  92394. *
  92395. * \param encoder An uninitialized encoder instance.
  92396. * \param file An open file. The file should have been opened
  92397. * with mode \c "w+b" and rewound. The file
  92398. * becomes owned by the encoder and should not be
  92399. * manipulated by the client while encoding.
  92400. * Unless \a file is \c stdout, it will be closed
  92401. * when FLAC__stream_encoder_finish() is called.
  92402. * Note however that a proper SEEKTABLE cannot be
  92403. * created when encoding to \c stdout since it is
  92404. * not seekable.
  92405. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92406. * pointer may be \c NULL if the callback is not
  92407. * desired.
  92408. * \param client_data This value will be supplied to callbacks in their
  92409. * \a client_data argument.
  92410. * \assert
  92411. * \code encoder != NULL \endcode
  92412. * \code file != NULL \endcode
  92413. * \retval FLAC__StreamEncoderInitStatus
  92414. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92415. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92416. */
  92417. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92418. /** Initialize the encoder instance to encode Ogg FLAC files.
  92419. *
  92420. * This flavor of initialization sets up the encoder to encode to a
  92421. * plain Ogg FLAC file. For non-stdio streams, you must use
  92422. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92423. *
  92424. * This function should be called after FLAC__stream_encoder_new() and
  92425. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92426. * or FLAC__stream_encoder_process_interleaved().
  92427. * initialization succeeded.
  92428. *
  92429. * \param encoder An uninitialized encoder instance.
  92430. * \param file An open file. The file should have been opened
  92431. * with mode \c "w+b" and rewound. The file
  92432. * becomes owned by the encoder and should not be
  92433. * manipulated by the client while encoding.
  92434. * Unless \a file is \c stdout, it will be closed
  92435. * when FLAC__stream_encoder_finish() is called.
  92436. * Note however that a proper SEEKTABLE cannot be
  92437. * created when encoding to \c stdout since it is
  92438. * not seekable.
  92439. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92440. * pointer may be \c NULL if the callback is not
  92441. * desired.
  92442. * \param client_data This value will be supplied to callbacks in their
  92443. * \a client_data argument.
  92444. * \assert
  92445. * \code encoder != NULL \endcode
  92446. * \code file != NULL \endcode
  92447. * \retval FLAC__StreamEncoderInitStatus
  92448. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92449. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92450. */
  92451. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92452. /** Initialize the encoder instance to encode native FLAC files.
  92453. *
  92454. * This flavor of initialization sets up the encoder to encode to a plain
  92455. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92456. * with Unicode filenames on Windows), you must use
  92457. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92458. * and provide callbacks for the I/O.
  92459. *
  92460. * This function should be called after FLAC__stream_encoder_new() and
  92461. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92462. * or FLAC__stream_encoder_process_interleaved().
  92463. * initialization succeeded.
  92464. *
  92465. * \param encoder An uninitialized encoder instance.
  92466. * \param filename The name of the file to encode to. The file will
  92467. * be opened with fopen(). Use \c NULL to encode to
  92468. * \c stdout. Note however that a proper SEEKTABLE
  92469. * cannot be created when encoding to \c stdout since
  92470. * it is not seekable.
  92471. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92472. * pointer may be \c NULL if the callback is not
  92473. * desired.
  92474. * \param client_data This value will be supplied to callbacks in their
  92475. * \a client_data argument.
  92476. * \assert
  92477. * \code encoder != NULL \endcode
  92478. * \retval FLAC__StreamEncoderInitStatus
  92479. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92480. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92481. */
  92482. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92483. /** Initialize the encoder instance to encode Ogg FLAC files.
  92484. *
  92485. * This flavor of initialization sets up the encoder to encode to a plain
  92486. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92487. * with Unicode filenames on Windows), you must use
  92488. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92489. * and provide callbacks for the I/O.
  92490. *
  92491. * This function should be called after FLAC__stream_encoder_new() and
  92492. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92493. * or FLAC__stream_encoder_process_interleaved().
  92494. * initialization succeeded.
  92495. *
  92496. * \param encoder An uninitialized encoder instance.
  92497. * \param filename The name of the file to encode to. The file will
  92498. * be opened with fopen(). Use \c NULL to encode to
  92499. * \c stdout. Note however that a proper SEEKTABLE
  92500. * cannot be created when encoding to \c stdout since
  92501. * it is not seekable.
  92502. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92503. * pointer may be \c NULL if the callback is not
  92504. * desired.
  92505. * \param client_data This value will be supplied to callbacks in their
  92506. * \a client_data argument.
  92507. * \assert
  92508. * \code encoder != NULL \endcode
  92509. * \retval FLAC__StreamEncoderInitStatus
  92510. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92511. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92512. */
  92513. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92514. /** Finish the encoding process.
  92515. * Flushes the encoding buffer, releases resources, resets the encoder
  92516. * settings to their defaults, and returns the encoder state to
  92517. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92518. * one or more write callbacks before returning, and will generate
  92519. * a metadata callback.
  92520. *
  92521. * Note that in the course of processing the last frame, errors can
  92522. * occur, so the caller should be sure to check the return value to
  92523. * ensure the file was encoded properly.
  92524. *
  92525. * In the event of a prematurely-terminated encode, it is not strictly
  92526. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92527. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92528. * with a FLAC__stream_encoder_finish().
  92529. *
  92530. * \param encoder An uninitialized encoder instance.
  92531. * \assert
  92532. * \code encoder != NULL \endcode
  92533. * \retval FLAC__bool
  92534. * \c false if an error occurred processing the last frame; or if verify
  92535. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92536. * verify mismatch; else \c true. If \c false, caller should check the
  92537. * state with FLAC__stream_encoder_get_state() for more information
  92538. * about the error.
  92539. */
  92540. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92541. /** Submit data for encoding.
  92542. * This version allows you to supply the input data via an array of
  92543. * pointers, each pointer pointing to an array of \a samples samples
  92544. * representing one channel. The samples need not be block-aligned,
  92545. * but each channel should have the same number of samples. Each sample
  92546. * should be a signed integer, right-justified to the resolution set by
  92547. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92548. * resolution is 16 bits per sample, the samples should all be in the
  92549. * range [-32768,32767].
  92550. *
  92551. * For applications where channel order is important, channels must
  92552. * follow the order as described in the
  92553. * <A HREF="../format.html#frame_header">frame header</A>.
  92554. *
  92555. * \param encoder An initialized encoder instance in the OK state.
  92556. * \param buffer An array of pointers to each channel's signal.
  92557. * \param samples The number of samples in one channel.
  92558. * \assert
  92559. * \code encoder != NULL \endcode
  92560. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92561. * \retval FLAC__bool
  92562. * \c true if successful, else \c false; in this case, check the
  92563. * encoder state with FLAC__stream_encoder_get_state() to see what
  92564. * went wrong.
  92565. */
  92566. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92567. /** Submit data for encoding.
  92568. * This version allows you to supply the input data where the channels
  92569. * are interleaved into a single array (i.e. channel0_sample0,
  92570. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92571. * The samples need not be block-aligned but they must be
  92572. * sample-aligned, i.e. the first value should be channel0_sample0
  92573. * and the last value channelN_sampleM. Each sample should be a signed
  92574. * integer, right-justified to the resolution set by
  92575. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92576. * resolution is 16 bits per sample, the samples should all be in the
  92577. * range [-32768,32767].
  92578. *
  92579. * For applications where channel order is important, channels must
  92580. * follow the order as described in the
  92581. * <A HREF="../format.html#frame_header">frame header</A>.
  92582. *
  92583. * \param encoder An initialized encoder instance in the OK state.
  92584. * \param buffer An array of channel-interleaved data (see above).
  92585. * \param samples The number of samples in one channel, the same as for
  92586. * FLAC__stream_encoder_process(). For example, if
  92587. * encoding two channels, \c 1000 \a samples corresponds
  92588. * to a \a buffer of 2000 values.
  92589. * \assert
  92590. * \code encoder != NULL \endcode
  92591. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92592. * \retval FLAC__bool
  92593. * \c true if successful, else \c false; in this case, check the
  92594. * encoder state with FLAC__stream_encoder_get_state() to see what
  92595. * went wrong.
  92596. */
  92597. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92598. /* \} */
  92599. #ifdef __cplusplus
  92600. }
  92601. #endif
  92602. #endif
  92603. /*** End of inlined file: stream_encoder.h ***/
  92604. #ifdef _MSC_VER
  92605. /* OPT: an MSVC built-in would be better */
  92606. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92607. {
  92608. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92609. return (x>>16) | (x<<16);
  92610. }
  92611. #endif
  92612. #if defined(_MSC_VER) && defined(_X86_)
  92613. /* OPT: an MSVC built-in would be better */
  92614. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92615. {
  92616. __asm {
  92617. mov edx, start
  92618. mov ecx, len
  92619. test ecx, ecx
  92620. loop1:
  92621. jz done1
  92622. mov eax, [edx]
  92623. bswap eax
  92624. mov [edx], eax
  92625. add edx, 4
  92626. dec ecx
  92627. jmp short loop1
  92628. done1:
  92629. }
  92630. }
  92631. #endif
  92632. /** \mainpage
  92633. *
  92634. * \section intro Introduction
  92635. *
  92636. * This is the documentation for the FLAC C and C++ APIs. It is
  92637. * highly interconnected; this introduction should give you a top
  92638. * level idea of the structure and how to find the information you
  92639. * need. As a prerequisite you should have at least a basic
  92640. * knowledge of the FLAC format, documented
  92641. * <A HREF="../format.html">here</A>.
  92642. *
  92643. * \section c_api FLAC C API
  92644. *
  92645. * The FLAC C API is the interface to libFLAC, a set of structures
  92646. * describing the components of FLAC streams, and functions for
  92647. * encoding and decoding streams, as well as manipulating FLAC
  92648. * metadata in files. The public include files will be installed
  92649. * in your include area (for example /usr/include/FLAC/...).
  92650. *
  92651. * By writing a little code and linking against libFLAC, it is
  92652. * relatively easy to add FLAC support to another program. The
  92653. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92654. * Complete source code of libFLAC as well as the command-line
  92655. * encoder and plugins is available and is a useful source of
  92656. * examples.
  92657. *
  92658. * Aside from encoders and decoders, libFLAC provides a powerful
  92659. * metadata interface for manipulating metadata in FLAC files. It
  92660. * allows the user to add, delete, and modify FLAC metadata blocks
  92661. * and it can automatically take advantage of PADDING blocks to avoid
  92662. * rewriting the entire FLAC file when changing the size of the
  92663. * metadata.
  92664. *
  92665. * libFLAC usually only requires the standard C library and C math
  92666. * library. In particular, threading is not used so there is no
  92667. * dependency on a thread library. However, libFLAC does not use
  92668. * global variables and should be thread-safe.
  92669. *
  92670. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92671. * However the metadata editing interfaces currently have limited
  92672. * read-only support for Ogg FLAC files.
  92673. *
  92674. * \section cpp_api FLAC C++ API
  92675. *
  92676. * The FLAC C++ API is a set of classes that encapsulate the
  92677. * structures and functions in libFLAC. They provide slightly more
  92678. * functionality with respect to metadata but are otherwise
  92679. * equivalent. For the most part, they share the same usage as
  92680. * their counterparts in libFLAC, and the FLAC C API documentation
  92681. * can be used as a supplement. The public include files
  92682. * for the C++ API will be installed in your include area (for
  92683. * example /usr/include/FLAC++/...).
  92684. *
  92685. * libFLAC++ is also licensed under
  92686. * <A HREF="../license.html">Xiph's BSD license</A>.
  92687. *
  92688. * \section getting_started Getting Started
  92689. *
  92690. * A good starting point for learning the API is to browse through
  92691. * the <A HREF="modules.html">modules</A>. Modules are logical
  92692. * groupings of related functions or classes, which correspond roughly
  92693. * to header files or sections of header files. Each module includes a
  92694. * detailed description of the general usage of its functions or
  92695. * classes.
  92696. *
  92697. * From there you can go on to look at the documentation of
  92698. * individual functions. You can see different views of the individual
  92699. * functions through the links in top bar across this page.
  92700. *
  92701. * If you prefer a more hands-on approach, you can jump right to some
  92702. * <A HREF="../documentation_example_code.html">example code</A>.
  92703. *
  92704. * \section porting_guide Porting Guide
  92705. *
  92706. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92707. * has been introduced which gives detailed instructions on how to
  92708. * port your code to newer versions of FLAC.
  92709. *
  92710. * \section embedded_developers Embedded Developers
  92711. *
  92712. * libFLAC has grown larger over time as more functionality has been
  92713. * included, but much of it may be unnecessary for a particular embedded
  92714. * implementation. Unused parts may be pruned by some simple editing of
  92715. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92716. * metadata interface are all independent from each other.
  92717. *
  92718. * It is easiest to just describe the dependencies:
  92719. *
  92720. * - All modules depend on the \link flac_format Format \endlink module.
  92721. * - The decoders and encoders depend on the bitbuffer.
  92722. * - The decoder is independent of the encoder. The encoder uses the
  92723. * decoder because of the verify feature, but this can be removed if
  92724. * not needed.
  92725. * - Parts of the metadata interface require the stream decoder (but not
  92726. * the encoder).
  92727. * - Ogg support is selectable through the compile time macro
  92728. * \c FLAC__HAS_OGG.
  92729. *
  92730. * For example, if your application only requires the stream decoder, no
  92731. * encoder, and no metadata interface, you can remove the stream encoder
  92732. * and the metadata interface, which will greatly reduce the size of the
  92733. * library.
  92734. *
  92735. * Also, there are several places in the libFLAC code with comments marked
  92736. * with "OPT:" where a #define can be changed to enable code that might be
  92737. * faster on a specific platform. Experimenting with these can yield faster
  92738. * binaries.
  92739. */
  92740. /** \defgroup porting Porting Guide for New Versions
  92741. *
  92742. * This module describes differences in the library interfaces from
  92743. * version to version. It assists in the porting of code that uses
  92744. * the libraries to newer versions of FLAC.
  92745. *
  92746. * One simple facility for making porting easier that has been added
  92747. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92748. * library's includes (e.g. \c include/FLAC/export.h). The
  92749. * \c #defines mirror the libraries'
  92750. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92751. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92752. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92753. * These can be used to support multiple versions of an API during the
  92754. * transition phase, e.g.
  92755. *
  92756. * \code
  92757. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92758. * legacy code
  92759. * #else
  92760. * new code
  92761. * #endif
  92762. * \endcode
  92763. *
  92764. * The the source will work for multiple versions and the legacy code can
  92765. * easily be removed when the transition is complete.
  92766. *
  92767. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92768. * include/FLAC/export.h), which can be used to determine whether or not
  92769. * the library has been compiled with support for Ogg FLAC. This is
  92770. * simpler than trying to call an Ogg init function and catching the
  92771. * error.
  92772. */
  92773. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92774. * \ingroup porting
  92775. *
  92776. * \brief
  92777. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92778. *
  92779. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92780. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92781. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92782. * decoding layers and three encoding layers have been merged into a
  92783. * single stream decoder and stream encoder. That is, the functionality
  92784. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92785. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92786. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92787. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92788. * is there is now a single API that can be used to encode or decode
  92789. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92790. * on both seekable and non-seekable streams.
  92791. *
  92792. * Instead of creating an encoder or decoder of a certain layer, now the
  92793. * client will always create a FLAC__StreamEncoder or
  92794. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92795. * initialization function. For example, for the decoder,
  92796. * FLAC__stream_decoder_init() has been replaced by
  92797. * FLAC__stream_decoder_init_stream(). This init function takes
  92798. * callbacks for the I/O, and the seeking callbacks are optional. This
  92799. * allows the client to use the same object for seekable and
  92800. * non-seekable streams. For decoding a FLAC file directly, the client
  92801. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92802. * and fewer callbacks; most of the other callbacks are supplied
  92803. * internally. For situations where fopen()ing by filename is not
  92804. * possible (e.g. Unicode filenames on Windows) the client can instead
  92805. * open the file itself and supply the FILE* to
  92806. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92807. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92808. * Since the callbacks and client data are now passed to the init
  92809. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92810. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92811. * rest of the calls to the decoder are the same as before.
  92812. *
  92813. * There are counterpart init functions for Ogg FLAC, e.g.
  92814. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92815. * and callbacks are the same as for native FLAC.
  92816. *
  92817. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92818. * been set up like so:
  92819. *
  92820. * \code
  92821. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92822. * if(decoder == NULL) do_something;
  92823. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92824. * [... other settings ...]
  92825. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92826. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92827. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92828. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92829. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92830. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92831. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92832. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92833. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92834. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92835. * \endcode
  92836. *
  92837. * In FLAC 1.1.3 it is like this:
  92838. *
  92839. * \code
  92840. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92841. * if(decoder == NULL) do_something;
  92842. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92843. * [... other settings ...]
  92844. * if(FLAC__stream_decoder_init_stream(
  92845. * decoder,
  92846. * my_read_callback,
  92847. * my_seek_callback, // or NULL
  92848. * my_tell_callback, // or NULL
  92849. * my_length_callback, // or NULL
  92850. * my_eof_callback, // or NULL
  92851. * my_write_callback,
  92852. * my_metadata_callback, // or NULL
  92853. * my_error_callback,
  92854. * my_client_data
  92855. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92856. * \endcode
  92857. *
  92858. * or you could do;
  92859. *
  92860. * \code
  92861. * [...]
  92862. * FILE *file = fopen("somefile.flac","rb");
  92863. * if(file == NULL) do_somthing;
  92864. * if(FLAC__stream_decoder_init_FILE(
  92865. * decoder,
  92866. * file,
  92867. * my_write_callback,
  92868. * my_metadata_callback, // or NULL
  92869. * my_error_callback,
  92870. * my_client_data
  92871. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92872. * \endcode
  92873. *
  92874. * or just:
  92875. *
  92876. * \code
  92877. * [...]
  92878. * if(FLAC__stream_decoder_init_file(
  92879. * decoder,
  92880. * "somefile.flac",
  92881. * my_write_callback,
  92882. * my_metadata_callback, // or NULL
  92883. * my_error_callback,
  92884. * my_client_data
  92885. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92886. * \endcode
  92887. *
  92888. * Another small change to the decoder is in how it handles unparseable
  92889. * streams. Before, when the decoder found an unparseable stream
  92890. * (reserved for when the decoder encounters a stream from a future
  92891. * encoder that it can't parse), it changed the state to
  92892. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92893. * drops sync and calls the error callback with a new error code
  92894. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92895. * more robust. If your error callback does not discriminate on the the
  92896. * error state, your code does not need to be changed.
  92897. *
  92898. * The encoder now has a new setting:
  92899. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92900. * method used to window the data before LPC analysis. You only need to
  92901. * add a call to this function if the default is not suitable. There
  92902. * are also two new convenience functions that may be useful:
  92903. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92904. * FLAC__metadata_get_cuesheet().
  92905. *
  92906. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92907. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92908. * is now \c size_t instead of \c unsigned.
  92909. */
  92910. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92911. * \ingroup porting
  92912. *
  92913. * \brief
  92914. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92915. *
  92916. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92917. * There was a slight change in the implementation of
  92918. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92919. * of the \a metadata array of pointers so the client no longer needs
  92920. * to maintain it after the call. The objects themselves that are
  92921. * pointed to by the array are still not copied though and must be
  92922. * maintained until the call to FLAC__stream_encoder_finish().
  92923. */
  92924. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92925. * \ingroup porting
  92926. *
  92927. * \brief
  92928. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92929. *
  92930. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92931. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92932. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92933. *
  92934. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92935. * has changed to reflect the conversion of one of the reserved bits
  92936. * into active use. It used to be \c 2 and now is \c 1. However the
  92937. * FLAC frame header length has not changed, so to skip the proper
  92938. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92939. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92940. */
  92941. /** \defgroup flac FLAC C API
  92942. *
  92943. * The FLAC C API is the interface to libFLAC, a set of structures
  92944. * describing the components of FLAC streams, and functions for
  92945. * encoding and decoding streams, as well as manipulating FLAC
  92946. * metadata in files.
  92947. *
  92948. * You should start with the format components as all other modules
  92949. * are dependent on it.
  92950. */
  92951. #endif
  92952. /*** End of inlined file: all.h ***/
  92953. /*** Start of inlined file: bitmath.c ***/
  92954. /*** Start of inlined file: juce_FlacHeader.h ***/
  92955. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92956. // tasks..
  92957. #define VERSION "1.2.1"
  92958. #define FLAC__NO_DLL 1
  92959. #if JUCE_MSVC
  92960. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92961. #endif
  92962. #if JUCE_MAC
  92963. #define FLAC__SYS_DARWIN 1
  92964. #endif
  92965. /*** End of inlined file: juce_FlacHeader.h ***/
  92966. #if JUCE_USE_FLAC
  92967. #if HAVE_CONFIG_H
  92968. # include <config.h>
  92969. #endif
  92970. /*** Start of inlined file: bitmath.h ***/
  92971. #ifndef FLAC__PRIVATE__BITMATH_H
  92972. #define FLAC__PRIVATE__BITMATH_H
  92973. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92974. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92975. unsigned FLAC__bitmath_silog2(int v);
  92976. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92977. #endif
  92978. /*** End of inlined file: bitmath.h ***/
  92979. /* An example of what FLAC__bitmath_ilog2() computes:
  92980. *
  92981. * ilog2( 0) = assertion failure
  92982. * ilog2( 1) = 0
  92983. * ilog2( 2) = 1
  92984. * ilog2( 3) = 1
  92985. * ilog2( 4) = 2
  92986. * ilog2( 5) = 2
  92987. * ilog2( 6) = 2
  92988. * ilog2( 7) = 2
  92989. * ilog2( 8) = 3
  92990. * ilog2( 9) = 3
  92991. * ilog2(10) = 3
  92992. * ilog2(11) = 3
  92993. * ilog2(12) = 3
  92994. * ilog2(13) = 3
  92995. * ilog2(14) = 3
  92996. * ilog2(15) = 3
  92997. * ilog2(16) = 4
  92998. * ilog2(17) = 4
  92999. * ilog2(18) = 4
  93000. */
  93001. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  93002. {
  93003. unsigned l = 0;
  93004. FLAC__ASSERT(v > 0);
  93005. while(v >>= 1)
  93006. l++;
  93007. return l;
  93008. }
  93009. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  93010. {
  93011. unsigned l = 0;
  93012. FLAC__ASSERT(v > 0);
  93013. while(v >>= 1)
  93014. l++;
  93015. return l;
  93016. }
  93017. /* An example of what FLAC__bitmath_silog2() computes:
  93018. *
  93019. * silog2(-10) = 5
  93020. * silog2(- 9) = 5
  93021. * silog2(- 8) = 4
  93022. * silog2(- 7) = 4
  93023. * silog2(- 6) = 4
  93024. * silog2(- 5) = 4
  93025. * silog2(- 4) = 3
  93026. * silog2(- 3) = 3
  93027. * silog2(- 2) = 2
  93028. * silog2(- 1) = 2
  93029. * silog2( 0) = 0
  93030. * silog2( 1) = 2
  93031. * silog2( 2) = 3
  93032. * silog2( 3) = 3
  93033. * silog2( 4) = 4
  93034. * silog2( 5) = 4
  93035. * silog2( 6) = 4
  93036. * silog2( 7) = 4
  93037. * silog2( 8) = 5
  93038. * silog2( 9) = 5
  93039. * silog2( 10) = 5
  93040. */
  93041. unsigned FLAC__bitmath_silog2(int v)
  93042. {
  93043. while(1) {
  93044. if(v == 0) {
  93045. return 0;
  93046. }
  93047. else if(v > 0) {
  93048. unsigned l = 0;
  93049. while(v) {
  93050. l++;
  93051. v >>= 1;
  93052. }
  93053. return l+1;
  93054. }
  93055. else if(v == -1) {
  93056. return 2;
  93057. }
  93058. else {
  93059. v++;
  93060. v = -v;
  93061. }
  93062. }
  93063. }
  93064. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  93065. {
  93066. while(1) {
  93067. if(v == 0) {
  93068. return 0;
  93069. }
  93070. else if(v > 0) {
  93071. unsigned l = 0;
  93072. while(v) {
  93073. l++;
  93074. v >>= 1;
  93075. }
  93076. return l+1;
  93077. }
  93078. else if(v == -1) {
  93079. return 2;
  93080. }
  93081. else {
  93082. v++;
  93083. v = -v;
  93084. }
  93085. }
  93086. }
  93087. #endif
  93088. /*** End of inlined file: bitmath.c ***/
  93089. /*** Start of inlined file: bitreader.c ***/
  93090. /*** Start of inlined file: juce_FlacHeader.h ***/
  93091. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93092. // tasks..
  93093. #define VERSION "1.2.1"
  93094. #define FLAC__NO_DLL 1
  93095. #if JUCE_MSVC
  93096. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93097. #endif
  93098. #if JUCE_MAC
  93099. #define FLAC__SYS_DARWIN 1
  93100. #endif
  93101. /*** End of inlined file: juce_FlacHeader.h ***/
  93102. #if JUCE_USE_FLAC
  93103. #if HAVE_CONFIG_H
  93104. # include <config.h>
  93105. #endif
  93106. #include <stdlib.h> /* for malloc() */
  93107. #include <string.h> /* for memcpy(), memset() */
  93108. #ifdef _MSC_VER
  93109. #include <winsock.h> /* for ntohl() */
  93110. #elif defined FLAC__SYS_DARWIN
  93111. #include <machine/endian.h> /* for ntohl() */
  93112. #elif defined __MINGW32__
  93113. #include <winsock.h> /* for ntohl() */
  93114. #else
  93115. #include <netinet/in.h> /* for ntohl() */
  93116. #endif
  93117. /*** Start of inlined file: bitreader.h ***/
  93118. #ifndef FLAC__PRIVATE__BITREADER_H
  93119. #define FLAC__PRIVATE__BITREADER_H
  93120. #include <stdio.h> /* for FILE */
  93121. /*** Start of inlined file: cpu.h ***/
  93122. #ifndef FLAC__PRIVATE__CPU_H
  93123. #define FLAC__PRIVATE__CPU_H
  93124. #ifdef HAVE_CONFIG_H
  93125. #include <config.h>
  93126. #endif
  93127. typedef enum {
  93128. FLAC__CPUINFO_TYPE_IA32,
  93129. FLAC__CPUINFO_TYPE_PPC,
  93130. FLAC__CPUINFO_TYPE_UNKNOWN
  93131. } FLAC__CPUInfo_Type;
  93132. typedef struct {
  93133. FLAC__bool cpuid;
  93134. FLAC__bool bswap;
  93135. FLAC__bool cmov;
  93136. FLAC__bool mmx;
  93137. FLAC__bool fxsr;
  93138. FLAC__bool sse;
  93139. FLAC__bool sse2;
  93140. FLAC__bool sse3;
  93141. FLAC__bool ssse3;
  93142. FLAC__bool _3dnow;
  93143. FLAC__bool ext3dnow;
  93144. FLAC__bool extmmx;
  93145. } FLAC__CPUInfo_IA32;
  93146. typedef struct {
  93147. FLAC__bool altivec;
  93148. FLAC__bool ppc64;
  93149. } FLAC__CPUInfo_PPC;
  93150. typedef struct {
  93151. FLAC__bool use_asm;
  93152. FLAC__CPUInfo_Type type;
  93153. union {
  93154. FLAC__CPUInfo_IA32 ia32;
  93155. FLAC__CPUInfo_PPC ppc;
  93156. } data;
  93157. } FLAC__CPUInfo;
  93158. void FLAC__cpu_info(FLAC__CPUInfo *info);
  93159. #ifndef FLAC__NO_ASM
  93160. #ifdef FLAC__CPU_IA32
  93161. #ifdef FLAC__HAS_NASM
  93162. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  93163. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  93164. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  93165. #endif
  93166. #endif
  93167. #endif
  93168. #endif
  93169. /*** End of inlined file: cpu.h ***/
  93170. /*
  93171. * opaque structure definition
  93172. */
  93173. struct FLAC__BitReader;
  93174. typedef struct FLAC__BitReader FLAC__BitReader;
  93175. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93176. /*
  93177. * construction, deletion, initialization, etc functions
  93178. */
  93179. FLAC__BitReader *FLAC__bitreader_new(void);
  93180. void FLAC__bitreader_delete(FLAC__BitReader *br);
  93181. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  93182. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  93183. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  93184. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  93185. /*
  93186. * CRC functions
  93187. */
  93188. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  93189. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  93190. /*
  93191. * info functions
  93192. */
  93193. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  93194. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  93195. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  93196. /*
  93197. * read functions
  93198. */
  93199. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  93200. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  93201. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  93202. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  93203. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  93204. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  93205. 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! */
  93206. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  93207. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93208. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93209. #ifndef FLAC__NO_ASM
  93210. # ifdef FLAC__CPU_IA32
  93211. # ifdef FLAC__HAS_NASM
  93212. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93213. # endif
  93214. # endif
  93215. #endif
  93216. #if 0 /* UNUSED */
  93217. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93218. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93219. #endif
  93220. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93221. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93222. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93223. #endif
  93224. /*** End of inlined file: bitreader.h ***/
  93225. /*** Start of inlined file: crc.h ***/
  93226. #ifndef FLAC__PRIVATE__CRC_H
  93227. #define FLAC__PRIVATE__CRC_H
  93228. /* 8 bit CRC generator, MSB shifted first
  93229. ** polynomial = x^8 + x^2 + x^1 + x^0
  93230. ** init = 0
  93231. */
  93232. extern FLAC__byte const FLAC__crc8_table[256];
  93233. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93234. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93235. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93236. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93237. /* 16 bit CRC generator, MSB shifted first
  93238. ** polynomial = x^16 + x^15 + x^2 + x^0
  93239. ** init = 0
  93240. */
  93241. extern unsigned FLAC__crc16_table[256];
  93242. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93243. /* this alternate may be faster on some systems/compilers */
  93244. #if 0
  93245. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93246. #endif
  93247. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93248. #endif
  93249. /*** End of inlined file: crc.h ***/
  93250. /* Things should be fastest when this matches the machine word size */
  93251. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93252. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93253. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93254. typedef FLAC__uint32 brword;
  93255. #define FLAC__BYTES_PER_WORD 4
  93256. #define FLAC__BITS_PER_WORD 32
  93257. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93258. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93259. #if WORDS_BIGENDIAN
  93260. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93261. #else
  93262. #if defined (_MSC_VER) && defined (_X86_)
  93263. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93264. #else
  93265. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93266. #endif
  93267. #endif
  93268. /* counts the # of zero MSBs in a word */
  93269. #define COUNT_ZERO_MSBS(word) ( \
  93270. (word) <= 0xffff ? \
  93271. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93272. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93273. )
  93274. /* this alternate might be slightly faster on some systems/compilers: */
  93275. #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])) )
  93276. /*
  93277. * This should be at least twice as large as the largest number of words
  93278. * required to represent any 'number' (in any encoding) you are going to
  93279. * read. With FLAC this is on the order of maybe a few hundred bits.
  93280. * If the buffer is smaller than that, the decoder won't be able to read
  93281. * in a whole number that is in a variable length encoding (e.g. Rice).
  93282. * But to be practical it should be at least 1K bytes.
  93283. *
  93284. * Increase this number to decrease the number of read callbacks, at the
  93285. * expense of using more memory. Or decrease for the reverse effect,
  93286. * keeping in mind the limit from the first paragraph. The optimal size
  93287. * also depends on the CPU cache size and other factors; some twiddling
  93288. * may be necessary to squeeze out the best performance.
  93289. */
  93290. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93291. static const unsigned char byte_to_unary_table[] = {
  93292. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93293. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93294. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93295. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93296. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93297. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93298. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93299. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93308. };
  93309. #ifdef min
  93310. #undef min
  93311. #endif
  93312. #define min(x,y) ((x)<(y)?(x):(y))
  93313. #ifdef max
  93314. #undef max
  93315. #endif
  93316. #define max(x,y) ((x)>(y)?(x):(y))
  93317. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93318. #ifdef _MSC_VER
  93319. #define FLAC__U64L(x) x
  93320. #else
  93321. #define FLAC__U64L(x) x##LLU
  93322. #endif
  93323. #ifndef FLaC__INLINE
  93324. #define FLaC__INLINE
  93325. #endif
  93326. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93327. struct FLAC__BitReader {
  93328. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93329. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93330. brword *buffer;
  93331. unsigned capacity; /* in words */
  93332. unsigned words; /* # of completed words in buffer */
  93333. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93334. unsigned consumed_words; /* #words ... */
  93335. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93336. unsigned read_crc16; /* the running frame CRC */
  93337. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93338. FLAC__BitReaderReadCallback read_callback;
  93339. void *client_data;
  93340. FLAC__CPUInfo cpu_info;
  93341. };
  93342. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93343. {
  93344. register unsigned crc = br->read_crc16;
  93345. #if FLAC__BYTES_PER_WORD == 4
  93346. switch(br->crc16_align) {
  93347. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93348. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93349. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93350. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93351. }
  93352. #elif FLAC__BYTES_PER_WORD == 8
  93353. switch(br->crc16_align) {
  93354. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93355. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93356. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93357. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93358. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93359. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93360. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93361. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93362. }
  93363. #else
  93364. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93365. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93366. br->read_crc16 = crc;
  93367. #endif
  93368. br->crc16_align = 0;
  93369. }
  93370. /* would be static except it needs to be called by asm routines */
  93371. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93372. {
  93373. unsigned start, end;
  93374. size_t bytes;
  93375. FLAC__byte *target;
  93376. /* first shift the unconsumed buffer data toward the front as much as possible */
  93377. if(br->consumed_words > 0) {
  93378. start = br->consumed_words;
  93379. end = br->words + (br->bytes? 1:0);
  93380. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93381. br->words -= start;
  93382. br->consumed_words = 0;
  93383. }
  93384. /*
  93385. * set the target for reading, taking into account word alignment and endianness
  93386. */
  93387. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93388. if(bytes == 0)
  93389. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93390. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93391. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93392. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93393. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93394. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93395. * ^^-------target, bytes=3
  93396. * on LE machines, have to byteswap the odd tail word so nothing is
  93397. * overwritten:
  93398. */
  93399. #if WORDS_BIGENDIAN
  93400. #else
  93401. if(br->bytes)
  93402. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93403. #endif
  93404. /* now it looks like:
  93405. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93406. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93407. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93408. * ^^-------target, bytes=3
  93409. */
  93410. /* read in the data; note that the callback may return a smaller number of bytes */
  93411. if(!br->read_callback(target, &bytes, br->client_data))
  93412. return false;
  93413. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93414. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93415. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93416. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93417. * now have to byteswap on LE machines:
  93418. */
  93419. #if WORDS_BIGENDIAN
  93420. #else
  93421. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93422. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93423. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93424. start = br->words;
  93425. local_swap32_block_(br->buffer + start, end - start);
  93426. }
  93427. else
  93428. # endif
  93429. for(start = br->words; start < end; start++)
  93430. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93431. #endif
  93432. /* now it looks like:
  93433. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93434. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93435. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93436. * finally we'll update the reader values:
  93437. */
  93438. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93439. br->words = end / FLAC__BYTES_PER_WORD;
  93440. br->bytes = end % FLAC__BYTES_PER_WORD;
  93441. return true;
  93442. }
  93443. /***********************************************************************
  93444. *
  93445. * Class constructor/destructor
  93446. *
  93447. ***********************************************************************/
  93448. FLAC__BitReader *FLAC__bitreader_new(void)
  93449. {
  93450. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93451. /* calloc() implies:
  93452. memset(br, 0, sizeof(FLAC__BitReader));
  93453. br->buffer = 0;
  93454. br->capacity = 0;
  93455. br->words = br->bytes = 0;
  93456. br->consumed_words = br->consumed_bits = 0;
  93457. br->read_callback = 0;
  93458. br->client_data = 0;
  93459. */
  93460. return br;
  93461. }
  93462. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93463. {
  93464. FLAC__ASSERT(0 != br);
  93465. FLAC__bitreader_free(br);
  93466. free(br);
  93467. }
  93468. /***********************************************************************
  93469. *
  93470. * Public class methods
  93471. *
  93472. ***********************************************************************/
  93473. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93474. {
  93475. FLAC__ASSERT(0 != br);
  93476. br->words = br->bytes = 0;
  93477. br->consumed_words = br->consumed_bits = 0;
  93478. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93479. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93480. if(br->buffer == 0)
  93481. return false;
  93482. br->read_callback = rcb;
  93483. br->client_data = cd;
  93484. br->cpu_info = cpu;
  93485. return true;
  93486. }
  93487. void FLAC__bitreader_free(FLAC__BitReader *br)
  93488. {
  93489. FLAC__ASSERT(0 != br);
  93490. if(0 != br->buffer)
  93491. free(br->buffer);
  93492. br->buffer = 0;
  93493. br->capacity = 0;
  93494. br->words = br->bytes = 0;
  93495. br->consumed_words = br->consumed_bits = 0;
  93496. br->read_callback = 0;
  93497. br->client_data = 0;
  93498. }
  93499. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93500. {
  93501. br->words = br->bytes = 0;
  93502. br->consumed_words = br->consumed_bits = 0;
  93503. return true;
  93504. }
  93505. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93506. {
  93507. unsigned i, j;
  93508. if(br == 0) {
  93509. fprintf(out, "bitreader is NULL\n");
  93510. }
  93511. else {
  93512. 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);
  93513. for(i = 0; i < br->words; i++) {
  93514. fprintf(out, "%08X: ", i);
  93515. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93516. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93517. fprintf(out, ".");
  93518. else
  93519. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93520. fprintf(out, "\n");
  93521. }
  93522. if(br->bytes > 0) {
  93523. fprintf(out, "%08X: ", i);
  93524. for(j = 0; j < br->bytes*8; j++)
  93525. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93526. fprintf(out, ".");
  93527. else
  93528. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93529. fprintf(out, "\n");
  93530. }
  93531. }
  93532. }
  93533. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93534. {
  93535. FLAC__ASSERT(0 != br);
  93536. FLAC__ASSERT(0 != br->buffer);
  93537. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93538. br->read_crc16 = (unsigned)seed;
  93539. br->crc16_align = br->consumed_bits;
  93540. }
  93541. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93542. {
  93543. FLAC__ASSERT(0 != br);
  93544. FLAC__ASSERT(0 != br->buffer);
  93545. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93546. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93547. /* CRC any tail bytes in a partially-consumed word */
  93548. if(br->consumed_bits) {
  93549. const brword tail = br->buffer[br->consumed_words];
  93550. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93551. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93552. }
  93553. return br->read_crc16;
  93554. }
  93555. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93556. {
  93557. return ((br->consumed_bits & 7) == 0);
  93558. }
  93559. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93560. {
  93561. return 8 - (br->consumed_bits & 7);
  93562. }
  93563. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93564. {
  93565. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93566. }
  93567. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93568. {
  93569. FLAC__ASSERT(0 != br);
  93570. FLAC__ASSERT(0 != br->buffer);
  93571. FLAC__ASSERT(bits <= 32);
  93572. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93573. FLAC__ASSERT(br->consumed_words <= br->words);
  93574. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93575. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93576. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93577. *val = 0;
  93578. return true;
  93579. }
  93580. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93581. if(!bitreader_read_from_client_(br))
  93582. return false;
  93583. }
  93584. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93585. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93586. if(br->consumed_bits) {
  93587. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93588. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93589. const brword word = br->buffer[br->consumed_words];
  93590. if(bits < n) {
  93591. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93592. br->consumed_bits += bits;
  93593. return true;
  93594. }
  93595. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93596. bits -= n;
  93597. crc16_update_word_(br, word);
  93598. br->consumed_words++;
  93599. br->consumed_bits = 0;
  93600. 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 */
  93601. *val <<= bits;
  93602. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93603. br->consumed_bits = bits;
  93604. }
  93605. return true;
  93606. }
  93607. else {
  93608. const brword word = br->buffer[br->consumed_words];
  93609. if(bits < FLAC__BITS_PER_WORD) {
  93610. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93611. br->consumed_bits = bits;
  93612. return true;
  93613. }
  93614. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93615. *val = word;
  93616. crc16_update_word_(br, word);
  93617. br->consumed_words++;
  93618. return true;
  93619. }
  93620. }
  93621. else {
  93622. /* in this case we're starting our read at a partial tail word;
  93623. * the reader has guaranteed that we have at least 'bits' bits
  93624. * available to read, which makes this case simpler.
  93625. */
  93626. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93627. if(br->consumed_bits) {
  93628. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93629. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93630. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93631. br->consumed_bits += bits;
  93632. return true;
  93633. }
  93634. else {
  93635. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93636. br->consumed_bits += bits;
  93637. return true;
  93638. }
  93639. }
  93640. }
  93641. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93642. {
  93643. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93644. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93645. return false;
  93646. /* sign-extend: */
  93647. *val <<= (32-bits);
  93648. *val >>= (32-bits);
  93649. return true;
  93650. }
  93651. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93652. {
  93653. FLAC__uint32 hi, lo;
  93654. if(bits > 32) {
  93655. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93656. return false;
  93657. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93658. return false;
  93659. *val = hi;
  93660. *val <<= 32;
  93661. *val |= lo;
  93662. }
  93663. else {
  93664. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93665. return false;
  93666. *val = lo;
  93667. }
  93668. return true;
  93669. }
  93670. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93671. {
  93672. FLAC__uint32 x8, x32 = 0;
  93673. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93674. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93675. return false;
  93676. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93677. return false;
  93678. x32 |= (x8 << 8);
  93679. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93680. return false;
  93681. x32 |= (x8 << 16);
  93682. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93683. return false;
  93684. x32 |= (x8 << 24);
  93685. *val = x32;
  93686. return true;
  93687. }
  93688. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93689. {
  93690. /*
  93691. * OPT: a faster implementation is possible but probably not that useful
  93692. * since this is only called a couple of times in the metadata readers.
  93693. */
  93694. FLAC__ASSERT(0 != br);
  93695. FLAC__ASSERT(0 != br->buffer);
  93696. if(bits > 0) {
  93697. const unsigned n = br->consumed_bits & 7;
  93698. unsigned m;
  93699. FLAC__uint32 x;
  93700. if(n != 0) {
  93701. m = min(8-n, bits);
  93702. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93703. return false;
  93704. bits -= m;
  93705. }
  93706. m = bits / 8;
  93707. if(m > 0) {
  93708. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93709. return false;
  93710. bits %= 8;
  93711. }
  93712. if(bits > 0) {
  93713. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93714. return false;
  93715. }
  93716. }
  93717. return true;
  93718. }
  93719. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93720. {
  93721. FLAC__uint32 x;
  93722. FLAC__ASSERT(0 != br);
  93723. FLAC__ASSERT(0 != br->buffer);
  93724. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93725. /* step 1: skip over partial head word to get word aligned */
  93726. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93727. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93728. return false;
  93729. nvals--;
  93730. }
  93731. if(0 == nvals)
  93732. return true;
  93733. /* step 2: skip whole words in chunks */
  93734. while(nvals >= FLAC__BYTES_PER_WORD) {
  93735. if(br->consumed_words < br->words) {
  93736. br->consumed_words++;
  93737. nvals -= FLAC__BYTES_PER_WORD;
  93738. }
  93739. else if(!bitreader_read_from_client_(br))
  93740. return false;
  93741. }
  93742. /* step 3: skip any remainder from partial tail bytes */
  93743. while(nvals) {
  93744. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93745. return false;
  93746. nvals--;
  93747. }
  93748. return true;
  93749. }
  93750. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93751. {
  93752. FLAC__uint32 x;
  93753. FLAC__ASSERT(0 != br);
  93754. FLAC__ASSERT(0 != br->buffer);
  93755. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93756. /* step 1: read from partial head word to get word aligned */
  93757. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93758. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93759. return false;
  93760. *val++ = (FLAC__byte)x;
  93761. nvals--;
  93762. }
  93763. if(0 == nvals)
  93764. return true;
  93765. /* step 2: read whole words in chunks */
  93766. while(nvals >= FLAC__BYTES_PER_WORD) {
  93767. if(br->consumed_words < br->words) {
  93768. const brword word = br->buffer[br->consumed_words++];
  93769. #if FLAC__BYTES_PER_WORD == 4
  93770. val[0] = (FLAC__byte)(word >> 24);
  93771. val[1] = (FLAC__byte)(word >> 16);
  93772. val[2] = (FLAC__byte)(word >> 8);
  93773. val[3] = (FLAC__byte)word;
  93774. #elif FLAC__BYTES_PER_WORD == 8
  93775. val[0] = (FLAC__byte)(word >> 56);
  93776. val[1] = (FLAC__byte)(word >> 48);
  93777. val[2] = (FLAC__byte)(word >> 40);
  93778. val[3] = (FLAC__byte)(word >> 32);
  93779. val[4] = (FLAC__byte)(word >> 24);
  93780. val[5] = (FLAC__byte)(word >> 16);
  93781. val[6] = (FLAC__byte)(word >> 8);
  93782. val[7] = (FLAC__byte)word;
  93783. #else
  93784. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93785. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93786. #endif
  93787. val += FLAC__BYTES_PER_WORD;
  93788. nvals -= FLAC__BYTES_PER_WORD;
  93789. }
  93790. else if(!bitreader_read_from_client_(br))
  93791. return false;
  93792. }
  93793. /* step 3: read any remainder from partial tail bytes */
  93794. while(nvals) {
  93795. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93796. return false;
  93797. *val++ = (FLAC__byte)x;
  93798. nvals--;
  93799. }
  93800. return true;
  93801. }
  93802. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93803. #if 0 /* slow but readable version */
  93804. {
  93805. unsigned bit;
  93806. FLAC__ASSERT(0 != br);
  93807. FLAC__ASSERT(0 != br->buffer);
  93808. *val = 0;
  93809. while(1) {
  93810. if(!FLAC__bitreader_read_bit(br, &bit))
  93811. return false;
  93812. if(bit)
  93813. break;
  93814. else
  93815. *val++;
  93816. }
  93817. return true;
  93818. }
  93819. #else
  93820. {
  93821. unsigned i;
  93822. FLAC__ASSERT(0 != br);
  93823. FLAC__ASSERT(0 != br->buffer);
  93824. *val = 0;
  93825. while(1) {
  93826. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93827. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93828. if(b) {
  93829. i = COUNT_ZERO_MSBS(b);
  93830. *val += i;
  93831. i++;
  93832. br->consumed_bits += i;
  93833. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93834. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93835. br->consumed_words++;
  93836. br->consumed_bits = 0;
  93837. }
  93838. return true;
  93839. }
  93840. else {
  93841. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93842. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93843. br->consumed_words++;
  93844. br->consumed_bits = 0;
  93845. /* didn't find stop bit yet, have to keep going... */
  93846. }
  93847. }
  93848. /* at this point we've eaten up all the whole words; have to try
  93849. * reading through any tail bytes before calling the read callback.
  93850. * this is a repeat of the above logic adjusted for the fact we
  93851. * don't have a whole word. note though if the client is feeding
  93852. * us data a byte at a time (unlikely), br->consumed_bits may not
  93853. * be zero.
  93854. */
  93855. if(br->bytes) {
  93856. const unsigned end = br->bytes * 8;
  93857. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93858. if(b) {
  93859. i = COUNT_ZERO_MSBS(b);
  93860. *val += i;
  93861. i++;
  93862. br->consumed_bits += i;
  93863. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93864. return true;
  93865. }
  93866. else {
  93867. *val += end - br->consumed_bits;
  93868. br->consumed_bits += end;
  93869. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93870. /* didn't find stop bit yet, have to keep going... */
  93871. }
  93872. }
  93873. if(!bitreader_read_from_client_(br))
  93874. return false;
  93875. }
  93876. }
  93877. #endif
  93878. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93879. {
  93880. FLAC__uint32 lsbs = 0, msbs = 0;
  93881. unsigned uval;
  93882. FLAC__ASSERT(0 != br);
  93883. FLAC__ASSERT(0 != br->buffer);
  93884. FLAC__ASSERT(parameter <= 31);
  93885. /* read the unary MSBs and end bit */
  93886. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93887. return false;
  93888. /* read the binary LSBs */
  93889. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93890. return false;
  93891. /* compose the value */
  93892. uval = (msbs << parameter) | lsbs;
  93893. if(uval & 1)
  93894. *val = -((int)(uval >> 1)) - 1;
  93895. else
  93896. *val = (int)(uval >> 1);
  93897. return true;
  93898. }
  93899. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93900. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93901. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93902. /* OPT: possibly faster version for use with MSVC */
  93903. #ifdef _MSC_VER
  93904. {
  93905. unsigned i;
  93906. unsigned uval = 0;
  93907. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93908. /* try and get br->consumed_words and br->consumed_bits into register;
  93909. * must remember to flush them back to *br before calling other
  93910. * bitwriter functions that use them, and before returning */
  93911. register unsigned cwords;
  93912. register unsigned cbits;
  93913. FLAC__ASSERT(0 != br);
  93914. FLAC__ASSERT(0 != br->buffer);
  93915. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93916. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93917. FLAC__ASSERT(parameter < 32);
  93918. /* 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 */
  93919. if(nvals == 0)
  93920. return true;
  93921. cbits = br->consumed_bits;
  93922. cwords = br->consumed_words;
  93923. while(1) {
  93924. /* read unary part */
  93925. while(1) {
  93926. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93927. brword b = br->buffer[cwords] << cbits;
  93928. if(b) {
  93929. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93930. __asm {
  93931. bsr eax, b
  93932. not eax
  93933. and eax, 31
  93934. mov i, eax
  93935. }
  93936. #else
  93937. i = COUNT_ZERO_MSBS(b);
  93938. #endif
  93939. uval += i;
  93940. bits = parameter;
  93941. i++;
  93942. cbits += i;
  93943. if(cbits == FLAC__BITS_PER_WORD) {
  93944. crc16_update_word_(br, br->buffer[cwords]);
  93945. cwords++;
  93946. cbits = 0;
  93947. }
  93948. goto break1;
  93949. }
  93950. else {
  93951. uval += FLAC__BITS_PER_WORD - cbits;
  93952. crc16_update_word_(br, br->buffer[cwords]);
  93953. cwords++;
  93954. cbits = 0;
  93955. /* didn't find stop bit yet, have to keep going... */
  93956. }
  93957. }
  93958. /* at this point we've eaten up all the whole words; have to try
  93959. * reading through any tail bytes before calling the read callback.
  93960. * this is a repeat of the above logic adjusted for the fact we
  93961. * don't have a whole word. note though if the client is feeding
  93962. * us data a byte at a time (unlikely), br->consumed_bits may not
  93963. * be zero.
  93964. */
  93965. if(br->bytes) {
  93966. const unsigned end = br->bytes * 8;
  93967. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93968. if(b) {
  93969. i = COUNT_ZERO_MSBS(b);
  93970. uval += i;
  93971. bits = parameter;
  93972. i++;
  93973. cbits += i;
  93974. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93975. goto break1;
  93976. }
  93977. else {
  93978. uval += end - cbits;
  93979. cbits += end;
  93980. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93981. /* didn't find stop bit yet, have to keep going... */
  93982. }
  93983. }
  93984. /* flush registers and read; bitreader_read_from_client_() does
  93985. * not touch br->consumed_bits at all but we still need to set
  93986. * it in case it fails and we have to return false.
  93987. */
  93988. br->consumed_bits = cbits;
  93989. br->consumed_words = cwords;
  93990. if(!bitreader_read_from_client_(br))
  93991. return false;
  93992. cwords = br->consumed_words;
  93993. }
  93994. break1:
  93995. /* read binary part */
  93996. FLAC__ASSERT(cwords <= br->words);
  93997. if(bits) {
  93998. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93999. /* flush registers and read; bitreader_read_from_client_() does
  94000. * not touch br->consumed_bits at all but we still need to set
  94001. * it in case it fails and we have to return false.
  94002. */
  94003. br->consumed_bits = cbits;
  94004. br->consumed_words = cwords;
  94005. if(!bitreader_read_from_client_(br))
  94006. return false;
  94007. cwords = br->consumed_words;
  94008. }
  94009. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94010. if(cbits) {
  94011. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94012. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94013. const brword word = br->buffer[cwords];
  94014. if(bits < n) {
  94015. uval <<= bits;
  94016. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  94017. cbits += bits;
  94018. goto break2;
  94019. }
  94020. uval <<= n;
  94021. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94022. bits -= n;
  94023. crc16_update_word_(br, word);
  94024. cwords++;
  94025. cbits = 0;
  94026. 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 */
  94027. uval <<= bits;
  94028. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  94029. cbits = bits;
  94030. }
  94031. goto break2;
  94032. }
  94033. else {
  94034. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  94035. uval <<= bits;
  94036. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94037. cbits = bits;
  94038. goto break2;
  94039. }
  94040. }
  94041. else {
  94042. /* in this case we're starting our read at a partial tail word;
  94043. * the reader has guaranteed that we have at least 'bits' bits
  94044. * available to read, which makes this case simpler.
  94045. */
  94046. uval <<= bits;
  94047. if(cbits) {
  94048. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94049. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  94050. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  94051. cbits += bits;
  94052. goto break2;
  94053. }
  94054. else {
  94055. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94056. cbits += bits;
  94057. goto break2;
  94058. }
  94059. }
  94060. }
  94061. break2:
  94062. /* compose the value */
  94063. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94064. /* are we done? */
  94065. --nvals;
  94066. if(nvals == 0) {
  94067. br->consumed_bits = cbits;
  94068. br->consumed_words = cwords;
  94069. return true;
  94070. }
  94071. uval = 0;
  94072. ++vals;
  94073. }
  94074. }
  94075. #else
  94076. {
  94077. unsigned i;
  94078. unsigned uval = 0;
  94079. /* try and get br->consumed_words and br->consumed_bits into register;
  94080. * must remember to flush them back to *br before calling other
  94081. * bitwriter functions that use them, and before returning */
  94082. register unsigned cwords;
  94083. register unsigned cbits;
  94084. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  94085. FLAC__ASSERT(0 != br);
  94086. FLAC__ASSERT(0 != br->buffer);
  94087. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94088. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94089. FLAC__ASSERT(parameter < 32);
  94090. /* 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 */
  94091. if(nvals == 0)
  94092. return true;
  94093. cbits = br->consumed_bits;
  94094. cwords = br->consumed_words;
  94095. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94096. while(1) {
  94097. /* read unary part */
  94098. while(1) {
  94099. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94100. brword b = br->buffer[cwords] << cbits;
  94101. if(b) {
  94102. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  94103. asm volatile (
  94104. "bsrl %1, %0;"
  94105. "notl %0;"
  94106. "andl $31, %0;"
  94107. : "=r"(i)
  94108. : "r"(b)
  94109. );
  94110. #else
  94111. i = COUNT_ZERO_MSBS(b);
  94112. #endif
  94113. uval += i;
  94114. cbits += i;
  94115. cbits++; /* skip over stop bit */
  94116. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  94117. crc16_update_word_(br, br->buffer[cwords]);
  94118. cwords++;
  94119. cbits = 0;
  94120. }
  94121. goto break1;
  94122. }
  94123. else {
  94124. uval += FLAC__BITS_PER_WORD - cbits;
  94125. crc16_update_word_(br, br->buffer[cwords]);
  94126. cwords++;
  94127. cbits = 0;
  94128. /* didn't find stop bit yet, have to keep going... */
  94129. }
  94130. }
  94131. /* at this point we've eaten up all the whole words; have to try
  94132. * reading through any tail bytes before calling the read callback.
  94133. * this is a repeat of the above logic adjusted for the fact we
  94134. * don't have a whole word. note though if the client is feeding
  94135. * us data a byte at a time (unlikely), br->consumed_bits may not
  94136. * be zero.
  94137. */
  94138. if(br->bytes) {
  94139. const unsigned end = br->bytes * 8;
  94140. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  94141. if(b) {
  94142. i = COUNT_ZERO_MSBS(b);
  94143. uval += i;
  94144. cbits += i;
  94145. cbits++; /* skip over stop bit */
  94146. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94147. goto break1;
  94148. }
  94149. else {
  94150. uval += end - cbits;
  94151. cbits += end;
  94152. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94153. /* didn't find stop bit yet, have to keep going... */
  94154. }
  94155. }
  94156. /* flush registers and read; bitreader_read_from_client_() does
  94157. * not touch br->consumed_bits at all but we still need to set
  94158. * it in case it fails and we have to return false.
  94159. */
  94160. br->consumed_bits = cbits;
  94161. br->consumed_words = cwords;
  94162. if(!bitreader_read_from_client_(br))
  94163. return false;
  94164. cwords = br->consumed_words;
  94165. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  94166. /* + uval to offset our count by the # of unary bits already
  94167. * consumed before the read, because we will add these back
  94168. * in all at once at break1
  94169. */
  94170. }
  94171. break1:
  94172. ucbits -= uval;
  94173. ucbits--; /* account for stop bit */
  94174. /* read binary part */
  94175. FLAC__ASSERT(cwords <= br->words);
  94176. if(parameter) {
  94177. while(ucbits < parameter) {
  94178. /* flush registers and read; bitreader_read_from_client_() does
  94179. * not touch br->consumed_bits at all but we still need to set
  94180. * it in case it fails and we have to return false.
  94181. */
  94182. br->consumed_bits = cbits;
  94183. br->consumed_words = cwords;
  94184. if(!bitreader_read_from_client_(br))
  94185. return false;
  94186. cwords = br->consumed_words;
  94187. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94188. }
  94189. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94190. if(cbits) {
  94191. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  94192. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94193. const brword word = br->buffer[cwords];
  94194. if(parameter < n) {
  94195. uval <<= parameter;
  94196. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  94197. cbits += parameter;
  94198. }
  94199. else {
  94200. uval <<= n;
  94201. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94202. crc16_update_word_(br, word);
  94203. cwords++;
  94204. cbits = parameter - n;
  94205. 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 */
  94206. uval <<= cbits;
  94207. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94208. }
  94209. }
  94210. }
  94211. else {
  94212. cbits = parameter;
  94213. uval <<= parameter;
  94214. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94215. }
  94216. }
  94217. else {
  94218. /* in this case we're starting our read at a partial tail word;
  94219. * the reader has guaranteed that we have at least 'parameter'
  94220. * bits available to read, which makes this case simpler.
  94221. */
  94222. uval <<= parameter;
  94223. if(cbits) {
  94224. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94225. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94226. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94227. cbits += parameter;
  94228. }
  94229. else {
  94230. cbits = parameter;
  94231. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94232. }
  94233. }
  94234. }
  94235. ucbits -= parameter;
  94236. /* compose the value */
  94237. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94238. /* are we done? */
  94239. --nvals;
  94240. if(nvals == 0) {
  94241. br->consumed_bits = cbits;
  94242. br->consumed_words = cwords;
  94243. return true;
  94244. }
  94245. uval = 0;
  94246. ++vals;
  94247. }
  94248. }
  94249. #endif
  94250. #if 0 /* UNUSED */
  94251. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94252. {
  94253. FLAC__uint32 lsbs = 0, msbs = 0;
  94254. unsigned bit, uval, k;
  94255. FLAC__ASSERT(0 != br);
  94256. FLAC__ASSERT(0 != br->buffer);
  94257. k = FLAC__bitmath_ilog2(parameter);
  94258. /* read the unary MSBs and end bit */
  94259. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94260. return false;
  94261. /* read the binary LSBs */
  94262. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94263. return false;
  94264. if(parameter == 1u<<k) {
  94265. /* compose the value */
  94266. uval = (msbs << k) | lsbs;
  94267. }
  94268. else {
  94269. unsigned d = (1 << (k+1)) - parameter;
  94270. if(lsbs >= d) {
  94271. if(!FLAC__bitreader_read_bit(br, &bit))
  94272. return false;
  94273. lsbs <<= 1;
  94274. lsbs |= bit;
  94275. lsbs -= d;
  94276. }
  94277. /* compose the value */
  94278. uval = msbs * parameter + lsbs;
  94279. }
  94280. /* unfold unsigned to signed */
  94281. if(uval & 1)
  94282. *val = -((int)(uval >> 1)) - 1;
  94283. else
  94284. *val = (int)(uval >> 1);
  94285. return true;
  94286. }
  94287. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94288. {
  94289. FLAC__uint32 lsbs, msbs = 0;
  94290. unsigned bit, k;
  94291. FLAC__ASSERT(0 != br);
  94292. FLAC__ASSERT(0 != br->buffer);
  94293. k = FLAC__bitmath_ilog2(parameter);
  94294. /* read the unary MSBs and end bit */
  94295. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94296. return false;
  94297. /* read the binary LSBs */
  94298. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94299. return false;
  94300. if(parameter == 1u<<k) {
  94301. /* compose the value */
  94302. *val = (msbs << k) | lsbs;
  94303. }
  94304. else {
  94305. unsigned d = (1 << (k+1)) - parameter;
  94306. if(lsbs >= d) {
  94307. if(!FLAC__bitreader_read_bit(br, &bit))
  94308. return false;
  94309. lsbs <<= 1;
  94310. lsbs |= bit;
  94311. lsbs -= d;
  94312. }
  94313. /* compose the value */
  94314. *val = msbs * parameter + lsbs;
  94315. }
  94316. return true;
  94317. }
  94318. #endif /* UNUSED */
  94319. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94320. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94321. {
  94322. FLAC__uint32 v = 0;
  94323. FLAC__uint32 x;
  94324. unsigned i;
  94325. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94326. return false;
  94327. if(raw)
  94328. raw[(*rawlen)++] = (FLAC__byte)x;
  94329. if(!(x & 0x80)) { /* 0xxxxxxx */
  94330. v = x;
  94331. i = 0;
  94332. }
  94333. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94334. v = x & 0x1F;
  94335. i = 1;
  94336. }
  94337. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94338. v = x & 0x0F;
  94339. i = 2;
  94340. }
  94341. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94342. v = x & 0x07;
  94343. i = 3;
  94344. }
  94345. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94346. v = x & 0x03;
  94347. i = 4;
  94348. }
  94349. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94350. v = x & 0x01;
  94351. i = 5;
  94352. }
  94353. else {
  94354. *val = 0xffffffff;
  94355. return true;
  94356. }
  94357. for( ; i; i--) {
  94358. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94359. return false;
  94360. if(raw)
  94361. raw[(*rawlen)++] = (FLAC__byte)x;
  94362. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94363. *val = 0xffffffff;
  94364. return true;
  94365. }
  94366. v <<= 6;
  94367. v |= (x & 0x3F);
  94368. }
  94369. *val = v;
  94370. return true;
  94371. }
  94372. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94373. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94374. {
  94375. FLAC__uint64 v = 0;
  94376. FLAC__uint32 x;
  94377. unsigned i;
  94378. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94379. return false;
  94380. if(raw)
  94381. raw[(*rawlen)++] = (FLAC__byte)x;
  94382. if(!(x & 0x80)) { /* 0xxxxxxx */
  94383. v = x;
  94384. i = 0;
  94385. }
  94386. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94387. v = x & 0x1F;
  94388. i = 1;
  94389. }
  94390. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94391. v = x & 0x0F;
  94392. i = 2;
  94393. }
  94394. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94395. v = x & 0x07;
  94396. i = 3;
  94397. }
  94398. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94399. v = x & 0x03;
  94400. i = 4;
  94401. }
  94402. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94403. v = x & 0x01;
  94404. i = 5;
  94405. }
  94406. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94407. v = 0;
  94408. i = 6;
  94409. }
  94410. else {
  94411. *val = FLAC__U64L(0xffffffffffffffff);
  94412. return true;
  94413. }
  94414. for( ; i; i--) {
  94415. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94416. return false;
  94417. if(raw)
  94418. raw[(*rawlen)++] = (FLAC__byte)x;
  94419. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94420. *val = FLAC__U64L(0xffffffffffffffff);
  94421. return true;
  94422. }
  94423. v <<= 6;
  94424. v |= (x & 0x3F);
  94425. }
  94426. *val = v;
  94427. return true;
  94428. }
  94429. #endif
  94430. /*** End of inlined file: bitreader.c ***/
  94431. /*** Start of inlined file: bitwriter.c ***/
  94432. /*** Start of inlined file: juce_FlacHeader.h ***/
  94433. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94434. // tasks..
  94435. #define VERSION "1.2.1"
  94436. #define FLAC__NO_DLL 1
  94437. #if JUCE_MSVC
  94438. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94439. #endif
  94440. #if JUCE_MAC
  94441. #define FLAC__SYS_DARWIN 1
  94442. #endif
  94443. /*** End of inlined file: juce_FlacHeader.h ***/
  94444. #if JUCE_USE_FLAC
  94445. #if HAVE_CONFIG_H
  94446. # include <config.h>
  94447. #endif
  94448. #include <stdlib.h> /* for malloc() */
  94449. #include <string.h> /* for memcpy(), memset() */
  94450. #ifdef _MSC_VER
  94451. #include <winsock.h> /* for ntohl() */
  94452. #elif defined FLAC__SYS_DARWIN
  94453. #include <machine/endian.h> /* for ntohl() */
  94454. #elif defined __MINGW32__
  94455. #include <winsock.h> /* for ntohl() */
  94456. #else
  94457. #include <netinet/in.h> /* for ntohl() */
  94458. #endif
  94459. #if 0 /* UNUSED */
  94460. #endif
  94461. /*** Start of inlined file: bitwriter.h ***/
  94462. #ifndef FLAC__PRIVATE__BITWRITER_H
  94463. #define FLAC__PRIVATE__BITWRITER_H
  94464. #include <stdio.h> /* for FILE */
  94465. /*
  94466. * opaque structure definition
  94467. */
  94468. struct FLAC__BitWriter;
  94469. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94470. /*
  94471. * construction, deletion, initialization, etc functions
  94472. */
  94473. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94474. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94475. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94476. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94477. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94478. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94479. /*
  94480. * CRC functions
  94481. *
  94482. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94483. */
  94484. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94485. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94486. /*
  94487. * info functions
  94488. */
  94489. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94490. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94491. /*
  94492. * direct buffer access
  94493. *
  94494. * there may be no calls on the bitwriter between get and release.
  94495. * the bitwriter continues to own the returned buffer.
  94496. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94497. */
  94498. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94499. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94500. /*
  94501. * write functions
  94502. */
  94503. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94504. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94505. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94506. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94507. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94508. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94509. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94510. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94511. #if 0 /* UNUSED */
  94512. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94513. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94514. #endif
  94515. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94516. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94517. #if 0 /* UNUSED */
  94518. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94519. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94520. #endif
  94521. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94522. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94523. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94524. #endif
  94525. /*** End of inlined file: bitwriter.h ***/
  94526. /*** Start of inlined file: alloc.h ***/
  94527. #ifndef FLAC__SHARE__ALLOC_H
  94528. #define FLAC__SHARE__ALLOC_H
  94529. #if HAVE_CONFIG_H
  94530. # include <config.h>
  94531. #endif
  94532. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94533. * before #including this file, otherwise SIZE_MAX might not be defined
  94534. */
  94535. #include <limits.h> /* for SIZE_MAX */
  94536. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94537. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94538. #endif
  94539. #include <stdlib.h> /* for size_t, malloc(), etc */
  94540. #ifndef SIZE_MAX
  94541. # ifndef SIZE_T_MAX
  94542. # ifdef _MSC_VER
  94543. # define SIZE_T_MAX UINT_MAX
  94544. # else
  94545. # error
  94546. # endif
  94547. # endif
  94548. # define SIZE_MAX SIZE_T_MAX
  94549. #endif
  94550. #ifndef FLaC__INLINE
  94551. #define FLaC__INLINE
  94552. #endif
  94553. /* avoid malloc()ing 0 bytes, see:
  94554. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94555. */
  94556. static FLaC__INLINE void *safe_malloc_(size_t size)
  94557. {
  94558. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94559. if(!size)
  94560. size++;
  94561. return malloc(size);
  94562. }
  94563. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94564. {
  94565. if(!nmemb || !size)
  94566. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94567. return calloc(nmemb, size);
  94568. }
  94569. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94570. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94571. {
  94572. size2 += size1;
  94573. if(size2 < size1)
  94574. return 0;
  94575. return safe_malloc_(size2);
  94576. }
  94577. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94578. {
  94579. size2 += size1;
  94580. if(size2 < size1)
  94581. return 0;
  94582. size3 += size2;
  94583. if(size3 < size2)
  94584. return 0;
  94585. return safe_malloc_(size3);
  94586. }
  94587. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94588. {
  94589. size2 += size1;
  94590. if(size2 < size1)
  94591. return 0;
  94592. size3 += size2;
  94593. if(size3 < size2)
  94594. return 0;
  94595. size4 += size3;
  94596. if(size4 < size3)
  94597. return 0;
  94598. return safe_malloc_(size4);
  94599. }
  94600. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94601. #if 0
  94602. needs support for cases where sizeof(size_t) != 4
  94603. {
  94604. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94605. if(sizeof(size_t) == 4) {
  94606. if ((double)size1 * (double)size2 < 4294967296.0)
  94607. return malloc(size1*size2);
  94608. }
  94609. return 0;
  94610. }
  94611. #else
  94612. /* better? */
  94613. {
  94614. if(!size1 || !size2)
  94615. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94616. if(size1 > SIZE_MAX / size2)
  94617. return 0;
  94618. return malloc(size1*size2);
  94619. }
  94620. #endif
  94621. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94622. {
  94623. if(!size1 || !size2 || !size3)
  94624. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94625. if(size1 > SIZE_MAX / size2)
  94626. return 0;
  94627. size1 *= size2;
  94628. if(size1 > SIZE_MAX / size3)
  94629. return 0;
  94630. return malloc(size1*size3);
  94631. }
  94632. /* size1*size2 + size3 */
  94633. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94634. {
  94635. if(!size1 || !size2)
  94636. return safe_malloc_(size3);
  94637. if(size1 > SIZE_MAX / size2)
  94638. return 0;
  94639. return safe_malloc_add_2op_(size1*size2, size3);
  94640. }
  94641. /* size1 * (size2 + size3) */
  94642. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94643. {
  94644. if(!size1 || (!size2 && !size3))
  94645. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94646. size2 += size3;
  94647. if(size2 < size3)
  94648. return 0;
  94649. return safe_malloc_mul_2op_(size1, size2);
  94650. }
  94651. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94652. {
  94653. size2 += size1;
  94654. if(size2 < size1)
  94655. return 0;
  94656. return realloc(ptr, size2);
  94657. }
  94658. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94659. {
  94660. size2 += size1;
  94661. if(size2 < size1)
  94662. return 0;
  94663. size3 += size2;
  94664. if(size3 < size2)
  94665. return 0;
  94666. return realloc(ptr, size3);
  94667. }
  94668. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94669. {
  94670. size2 += size1;
  94671. if(size2 < size1)
  94672. return 0;
  94673. size3 += size2;
  94674. if(size3 < size2)
  94675. return 0;
  94676. size4 += size3;
  94677. if(size4 < size3)
  94678. return 0;
  94679. return realloc(ptr, size4);
  94680. }
  94681. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94682. {
  94683. if(!size1 || !size2)
  94684. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94685. if(size1 > SIZE_MAX / size2)
  94686. return 0;
  94687. return realloc(ptr, size1*size2);
  94688. }
  94689. /* size1 * (size2 + size3) */
  94690. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94691. {
  94692. if(!size1 || (!size2 && !size3))
  94693. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94694. size2 += size3;
  94695. if(size2 < size3)
  94696. return 0;
  94697. return safe_realloc_mul_2op_(ptr, size1, size2);
  94698. }
  94699. #endif
  94700. /*** End of inlined file: alloc.h ***/
  94701. /* Things should be fastest when this matches the machine word size */
  94702. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94703. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94704. typedef FLAC__uint32 bwword;
  94705. #define FLAC__BYTES_PER_WORD 4
  94706. #define FLAC__BITS_PER_WORD 32
  94707. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94708. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94709. #if WORDS_BIGENDIAN
  94710. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94711. #else
  94712. #ifdef _MSC_VER
  94713. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94714. #else
  94715. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94716. #endif
  94717. #endif
  94718. /*
  94719. * The default capacity here doesn't matter too much. The buffer always grows
  94720. * to hold whatever is written to it. Usually the encoder will stop adding at
  94721. * a frame or metadata block, then write that out and clear the buffer for the
  94722. * next one.
  94723. */
  94724. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94725. /* When growing, increment 4K at a time */
  94726. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94727. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94728. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94729. #ifdef min
  94730. #undef min
  94731. #endif
  94732. #define min(x,y) ((x)<(y)?(x):(y))
  94733. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94734. #ifdef _MSC_VER
  94735. #define FLAC__U64L(x) x
  94736. #else
  94737. #define FLAC__U64L(x) x##LLU
  94738. #endif
  94739. #ifndef FLaC__INLINE
  94740. #define FLaC__INLINE
  94741. #endif
  94742. struct FLAC__BitWriter {
  94743. bwword *buffer;
  94744. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94745. unsigned capacity; /* capacity of buffer in words */
  94746. unsigned words; /* # of complete words in buffer */
  94747. unsigned bits; /* # of used bits in accum */
  94748. };
  94749. /* * WATCHOUT: The current implementation only grows the buffer. */
  94750. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94751. {
  94752. unsigned new_capacity;
  94753. bwword *new_buffer;
  94754. FLAC__ASSERT(0 != bw);
  94755. FLAC__ASSERT(0 != bw->buffer);
  94756. /* calculate total words needed to store 'bits_to_add' additional bits */
  94757. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94758. /* it's possible (due to pessimism in the growth estimation that
  94759. * leads to this call) that we don't actually need to grow
  94760. */
  94761. if(bw->capacity >= new_capacity)
  94762. return true;
  94763. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94764. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94765. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94766. /* make sure we got everything right */
  94767. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94768. FLAC__ASSERT(new_capacity > bw->capacity);
  94769. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94770. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94771. if(new_buffer == 0)
  94772. return false;
  94773. bw->buffer = new_buffer;
  94774. bw->capacity = new_capacity;
  94775. return true;
  94776. }
  94777. /***********************************************************************
  94778. *
  94779. * Class constructor/destructor
  94780. *
  94781. ***********************************************************************/
  94782. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94783. {
  94784. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94785. /* note that calloc() sets all members to 0 for us */
  94786. return bw;
  94787. }
  94788. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94789. {
  94790. FLAC__ASSERT(0 != bw);
  94791. FLAC__bitwriter_free(bw);
  94792. free(bw);
  94793. }
  94794. /***********************************************************************
  94795. *
  94796. * Public class methods
  94797. *
  94798. ***********************************************************************/
  94799. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94800. {
  94801. FLAC__ASSERT(0 != bw);
  94802. bw->words = bw->bits = 0;
  94803. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94804. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94805. if(bw->buffer == 0)
  94806. return false;
  94807. return true;
  94808. }
  94809. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94810. {
  94811. FLAC__ASSERT(0 != bw);
  94812. if(0 != bw->buffer)
  94813. free(bw->buffer);
  94814. bw->buffer = 0;
  94815. bw->capacity = 0;
  94816. bw->words = bw->bits = 0;
  94817. }
  94818. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94819. {
  94820. bw->words = bw->bits = 0;
  94821. }
  94822. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94823. {
  94824. unsigned i, j;
  94825. if(bw == 0) {
  94826. fprintf(out, "bitwriter is NULL\n");
  94827. }
  94828. else {
  94829. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94830. for(i = 0; i < bw->words; i++) {
  94831. fprintf(out, "%08X: ", i);
  94832. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94833. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94834. fprintf(out, "\n");
  94835. }
  94836. if(bw->bits > 0) {
  94837. fprintf(out, "%08X: ", i);
  94838. for(j = 0; j < bw->bits; j++)
  94839. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94840. fprintf(out, "\n");
  94841. }
  94842. }
  94843. }
  94844. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94845. {
  94846. const FLAC__byte *buffer;
  94847. size_t bytes;
  94848. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94849. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94850. return false;
  94851. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94852. FLAC__bitwriter_release_buffer(bw);
  94853. return true;
  94854. }
  94855. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94856. {
  94857. const FLAC__byte *buffer;
  94858. size_t bytes;
  94859. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94860. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94861. return false;
  94862. *crc = FLAC__crc8(buffer, bytes);
  94863. FLAC__bitwriter_release_buffer(bw);
  94864. return true;
  94865. }
  94866. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94867. {
  94868. return ((bw->bits & 7) == 0);
  94869. }
  94870. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94871. {
  94872. return FLAC__TOTAL_BITS(bw);
  94873. }
  94874. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94875. {
  94876. FLAC__ASSERT((bw->bits & 7) == 0);
  94877. /* double protection */
  94878. if(bw->bits & 7)
  94879. return false;
  94880. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94881. if(bw->bits) {
  94882. FLAC__ASSERT(bw->words <= bw->capacity);
  94883. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94884. return false;
  94885. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94886. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94887. }
  94888. /* now we can just return what we have */
  94889. *buffer = (FLAC__byte*)bw->buffer;
  94890. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94891. return true;
  94892. }
  94893. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94894. {
  94895. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94896. * get-mode' flag could be added everywhere and then cleared here
  94897. */
  94898. (void)bw;
  94899. }
  94900. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94901. {
  94902. unsigned n;
  94903. FLAC__ASSERT(0 != bw);
  94904. FLAC__ASSERT(0 != bw->buffer);
  94905. if(bits == 0)
  94906. return true;
  94907. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94908. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94909. return false;
  94910. /* first part gets to word alignment */
  94911. if(bw->bits) {
  94912. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94913. bw->accum <<= n;
  94914. bits -= n;
  94915. bw->bits += n;
  94916. if(bw->bits == FLAC__BITS_PER_WORD) {
  94917. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94918. bw->bits = 0;
  94919. }
  94920. else
  94921. return true;
  94922. }
  94923. /* do whole words */
  94924. while(bits >= FLAC__BITS_PER_WORD) {
  94925. bw->buffer[bw->words++] = 0;
  94926. bits -= FLAC__BITS_PER_WORD;
  94927. }
  94928. /* do any leftovers */
  94929. if(bits > 0) {
  94930. bw->accum = 0;
  94931. bw->bits = bits;
  94932. }
  94933. return true;
  94934. }
  94935. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94936. {
  94937. register unsigned left;
  94938. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94939. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94940. FLAC__ASSERT(0 != bw);
  94941. FLAC__ASSERT(0 != bw->buffer);
  94942. FLAC__ASSERT(bits <= 32);
  94943. if(bits == 0)
  94944. return true;
  94945. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94946. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94947. return false;
  94948. left = FLAC__BITS_PER_WORD - bw->bits;
  94949. if(bits < left) {
  94950. bw->accum <<= bits;
  94951. bw->accum |= val;
  94952. bw->bits += bits;
  94953. }
  94954. 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 */
  94955. bw->accum <<= left;
  94956. bw->accum |= val >> (bw->bits = bits - left);
  94957. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94958. bw->accum = val;
  94959. }
  94960. else {
  94961. bw->accum = val;
  94962. bw->bits = 0;
  94963. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94964. }
  94965. return true;
  94966. }
  94967. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94968. {
  94969. /* zero-out unused bits */
  94970. if(bits < 32)
  94971. val &= (~(0xffffffff << bits));
  94972. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94973. }
  94974. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94975. {
  94976. /* this could be a little faster but it's not used for much */
  94977. if(bits > 32) {
  94978. return
  94979. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94980. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94981. }
  94982. else
  94983. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94984. }
  94985. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94986. {
  94987. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94988. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94989. return false;
  94990. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94991. return false;
  94992. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94993. return false;
  94994. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94995. return false;
  94996. return true;
  94997. }
  94998. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94999. {
  95000. unsigned i;
  95001. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  95002. for(i = 0; i < nvals; i++) {
  95003. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  95004. return false;
  95005. }
  95006. return true;
  95007. }
  95008. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  95009. {
  95010. if(val < 32)
  95011. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  95012. else
  95013. return
  95014. FLAC__bitwriter_write_zeroes(bw, val) &&
  95015. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  95016. }
  95017. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  95018. {
  95019. FLAC__uint32 uval;
  95020. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  95021. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95022. uval = (val<<1) ^ (val>>31);
  95023. return 1 + parameter + (uval >> parameter);
  95024. }
  95025. #if 0 /* UNUSED */
  95026. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  95027. {
  95028. unsigned bits, msbs, uval;
  95029. unsigned k;
  95030. FLAC__ASSERT(parameter > 0);
  95031. /* fold signed to unsigned */
  95032. if(val < 0)
  95033. uval = (unsigned)(((-(++val)) << 1) + 1);
  95034. else
  95035. uval = (unsigned)(val << 1);
  95036. k = FLAC__bitmath_ilog2(parameter);
  95037. if(parameter == 1u<<k) {
  95038. FLAC__ASSERT(k <= 30);
  95039. msbs = uval >> k;
  95040. bits = 1 + k + msbs;
  95041. }
  95042. else {
  95043. unsigned q, r, d;
  95044. d = (1 << (k+1)) - parameter;
  95045. q = uval / parameter;
  95046. r = uval - (q * parameter);
  95047. bits = 1 + q + k;
  95048. if(r >= d)
  95049. bits++;
  95050. }
  95051. return bits;
  95052. }
  95053. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  95054. {
  95055. unsigned bits, msbs;
  95056. unsigned k;
  95057. FLAC__ASSERT(parameter > 0);
  95058. k = FLAC__bitmath_ilog2(parameter);
  95059. if(parameter == 1u<<k) {
  95060. FLAC__ASSERT(k <= 30);
  95061. msbs = uval >> k;
  95062. bits = 1 + k + msbs;
  95063. }
  95064. else {
  95065. unsigned q, r, d;
  95066. d = (1 << (k+1)) - parameter;
  95067. q = uval / parameter;
  95068. r = uval - (q * parameter);
  95069. bits = 1 + q + k;
  95070. if(r >= d)
  95071. bits++;
  95072. }
  95073. return bits;
  95074. }
  95075. #endif /* UNUSED */
  95076. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  95077. {
  95078. unsigned total_bits, interesting_bits, msbs;
  95079. FLAC__uint32 uval, pattern;
  95080. FLAC__ASSERT(0 != bw);
  95081. FLAC__ASSERT(0 != bw->buffer);
  95082. FLAC__ASSERT(parameter < 8*sizeof(uval));
  95083. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95084. uval = (val<<1) ^ (val>>31);
  95085. msbs = uval >> parameter;
  95086. interesting_bits = 1 + parameter;
  95087. total_bits = interesting_bits + msbs;
  95088. pattern = 1 << parameter; /* the unary end bit */
  95089. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  95090. if(total_bits <= 32)
  95091. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  95092. else
  95093. return
  95094. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  95095. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  95096. }
  95097. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  95098. {
  95099. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  95100. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  95101. FLAC__uint32 uval;
  95102. unsigned left;
  95103. const unsigned lsbits = 1 + parameter;
  95104. unsigned msbits;
  95105. FLAC__ASSERT(0 != bw);
  95106. FLAC__ASSERT(0 != bw->buffer);
  95107. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  95108. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  95109. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  95110. while(nvals) {
  95111. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95112. uval = (*vals<<1) ^ (*vals>>31);
  95113. msbits = uval >> parameter;
  95114. #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) */
  95115. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95116. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95117. bw->bits = bw->bits + msbits + lsbits;
  95118. uval |= mask1; /* set stop bit */
  95119. uval &= mask2; /* mask off unused top bits */
  95120. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  95121. bw->accum <<= msbits;
  95122. bw->accum <<= lsbits;
  95123. bw->accum |= uval;
  95124. if(bw->bits == FLAC__BITS_PER_WORD) {
  95125. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95126. bw->bits = 0;
  95127. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  95128. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  95129. FLAC__ASSERT(bw->capacity == bw->words);
  95130. return false;
  95131. }
  95132. }
  95133. }
  95134. else {
  95135. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  95136. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95137. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95138. bw->bits = bw->bits + msbits + lsbits;
  95139. uval |= mask1; /* set stop bit */
  95140. uval &= mask2; /* mask off unused top bits */
  95141. bw->accum <<= msbits + lsbits;
  95142. bw->accum |= uval;
  95143. }
  95144. else {
  95145. #endif
  95146. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  95147. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  95148. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  95149. return false;
  95150. if(msbits) {
  95151. /* first part gets to word alignment */
  95152. if(bw->bits) {
  95153. left = FLAC__BITS_PER_WORD - bw->bits;
  95154. if(msbits < left) {
  95155. bw->accum <<= msbits;
  95156. bw->bits += msbits;
  95157. goto break1;
  95158. }
  95159. else {
  95160. bw->accum <<= left;
  95161. msbits -= left;
  95162. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95163. bw->bits = 0;
  95164. }
  95165. }
  95166. /* do whole words */
  95167. while(msbits >= FLAC__BITS_PER_WORD) {
  95168. bw->buffer[bw->words++] = 0;
  95169. msbits -= FLAC__BITS_PER_WORD;
  95170. }
  95171. /* do any leftovers */
  95172. if(msbits > 0) {
  95173. bw->accum = 0;
  95174. bw->bits = msbits;
  95175. }
  95176. }
  95177. break1:
  95178. uval |= mask1; /* set stop bit */
  95179. uval &= mask2; /* mask off unused top bits */
  95180. left = FLAC__BITS_PER_WORD - bw->bits;
  95181. if(lsbits < left) {
  95182. bw->accum <<= lsbits;
  95183. bw->accum |= uval;
  95184. bw->bits += lsbits;
  95185. }
  95186. else {
  95187. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  95188. * be > lsbits (because of previous assertions) so it would have
  95189. * triggered the (lsbits<left) case above.
  95190. */
  95191. FLAC__ASSERT(bw->bits);
  95192. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  95193. bw->accum <<= left;
  95194. bw->accum |= uval >> (bw->bits = lsbits - left);
  95195. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95196. bw->accum = uval;
  95197. }
  95198. #if 1
  95199. }
  95200. #endif
  95201. vals++;
  95202. nvals--;
  95203. }
  95204. return true;
  95205. }
  95206. #if 0 /* UNUSED */
  95207. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95208. {
  95209. unsigned total_bits, msbs, uval;
  95210. unsigned k;
  95211. FLAC__ASSERT(0 != bw);
  95212. FLAC__ASSERT(0 != bw->buffer);
  95213. FLAC__ASSERT(parameter > 0);
  95214. /* fold signed to unsigned */
  95215. if(val < 0)
  95216. uval = (unsigned)(((-(++val)) << 1) + 1);
  95217. else
  95218. uval = (unsigned)(val << 1);
  95219. k = FLAC__bitmath_ilog2(parameter);
  95220. if(parameter == 1u<<k) {
  95221. unsigned pattern;
  95222. FLAC__ASSERT(k <= 30);
  95223. msbs = uval >> k;
  95224. total_bits = 1 + k + msbs;
  95225. pattern = 1 << k; /* the unary end bit */
  95226. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95227. if(total_bits <= 32) {
  95228. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95229. return false;
  95230. }
  95231. else {
  95232. /* write the unary MSBs */
  95233. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95234. return false;
  95235. /* write the unary end bit and binary LSBs */
  95236. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95237. return false;
  95238. }
  95239. }
  95240. else {
  95241. unsigned q, r, d;
  95242. d = (1 << (k+1)) - parameter;
  95243. q = uval / parameter;
  95244. r = uval - (q * parameter);
  95245. /* write the unary MSBs */
  95246. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95247. return false;
  95248. /* write the unary end bit */
  95249. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95250. return false;
  95251. /* write the binary LSBs */
  95252. if(r >= d) {
  95253. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95254. return false;
  95255. }
  95256. else {
  95257. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95258. return false;
  95259. }
  95260. }
  95261. return true;
  95262. }
  95263. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95264. {
  95265. unsigned total_bits, msbs;
  95266. unsigned k;
  95267. FLAC__ASSERT(0 != bw);
  95268. FLAC__ASSERT(0 != bw->buffer);
  95269. FLAC__ASSERT(parameter > 0);
  95270. k = FLAC__bitmath_ilog2(parameter);
  95271. if(parameter == 1u<<k) {
  95272. unsigned pattern;
  95273. FLAC__ASSERT(k <= 30);
  95274. msbs = uval >> k;
  95275. total_bits = 1 + k + msbs;
  95276. pattern = 1 << k; /* the unary end bit */
  95277. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95278. if(total_bits <= 32) {
  95279. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95280. return false;
  95281. }
  95282. else {
  95283. /* write the unary MSBs */
  95284. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95285. return false;
  95286. /* write the unary end bit and binary LSBs */
  95287. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95288. return false;
  95289. }
  95290. }
  95291. else {
  95292. unsigned q, r, d;
  95293. d = (1 << (k+1)) - parameter;
  95294. q = uval / parameter;
  95295. r = uval - (q * parameter);
  95296. /* write the unary MSBs */
  95297. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95298. return false;
  95299. /* write the unary end bit */
  95300. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95301. return false;
  95302. /* write the binary LSBs */
  95303. if(r >= d) {
  95304. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95305. return false;
  95306. }
  95307. else {
  95308. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95309. return false;
  95310. }
  95311. }
  95312. return true;
  95313. }
  95314. #endif /* UNUSED */
  95315. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95316. {
  95317. FLAC__bool ok = 1;
  95318. FLAC__ASSERT(0 != bw);
  95319. FLAC__ASSERT(0 != bw->buffer);
  95320. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95321. if(val < 0x80) {
  95322. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95323. }
  95324. else if(val < 0x800) {
  95325. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95326. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95327. }
  95328. else if(val < 0x10000) {
  95329. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95330. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95331. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95332. }
  95333. else if(val < 0x200000) {
  95334. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95335. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95336. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95337. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95338. }
  95339. else if(val < 0x4000000) {
  95340. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95341. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95342. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95343. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95344. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95345. }
  95346. else {
  95347. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95348. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95349. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95350. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95351. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95352. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95353. }
  95354. return ok;
  95355. }
  95356. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95357. {
  95358. FLAC__bool ok = 1;
  95359. FLAC__ASSERT(0 != bw);
  95360. FLAC__ASSERT(0 != bw->buffer);
  95361. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95362. if(val < 0x80) {
  95363. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95364. }
  95365. else if(val < 0x800) {
  95366. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95367. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95368. }
  95369. else if(val < 0x10000) {
  95370. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95371. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95372. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95373. }
  95374. else if(val < 0x200000) {
  95375. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95376. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95377. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95378. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95379. }
  95380. else if(val < 0x4000000) {
  95381. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95382. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95383. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95384. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95385. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95386. }
  95387. else if(val < 0x80000000) {
  95388. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95389. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95390. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95391. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95392. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95393. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95394. }
  95395. else {
  95396. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95397. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95398. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95399. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95400. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95401. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95402. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95403. }
  95404. return ok;
  95405. }
  95406. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95407. {
  95408. /* 0-pad to byte boundary */
  95409. if(bw->bits & 7u)
  95410. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95411. else
  95412. return true;
  95413. }
  95414. #endif
  95415. /*** End of inlined file: bitwriter.c ***/
  95416. /*** Start of inlined file: cpu.c ***/
  95417. /*** Start of inlined file: juce_FlacHeader.h ***/
  95418. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95419. // tasks..
  95420. #define VERSION "1.2.1"
  95421. #define FLAC__NO_DLL 1
  95422. #if JUCE_MSVC
  95423. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95424. #endif
  95425. #if JUCE_MAC
  95426. #define FLAC__SYS_DARWIN 1
  95427. #endif
  95428. /*** End of inlined file: juce_FlacHeader.h ***/
  95429. #if JUCE_USE_FLAC
  95430. #if HAVE_CONFIG_H
  95431. # include <config.h>
  95432. #endif
  95433. #include <stdlib.h>
  95434. #include <stdio.h>
  95435. #if defined FLAC__CPU_IA32
  95436. # include <signal.h>
  95437. #elif defined FLAC__CPU_PPC
  95438. # if !defined FLAC__NO_ASM
  95439. # if defined FLAC__SYS_DARWIN
  95440. # include <sys/sysctl.h>
  95441. # include <mach/mach.h>
  95442. # include <mach/mach_host.h>
  95443. # include <mach/host_info.h>
  95444. # include <mach/machine.h>
  95445. # ifndef CPU_SUBTYPE_POWERPC_970
  95446. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95447. # endif
  95448. # else /* FLAC__SYS_DARWIN */
  95449. # include <signal.h>
  95450. # include <setjmp.h>
  95451. static sigjmp_buf jmpbuf;
  95452. static volatile sig_atomic_t canjump = 0;
  95453. static void sigill_handler (int sig)
  95454. {
  95455. if (!canjump) {
  95456. signal (sig, SIG_DFL);
  95457. raise (sig);
  95458. }
  95459. canjump = 0;
  95460. siglongjmp (jmpbuf, 1);
  95461. }
  95462. # endif /* FLAC__SYS_DARWIN */
  95463. # endif /* FLAC__NO_ASM */
  95464. #endif /* FLAC__CPU_PPC */
  95465. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95466. #include <sys/param.h>
  95467. #include <sys/sysctl.h>
  95468. #include <machine/cpu.h>
  95469. #endif
  95470. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95471. #include <sys/types.h>
  95472. #include <sys/sysctl.h>
  95473. #endif
  95474. #if defined(__APPLE__)
  95475. /* how to get sysctlbyname()? */
  95476. #endif
  95477. /* these are flags in EDX of CPUID AX=00000001 */
  95478. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95479. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95480. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95481. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95482. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95483. /* these are flags in ECX of CPUID AX=00000001 */
  95484. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95485. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95486. /* these are flags in EDX of CPUID AX=80000001 */
  95487. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95488. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95489. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95490. /*
  95491. * Extra stuff needed for detection of OS support for SSE on IA-32
  95492. */
  95493. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95494. # if defined(__linux__)
  95495. /*
  95496. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95497. * modify the return address to jump over the offending SSE instruction
  95498. * and also the operation following it that indicates the instruction
  95499. * executed successfully. In this way we use no global variables and
  95500. * stay thread-safe.
  95501. *
  95502. * 3 + 3 + 6:
  95503. * 3 bytes for "xorps xmm0,xmm0"
  95504. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95505. * 6 bytes extra in case our estimate is wrong
  95506. * 12 bytes puts us in the NOP "landing zone"
  95507. */
  95508. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95509. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95510. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95511. {
  95512. (void)signal;
  95513. sc.eip += 3 + 3 + 6;
  95514. }
  95515. # else
  95516. # include <sys/ucontext.h>
  95517. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95518. {
  95519. (void)signal, (void)si;
  95520. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95521. }
  95522. # endif
  95523. # elif defined(_MSC_VER)
  95524. # include <windows.h>
  95525. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95526. # ifdef USE_TRY_CATCH_FLAVOR
  95527. # else
  95528. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95529. {
  95530. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95531. ep->ContextRecord->Eip += 3 + 3 + 6;
  95532. return EXCEPTION_CONTINUE_EXECUTION;
  95533. }
  95534. return EXCEPTION_CONTINUE_SEARCH;
  95535. }
  95536. # endif
  95537. # endif
  95538. #endif
  95539. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95540. {
  95541. /*
  95542. * IA32-specific
  95543. */
  95544. #ifdef FLAC__CPU_IA32
  95545. info->type = FLAC__CPUINFO_TYPE_IA32;
  95546. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95547. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95548. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95549. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95550. info->data.ia32.cmov = false;
  95551. info->data.ia32.mmx = false;
  95552. info->data.ia32.fxsr = false;
  95553. info->data.ia32.sse = false;
  95554. info->data.ia32.sse2 = false;
  95555. info->data.ia32.sse3 = false;
  95556. info->data.ia32.ssse3 = false;
  95557. info->data.ia32._3dnow = false;
  95558. info->data.ia32.ext3dnow = false;
  95559. info->data.ia32.extmmx = false;
  95560. if(info->data.ia32.cpuid) {
  95561. /* http://www.sandpile.org/ia32/cpuid.htm */
  95562. FLAC__uint32 flags_edx, flags_ecx;
  95563. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95564. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95565. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95566. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95567. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95568. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95569. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95570. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95571. #ifdef FLAC__USE_3DNOW
  95572. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95573. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95574. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95575. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95576. #else
  95577. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95578. #endif
  95579. #ifdef DEBUG
  95580. fprintf(stderr, "CPU info (IA-32):\n");
  95581. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95582. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95583. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95584. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95585. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95586. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95587. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95588. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95589. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95590. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95591. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95592. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95593. #endif
  95594. /*
  95595. * now have to check for OS support of SSE/SSE2
  95596. */
  95597. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95598. #if defined FLAC__NO_SSE_OS
  95599. /* assume user knows better than us; turn it off */
  95600. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95601. #elif defined FLAC__SSE_OS
  95602. /* assume user knows better than us; leave as detected above */
  95603. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95604. int sse = 0;
  95605. size_t len;
  95606. /* at least one of these must work: */
  95607. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95608. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95609. if(!sse)
  95610. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95611. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95612. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95613. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95614. size_t len = sizeof(val);
  95615. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95616. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95617. else { /* double-check SSE2 */
  95618. mib[1] = CPU_SSE2;
  95619. len = sizeof(val);
  95620. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95621. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95622. }
  95623. # else
  95624. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95625. # endif
  95626. #elif defined(__linux__)
  95627. int sse = 0;
  95628. struct sigaction sigill_save;
  95629. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95630. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95631. #else
  95632. struct sigaction sigill_sse;
  95633. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95634. __sigemptyset(&sigill_sse.sa_mask);
  95635. 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 */
  95636. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95637. #endif
  95638. {
  95639. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95640. /* see sigill_handler_sse_os() for an explanation of the following: */
  95641. asm volatile (
  95642. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95643. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95644. "incl %0\n\t" /* SIGILL handler will jump over this */
  95645. /* landing zone */
  95646. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95647. "nop\n\t"
  95648. "nop\n\t"
  95649. "nop\n\t"
  95650. "nop\n\t"
  95651. "nop\n\t"
  95652. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95653. "nop\n\t"
  95654. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95655. : "=r"(sse)
  95656. : "r"(sse)
  95657. );
  95658. sigaction(SIGILL, &sigill_save, NULL);
  95659. }
  95660. if(!sse)
  95661. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95662. #elif defined(_MSC_VER)
  95663. # ifdef USE_TRY_CATCH_FLAVOR
  95664. _try {
  95665. __asm {
  95666. # if _MSC_VER <= 1200
  95667. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95668. _emit 0x0F
  95669. _emit 0x57
  95670. _emit 0xC0
  95671. # else
  95672. xorps xmm0,xmm0
  95673. # endif
  95674. }
  95675. }
  95676. _except(EXCEPTION_EXECUTE_HANDLER) {
  95677. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95678. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95679. }
  95680. # else
  95681. int sse = 0;
  95682. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95683. /* see GCC version above for explanation */
  95684. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95685. /* http://www.codeproject.com/cpp/gccasm.asp */
  95686. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95687. __asm {
  95688. # if _MSC_VER <= 1200
  95689. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95690. _emit 0x0F
  95691. _emit 0x57
  95692. _emit 0xC0
  95693. # else
  95694. xorps xmm0,xmm0
  95695. # endif
  95696. inc sse
  95697. nop
  95698. nop
  95699. nop
  95700. nop
  95701. nop
  95702. nop
  95703. nop
  95704. nop
  95705. nop
  95706. }
  95707. SetUnhandledExceptionFilter(save);
  95708. if(!sse)
  95709. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95710. # endif
  95711. #else
  95712. /* no way to test, disable to be safe */
  95713. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95714. #endif
  95715. #ifdef DEBUG
  95716. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95717. #endif
  95718. }
  95719. }
  95720. #else
  95721. info->use_asm = false;
  95722. #endif
  95723. /*
  95724. * PPC-specific
  95725. */
  95726. #elif defined FLAC__CPU_PPC
  95727. info->type = FLAC__CPUINFO_TYPE_PPC;
  95728. # if !defined FLAC__NO_ASM
  95729. info->use_asm = true;
  95730. # ifdef FLAC__USE_ALTIVEC
  95731. # if defined FLAC__SYS_DARWIN
  95732. {
  95733. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95734. size_t len = sizeof(val);
  95735. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95736. }
  95737. {
  95738. host_basic_info_data_t hostInfo;
  95739. mach_msg_type_number_t infoCount;
  95740. infoCount = HOST_BASIC_INFO_COUNT;
  95741. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95742. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95743. }
  95744. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95745. {
  95746. /* no Darwin, do it the brute-force way */
  95747. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95748. info->data.ppc.altivec = 0;
  95749. info->data.ppc.ppc64 = 0;
  95750. signal (SIGILL, sigill_handler);
  95751. canjump = 0;
  95752. if (!sigsetjmp (jmpbuf, 1)) {
  95753. canjump = 1;
  95754. asm volatile (
  95755. "mtspr 256, %0\n\t"
  95756. "vand %%v0, %%v0, %%v0"
  95757. :
  95758. : "r" (-1)
  95759. );
  95760. info->data.ppc.altivec = 1;
  95761. }
  95762. canjump = 0;
  95763. if (!sigsetjmp (jmpbuf, 1)) {
  95764. int x = 0;
  95765. canjump = 1;
  95766. /* PPC64 hardware implements the cntlzd instruction */
  95767. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95768. info->data.ppc.ppc64 = 1;
  95769. }
  95770. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95771. }
  95772. # endif
  95773. # else /* !FLAC__USE_ALTIVEC */
  95774. info->data.ppc.altivec = 0;
  95775. info->data.ppc.ppc64 = 0;
  95776. # endif
  95777. # else
  95778. info->use_asm = false;
  95779. # endif
  95780. /*
  95781. * unknown CPI
  95782. */
  95783. #else
  95784. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95785. info->use_asm = false;
  95786. #endif
  95787. }
  95788. #endif
  95789. /*** End of inlined file: cpu.c ***/
  95790. /*** Start of inlined file: crc.c ***/
  95791. /*** Start of inlined file: juce_FlacHeader.h ***/
  95792. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95793. // tasks..
  95794. #define VERSION "1.2.1"
  95795. #define FLAC__NO_DLL 1
  95796. #if JUCE_MSVC
  95797. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95798. #endif
  95799. #if JUCE_MAC
  95800. #define FLAC__SYS_DARWIN 1
  95801. #endif
  95802. /*** End of inlined file: juce_FlacHeader.h ***/
  95803. #if JUCE_USE_FLAC
  95804. #if HAVE_CONFIG_H
  95805. # include <config.h>
  95806. #endif
  95807. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95808. FLAC__byte const FLAC__crc8_table[256] = {
  95809. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95810. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95811. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95812. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95813. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95814. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95815. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95816. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95817. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95818. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95819. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95820. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95821. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95822. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95823. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95824. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95825. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95826. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95827. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95828. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95829. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95830. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95831. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95832. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95833. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95834. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95835. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95836. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95837. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95838. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95839. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95840. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95841. };
  95842. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95843. unsigned FLAC__crc16_table[256] = {
  95844. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95845. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95846. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95847. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95848. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95849. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95850. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95851. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95852. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95853. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95854. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95855. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95856. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95857. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95858. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95859. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95860. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95861. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95862. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95863. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95864. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95865. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95866. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95867. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95868. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95869. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95870. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95871. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95872. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95873. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95874. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95875. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95876. };
  95877. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95878. {
  95879. *crc = FLAC__crc8_table[*crc ^ data];
  95880. }
  95881. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95882. {
  95883. while(len--)
  95884. *crc = FLAC__crc8_table[*crc ^ *data++];
  95885. }
  95886. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95887. {
  95888. FLAC__uint8 crc = 0;
  95889. while(len--)
  95890. crc = FLAC__crc8_table[crc ^ *data++];
  95891. return crc;
  95892. }
  95893. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95894. {
  95895. unsigned crc = 0;
  95896. while(len--)
  95897. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95898. return crc;
  95899. }
  95900. #endif
  95901. /*** End of inlined file: crc.c ***/
  95902. /*** Start of inlined file: fixed.c ***/
  95903. /*** Start of inlined file: juce_FlacHeader.h ***/
  95904. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95905. // tasks..
  95906. #define VERSION "1.2.1"
  95907. #define FLAC__NO_DLL 1
  95908. #if JUCE_MSVC
  95909. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95910. #endif
  95911. #if JUCE_MAC
  95912. #define FLAC__SYS_DARWIN 1
  95913. #endif
  95914. /*** End of inlined file: juce_FlacHeader.h ***/
  95915. #if JUCE_USE_FLAC
  95916. #if HAVE_CONFIG_H
  95917. # include <config.h>
  95918. #endif
  95919. #include <math.h>
  95920. #include <string.h>
  95921. /*** Start of inlined file: fixed.h ***/
  95922. #ifndef FLAC__PRIVATE__FIXED_H
  95923. #define FLAC__PRIVATE__FIXED_H
  95924. #ifdef HAVE_CONFIG_H
  95925. #include <config.h>
  95926. #endif
  95927. /*** Start of inlined file: float.h ***/
  95928. #ifndef FLAC__PRIVATE__FLOAT_H
  95929. #define FLAC__PRIVATE__FLOAT_H
  95930. #ifdef HAVE_CONFIG_H
  95931. #include <config.h>
  95932. #endif
  95933. /*
  95934. * These typedefs make it easier to ensure that integer versions of
  95935. * the library really only contain integer operations. All the code
  95936. * in libFLAC should use FLAC__float and FLAC__double in place of
  95937. * float and double, and be protected by checks of the macro
  95938. * FLAC__INTEGER_ONLY_LIBRARY.
  95939. *
  95940. * FLAC__real is the basic floating point type used in LPC analysis.
  95941. */
  95942. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95943. typedef double FLAC__double;
  95944. typedef float FLAC__float;
  95945. /*
  95946. * WATCHOUT: changing FLAC__real will change the signatures of many
  95947. * functions that have assembly language equivalents and break them.
  95948. */
  95949. typedef float FLAC__real;
  95950. #else
  95951. /*
  95952. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95953. * for the integer part and lower 16 bits for the fractional part.
  95954. */
  95955. typedef FLAC__int32 FLAC__fixedpoint;
  95956. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95957. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95958. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95959. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95960. extern const FLAC__fixedpoint FLAC__FP_E;
  95961. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95962. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95963. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95964. /*
  95965. * FLAC__fixedpoint_log2()
  95966. * --------------------------------------------------------------------
  95967. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95968. * algorithm by Knuth for x >= 1.0
  95969. *
  95970. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95971. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95972. *
  95973. * 'precision' roughly limits the number of iterations that are done;
  95974. * use (unsigned)(-1) for maximum precision.
  95975. *
  95976. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95977. * function will punt and return 0.
  95978. *
  95979. * The return value will also have 'fracbits' fractional bits.
  95980. */
  95981. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95982. #endif
  95983. #endif
  95984. /*** End of inlined file: float.h ***/
  95985. /*** Start of inlined file: format.h ***/
  95986. #ifndef FLAC__PRIVATE__FORMAT_H
  95987. #define FLAC__PRIVATE__FORMAT_H
  95988. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95989. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95990. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95991. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95992. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95993. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95994. #endif
  95995. /*** End of inlined file: format.h ***/
  95996. /*
  95997. * FLAC__fixed_compute_best_predictor()
  95998. * --------------------------------------------------------------------
  95999. * Compute the best fixed predictor and the expected bits-per-sample
  96000. * of the residual signal for each order. The _wide() version uses
  96001. * 64-bit integers which is statistically necessary when bits-per-
  96002. * sample + log2(blocksize) > 30
  96003. *
  96004. * IN data[0,data_len-1]
  96005. * IN data_len
  96006. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  96007. */
  96008. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96009. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96010. # ifndef FLAC__NO_ASM
  96011. # ifdef FLAC__CPU_IA32
  96012. # ifdef FLAC__HAS_NASM
  96013. 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]);
  96014. # endif
  96015. # endif
  96016. # endif
  96017. 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]);
  96018. #else
  96019. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96020. 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]);
  96021. #endif
  96022. /*
  96023. * FLAC__fixed_compute_residual()
  96024. * --------------------------------------------------------------------
  96025. * Compute the residual signal obtained from sutracting the predicted
  96026. * signal from the original.
  96027. *
  96028. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96029. * IN data_len length of original signal
  96030. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96031. * OUT residual[0,data_len-1] residual signal
  96032. */
  96033. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  96034. /*
  96035. * FLAC__fixed_restore_signal()
  96036. * --------------------------------------------------------------------
  96037. * Restore the original signal by summing the residual and the
  96038. * predictor.
  96039. *
  96040. * IN residual[0,data_len-1] residual signal
  96041. * IN data_len length of original signal
  96042. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96043. * *** IMPORTANT: the caller must pass in the historical samples:
  96044. * IN data[-order,-1] previously-reconstructed historical samples
  96045. * OUT data[0,data_len-1] original signal
  96046. */
  96047. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  96048. #endif
  96049. /*** End of inlined file: fixed.h ***/
  96050. #ifndef M_LN2
  96051. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96052. #define M_LN2 0.69314718055994530942
  96053. #endif
  96054. #ifdef min
  96055. #undef min
  96056. #endif
  96057. #define min(x,y) ((x) < (y)? (x) : (y))
  96058. #ifdef local_abs
  96059. #undef local_abs
  96060. #endif
  96061. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  96062. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96063. /* rbps stands for residual bits per sample
  96064. *
  96065. * (ln(2) * err)
  96066. * rbps = log (-----------)
  96067. * 2 ( n )
  96068. */
  96069. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  96070. {
  96071. FLAC__uint32 rbps;
  96072. unsigned bits; /* the number of bits required to represent a number */
  96073. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96074. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96075. FLAC__ASSERT(err > 0);
  96076. FLAC__ASSERT(n > 0);
  96077. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96078. if(err <= n)
  96079. return 0;
  96080. /*
  96081. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96082. * These allow us later to know we won't lose too much precision in the
  96083. * fixed-point division (err<<fracbits)/n.
  96084. */
  96085. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  96086. err <<= fracbits;
  96087. err /= n;
  96088. /* err now holds err/n with fracbits fractional bits */
  96089. /*
  96090. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96091. * our purposes.
  96092. */
  96093. FLAC__ASSERT(err > 0);
  96094. bits = FLAC__bitmath_ilog2(err)+1;
  96095. if(bits > 16) {
  96096. err >>= (bits-16);
  96097. fracbits -= (bits-16);
  96098. }
  96099. rbps = (FLAC__uint32)err;
  96100. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96101. rbps *= FLAC__FP_LN2;
  96102. fracbits += 16;
  96103. FLAC__ASSERT(fracbits >= 0);
  96104. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96105. {
  96106. const int f = fracbits & 3;
  96107. if(f) {
  96108. rbps >>= f;
  96109. fracbits -= f;
  96110. }
  96111. }
  96112. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96113. if(rbps == 0)
  96114. return 0;
  96115. /*
  96116. * The return value must have 16 fractional bits. Since the whole part
  96117. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96118. * must be >= -3, these assertion allows us to be able to shift rbps
  96119. * left if necessary to get 16 fracbits without losing any bits of the
  96120. * whole part of rbps.
  96121. *
  96122. * There is a slight chance due to accumulated error that the whole part
  96123. * will require 6 bits, so we use 6 in the assertion. Really though as
  96124. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96125. */
  96126. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96127. FLAC__ASSERT(fracbits >= -3);
  96128. /* now shift the decimal point into place */
  96129. if(fracbits < 16)
  96130. return rbps << (16-fracbits);
  96131. else if(fracbits > 16)
  96132. return rbps >> (fracbits-16);
  96133. else
  96134. return rbps;
  96135. }
  96136. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  96137. {
  96138. FLAC__uint32 rbps;
  96139. unsigned bits; /* the number of bits required to represent a number */
  96140. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96141. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96142. FLAC__ASSERT(err > 0);
  96143. FLAC__ASSERT(n > 0);
  96144. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96145. if(err <= n)
  96146. return 0;
  96147. /*
  96148. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96149. * These allow us later to know we won't lose too much precision in the
  96150. * fixed-point division (err<<fracbits)/n.
  96151. */
  96152. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  96153. err <<= fracbits;
  96154. err /= n;
  96155. /* err now holds err/n with fracbits fractional bits */
  96156. /*
  96157. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96158. * our purposes.
  96159. */
  96160. FLAC__ASSERT(err > 0);
  96161. bits = FLAC__bitmath_ilog2_wide(err)+1;
  96162. if(bits > 16) {
  96163. err >>= (bits-16);
  96164. fracbits -= (bits-16);
  96165. }
  96166. rbps = (FLAC__uint32)err;
  96167. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96168. rbps *= FLAC__FP_LN2;
  96169. fracbits += 16;
  96170. FLAC__ASSERT(fracbits >= 0);
  96171. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96172. {
  96173. const int f = fracbits & 3;
  96174. if(f) {
  96175. rbps >>= f;
  96176. fracbits -= f;
  96177. }
  96178. }
  96179. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96180. if(rbps == 0)
  96181. return 0;
  96182. /*
  96183. * The return value must have 16 fractional bits. Since the whole part
  96184. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96185. * must be >= -3, these assertion allows us to be able to shift rbps
  96186. * left if necessary to get 16 fracbits without losing any bits of the
  96187. * whole part of rbps.
  96188. *
  96189. * There is a slight chance due to accumulated error that the whole part
  96190. * will require 6 bits, so we use 6 in the assertion. Really though as
  96191. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96192. */
  96193. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96194. FLAC__ASSERT(fracbits >= -3);
  96195. /* now shift the decimal point into place */
  96196. if(fracbits < 16)
  96197. return rbps << (16-fracbits);
  96198. else if(fracbits > 16)
  96199. return rbps >> (fracbits-16);
  96200. else
  96201. return rbps;
  96202. }
  96203. #endif
  96204. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96205. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96206. #else
  96207. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96208. #endif
  96209. {
  96210. FLAC__int32 last_error_0 = data[-1];
  96211. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96212. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96213. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96214. FLAC__int32 error, save;
  96215. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96216. unsigned i, order;
  96217. for(i = 0; i < data_len; i++) {
  96218. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96219. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96220. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96221. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96222. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96223. }
  96224. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96225. order = 0;
  96226. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96227. order = 1;
  96228. else if(total_error_2 < min(total_error_3, total_error_4))
  96229. order = 2;
  96230. else if(total_error_3 < total_error_4)
  96231. order = 3;
  96232. else
  96233. order = 4;
  96234. /* Estimate the expected number of bits per residual signal sample. */
  96235. /* 'total_error*' is linearly related to the variance of the residual */
  96236. /* signal, so we use it directly to compute E(|x|) */
  96237. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96238. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96239. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96240. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96241. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96242. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96243. 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);
  96244. 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);
  96245. 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);
  96246. 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);
  96247. 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);
  96248. #else
  96249. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96250. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96251. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96252. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96253. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96254. #endif
  96255. return order;
  96256. }
  96257. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96258. 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])
  96259. #else
  96260. 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])
  96261. #endif
  96262. {
  96263. FLAC__int32 last_error_0 = data[-1];
  96264. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96265. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96266. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96267. FLAC__int32 error, save;
  96268. /* total_error_* are 64-bits to avoid overflow when encoding
  96269. * erratic signals when the bits-per-sample and blocksize are
  96270. * large.
  96271. */
  96272. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96273. unsigned i, order;
  96274. for(i = 0; i < data_len; i++) {
  96275. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96276. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96277. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96278. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96279. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96280. }
  96281. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96282. order = 0;
  96283. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96284. order = 1;
  96285. else if(total_error_2 < min(total_error_3, total_error_4))
  96286. order = 2;
  96287. else if(total_error_3 < total_error_4)
  96288. order = 3;
  96289. else
  96290. order = 4;
  96291. /* Estimate the expected number of bits per residual signal sample. */
  96292. /* 'total_error*' is linearly related to the variance of the residual */
  96293. /* signal, so we use it directly to compute E(|x|) */
  96294. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96295. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96296. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96297. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96298. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96299. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96300. #if defined _MSC_VER || defined __MINGW32__
  96301. /* with MSVC you have to spoon feed it the casting */
  96302. 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);
  96303. 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);
  96304. 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);
  96305. 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);
  96306. 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);
  96307. #else
  96308. 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);
  96309. 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);
  96310. 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);
  96311. 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);
  96312. 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);
  96313. #endif
  96314. #else
  96315. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96316. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96317. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96318. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96319. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96320. #endif
  96321. return order;
  96322. }
  96323. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96324. {
  96325. const int idata_len = (int)data_len;
  96326. int i;
  96327. switch(order) {
  96328. case 0:
  96329. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96330. memcpy(residual, data, sizeof(residual[0])*data_len);
  96331. break;
  96332. case 1:
  96333. for(i = 0; i < idata_len; i++)
  96334. residual[i] = data[i] - data[i-1];
  96335. break;
  96336. case 2:
  96337. for(i = 0; i < idata_len; i++)
  96338. #if 1 /* OPT: may be faster with some compilers on some systems */
  96339. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96340. #else
  96341. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96342. #endif
  96343. break;
  96344. case 3:
  96345. for(i = 0; i < idata_len; i++)
  96346. #if 1 /* OPT: may be faster with some compilers on some systems */
  96347. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96348. #else
  96349. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96350. #endif
  96351. break;
  96352. case 4:
  96353. for(i = 0; i < idata_len; i++)
  96354. #if 1 /* OPT: may be faster with some compilers on some systems */
  96355. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96356. #else
  96357. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96358. #endif
  96359. break;
  96360. default:
  96361. FLAC__ASSERT(0);
  96362. }
  96363. }
  96364. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96365. {
  96366. int i, idata_len = (int)data_len;
  96367. switch(order) {
  96368. case 0:
  96369. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96370. memcpy(data, residual, sizeof(residual[0])*data_len);
  96371. break;
  96372. case 1:
  96373. for(i = 0; i < idata_len; i++)
  96374. data[i] = residual[i] + data[i-1];
  96375. break;
  96376. case 2:
  96377. for(i = 0; i < idata_len; i++)
  96378. #if 1 /* OPT: may be faster with some compilers on some systems */
  96379. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96380. #else
  96381. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96382. #endif
  96383. break;
  96384. case 3:
  96385. for(i = 0; i < idata_len; i++)
  96386. #if 1 /* OPT: may be faster with some compilers on some systems */
  96387. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96388. #else
  96389. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96390. #endif
  96391. break;
  96392. case 4:
  96393. for(i = 0; i < idata_len; i++)
  96394. #if 1 /* OPT: may be faster with some compilers on some systems */
  96395. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96396. #else
  96397. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96398. #endif
  96399. break;
  96400. default:
  96401. FLAC__ASSERT(0);
  96402. }
  96403. }
  96404. #endif
  96405. /*** End of inlined file: fixed.c ***/
  96406. /*** Start of inlined file: float.c ***/
  96407. /*** Start of inlined file: juce_FlacHeader.h ***/
  96408. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96409. // tasks..
  96410. #define VERSION "1.2.1"
  96411. #define FLAC__NO_DLL 1
  96412. #if JUCE_MSVC
  96413. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96414. #endif
  96415. #if JUCE_MAC
  96416. #define FLAC__SYS_DARWIN 1
  96417. #endif
  96418. /*** End of inlined file: juce_FlacHeader.h ***/
  96419. #if JUCE_USE_FLAC
  96420. #if HAVE_CONFIG_H
  96421. # include <config.h>
  96422. #endif
  96423. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96424. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96425. #ifdef _MSC_VER
  96426. #define FLAC__U64L(x) x
  96427. #else
  96428. #define FLAC__U64L(x) x##LLU
  96429. #endif
  96430. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96431. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96432. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96433. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96434. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96435. /* Lookup tables for Knuth's logarithm algorithm */
  96436. #define LOG2_LOOKUP_PRECISION 16
  96437. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96438. {
  96439. /*
  96440. * 0 fraction bits
  96441. */
  96442. /* undefined */ 0x00000000,
  96443. /* lg(2/1) = */ 0x00000001,
  96444. /* lg(4/3) = */ 0x00000000,
  96445. /* lg(8/7) = */ 0x00000000,
  96446. /* lg(16/15) = */ 0x00000000,
  96447. /* lg(32/31) = */ 0x00000000,
  96448. /* lg(64/63) = */ 0x00000000,
  96449. /* lg(128/127) = */ 0x00000000,
  96450. /* lg(256/255) = */ 0x00000000,
  96451. /* lg(512/511) = */ 0x00000000,
  96452. /* lg(1024/1023) = */ 0x00000000,
  96453. /* lg(2048/2047) = */ 0x00000000,
  96454. /* lg(4096/4095) = */ 0x00000000,
  96455. /* lg(8192/8191) = */ 0x00000000,
  96456. /* lg(16384/16383) = */ 0x00000000,
  96457. /* lg(32768/32767) = */ 0x00000000
  96458. },
  96459. {
  96460. /*
  96461. * 4 fraction bits
  96462. */
  96463. /* undefined */ 0x00000000,
  96464. /* lg(2/1) = */ 0x00000010,
  96465. /* lg(4/3) = */ 0x00000007,
  96466. /* lg(8/7) = */ 0x00000003,
  96467. /* lg(16/15) = */ 0x00000001,
  96468. /* lg(32/31) = */ 0x00000001,
  96469. /* lg(64/63) = */ 0x00000000,
  96470. /* lg(128/127) = */ 0x00000000,
  96471. /* lg(256/255) = */ 0x00000000,
  96472. /* lg(512/511) = */ 0x00000000,
  96473. /* lg(1024/1023) = */ 0x00000000,
  96474. /* lg(2048/2047) = */ 0x00000000,
  96475. /* lg(4096/4095) = */ 0x00000000,
  96476. /* lg(8192/8191) = */ 0x00000000,
  96477. /* lg(16384/16383) = */ 0x00000000,
  96478. /* lg(32768/32767) = */ 0x00000000
  96479. },
  96480. {
  96481. /*
  96482. * 8 fraction bits
  96483. */
  96484. /* undefined */ 0x00000000,
  96485. /* lg(2/1) = */ 0x00000100,
  96486. /* lg(4/3) = */ 0x0000006a,
  96487. /* lg(8/7) = */ 0x00000031,
  96488. /* lg(16/15) = */ 0x00000018,
  96489. /* lg(32/31) = */ 0x0000000c,
  96490. /* lg(64/63) = */ 0x00000006,
  96491. /* lg(128/127) = */ 0x00000003,
  96492. /* lg(256/255) = */ 0x00000001,
  96493. /* lg(512/511) = */ 0x00000001,
  96494. /* lg(1024/1023) = */ 0x00000000,
  96495. /* lg(2048/2047) = */ 0x00000000,
  96496. /* lg(4096/4095) = */ 0x00000000,
  96497. /* lg(8192/8191) = */ 0x00000000,
  96498. /* lg(16384/16383) = */ 0x00000000,
  96499. /* lg(32768/32767) = */ 0x00000000
  96500. },
  96501. {
  96502. /*
  96503. * 12 fraction bits
  96504. */
  96505. /* undefined */ 0x00000000,
  96506. /* lg(2/1) = */ 0x00001000,
  96507. /* lg(4/3) = */ 0x000006a4,
  96508. /* lg(8/7) = */ 0x00000315,
  96509. /* lg(16/15) = */ 0x0000017d,
  96510. /* lg(32/31) = */ 0x000000bc,
  96511. /* lg(64/63) = */ 0x0000005d,
  96512. /* lg(128/127) = */ 0x0000002e,
  96513. /* lg(256/255) = */ 0x00000017,
  96514. /* lg(512/511) = */ 0x0000000c,
  96515. /* lg(1024/1023) = */ 0x00000006,
  96516. /* lg(2048/2047) = */ 0x00000003,
  96517. /* lg(4096/4095) = */ 0x00000001,
  96518. /* lg(8192/8191) = */ 0x00000001,
  96519. /* lg(16384/16383) = */ 0x00000000,
  96520. /* lg(32768/32767) = */ 0x00000000
  96521. },
  96522. {
  96523. /*
  96524. * 16 fraction bits
  96525. */
  96526. /* undefined */ 0x00000000,
  96527. /* lg(2/1) = */ 0x00010000,
  96528. /* lg(4/3) = */ 0x00006a40,
  96529. /* lg(8/7) = */ 0x00003151,
  96530. /* lg(16/15) = */ 0x000017d6,
  96531. /* lg(32/31) = */ 0x00000bba,
  96532. /* lg(64/63) = */ 0x000005d1,
  96533. /* lg(128/127) = */ 0x000002e6,
  96534. /* lg(256/255) = */ 0x00000172,
  96535. /* lg(512/511) = */ 0x000000b9,
  96536. /* lg(1024/1023) = */ 0x0000005c,
  96537. /* lg(2048/2047) = */ 0x0000002e,
  96538. /* lg(4096/4095) = */ 0x00000017,
  96539. /* lg(8192/8191) = */ 0x0000000c,
  96540. /* lg(16384/16383) = */ 0x00000006,
  96541. /* lg(32768/32767) = */ 0x00000003
  96542. },
  96543. {
  96544. /*
  96545. * 20 fraction bits
  96546. */
  96547. /* undefined */ 0x00000000,
  96548. /* lg(2/1) = */ 0x00100000,
  96549. /* lg(4/3) = */ 0x0006a3fe,
  96550. /* lg(8/7) = */ 0x00031513,
  96551. /* lg(16/15) = */ 0x00017d60,
  96552. /* lg(32/31) = */ 0x0000bb9d,
  96553. /* lg(64/63) = */ 0x00005d10,
  96554. /* lg(128/127) = */ 0x00002e59,
  96555. /* lg(256/255) = */ 0x00001721,
  96556. /* lg(512/511) = */ 0x00000b8e,
  96557. /* lg(1024/1023) = */ 0x000005c6,
  96558. /* lg(2048/2047) = */ 0x000002e3,
  96559. /* lg(4096/4095) = */ 0x00000171,
  96560. /* lg(8192/8191) = */ 0x000000b9,
  96561. /* lg(16384/16383) = */ 0x0000005c,
  96562. /* lg(32768/32767) = */ 0x0000002e
  96563. },
  96564. {
  96565. /*
  96566. * 24 fraction bits
  96567. */
  96568. /* undefined */ 0x00000000,
  96569. /* lg(2/1) = */ 0x01000000,
  96570. /* lg(4/3) = */ 0x006a3fe6,
  96571. /* lg(8/7) = */ 0x00315130,
  96572. /* lg(16/15) = */ 0x0017d605,
  96573. /* lg(32/31) = */ 0x000bb9ca,
  96574. /* lg(64/63) = */ 0x0005d0fc,
  96575. /* lg(128/127) = */ 0x0002e58f,
  96576. /* lg(256/255) = */ 0x0001720e,
  96577. /* lg(512/511) = */ 0x0000b8d8,
  96578. /* lg(1024/1023) = */ 0x00005c61,
  96579. /* lg(2048/2047) = */ 0x00002e2d,
  96580. /* lg(4096/4095) = */ 0x00001716,
  96581. /* lg(8192/8191) = */ 0x00000b8b,
  96582. /* lg(16384/16383) = */ 0x000005c5,
  96583. /* lg(32768/32767) = */ 0x000002e3
  96584. },
  96585. {
  96586. /*
  96587. * 28 fraction bits
  96588. */
  96589. /* undefined */ 0x00000000,
  96590. /* lg(2/1) = */ 0x10000000,
  96591. /* lg(4/3) = */ 0x06a3fe5c,
  96592. /* lg(8/7) = */ 0x03151301,
  96593. /* lg(16/15) = */ 0x017d6049,
  96594. /* lg(32/31) = */ 0x00bb9ca6,
  96595. /* lg(64/63) = */ 0x005d0fba,
  96596. /* lg(128/127) = */ 0x002e58f7,
  96597. /* lg(256/255) = */ 0x001720da,
  96598. /* lg(512/511) = */ 0x000b8d87,
  96599. /* lg(1024/1023) = */ 0x0005c60b,
  96600. /* lg(2048/2047) = */ 0x0002e2d7,
  96601. /* lg(4096/4095) = */ 0x00017160,
  96602. /* lg(8192/8191) = */ 0x0000b8ad,
  96603. /* lg(16384/16383) = */ 0x00005c56,
  96604. /* lg(32768/32767) = */ 0x00002e2b
  96605. }
  96606. };
  96607. #if 0
  96608. static const FLAC__uint64 log2_lookup_wide[] = {
  96609. {
  96610. /*
  96611. * 32 fraction bits
  96612. */
  96613. /* undefined */ 0x00000000,
  96614. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96615. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96616. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96617. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96618. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96619. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96620. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96621. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96622. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96623. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96624. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96625. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96626. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96627. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96628. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96629. },
  96630. {
  96631. /*
  96632. * 48 fraction bits
  96633. */
  96634. /* undefined */ 0x00000000,
  96635. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96636. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96637. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96638. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96639. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96640. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96641. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96642. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96643. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96644. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96645. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96646. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96647. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96648. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96649. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96650. }
  96651. };
  96652. #endif
  96653. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96654. {
  96655. const FLAC__uint32 ONE = (1u << fracbits);
  96656. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96657. FLAC__ASSERT(fracbits < 32);
  96658. FLAC__ASSERT((fracbits & 0x3) == 0);
  96659. if(x < ONE)
  96660. return 0;
  96661. if(precision > LOG2_LOOKUP_PRECISION)
  96662. precision = LOG2_LOOKUP_PRECISION;
  96663. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96664. {
  96665. FLAC__uint32 y = 0;
  96666. FLAC__uint32 z = x >> 1, k = 1;
  96667. while (x > ONE && k < precision) {
  96668. if (x - z >= ONE) {
  96669. x -= z;
  96670. z = x >> k;
  96671. y += table[k];
  96672. }
  96673. else {
  96674. z >>= 1;
  96675. k++;
  96676. }
  96677. }
  96678. return y;
  96679. }
  96680. }
  96681. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96682. #endif
  96683. /*** End of inlined file: float.c ***/
  96684. /*** Start of inlined file: format.c ***/
  96685. /*** Start of inlined file: juce_FlacHeader.h ***/
  96686. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96687. // tasks..
  96688. #define VERSION "1.2.1"
  96689. #define FLAC__NO_DLL 1
  96690. #if JUCE_MSVC
  96691. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96692. #endif
  96693. #if JUCE_MAC
  96694. #define FLAC__SYS_DARWIN 1
  96695. #endif
  96696. /*** End of inlined file: juce_FlacHeader.h ***/
  96697. #if JUCE_USE_FLAC
  96698. #if HAVE_CONFIG_H
  96699. # include <config.h>
  96700. #endif
  96701. #include <stdio.h>
  96702. #include <stdlib.h> /* for qsort() */
  96703. #include <string.h> /* for memset() */
  96704. #ifndef FLaC__INLINE
  96705. #define FLaC__INLINE
  96706. #endif
  96707. #ifdef min
  96708. #undef min
  96709. #endif
  96710. #define min(a,b) ((a)<(b)?(a):(b))
  96711. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96712. #ifdef _MSC_VER
  96713. #define FLAC__U64L(x) x
  96714. #else
  96715. #define FLAC__U64L(x) x##LLU
  96716. #endif
  96717. /* VERSION should come from configure */
  96718. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96719. ;
  96720. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96721. /* yet one more hack because of MSVC6: */
  96722. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96723. #else
  96724. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96725. #endif
  96726. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96727. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96728. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96729. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96730. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96731. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96732. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96733. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96734. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96735. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96736. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96737. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96738. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96739. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96740. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96741. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96742. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96743. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96744. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96745. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96746. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96747. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96748. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96749. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96750. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96751. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96752. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96753. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96754. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96755. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96756. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96757. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96758. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96759. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96760. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96761. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96762. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96763. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96764. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96765. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96766. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96767. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96768. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96769. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96770. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96771. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96772. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96773. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96774. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96775. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96776. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96777. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96778. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96779. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96780. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96781. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96782. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96783. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96784. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96785. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96786. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96787. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96788. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96789. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96790. "PARTITIONED_RICE",
  96791. "PARTITIONED_RICE2"
  96792. };
  96793. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96794. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96795. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96796. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96797. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96798. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96799. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96800. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96801. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96802. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96803. "CONSTANT",
  96804. "VERBATIM",
  96805. "FIXED",
  96806. "LPC"
  96807. };
  96808. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96809. "INDEPENDENT",
  96810. "LEFT_SIDE",
  96811. "RIGHT_SIDE",
  96812. "MID_SIDE"
  96813. };
  96814. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96815. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96816. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96817. };
  96818. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96819. "STREAMINFO",
  96820. "PADDING",
  96821. "APPLICATION",
  96822. "SEEKTABLE",
  96823. "VORBIS_COMMENT",
  96824. "CUESHEET",
  96825. "PICTURE"
  96826. };
  96827. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96828. "Other",
  96829. "32x32 pixels 'file icon' (PNG only)",
  96830. "Other file icon",
  96831. "Cover (front)",
  96832. "Cover (back)",
  96833. "Leaflet page",
  96834. "Media (e.g. label side of CD)",
  96835. "Lead artist/lead performer/soloist",
  96836. "Artist/performer",
  96837. "Conductor",
  96838. "Band/Orchestra",
  96839. "Composer",
  96840. "Lyricist/text writer",
  96841. "Recording Location",
  96842. "During recording",
  96843. "During performance",
  96844. "Movie/video screen capture",
  96845. "A bright coloured fish",
  96846. "Illustration",
  96847. "Band/artist logotype",
  96848. "Publisher/Studio logotype"
  96849. };
  96850. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96851. {
  96852. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96853. return false;
  96854. }
  96855. else
  96856. return true;
  96857. }
  96858. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96859. {
  96860. if(
  96861. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96862. (
  96863. sample_rate >= (1u << 16) &&
  96864. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96865. )
  96866. ) {
  96867. return false;
  96868. }
  96869. else
  96870. return true;
  96871. }
  96872. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96873. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96874. {
  96875. unsigned i;
  96876. FLAC__uint64 prev_sample_number = 0;
  96877. FLAC__bool got_prev = false;
  96878. FLAC__ASSERT(0 != seek_table);
  96879. for(i = 0; i < seek_table->num_points; i++) {
  96880. if(got_prev) {
  96881. if(
  96882. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96883. seek_table->points[i].sample_number <= prev_sample_number
  96884. )
  96885. return false;
  96886. }
  96887. prev_sample_number = seek_table->points[i].sample_number;
  96888. got_prev = true;
  96889. }
  96890. return true;
  96891. }
  96892. /* used as the sort predicate for qsort() */
  96893. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96894. {
  96895. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96896. if(l->sample_number == r->sample_number)
  96897. return 0;
  96898. else if(l->sample_number < r->sample_number)
  96899. return -1;
  96900. else
  96901. return 1;
  96902. }
  96903. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96904. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96905. {
  96906. unsigned i, j;
  96907. FLAC__bool first;
  96908. FLAC__ASSERT(0 != seek_table);
  96909. /* sort the seekpoints */
  96910. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96911. /* uniquify the seekpoints */
  96912. first = true;
  96913. for(i = j = 0; i < seek_table->num_points; i++) {
  96914. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96915. if(!first) {
  96916. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96917. continue;
  96918. }
  96919. }
  96920. first = false;
  96921. seek_table->points[j++] = seek_table->points[i];
  96922. }
  96923. for(i = j; i < seek_table->num_points; i++) {
  96924. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96925. seek_table->points[i].stream_offset = 0;
  96926. seek_table->points[i].frame_samples = 0;
  96927. }
  96928. return j;
  96929. }
  96930. /*
  96931. * also disallows non-shortest-form encodings, c.f.
  96932. * http://www.unicode.org/versions/corrigendum1.html
  96933. * and a more clear explanation at the end of this section:
  96934. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96935. */
  96936. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96937. {
  96938. FLAC__ASSERT(0 != utf8);
  96939. if ((utf8[0] & 0x80) == 0) {
  96940. return 1;
  96941. }
  96942. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96943. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96944. return 0;
  96945. return 2;
  96946. }
  96947. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96948. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96949. return 0;
  96950. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96951. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96952. return 0;
  96953. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96954. return 0;
  96955. return 3;
  96956. }
  96957. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96958. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96959. return 0;
  96960. return 4;
  96961. }
  96962. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96963. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96964. return 0;
  96965. return 5;
  96966. }
  96967. 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) {
  96968. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96969. return 0;
  96970. return 6;
  96971. }
  96972. else {
  96973. return 0;
  96974. }
  96975. }
  96976. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96977. {
  96978. char c;
  96979. for(c = *name; c; c = *(++name))
  96980. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96981. return false;
  96982. return true;
  96983. }
  96984. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96985. {
  96986. if(length == (unsigned)(-1)) {
  96987. while(*value) {
  96988. unsigned n = utf8len_(value);
  96989. if(n == 0)
  96990. return false;
  96991. value += n;
  96992. }
  96993. }
  96994. else {
  96995. const FLAC__byte *end = value + length;
  96996. while(value < end) {
  96997. unsigned n = utf8len_(value);
  96998. if(n == 0)
  96999. return false;
  97000. value += n;
  97001. }
  97002. if(value != end)
  97003. return false;
  97004. }
  97005. return true;
  97006. }
  97007. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  97008. {
  97009. const FLAC__byte *s, *end;
  97010. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  97011. if(*s < 0x20 || *s > 0x7D)
  97012. return false;
  97013. }
  97014. if(s == end)
  97015. return false;
  97016. s++; /* skip '=' */
  97017. while(s < end) {
  97018. unsigned n = utf8len_(s);
  97019. if(n == 0)
  97020. return false;
  97021. s += n;
  97022. }
  97023. if(s != end)
  97024. return false;
  97025. return true;
  97026. }
  97027. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97028. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  97029. {
  97030. unsigned i, j;
  97031. if(check_cd_da_subset) {
  97032. if(cue_sheet->lead_in < 2 * 44100) {
  97033. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  97034. return false;
  97035. }
  97036. if(cue_sheet->lead_in % 588 != 0) {
  97037. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  97038. return false;
  97039. }
  97040. }
  97041. if(cue_sheet->num_tracks == 0) {
  97042. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  97043. return false;
  97044. }
  97045. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  97046. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  97047. return false;
  97048. }
  97049. for(i = 0; i < cue_sheet->num_tracks; i++) {
  97050. if(cue_sheet->tracks[i].number == 0) {
  97051. if(violation) *violation = "cue sheet may not have a track number 0";
  97052. return false;
  97053. }
  97054. if(check_cd_da_subset) {
  97055. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  97056. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  97057. return false;
  97058. }
  97059. }
  97060. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  97061. if(violation) {
  97062. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  97063. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  97064. else
  97065. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  97066. }
  97067. return false;
  97068. }
  97069. if(i < cue_sheet->num_tracks - 1) {
  97070. if(cue_sheet->tracks[i].num_indices == 0) {
  97071. if(violation) *violation = "cue sheet track must have at least one index point";
  97072. return false;
  97073. }
  97074. if(cue_sheet->tracks[i].indices[0].number > 1) {
  97075. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  97076. return false;
  97077. }
  97078. }
  97079. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  97080. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  97081. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  97082. return false;
  97083. }
  97084. if(j > 0) {
  97085. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  97086. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  97087. return false;
  97088. }
  97089. }
  97090. }
  97091. }
  97092. return true;
  97093. }
  97094. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97095. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  97096. {
  97097. char *p;
  97098. FLAC__byte *b;
  97099. for(p = picture->mime_type; *p; p++) {
  97100. if(*p < 0x20 || *p > 0x7e) {
  97101. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  97102. return false;
  97103. }
  97104. }
  97105. for(b = picture->description; *b; ) {
  97106. unsigned n = utf8len_(b);
  97107. if(n == 0) {
  97108. if(violation) *violation = "description string must be valid UTF-8";
  97109. return false;
  97110. }
  97111. b += n;
  97112. }
  97113. return true;
  97114. }
  97115. /*
  97116. * These routines are private to libFLAC
  97117. */
  97118. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  97119. {
  97120. return
  97121. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  97122. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  97123. blocksize,
  97124. predictor_order
  97125. );
  97126. }
  97127. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  97128. {
  97129. unsigned max_rice_partition_order = 0;
  97130. while(!(blocksize & 1)) {
  97131. max_rice_partition_order++;
  97132. blocksize >>= 1;
  97133. }
  97134. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  97135. }
  97136. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  97137. {
  97138. unsigned max_rice_partition_order = limit;
  97139. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  97140. max_rice_partition_order--;
  97141. FLAC__ASSERT(
  97142. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  97143. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  97144. );
  97145. return max_rice_partition_order;
  97146. }
  97147. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97148. {
  97149. FLAC__ASSERT(0 != object);
  97150. object->parameters = 0;
  97151. object->raw_bits = 0;
  97152. object->capacity_by_order = 0;
  97153. }
  97154. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97155. {
  97156. FLAC__ASSERT(0 != object);
  97157. if(0 != object->parameters)
  97158. free(object->parameters);
  97159. if(0 != object->raw_bits)
  97160. free(object->raw_bits);
  97161. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  97162. }
  97163. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  97164. {
  97165. FLAC__ASSERT(0 != object);
  97166. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  97167. if(object->capacity_by_order < max_partition_order) {
  97168. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  97169. return false;
  97170. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  97171. return false;
  97172. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  97173. object->capacity_by_order = max_partition_order;
  97174. }
  97175. return true;
  97176. }
  97177. #endif
  97178. /*** End of inlined file: format.c ***/
  97179. /*** Start of inlined file: lpc_flac.c ***/
  97180. /*** Start of inlined file: juce_FlacHeader.h ***/
  97181. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97182. // tasks..
  97183. #define VERSION "1.2.1"
  97184. #define FLAC__NO_DLL 1
  97185. #if JUCE_MSVC
  97186. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97187. #endif
  97188. #if JUCE_MAC
  97189. #define FLAC__SYS_DARWIN 1
  97190. #endif
  97191. /*** End of inlined file: juce_FlacHeader.h ***/
  97192. #if JUCE_USE_FLAC
  97193. #if HAVE_CONFIG_H
  97194. # include <config.h>
  97195. #endif
  97196. #include <math.h>
  97197. /*** Start of inlined file: lpc.h ***/
  97198. #ifndef FLAC__PRIVATE__LPC_H
  97199. #define FLAC__PRIVATE__LPC_H
  97200. #ifdef HAVE_CONFIG_H
  97201. #include <config.h>
  97202. #endif
  97203. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97204. /*
  97205. * FLAC__lpc_window_data()
  97206. * --------------------------------------------------------------------
  97207. * Applies the given window to the data.
  97208. * OPT: asm implementation
  97209. *
  97210. * IN in[0,data_len-1]
  97211. * IN window[0,data_len-1]
  97212. * OUT out[0,lag-1]
  97213. * IN data_len
  97214. */
  97215. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97216. /*
  97217. * FLAC__lpc_compute_autocorrelation()
  97218. * --------------------------------------------------------------------
  97219. * Compute the autocorrelation for lags between 0 and lag-1.
  97220. * Assumes data[] outside of [0,data_len-1] == 0.
  97221. * Asserts that lag > 0.
  97222. *
  97223. * IN data[0,data_len-1]
  97224. * IN data_len
  97225. * IN 0 < lag <= data_len
  97226. * OUT autoc[0,lag-1]
  97227. */
  97228. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97229. #ifndef FLAC__NO_ASM
  97230. # ifdef FLAC__CPU_IA32
  97231. # ifdef FLAC__HAS_NASM
  97232. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97233. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97234. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97235. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97236. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97237. # endif
  97238. # endif
  97239. #endif
  97240. /*
  97241. * FLAC__lpc_compute_lp_coefficients()
  97242. * --------------------------------------------------------------------
  97243. * Computes LP coefficients for orders 1..max_order.
  97244. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97245. * and there is no point in calculating a predictor.
  97246. *
  97247. * IN autoc[0,max_order] autocorrelation values
  97248. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97249. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97250. * *** IMPORTANT:
  97251. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97252. * OUT error[0,max_order-1] error for each order (more
  97253. * specifically, the variance of
  97254. * the error signal times # of
  97255. * samples in the signal)
  97256. *
  97257. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97258. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97259. * in lp_coeff[7][0,7], etc.
  97260. */
  97261. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97262. /*
  97263. * FLAC__lpc_quantize_coefficients()
  97264. * --------------------------------------------------------------------
  97265. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97266. * must be less than 32 (sizeof(FLAC__int32)*8).
  97267. *
  97268. * IN lp_coeff[0,order-1] LP coefficients
  97269. * IN order LP order
  97270. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97271. * desired precision (in bits, including sign
  97272. * bit) of largest coefficient
  97273. * OUT qlp_coeff[0,order-1] quantized coefficients
  97274. * OUT shift # of bits to shift right to get approximated
  97275. * LP coefficients. NOTE: could be negative.
  97276. * RETURN 0 => quantization OK
  97277. * 1 => coefficients require too much shifting for *shift to
  97278. * fit in the LPC subframe header. 'shift' is unset.
  97279. * 2 => coefficients are all zero, which is bad. 'shift' is
  97280. * unset.
  97281. */
  97282. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97283. /*
  97284. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97285. * --------------------------------------------------------------------
  97286. * Compute the residual signal obtained from sutracting the predicted
  97287. * signal from the original.
  97288. *
  97289. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97290. * IN data_len length of original signal
  97291. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97292. * IN order > 0 LP order
  97293. * IN lp_quantization quantization of LP coefficients in bits
  97294. * OUT residual[0,data_len-1] residual signal
  97295. */
  97296. 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[]);
  97297. 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[]);
  97298. #ifndef FLAC__NO_ASM
  97299. # ifdef FLAC__CPU_IA32
  97300. # ifdef FLAC__HAS_NASM
  97301. 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[]);
  97302. 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[]);
  97303. # endif
  97304. # endif
  97305. #endif
  97306. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97307. /*
  97308. * FLAC__lpc_restore_signal()
  97309. * --------------------------------------------------------------------
  97310. * Restore the original signal by summing the residual and the
  97311. * predictor.
  97312. *
  97313. * IN residual[0,data_len-1] residual signal
  97314. * IN data_len length of original signal
  97315. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97316. * IN order > 0 LP order
  97317. * IN lp_quantization quantization of LP coefficients in bits
  97318. * *** IMPORTANT: the caller must pass in the historical samples:
  97319. * IN data[-order,-1] previously-reconstructed historical samples
  97320. * OUT data[0,data_len-1] original signal
  97321. */
  97322. 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[]);
  97323. 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[]);
  97324. #ifndef FLAC__NO_ASM
  97325. # ifdef FLAC__CPU_IA32
  97326. # ifdef FLAC__HAS_NASM
  97327. 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[]);
  97328. 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[]);
  97329. # endif /* FLAC__HAS_NASM */
  97330. # elif defined FLAC__CPU_PPC
  97331. 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[]);
  97332. 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[]);
  97333. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97334. #endif /* FLAC__NO_ASM */
  97335. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97336. /*
  97337. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97338. * --------------------------------------------------------------------
  97339. * Compute the expected number of bits per residual signal sample
  97340. * based on the LP error (which is related to the residual variance).
  97341. *
  97342. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97343. * IN total_samples > 0 # of samples in residual signal
  97344. * RETURN expected bits per sample
  97345. */
  97346. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97347. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97348. /*
  97349. * FLAC__lpc_compute_best_order()
  97350. * --------------------------------------------------------------------
  97351. * Compute the best order from the array of signal errors returned
  97352. * during coefficient computation.
  97353. *
  97354. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97355. * IN max_order > 0 max LP order
  97356. * IN total_samples > 0 # of samples in residual signal
  97357. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97358. * (includes warmup sample size and quantized LP coefficient)
  97359. * RETURN [1,max_order] best order
  97360. */
  97361. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97362. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97363. #endif
  97364. /*** End of inlined file: lpc.h ***/
  97365. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97366. #include <stdio.h>
  97367. #endif
  97368. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97369. #ifndef M_LN2
  97370. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97371. #define M_LN2 0.69314718055994530942
  97372. #endif
  97373. /* OPT: #undef'ing this may improve the speed on some architectures */
  97374. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97375. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97376. {
  97377. unsigned i;
  97378. for(i = 0; i < data_len; i++)
  97379. out[i] = in[i] * window[i];
  97380. }
  97381. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97382. {
  97383. /* a readable, but slower, version */
  97384. #if 0
  97385. FLAC__real d;
  97386. unsigned i;
  97387. FLAC__ASSERT(lag > 0);
  97388. FLAC__ASSERT(lag <= data_len);
  97389. /*
  97390. * Technically we should subtract the mean first like so:
  97391. * for(i = 0; i < data_len; i++)
  97392. * data[i] -= mean;
  97393. * but it appears not to make enough of a difference to matter, and
  97394. * most signals are already closely centered around zero
  97395. */
  97396. while(lag--) {
  97397. for(i = lag, d = 0.0; i < data_len; i++)
  97398. d += data[i] * data[i - lag];
  97399. autoc[lag] = d;
  97400. }
  97401. #endif
  97402. /*
  97403. * this version tends to run faster because of better data locality
  97404. * ('data_len' is usually much larger than 'lag')
  97405. */
  97406. FLAC__real d;
  97407. unsigned sample, coeff;
  97408. const unsigned limit = data_len - lag;
  97409. FLAC__ASSERT(lag > 0);
  97410. FLAC__ASSERT(lag <= data_len);
  97411. for(coeff = 0; coeff < lag; coeff++)
  97412. autoc[coeff] = 0.0;
  97413. for(sample = 0; sample <= limit; sample++) {
  97414. d = data[sample];
  97415. for(coeff = 0; coeff < lag; coeff++)
  97416. autoc[coeff] += d * data[sample+coeff];
  97417. }
  97418. for(; sample < data_len; sample++) {
  97419. d = data[sample];
  97420. for(coeff = 0; coeff < data_len - sample; coeff++)
  97421. autoc[coeff] += d * data[sample+coeff];
  97422. }
  97423. }
  97424. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97425. {
  97426. unsigned i, j;
  97427. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97428. FLAC__ASSERT(0 != max_order);
  97429. FLAC__ASSERT(0 < *max_order);
  97430. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97431. FLAC__ASSERT(autoc[0] != 0.0);
  97432. err = autoc[0];
  97433. for(i = 0; i < *max_order; i++) {
  97434. /* Sum up this iteration's reflection coefficient. */
  97435. r = -autoc[i+1];
  97436. for(j = 0; j < i; j++)
  97437. r -= lpc[j] * autoc[i-j];
  97438. ref[i] = (r/=err);
  97439. /* Update LPC coefficients and total error. */
  97440. lpc[i]=r;
  97441. for(j = 0; j < (i>>1); j++) {
  97442. FLAC__double tmp = lpc[j];
  97443. lpc[j] += r * lpc[i-1-j];
  97444. lpc[i-1-j] += r * tmp;
  97445. }
  97446. if(i & 1)
  97447. lpc[j] += lpc[j] * r;
  97448. err *= (1.0 - r * r);
  97449. /* save this order */
  97450. for(j = 0; j <= i; j++)
  97451. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97452. error[i] = err;
  97453. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97454. if(err == 0.0) {
  97455. *max_order = i+1;
  97456. return;
  97457. }
  97458. }
  97459. }
  97460. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97461. {
  97462. unsigned i;
  97463. FLAC__double cmax;
  97464. FLAC__int32 qmax, qmin;
  97465. FLAC__ASSERT(precision > 0);
  97466. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97467. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97468. precision--;
  97469. qmax = 1 << precision;
  97470. qmin = -qmax;
  97471. qmax--;
  97472. /* calc cmax = max( |lp_coeff[i]| ) */
  97473. cmax = 0.0;
  97474. for(i = 0; i < order; i++) {
  97475. const FLAC__double d = fabs(lp_coeff[i]);
  97476. if(d > cmax)
  97477. cmax = d;
  97478. }
  97479. if(cmax <= 0.0) {
  97480. /* => coefficients are all 0, which means our constant-detect didn't work */
  97481. return 2;
  97482. }
  97483. else {
  97484. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97485. const int min_shiftlimit = -max_shiftlimit - 1;
  97486. int log2cmax;
  97487. (void)frexp(cmax, &log2cmax);
  97488. log2cmax--;
  97489. *shift = (int)precision - log2cmax - 1;
  97490. if(*shift > max_shiftlimit)
  97491. *shift = max_shiftlimit;
  97492. else if(*shift < min_shiftlimit)
  97493. return 1;
  97494. }
  97495. if(*shift >= 0) {
  97496. FLAC__double error = 0.0;
  97497. FLAC__int32 q;
  97498. for(i = 0; i < order; i++) {
  97499. error += lp_coeff[i] * (1 << *shift);
  97500. #if 1 /* unfortunately lround() is C99 */
  97501. if(error >= 0.0)
  97502. q = (FLAC__int32)(error + 0.5);
  97503. else
  97504. q = (FLAC__int32)(error - 0.5);
  97505. #else
  97506. q = lround(error);
  97507. #endif
  97508. #ifdef FLAC__OVERFLOW_DETECT
  97509. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97510. 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]);
  97511. else if(q < qmin)
  97512. 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]);
  97513. #endif
  97514. if(q > qmax)
  97515. q = qmax;
  97516. else if(q < qmin)
  97517. q = qmin;
  97518. error -= q;
  97519. qlp_coeff[i] = q;
  97520. }
  97521. }
  97522. /* negative shift is very rare but due to design flaw, negative shift is
  97523. * a NOP in the decoder, so it must be handled specially by scaling down
  97524. * coeffs
  97525. */
  97526. else {
  97527. const int nshift = -(*shift);
  97528. FLAC__double error = 0.0;
  97529. FLAC__int32 q;
  97530. #ifdef DEBUG
  97531. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97532. #endif
  97533. for(i = 0; i < order; i++) {
  97534. error += lp_coeff[i] / (1 << nshift);
  97535. #if 1 /* unfortunately lround() is C99 */
  97536. if(error >= 0.0)
  97537. q = (FLAC__int32)(error + 0.5);
  97538. else
  97539. q = (FLAC__int32)(error - 0.5);
  97540. #else
  97541. q = lround(error);
  97542. #endif
  97543. #ifdef FLAC__OVERFLOW_DETECT
  97544. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97545. 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]);
  97546. else if(q < qmin)
  97547. 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]);
  97548. #endif
  97549. if(q > qmax)
  97550. q = qmax;
  97551. else if(q < qmin)
  97552. q = qmin;
  97553. error -= q;
  97554. qlp_coeff[i] = q;
  97555. }
  97556. *shift = 0;
  97557. }
  97558. return 0;
  97559. }
  97560. 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[])
  97561. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97562. {
  97563. FLAC__int64 sumo;
  97564. unsigned i, j;
  97565. FLAC__int32 sum;
  97566. const FLAC__int32 *history;
  97567. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97568. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97569. for(i=0;i<order;i++)
  97570. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97571. fprintf(stderr,"\n");
  97572. #endif
  97573. FLAC__ASSERT(order > 0);
  97574. for(i = 0; i < data_len; i++) {
  97575. sumo = 0;
  97576. sum = 0;
  97577. history = data;
  97578. for(j = 0; j < order; j++) {
  97579. sum += qlp_coeff[j] * (*(--history));
  97580. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97581. #if defined _MSC_VER
  97582. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97583. 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);
  97584. #else
  97585. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97586. 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);
  97587. #endif
  97588. }
  97589. *(residual++) = *(data++) - (sum >> lp_quantization);
  97590. }
  97591. /* Here's a slower but clearer version:
  97592. for(i = 0; i < data_len; i++) {
  97593. sum = 0;
  97594. for(j = 0; j < order; j++)
  97595. sum += qlp_coeff[j] * data[i-j-1];
  97596. residual[i] = data[i] - (sum >> lp_quantization);
  97597. }
  97598. */
  97599. }
  97600. #else /* fully unrolled version for normal use */
  97601. {
  97602. int i;
  97603. FLAC__int32 sum;
  97604. FLAC__ASSERT(order > 0);
  97605. FLAC__ASSERT(order <= 32);
  97606. /*
  97607. * We do unique versions up to 12th order since that's the subset limit.
  97608. * Also they are roughly ordered to match frequency of occurrence to
  97609. * minimize branching.
  97610. */
  97611. if(order <= 12) {
  97612. if(order > 8) {
  97613. if(order > 10) {
  97614. if(order == 12) {
  97615. for(i = 0; i < (int)data_len; i++) {
  97616. sum = 0;
  97617. sum += qlp_coeff[11] * data[i-12];
  97618. sum += qlp_coeff[10] * data[i-11];
  97619. sum += qlp_coeff[9] * data[i-10];
  97620. sum += qlp_coeff[8] * data[i-9];
  97621. sum += qlp_coeff[7] * data[i-8];
  97622. sum += qlp_coeff[6] * data[i-7];
  97623. sum += qlp_coeff[5] * data[i-6];
  97624. sum += qlp_coeff[4] * data[i-5];
  97625. sum += qlp_coeff[3] * data[i-4];
  97626. sum += qlp_coeff[2] * data[i-3];
  97627. sum += qlp_coeff[1] * data[i-2];
  97628. sum += qlp_coeff[0] * data[i-1];
  97629. residual[i] = data[i] - (sum >> lp_quantization);
  97630. }
  97631. }
  97632. else { /* order == 11 */
  97633. for(i = 0; i < (int)data_len; i++) {
  97634. sum = 0;
  97635. sum += qlp_coeff[10] * data[i-11];
  97636. sum += qlp_coeff[9] * data[i-10];
  97637. sum += qlp_coeff[8] * data[i-9];
  97638. sum += qlp_coeff[7] * data[i-8];
  97639. sum += qlp_coeff[6] * data[i-7];
  97640. sum += qlp_coeff[5] * data[i-6];
  97641. sum += qlp_coeff[4] * data[i-5];
  97642. sum += qlp_coeff[3] * data[i-4];
  97643. sum += qlp_coeff[2] * data[i-3];
  97644. sum += qlp_coeff[1] * data[i-2];
  97645. sum += qlp_coeff[0] * data[i-1];
  97646. residual[i] = data[i] - (sum >> lp_quantization);
  97647. }
  97648. }
  97649. }
  97650. else {
  97651. if(order == 10) {
  97652. for(i = 0; i < (int)data_len; i++) {
  97653. sum = 0;
  97654. sum += qlp_coeff[9] * data[i-10];
  97655. sum += qlp_coeff[8] * data[i-9];
  97656. sum += qlp_coeff[7] * data[i-8];
  97657. sum += qlp_coeff[6] * data[i-7];
  97658. sum += qlp_coeff[5] * data[i-6];
  97659. sum += qlp_coeff[4] * data[i-5];
  97660. sum += qlp_coeff[3] * data[i-4];
  97661. sum += qlp_coeff[2] * data[i-3];
  97662. sum += qlp_coeff[1] * data[i-2];
  97663. sum += qlp_coeff[0] * data[i-1];
  97664. residual[i] = data[i] - (sum >> lp_quantization);
  97665. }
  97666. }
  97667. else { /* order == 9 */
  97668. for(i = 0; i < (int)data_len; i++) {
  97669. sum = 0;
  97670. sum += qlp_coeff[8] * data[i-9];
  97671. sum += qlp_coeff[7] * data[i-8];
  97672. sum += qlp_coeff[6] * data[i-7];
  97673. sum += qlp_coeff[5] * data[i-6];
  97674. sum += qlp_coeff[4] * data[i-5];
  97675. sum += qlp_coeff[3] * data[i-4];
  97676. sum += qlp_coeff[2] * data[i-3];
  97677. sum += qlp_coeff[1] * data[i-2];
  97678. sum += qlp_coeff[0] * data[i-1];
  97679. residual[i] = data[i] - (sum >> lp_quantization);
  97680. }
  97681. }
  97682. }
  97683. }
  97684. else if(order > 4) {
  97685. if(order > 6) {
  97686. if(order == 8) {
  97687. for(i = 0; i < (int)data_len; i++) {
  97688. sum = 0;
  97689. sum += qlp_coeff[7] * data[i-8];
  97690. sum += qlp_coeff[6] * data[i-7];
  97691. sum += qlp_coeff[5] * data[i-6];
  97692. sum += qlp_coeff[4] * data[i-5];
  97693. sum += qlp_coeff[3] * data[i-4];
  97694. sum += qlp_coeff[2] * data[i-3];
  97695. sum += qlp_coeff[1] * data[i-2];
  97696. sum += qlp_coeff[0] * data[i-1];
  97697. residual[i] = data[i] - (sum >> lp_quantization);
  97698. }
  97699. }
  97700. else { /* order == 7 */
  97701. for(i = 0; i < (int)data_len; i++) {
  97702. sum = 0;
  97703. sum += qlp_coeff[6] * data[i-7];
  97704. sum += qlp_coeff[5] * data[i-6];
  97705. sum += qlp_coeff[4] * data[i-5];
  97706. sum += qlp_coeff[3] * data[i-4];
  97707. sum += qlp_coeff[2] * data[i-3];
  97708. sum += qlp_coeff[1] * data[i-2];
  97709. sum += qlp_coeff[0] * data[i-1];
  97710. residual[i] = data[i] - (sum >> lp_quantization);
  97711. }
  97712. }
  97713. }
  97714. else {
  97715. if(order == 6) {
  97716. for(i = 0; i < (int)data_len; i++) {
  97717. sum = 0;
  97718. sum += qlp_coeff[5] * data[i-6];
  97719. sum += qlp_coeff[4] * data[i-5];
  97720. sum += qlp_coeff[3] * data[i-4];
  97721. sum += qlp_coeff[2] * data[i-3];
  97722. sum += qlp_coeff[1] * data[i-2];
  97723. sum += qlp_coeff[0] * data[i-1];
  97724. residual[i] = data[i] - (sum >> lp_quantization);
  97725. }
  97726. }
  97727. else { /* order == 5 */
  97728. for(i = 0; i < (int)data_len; i++) {
  97729. sum = 0;
  97730. sum += qlp_coeff[4] * data[i-5];
  97731. sum += qlp_coeff[3] * data[i-4];
  97732. sum += qlp_coeff[2] * data[i-3];
  97733. sum += qlp_coeff[1] * data[i-2];
  97734. sum += qlp_coeff[0] * data[i-1];
  97735. residual[i] = data[i] - (sum >> lp_quantization);
  97736. }
  97737. }
  97738. }
  97739. }
  97740. else {
  97741. if(order > 2) {
  97742. if(order == 4) {
  97743. for(i = 0; i < (int)data_len; i++) {
  97744. sum = 0;
  97745. sum += qlp_coeff[3] * data[i-4];
  97746. sum += qlp_coeff[2] * data[i-3];
  97747. sum += qlp_coeff[1] * data[i-2];
  97748. sum += qlp_coeff[0] * data[i-1];
  97749. residual[i] = data[i] - (sum >> lp_quantization);
  97750. }
  97751. }
  97752. else { /* order == 3 */
  97753. for(i = 0; i < (int)data_len; i++) {
  97754. sum = 0;
  97755. sum += qlp_coeff[2] * data[i-3];
  97756. sum += qlp_coeff[1] * data[i-2];
  97757. sum += qlp_coeff[0] * data[i-1];
  97758. residual[i] = data[i] - (sum >> lp_quantization);
  97759. }
  97760. }
  97761. }
  97762. else {
  97763. if(order == 2) {
  97764. for(i = 0; i < (int)data_len; i++) {
  97765. sum = 0;
  97766. sum += qlp_coeff[1] * data[i-2];
  97767. sum += qlp_coeff[0] * data[i-1];
  97768. residual[i] = data[i] - (sum >> lp_quantization);
  97769. }
  97770. }
  97771. else { /* order == 1 */
  97772. for(i = 0; i < (int)data_len; i++)
  97773. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97774. }
  97775. }
  97776. }
  97777. }
  97778. else { /* order > 12 */
  97779. for(i = 0; i < (int)data_len; i++) {
  97780. sum = 0;
  97781. switch(order) {
  97782. case 32: sum += qlp_coeff[31] * data[i-32];
  97783. case 31: sum += qlp_coeff[30] * data[i-31];
  97784. case 30: sum += qlp_coeff[29] * data[i-30];
  97785. case 29: sum += qlp_coeff[28] * data[i-29];
  97786. case 28: sum += qlp_coeff[27] * data[i-28];
  97787. case 27: sum += qlp_coeff[26] * data[i-27];
  97788. case 26: sum += qlp_coeff[25] * data[i-26];
  97789. case 25: sum += qlp_coeff[24] * data[i-25];
  97790. case 24: sum += qlp_coeff[23] * data[i-24];
  97791. case 23: sum += qlp_coeff[22] * data[i-23];
  97792. case 22: sum += qlp_coeff[21] * data[i-22];
  97793. case 21: sum += qlp_coeff[20] * data[i-21];
  97794. case 20: sum += qlp_coeff[19] * data[i-20];
  97795. case 19: sum += qlp_coeff[18] * data[i-19];
  97796. case 18: sum += qlp_coeff[17] * data[i-18];
  97797. case 17: sum += qlp_coeff[16] * data[i-17];
  97798. case 16: sum += qlp_coeff[15] * data[i-16];
  97799. case 15: sum += qlp_coeff[14] * data[i-15];
  97800. case 14: sum += qlp_coeff[13] * data[i-14];
  97801. case 13: sum += qlp_coeff[12] * data[i-13];
  97802. sum += qlp_coeff[11] * data[i-12];
  97803. sum += qlp_coeff[10] * data[i-11];
  97804. sum += qlp_coeff[ 9] * data[i-10];
  97805. sum += qlp_coeff[ 8] * data[i- 9];
  97806. sum += qlp_coeff[ 7] * data[i- 8];
  97807. sum += qlp_coeff[ 6] * data[i- 7];
  97808. sum += qlp_coeff[ 5] * data[i- 6];
  97809. sum += qlp_coeff[ 4] * data[i- 5];
  97810. sum += qlp_coeff[ 3] * data[i- 4];
  97811. sum += qlp_coeff[ 2] * data[i- 3];
  97812. sum += qlp_coeff[ 1] * data[i- 2];
  97813. sum += qlp_coeff[ 0] * data[i- 1];
  97814. }
  97815. residual[i] = data[i] - (sum >> lp_quantization);
  97816. }
  97817. }
  97818. }
  97819. #endif
  97820. 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[])
  97821. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97822. {
  97823. unsigned i, j;
  97824. FLAC__int64 sum;
  97825. const FLAC__int32 *history;
  97826. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97827. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97828. for(i=0;i<order;i++)
  97829. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97830. fprintf(stderr,"\n");
  97831. #endif
  97832. FLAC__ASSERT(order > 0);
  97833. for(i = 0; i < data_len; i++) {
  97834. sum = 0;
  97835. history = data;
  97836. for(j = 0; j < order; j++)
  97837. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97838. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97839. #if defined _MSC_VER
  97840. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97841. #else
  97842. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97843. #endif
  97844. break;
  97845. }
  97846. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97847. #if defined _MSC_VER
  97848. 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));
  97849. #else
  97850. 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)));
  97851. #endif
  97852. break;
  97853. }
  97854. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97855. }
  97856. }
  97857. #else /* fully unrolled version for normal use */
  97858. {
  97859. int i;
  97860. FLAC__int64 sum;
  97861. FLAC__ASSERT(order > 0);
  97862. FLAC__ASSERT(order <= 32);
  97863. /*
  97864. * We do unique versions up to 12th order since that's the subset limit.
  97865. * Also they are roughly ordered to match frequency of occurrence to
  97866. * minimize branching.
  97867. */
  97868. if(order <= 12) {
  97869. if(order > 8) {
  97870. if(order > 10) {
  97871. if(order == 12) {
  97872. for(i = 0; i < (int)data_len; i++) {
  97873. sum = 0;
  97874. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97875. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97876. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97877. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97878. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97879. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97880. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97881. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97882. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97883. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97884. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97885. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97886. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97887. }
  97888. }
  97889. else { /* order == 11 */
  97890. for(i = 0; i < (int)data_len; i++) {
  97891. sum = 0;
  97892. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97893. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97894. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97895. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97896. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97897. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97898. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97899. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97900. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97901. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97902. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97903. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97904. }
  97905. }
  97906. }
  97907. else {
  97908. if(order == 10) {
  97909. for(i = 0; i < (int)data_len; i++) {
  97910. sum = 0;
  97911. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97912. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97913. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97914. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97915. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97916. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97917. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97918. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97919. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97920. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97921. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97922. }
  97923. }
  97924. else { /* order == 9 */
  97925. for(i = 0; i < (int)data_len; i++) {
  97926. sum = 0;
  97927. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97928. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97929. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97930. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97931. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97932. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97933. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97934. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97935. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97936. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97937. }
  97938. }
  97939. }
  97940. }
  97941. else if(order > 4) {
  97942. if(order > 6) {
  97943. if(order == 8) {
  97944. for(i = 0; i < (int)data_len; i++) {
  97945. sum = 0;
  97946. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97947. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97948. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97949. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97950. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97951. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97952. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97953. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97954. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97955. }
  97956. }
  97957. else { /* order == 7 */
  97958. for(i = 0; i < (int)data_len; i++) {
  97959. sum = 0;
  97960. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97961. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97962. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97963. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97964. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97965. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97966. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97967. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97968. }
  97969. }
  97970. }
  97971. else {
  97972. if(order == 6) {
  97973. for(i = 0; i < (int)data_len; i++) {
  97974. sum = 0;
  97975. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97976. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97977. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97978. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97979. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97980. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97981. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97982. }
  97983. }
  97984. else { /* order == 5 */
  97985. for(i = 0; i < (int)data_len; i++) {
  97986. sum = 0;
  97987. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97988. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97989. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97990. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97991. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97992. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97993. }
  97994. }
  97995. }
  97996. }
  97997. else {
  97998. if(order > 2) {
  97999. if(order == 4) {
  98000. for(i = 0; i < (int)data_len; i++) {
  98001. sum = 0;
  98002. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98003. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98004. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98005. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98006. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98007. }
  98008. }
  98009. else { /* order == 3 */
  98010. for(i = 0; i < (int)data_len; i++) {
  98011. sum = 0;
  98012. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98013. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98014. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98015. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98016. }
  98017. }
  98018. }
  98019. else {
  98020. if(order == 2) {
  98021. for(i = 0; i < (int)data_len; i++) {
  98022. sum = 0;
  98023. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98024. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98025. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98026. }
  98027. }
  98028. else { /* order == 1 */
  98029. for(i = 0; i < (int)data_len; i++)
  98030. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98031. }
  98032. }
  98033. }
  98034. }
  98035. else { /* order > 12 */
  98036. for(i = 0; i < (int)data_len; i++) {
  98037. sum = 0;
  98038. switch(order) {
  98039. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98040. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98041. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98042. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98043. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98044. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98045. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98046. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98047. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98048. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98049. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98050. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98051. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98052. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98053. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98054. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98055. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98056. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98057. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98058. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98059. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98060. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98061. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98062. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98063. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98064. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98065. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98066. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98067. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98068. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98069. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98070. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98071. }
  98072. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98073. }
  98074. }
  98075. }
  98076. #endif
  98077. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98078. 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[])
  98079. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98080. {
  98081. FLAC__int64 sumo;
  98082. unsigned i, j;
  98083. FLAC__int32 sum;
  98084. const FLAC__int32 *r = residual, *history;
  98085. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98086. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98087. for(i=0;i<order;i++)
  98088. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98089. fprintf(stderr,"\n");
  98090. #endif
  98091. FLAC__ASSERT(order > 0);
  98092. for(i = 0; i < data_len; i++) {
  98093. sumo = 0;
  98094. sum = 0;
  98095. history = data;
  98096. for(j = 0; j < order; j++) {
  98097. sum += qlp_coeff[j] * (*(--history));
  98098. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  98099. #if defined _MSC_VER
  98100. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  98101. 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);
  98102. #else
  98103. if(sumo > 2147483647ll || sumo < -2147483648ll)
  98104. 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);
  98105. #endif
  98106. }
  98107. *(data++) = *(r++) + (sum >> lp_quantization);
  98108. }
  98109. /* Here's a slower but clearer version:
  98110. for(i = 0; i < data_len; i++) {
  98111. sum = 0;
  98112. for(j = 0; j < order; j++)
  98113. sum += qlp_coeff[j] * data[i-j-1];
  98114. data[i] = residual[i] + (sum >> lp_quantization);
  98115. }
  98116. */
  98117. }
  98118. #else /* fully unrolled version for normal use */
  98119. {
  98120. int i;
  98121. FLAC__int32 sum;
  98122. FLAC__ASSERT(order > 0);
  98123. FLAC__ASSERT(order <= 32);
  98124. /*
  98125. * We do unique versions up to 12th order since that's the subset limit.
  98126. * Also they are roughly ordered to match frequency of occurrence to
  98127. * minimize branching.
  98128. */
  98129. if(order <= 12) {
  98130. if(order > 8) {
  98131. if(order > 10) {
  98132. if(order == 12) {
  98133. for(i = 0; i < (int)data_len; i++) {
  98134. sum = 0;
  98135. sum += qlp_coeff[11] * data[i-12];
  98136. sum += qlp_coeff[10] * data[i-11];
  98137. sum += qlp_coeff[9] * data[i-10];
  98138. sum += qlp_coeff[8] * data[i-9];
  98139. sum += qlp_coeff[7] * data[i-8];
  98140. sum += qlp_coeff[6] * data[i-7];
  98141. sum += qlp_coeff[5] * data[i-6];
  98142. sum += qlp_coeff[4] * data[i-5];
  98143. sum += qlp_coeff[3] * data[i-4];
  98144. sum += qlp_coeff[2] * data[i-3];
  98145. sum += qlp_coeff[1] * data[i-2];
  98146. sum += qlp_coeff[0] * data[i-1];
  98147. data[i] = residual[i] + (sum >> lp_quantization);
  98148. }
  98149. }
  98150. else { /* order == 11 */
  98151. for(i = 0; i < (int)data_len; i++) {
  98152. sum = 0;
  98153. sum += qlp_coeff[10] * data[i-11];
  98154. sum += qlp_coeff[9] * data[i-10];
  98155. sum += qlp_coeff[8] * data[i-9];
  98156. sum += qlp_coeff[7] * data[i-8];
  98157. sum += qlp_coeff[6] * data[i-7];
  98158. sum += qlp_coeff[5] * data[i-6];
  98159. sum += qlp_coeff[4] * data[i-5];
  98160. sum += qlp_coeff[3] * data[i-4];
  98161. sum += qlp_coeff[2] * data[i-3];
  98162. sum += qlp_coeff[1] * data[i-2];
  98163. sum += qlp_coeff[0] * data[i-1];
  98164. data[i] = residual[i] + (sum >> lp_quantization);
  98165. }
  98166. }
  98167. }
  98168. else {
  98169. if(order == 10) {
  98170. for(i = 0; i < (int)data_len; i++) {
  98171. sum = 0;
  98172. sum += qlp_coeff[9] * data[i-10];
  98173. sum += qlp_coeff[8] * data[i-9];
  98174. sum += qlp_coeff[7] * data[i-8];
  98175. sum += qlp_coeff[6] * data[i-7];
  98176. sum += qlp_coeff[5] * data[i-6];
  98177. sum += qlp_coeff[4] * data[i-5];
  98178. sum += qlp_coeff[3] * data[i-4];
  98179. sum += qlp_coeff[2] * data[i-3];
  98180. sum += qlp_coeff[1] * data[i-2];
  98181. sum += qlp_coeff[0] * data[i-1];
  98182. data[i] = residual[i] + (sum >> lp_quantization);
  98183. }
  98184. }
  98185. else { /* order == 9 */
  98186. for(i = 0; i < (int)data_len; i++) {
  98187. sum = 0;
  98188. sum += qlp_coeff[8] * data[i-9];
  98189. sum += qlp_coeff[7] * data[i-8];
  98190. sum += qlp_coeff[6] * data[i-7];
  98191. sum += qlp_coeff[5] * data[i-6];
  98192. sum += qlp_coeff[4] * data[i-5];
  98193. sum += qlp_coeff[3] * data[i-4];
  98194. sum += qlp_coeff[2] * data[i-3];
  98195. sum += qlp_coeff[1] * data[i-2];
  98196. sum += qlp_coeff[0] * data[i-1];
  98197. data[i] = residual[i] + (sum >> lp_quantization);
  98198. }
  98199. }
  98200. }
  98201. }
  98202. else if(order > 4) {
  98203. if(order > 6) {
  98204. if(order == 8) {
  98205. for(i = 0; i < (int)data_len; i++) {
  98206. sum = 0;
  98207. sum += qlp_coeff[7] * data[i-8];
  98208. sum += qlp_coeff[6] * data[i-7];
  98209. sum += qlp_coeff[5] * data[i-6];
  98210. sum += qlp_coeff[4] * data[i-5];
  98211. sum += qlp_coeff[3] * data[i-4];
  98212. sum += qlp_coeff[2] * data[i-3];
  98213. sum += qlp_coeff[1] * data[i-2];
  98214. sum += qlp_coeff[0] * data[i-1];
  98215. data[i] = residual[i] + (sum >> lp_quantization);
  98216. }
  98217. }
  98218. else { /* order == 7 */
  98219. for(i = 0; i < (int)data_len; i++) {
  98220. sum = 0;
  98221. sum += qlp_coeff[6] * data[i-7];
  98222. sum += qlp_coeff[5] * data[i-6];
  98223. sum += qlp_coeff[4] * data[i-5];
  98224. sum += qlp_coeff[3] * data[i-4];
  98225. sum += qlp_coeff[2] * data[i-3];
  98226. sum += qlp_coeff[1] * data[i-2];
  98227. sum += qlp_coeff[0] * data[i-1];
  98228. data[i] = residual[i] + (sum >> lp_quantization);
  98229. }
  98230. }
  98231. }
  98232. else {
  98233. if(order == 6) {
  98234. for(i = 0; i < (int)data_len; i++) {
  98235. sum = 0;
  98236. sum += qlp_coeff[5] * data[i-6];
  98237. sum += qlp_coeff[4] * data[i-5];
  98238. sum += qlp_coeff[3] * data[i-4];
  98239. sum += qlp_coeff[2] * data[i-3];
  98240. sum += qlp_coeff[1] * data[i-2];
  98241. sum += qlp_coeff[0] * data[i-1];
  98242. data[i] = residual[i] + (sum >> lp_quantization);
  98243. }
  98244. }
  98245. else { /* order == 5 */
  98246. for(i = 0; i < (int)data_len; i++) {
  98247. sum = 0;
  98248. sum += qlp_coeff[4] * data[i-5];
  98249. sum += qlp_coeff[3] * data[i-4];
  98250. sum += qlp_coeff[2] * data[i-3];
  98251. sum += qlp_coeff[1] * data[i-2];
  98252. sum += qlp_coeff[0] * data[i-1];
  98253. data[i] = residual[i] + (sum >> lp_quantization);
  98254. }
  98255. }
  98256. }
  98257. }
  98258. else {
  98259. if(order > 2) {
  98260. if(order == 4) {
  98261. for(i = 0; i < (int)data_len; i++) {
  98262. sum = 0;
  98263. sum += qlp_coeff[3] * data[i-4];
  98264. sum += qlp_coeff[2] * data[i-3];
  98265. sum += qlp_coeff[1] * data[i-2];
  98266. sum += qlp_coeff[0] * data[i-1];
  98267. data[i] = residual[i] + (sum >> lp_quantization);
  98268. }
  98269. }
  98270. else { /* order == 3 */
  98271. for(i = 0; i < (int)data_len; i++) {
  98272. sum = 0;
  98273. sum += qlp_coeff[2] * data[i-3];
  98274. sum += qlp_coeff[1] * data[i-2];
  98275. sum += qlp_coeff[0] * data[i-1];
  98276. data[i] = residual[i] + (sum >> lp_quantization);
  98277. }
  98278. }
  98279. }
  98280. else {
  98281. if(order == 2) {
  98282. for(i = 0; i < (int)data_len; i++) {
  98283. sum = 0;
  98284. sum += qlp_coeff[1] * data[i-2];
  98285. sum += qlp_coeff[0] * data[i-1];
  98286. data[i] = residual[i] + (sum >> lp_quantization);
  98287. }
  98288. }
  98289. else { /* order == 1 */
  98290. for(i = 0; i < (int)data_len; i++)
  98291. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98292. }
  98293. }
  98294. }
  98295. }
  98296. else { /* order > 12 */
  98297. for(i = 0; i < (int)data_len; i++) {
  98298. sum = 0;
  98299. switch(order) {
  98300. case 32: sum += qlp_coeff[31] * data[i-32];
  98301. case 31: sum += qlp_coeff[30] * data[i-31];
  98302. case 30: sum += qlp_coeff[29] * data[i-30];
  98303. case 29: sum += qlp_coeff[28] * data[i-29];
  98304. case 28: sum += qlp_coeff[27] * data[i-28];
  98305. case 27: sum += qlp_coeff[26] * data[i-27];
  98306. case 26: sum += qlp_coeff[25] * data[i-26];
  98307. case 25: sum += qlp_coeff[24] * data[i-25];
  98308. case 24: sum += qlp_coeff[23] * data[i-24];
  98309. case 23: sum += qlp_coeff[22] * data[i-23];
  98310. case 22: sum += qlp_coeff[21] * data[i-22];
  98311. case 21: sum += qlp_coeff[20] * data[i-21];
  98312. case 20: sum += qlp_coeff[19] * data[i-20];
  98313. case 19: sum += qlp_coeff[18] * data[i-19];
  98314. case 18: sum += qlp_coeff[17] * data[i-18];
  98315. case 17: sum += qlp_coeff[16] * data[i-17];
  98316. case 16: sum += qlp_coeff[15] * data[i-16];
  98317. case 15: sum += qlp_coeff[14] * data[i-15];
  98318. case 14: sum += qlp_coeff[13] * data[i-14];
  98319. case 13: sum += qlp_coeff[12] * data[i-13];
  98320. sum += qlp_coeff[11] * data[i-12];
  98321. sum += qlp_coeff[10] * data[i-11];
  98322. sum += qlp_coeff[ 9] * data[i-10];
  98323. sum += qlp_coeff[ 8] * data[i- 9];
  98324. sum += qlp_coeff[ 7] * data[i- 8];
  98325. sum += qlp_coeff[ 6] * data[i- 7];
  98326. sum += qlp_coeff[ 5] * data[i- 6];
  98327. sum += qlp_coeff[ 4] * data[i- 5];
  98328. sum += qlp_coeff[ 3] * data[i- 4];
  98329. sum += qlp_coeff[ 2] * data[i- 3];
  98330. sum += qlp_coeff[ 1] * data[i- 2];
  98331. sum += qlp_coeff[ 0] * data[i- 1];
  98332. }
  98333. data[i] = residual[i] + (sum >> lp_quantization);
  98334. }
  98335. }
  98336. }
  98337. #endif
  98338. 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[])
  98339. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98340. {
  98341. unsigned i, j;
  98342. FLAC__int64 sum;
  98343. const FLAC__int32 *r = residual, *history;
  98344. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98345. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98346. for(i=0;i<order;i++)
  98347. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98348. fprintf(stderr,"\n");
  98349. #endif
  98350. FLAC__ASSERT(order > 0);
  98351. for(i = 0; i < data_len; i++) {
  98352. sum = 0;
  98353. history = data;
  98354. for(j = 0; j < order; j++)
  98355. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98356. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98357. #ifdef _MSC_VER
  98358. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98359. #else
  98360. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98361. #endif
  98362. break;
  98363. }
  98364. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98365. #ifdef _MSC_VER
  98366. 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));
  98367. #else
  98368. 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)));
  98369. #endif
  98370. break;
  98371. }
  98372. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98373. }
  98374. }
  98375. #else /* fully unrolled version for normal use */
  98376. {
  98377. int i;
  98378. FLAC__int64 sum;
  98379. FLAC__ASSERT(order > 0);
  98380. FLAC__ASSERT(order <= 32);
  98381. /*
  98382. * We do unique versions up to 12th order since that's the subset limit.
  98383. * Also they are roughly ordered to match frequency of occurrence to
  98384. * minimize branching.
  98385. */
  98386. if(order <= 12) {
  98387. if(order > 8) {
  98388. if(order > 10) {
  98389. if(order == 12) {
  98390. for(i = 0; i < (int)data_len; i++) {
  98391. sum = 0;
  98392. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98393. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98394. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98395. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98396. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98397. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98398. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98399. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98400. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98401. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98402. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98403. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98404. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98405. }
  98406. }
  98407. else { /* order == 11 */
  98408. for(i = 0; i < (int)data_len; i++) {
  98409. sum = 0;
  98410. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98411. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98412. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98413. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98414. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98415. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98416. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98417. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98418. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98419. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98420. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98421. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98422. }
  98423. }
  98424. }
  98425. else {
  98426. if(order == 10) {
  98427. for(i = 0; i < (int)data_len; i++) {
  98428. sum = 0;
  98429. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98430. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98431. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98432. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98433. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98434. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98435. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98436. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98437. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98438. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98439. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98440. }
  98441. }
  98442. else { /* order == 9 */
  98443. for(i = 0; i < (int)data_len; i++) {
  98444. sum = 0;
  98445. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98446. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98447. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98448. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98449. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98450. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98451. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98452. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98453. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98454. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98455. }
  98456. }
  98457. }
  98458. }
  98459. else if(order > 4) {
  98460. if(order > 6) {
  98461. if(order == 8) {
  98462. for(i = 0; i < (int)data_len; i++) {
  98463. sum = 0;
  98464. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98465. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98466. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98467. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98468. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98469. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98470. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98471. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98472. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98473. }
  98474. }
  98475. else { /* order == 7 */
  98476. for(i = 0; i < (int)data_len; i++) {
  98477. sum = 0;
  98478. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98479. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98480. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98481. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98482. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98483. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98484. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98485. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98486. }
  98487. }
  98488. }
  98489. else {
  98490. if(order == 6) {
  98491. for(i = 0; i < (int)data_len; i++) {
  98492. sum = 0;
  98493. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98494. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98495. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98496. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98497. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98498. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98499. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98500. }
  98501. }
  98502. else { /* order == 5 */
  98503. for(i = 0; i < (int)data_len; i++) {
  98504. sum = 0;
  98505. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98506. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98507. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98508. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98509. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98510. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98511. }
  98512. }
  98513. }
  98514. }
  98515. else {
  98516. if(order > 2) {
  98517. if(order == 4) {
  98518. for(i = 0; i < (int)data_len; i++) {
  98519. sum = 0;
  98520. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98521. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98522. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98523. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98524. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98525. }
  98526. }
  98527. else { /* order == 3 */
  98528. for(i = 0; i < (int)data_len; i++) {
  98529. sum = 0;
  98530. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98531. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98532. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98533. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98534. }
  98535. }
  98536. }
  98537. else {
  98538. if(order == 2) {
  98539. for(i = 0; i < (int)data_len; i++) {
  98540. sum = 0;
  98541. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98542. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98543. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98544. }
  98545. }
  98546. else { /* order == 1 */
  98547. for(i = 0; i < (int)data_len; i++)
  98548. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98549. }
  98550. }
  98551. }
  98552. }
  98553. else { /* order > 12 */
  98554. for(i = 0; i < (int)data_len; i++) {
  98555. sum = 0;
  98556. switch(order) {
  98557. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98558. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98559. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98560. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98561. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98562. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98563. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98564. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98565. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98566. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98567. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98568. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98569. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98570. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98571. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98572. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98573. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98574. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98575. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98576. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98577. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98578. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98579. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98580. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98581. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98582. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98583. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98584. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98585. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98586. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98587. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98588. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98589. }
  98590. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98591. }
  98592. }
  98593. }
  98594. #endif
  98595. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98596. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98597. {
  98598. FLAC__double error_scale;
  98599. FLAC__ASSERT(total_samples > 0);
  98600. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98601. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98602. }
  98603. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98604. {
  98605. if(lpc_error > 0.0) {
  98606. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98607. if(bps >= 0.0)
  98608. return bps;
  98609. else
  98610. return 0.0;
  98611. }
  98612. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98613. return 1e32;
  98614. }
  98615. else {
  98616. return 0.0;
  98617. }
  98618. }
  98619. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98620. {
  98621. 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 */
  98622. FLAC__double bits, best_bits, error_scale;
  98623. FLAC__ASSERT(max_order > 0);
  98624. FLAC__ASSERT(total_samples > 0);
  98625. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98626. best_index = 0;
  98627. best_bits = (unsigned)(-1);
  98628. for(index = 0, order = 1; index < max_order; index++, order++) {
  98629. 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);
  98630. if(bits < best_bits) {
  98631. best_index = index;
  98632. best_bits = bits;
  98633. }
  98634. }
  98635. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98636. }
  98637. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98638. #endif
  98639. /*** End of inlined file: lpc_flac.c ***/
  98640. /*** Start of inlined file: md5.c ***/
  98641. /*** Start of inlined file: juce_FlacHeader.h ***/
  98642. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98643. // tasks..
  98644. #define VERSION "1.2.1"
  98645. #define FLAC__NO_DLL 1
  98646. #if JUCE_MSVC
  98647. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98648. #endif
  98649. #if JUCE_MAC
  98650. #define FLAC__SYS_DARWIN 1
  98651. #endif
  98652. /*** End of inlined file: juce_FlacHeader.h ***/
  98653. #if JUCE_USE_FLAC
  98654. #if HAVE_CONFIG_H
  98655. # include <config.h>
  98656. #endif
  98657. #include <stdlib.h> /* for malloc() */
  98658. #include <string.h> /* for memcpy() */
  98659. /*** Start of inlined file: md5.h ***/
  98660. #ifndef FLAC__PRIVATE__MD5_H
  98661. #define FLAC__PRIVATE__MD5_H
  98662. /*
  98663. * This is the header file for the MD5 message-digest algorithm.
  98664. * The algorithm is due to Ron Rivest. This code was
  98665. * written by Colin Plumb in 1993, no copyright is claimed.
  98666. * This code is in the public domain; do with it what you wish.
  98667. *
  98668. * Equivalent code is available from RSA Data Security, Inc.
  98669. * This code has been tested against that, and is equivalent,
  98670. * except that you don't need to include two pages of legalese
  98671. * with every copy.
  98672. *
  98673. * To compute the message digest of a chunk of bytes, declare an
  98674. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98675. * needed on buffers full of bytes, and then call MD5Final, which
  98676. * will fill a supplied 16-byte array with the digest.
  98677. *
  98678. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98679. * header definitions; now uses stuff from dpkg's config.h
  98680. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98681. * Still in the public domain.
  98682. *
  98683. * Josh Coalson: made some changes to integrate with libFLAC.
  98684. * Still in the public domain, with no warranty.
  98685. */
  98686. typedef struct {
  98687. FLAC__uint32 in[16];
  98688. FLAC__uint32 buf[4];
  98689. FLAC__uint32 bytes[2];
  98690. FLAC__byte *internal_buf;
  98691. size_t capacity;
  98692. } FLAC__MD5Context;
  98693. void FLAC__MD5Init(FLAC__MD5Context *context);
  98694. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98695. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98696. #endif
  98697. /*** End of inlined file: md5.h ***/
  98698. #ifndef FLaC__INLINE
  98699. #define FLaC__INLINE
  98700. #endif
  98701. /*
  98702. * This code implements the MD5 message-digest algorithm.
  98703. * The algorithm is due to Ron Rivest. This code was
  98704. * written by Colin Plumb in 1993, no copyright is claimed.
  98705. * This code is in the public domain; do with it what you wish.
  98706. *
  98707. * Equivalent code is available from RSA Data Security, Inc.
  98708. * This code has been tested against that, and is equivalent,
  98709. * except that you don't need to include two pages of legalese
  98710. * with every copy.
  98711. *
  98712. * To compute the message digest of a chunk of bytes, declare an
  98713. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98714. * needed on buffers full of bytes, and then call MD5Final, which
  98715. * will fill a supplied 16-byte array with the digest.
  98716. *
  98717. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98718. * definitions; now uses stuff from dpkg's config.h.
  98719. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98720. * Still in the public domain.
  98721. *
  98722. * Josh Coalson: made some changes to integrate with libFLAC.
  98723. * Still in the public domain.
  98724. */
  98725. /* The four core functions - F1 is optimized somewhat */
  98726. /* #define F1(x, y, z) (x & y | ~x & z) */
  98727. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98728. #define F2(x, y, z) F1(z, x, y)
  98729. #define F3(x, y, z) (x ^ y ^ z)
  98730. #define F4(x, y, z) (y ^ (x | ~z))
  98731. /* This is the central step in the MD5 algorithm. */
  98732. #define MD5STEP(f,w,x,y,z,in,s) \
  98733. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98734. /*
  98735. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98736. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98737. * the data and converts bytes into longwords for this routine.
  98738. */
  98739. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98740. {
  98741. register FLAC__uint32 a, b, c, d;
  98742. a = buf[0];
  98743. b = buf[1];
  98744. c = buf[2];
  98745. d = buf[3];
  98746. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98747. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98748. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98749. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98750. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98751. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98752. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98753. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98754. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98755. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98756. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98757. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98758. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98759. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98760. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98761. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98762. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98763. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98764. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98765. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98766. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98767. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98768. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98769. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98770. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98771. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98772. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98773. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98774. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98775. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98776. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98777. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98778. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98779. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98780. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98781. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98782. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98783. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98784. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98785. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98786. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98787. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98788. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98789. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98790. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98791. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98792. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98793. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98794. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98795. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98796. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98797. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98798. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98799. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98800. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98801. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98802. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98803. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98804. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98805. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98806. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98807. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98808. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98809. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98810. buf[0] += a;
  98811. buf[1] += b;
  98812. buf[2] += c;
  98813. buf[3] += d;
  98814. }
  98815. #if WORDS_BIGENDIAN
  98816. //@@@@@@ OPT: use bswap/intrinsics
  98817. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98818. {
  98819. register FLAC__uint32 x;
  98820. do {
  98821. x = *buf;
  98822. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98823. *buf++ = (x >> 16) | (x << 16);
  98824. } while (--words);
  98825. }
  98826. static void byteSwapX16(FLAC__uint32 *buf)
  98827. {
  98828. register FLAC__uint32 x;
  98829. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98830. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98831. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98832. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98833. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98834. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98835. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98836. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98837. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98838. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98839. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98840. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98841. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98842. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98843. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98844. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98845. }
  98846. #else
  98847. #define byteSwap(buf, words)
  98848. #define byteSwapX16(buf)
  98849. #endif
  98850. /*
  98851. * Update context to reflect the concatenation of another buffer full
  98852. * of bytes.
  98853. */
  98854. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98855. {
  98856. FLAC__uint32 t;
  98857. /* Update byte count */
  98858. t = ctx->bytes[0];
  98859. if ((ctx->bytes[0] = t + len) < t)
  98860. ctx->bytes[1]++; /* Carry from low to high */
  98861. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98862. if (t > len) {
  98863. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98864. return;
  98865. }
  98866. /* First chunk is an odd size */
  98867. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98868. byteSwapX16(ctx->in);
  98869. FLAC__MD5Transform(ctx->buf, ctx->in);
  98870. buf += t;
  98871. len -= t;
  98872. /* Process data in 64-byte chunks */
  98873. while (len >= 64) {
  98874. memcpy(ctx->in, buf, 64);
  98875. byteSwapX16(ctx->in);
  98876. FLAC__MD5Transform(ctx->buf, ctx->in);
  98877. buf += 64;
  98878. len -= 64;
  98879. }
  98880. /* Handle any remaining bytes of data. */
  98881. memcpy(ctx->in, buf, len);
  98882. }
  98883. /*
  98884. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98885. * initialization constants.
  98886. */
  98887. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98888. {
  98889. ctx->buf[0] = 0x67452301;
  98890. ctx->buf[1] = 0xefcdab89;
  98891. ctx->buf[2] = 0x98badcfe;
  98892. ctx->buf[3] = 0x10325476;
  98893. ctx->bytes[0] = 0;
  98894. ctx->bytes[1] = 0;
  98895. ctx->internal_buf = 0;
  98896. ctx->capacity = 0;
  98897. }
  98898. /*
  98899. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98900. * 1 0* (64-bit count of bits processed, MSB-first)
  98901. */
  98902. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98903. {
  98904. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98905. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98906. /* Set the first char of padding to 0x80. There is always room. */
  98907. *p++ = 0x80;
  98908. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98909. count = 56 - 1 - count;
  98910. if (count < 0) { /* Padding forces an extra block */
  98911. memset(p, 0, count + 8);
  98912. byteSwapX16(ctx->in);
  98913. FLAC__MD5Transform(ctx->buf, ctx->in);
  98914. p = (FLAC__byte *)ctx->in;
  98915. count = 56;
  98916. }
  98917. memset(p, 0, count);
  98918. byteSwap(ctx->in, 14);
  98919. /* Append length in bits and transform */
  98920. ctx->in[14] = ctx->bytes[0] << 3;
  98921. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98922. FLAC__MD5Transform(ctx->buf, ctx->in);
  98923. byteSwap(ctx->buf, 4);
  98924. memcpy(digest, ctx->buf, 16);
  98925. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98926. if(0 != ctx->internal_buf) {
  98927. free(ctx->internal_buf);
  98928. ctx->internal_buf = 0;
  98929. ctx->capacity = 0;
  98930. }
  98931. }
  98932. /*
  98933. * Convert the incoming audio signal to a byte stream
  98934. */
  98935. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98936. {
  98937. unsigned channel, sample;
  98938. register FLAC__int32 a_word;
  98939. register FLAC__byte *buf_ = buf;
  98940. #if WORDS_BIGENDIAN
  98941. #else
  98942. if(channels == 2 && bytes_per_sample == 2) {
  98943. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98944. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98945. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98946. *buf1_ = (FLAC__int16)signal[1][sample];
  98947. }
  98948. else if(channels == 1 && bytes_per_sample == 2) {
  98949. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98950. for(sample = 0; sample < samples; sample++)
  98951. *buf1_++ = (FLAC__int16)signal[0][sample];
  98952. }
  98953. else
  98954. #endif
  98955. if(bytes_per_sample == 2) {
  98956. if(channels == 2) {
  98957. for(sample = 0; sample < samples; sample++) {
  98958. a_word = signal[0][sample];
  98959. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98960. *buf_++ = (FLAC__byte)a_word;
  98961. a_word = signal[1][sample];
  98962. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98963. *buf_++ = (FLAC__byte)a_word;
  98964. }
  98965. }
  98966. else if(channels == 1) {
  98967. for(sample = 0; sample < samples; sample++) {
  98968. a_word = signal[0][sample];
  98969. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98970. *buf_++ = (FLAC__byte)a_word;
  98971. }
  98972. }
  98973. else {
  98974. for(sample = 0; sample < samples; sample++) {
  98975. for(channel = 0; channel < channels; channel++) {
  98976. a_word = signal[channel][sample];
  98977. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98978. *buf_++ = (FLAC__byte)a_word;
  98979. }
  98980. }
  98981. }
  98982. }
  98983. else if(bytes_per_sample == 3) {
  98984. if(channels == 2) {
  98985. for(sample = 0; sample < samples; sample++) {
  98986. a_word = signal[0][sample];
  98987. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98988. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98989. *buf_++ = (FLAC__byte)a_word;
  98990. a_word = signal[1][sample];
  98991. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98992. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98993. *buf_++ = (FLAC__byte)a_word;
  98994. }
  98995. }
  98996. else if(channels == 1) {
  98997. for(sample = 0; sample < samples; sample++) {
  98998. a_word = signal[0][sample];
  98999. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99000. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99001. *buf_++ = (FLAC__byte)a_word;
  99002. }
  99003. }
  99004. else {
  99005. for(sample = 0; sample < samples; sample++) {
  99006. for(channel = 0; channel < channels; channel++) {
  99007. a_word = signal[channel][sample];
  99008. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99009. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99010. *buf_++ = (FLAC__byte)a_word;
  99011. }
  99012. }
  99013. }
  99014. }
  99015. else if(bytes_per_sample == 1) {
  99016. if(channels == 2) {
  99017. for(sample = 0; sample < samples; sample++) {
  99018. a_word = signal[0][sample];
  99019. *buf_++ = (FLAC__byte)a_word;
  99020. a_word = signal[1][sample];
  99021. *buf_++ = (FLAC__byte)a_word;
  99022. }
  99023. }
  99024. else if(channels == 1) {
  99025. for(sample = 0; sample < samples; sample++) {
  99026. a_word = signal[0][sample];
  99027. *buf_++ = (FLAC__byte)a_word;
  99028. }
  99029. }
  99030. else {
  99031. for(sample = 0; sample < samples; sample++) {
  99032. for(channel = 0; channel < channels; channel++) {
  99033. a_word = signal[channel][sample];
  99034. *buf_++ = (FLAC__byte)a_word;
  99035. }
  99036. }
  99037. }
  99038. }
  99039. else { /* bytes_per_sample == 4, maybe optimize more later */
  99040. for(sample = 0; sample < samples; sample++) {
  99041. for(channel = 0; channel < channels; channel++) {
  99042. a_word = signal[channel][sample];
  99043. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99044. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99045. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99046. *buf_++ = (FLAC__byte)a_word;
  99047. }
  99048. }
  99049. }
  99050. }
  99051. /*
  99052. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  99053. */
  99054. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  99055. {
  99056. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  99057. /* overflow check */
  99058. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  99059. return false;
  99060. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  99061. return false;
  99062. if(ctx->capacity < bytes_needed) {
  99063. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  99064. if(0 == tmp) {
  99065. free(ctx->internal_buf);
  99066. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  99067. return false;
  99068. }
  99069. ctx->internal_buf = tmp;
  99070. ctx->capacity = bytes_needed;
  99071. }
  99072. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  99073. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  99074. return true;
  99075. }
  99076. #endif
  99077. /*** End of inlined file: md5.c ***/
  99078. /*** Start of inlined file: memory.c ***/
  99079. /*** Start of inlined file: juce_FlacHeader.h ***/
  99080. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99081. // tasks..
  99082. #define VERSION "1.2.1"
  99083. #define FLAC__NO_DLL 1
  99084. #if JUCE_MSVC
  99085. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99086. #endif
  99087. #if JUCE_MAC
  99088. #define FLAC__SYS_DARWIN 1
  99089. #endif
  99090. /*** End of inlined file: juce_FlacHeader.h ***/
  99091. #if JUCE_USE_FLAC
  99092. #if HAVE_CONFIG_H
  99093. # include <config.h>
  99094. #endif
  99095. /*** Start of inlined file: memory.h ***/
  99096. #ifndef FLAC__PRIVATE__MEMORY_H
  99097. #define FLAC__PRIVATE__MEMORY_H
  99098. #ifdef HAVE_CONFIG_H
  99099. #include <config.h>
  99100. #endif
  99101. #include <stdlib.h> /* for size_t */
  99102. /* Returns the unaligned address returned by malloc.
  99103. * Use free() on this address to deallocate.
  99104. */
  99105. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  99106. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  99107. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  99108. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  99109. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  99110. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99111. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  99112. #endif
  99113. #endif
  99114. /*** End of inlined file: memory.h ***/
  99115. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  99116. {
  99117. void *x;
  99118. FLAC__ASSERT(0 != aligned_address);
  99119. #ifdef FLAC__ALIGN_MALLOC_DATA
  99120. /* align on 32-byte (256-bit) boundary */
  99121. x = safe_malloc_add_2op_(bytes, /*+*/31);
  99122. #ifdef SIZEOF_VOIDP
  99123. #if SIZEOF_VOIDP == 4
  99124. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  99125. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99126. #elif SIZEOF_VOIDP == 8
  99127. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99128. #else
  99129. # error Unsupported sizeof(void*)
  99130. #endif
  99131. #else
  99132. /* there's got to be a better way to do this right for all archs */
  99133. if(sizeof(void*) == sizeof(unsigned))
  99134. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99135. else if(sizeof(void*) == sizeof(FLAC__uint64))
  99136. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99137. else
  99138. return 0;
  99139. #endif
  99140. #else
  99141. x = safe_malloc_(bytes);
  99142. *aligned_address = x;
  99143. #endif
  99144. return x;
  99145. }
  99146. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  99147. {
  99148. FLAC__int32 *pu; /* unaligned pointer */
  99149. union { /* union needed to comply with C99 pointer aliasing rules */
  99150. FLAC__int32 *pa; /* aligned pointer */
  99151. void *pv; /* aligned pointer alias */
  99152. } u;
  99153. FLAC__ASSERT(elements > 0);
  99154. FLAC__ASSERT(0 != unaligned_pointer);
  99155. FLAC__ASSERT(0 != aligned_pointer);
  99156. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99157. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  99158. if(0 == pu) {
  99159. return false;
  99160. }
  99161. else {
  99162. if(*unaligned_pointer != 0)
  99163. free(*unaligned_pointer);
  99164. *unaligned_pointer = pu;
  99165. *aligned_pointer = u.pa;
  99166. return true;
  99167. }
  99168. }
  99169. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  99170. {
  99171. FLAC__uint32 *pu; /* unaligned pointer */
  99172. union { /* union needed to comply with C99 pointer aliasing rules */
  99173. FLAC__uint32 *pa; /* aligned pointer */
  99174. void *pv; /* aligned pointer alias */
  99175. } u;
  99176. FLAC__ASSERT(elements > 0);
  99177. FLAC__ASSERT(0 != unaligned_pointer);
  99178. FLAC__ASSERT(0 != aligned_pointer);
  99179. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99180. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99181. if(0 == pu) {
  99182. return false;
  99183. }
  99184. else {
  99185. if(*unaligned_pointer != 0)
  99186. free(*unaligned_pointer);
  99187. *unaligned_pointer = pu;
  99188. *aligned_pointer = u.pa;
  99189. return true;
  99190. }
  99191. }
  99192. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  99193. {
  99194. FLAC__uint64 *pu; /* unaligned pointer */
  99195. union { /* union needed to comply with C99 pointer aliasing rules */
  99196. FLAC__uint64 *pa; /* aligned pointer */
  99197. void *pv; /* aligned pointer alias */
  99198. } u;
  99199. FLAC__ASSERT(elements > 0);
  99200. FLAC__ASSERT(0 != unaligned_pointer);
  99201. FLAC__ASSERT(0 != aligned_pointer);
  99202. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99203. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99204. if(0 == pu) {
  99205. return false;
  99206. }
  99207. else {
  99208. if(*unaligned_pointer != 0)
  99209. free(*unaligned_pointer);
  99210. *unaligned_pointer = pu;
  99211. *aligned_pointer = u.pa;
  99212. return true;
  99213. }
  99214. }
  99215. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99216. {
  99217. unsigned *pu; /* unaligned pointer */
  99218. union { /* union needed to comply with C99 pointer aliasing rules */
  99219. unsigned *pa; /* aligned pointer */
  99220. void *pv; /* aligned pointer alias */
  99221. } u;
  99222. FLAC__ASSERT(elements > 0);
  99223. FLAC__ASSERT(0 != unaligned_pointer);
  99224. FLAC__ASSERT(0 != aligned_pointer);
  99225. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99226. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99227. if(0 == pu) {
  99228. return false;
  99229. }
  99230. else {
  99231. if(*unaligned_pointer != 0)
  99232. free(*unaligned_pointer);
  99233. *unaligned_pointer = pu;
  99234. *aligned_pointer = u.pa;
  99235. return true;
  99236. }
  99237. }
  99238. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99239. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99240. {
  99241. FLAC__real *pu; /* unaligned pointer */
  99242. union { /* union needed to comply with C99 pointer aliasing rules */
  99243. FLAC__real *pa; /* aligned pointer */
  99244. void *pv; /* aligned pointer alias */
  99245. } u;
  99246. FLAC__ASSERT(elements > 0);
  99247. FLAC__ASSERT(0 != unaligned_pointer);
  99248. FLAC__ASSERT(0 != aligned_pointer);
  99249. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99250. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99251. if(0 == pu) {
  99252. return false;
  99253. }
  99254. else {
  99255. if(*unaligned_pointer != 0)
  99256. free(*unaligned_pointer);
  99257. *unaligned_pointer = pu;
  99258. *aligned_pointer = u.pa;
  99259. return true;
  99260. }
  99261. }
  99262. #endif
  99263. #endif
  99264. /*** End of inlined file: memory.c ***/
  99265. /*** Start of inlined file: stream_decoder.c ***/
  99266. /*** Start of inlined file: juce_FlacHeader.h ***/
  99267. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99268. // tasks..
  99269. #define VERSION "1.2.1"
  99270. #define FLAC__NO_DLL 1
  99271. #if JUCE_MSVC
  99272. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99273. #endif
  99274. #if JUCE_MAC
  99275. #define FLAC__SYS_DARWIN 1
  99276. #endif
  99277. /*** End of inlined file: juce_FlacHeader.h ***/
  99278. #if JUCE_USE_FLAC
  99279. #if HAVE_CONFIG_H
  99280. # include <config.h>
  99281. #endif
  99282. #if defined _MSC_VER || defined __MINGW32__
  99283. #include <io.h> /* for _setmode() */
  99284. #include <fcntl.h> /* for _O_BINARY */
  99285. #endif
  99286. #if defined __CYGWIN__ || defined __EMX__
  99287. #include <io.h> /* for setmode(), O_BINARY */
  99288. #include <fcntl.h> /* for _O_BINARY */
  99289. #endif
  99290. #include <stdio.h>
  99291. #include <stdlib.h> /* for malloc() */
  99292. #include <string.h> /* for memset/memcpy() */
  99293. #include <sys/stat.h> /* for stat() */
  99294. #include <sys/types.h> /* for off_t */
  99295. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99296. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99297. #define fseeko fseek
  99298. #define ftello ftell
  99299. #endif
  99300. #endif
  99301. /*** Start of inlined file: stream_decoder.h ***/
  99302. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99303. #define FLAC__PROTECTED__STREAM_DECODER_H
  99304. #if FLAC__HAS_OGG
  99305. #include "include/private/ogg_decoder_aspect.h"
  99306. #endif
  99307. typedef struct FLAC__StreamDecoderProtected {
  99308. FLAC__StreamDecoderState state;
  99309. unsigned channels;
  99310. FLAC__ChannelAssignment channel_assignment;
  99311. unsigned bits_per_sample;
  99312. unsigned sample_rate; /* in Hz */
  99313. unsigned blocksize; /* in samples (per channel) */
  99314. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99315. #if FLAC__HAS_OGG
  99316. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99317. #endif
  99318. } FLAC__StreamDecoderProtected;
  99319. /*
  99320. * return the number of input bytes consumed
  99321. */
  99322. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99323. #endif
  99324. /*** End of inlined file: stream_decoder.h ***/
  99325. #ifdef max
  99326. #undef max
  99327. #endif
  99328. #define max(a,b) ((a)>(b)?(a):(b))
  99329. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99330. #ifdef _MSC_VER
  99331. #define FLAC__U64L(x) x
  99332. #else
  99333. #define FLAC__U64L(x) x##LLU
  99334. #endif
  99335. /* technically this should be in an "export.c" but this is convenient enough */
  99336. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99337. #if FLAC__HAS_OGG
  99338. 1
  99339. #else
  99340. 0
  99341. #endif
  99342. ;
  99343. /***********************************************************************
  99344. *
  99345. * Private static data
  99346. *
  99347. ***********************************************************************/
  99348. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99349. /***********************************************************************
  99350. *
  99351. * Private class method prototypes
  99352. *
  99353. ***********************************************************************/
  99354. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99355. static FILE *get_binary_stdin_(void);
  99356. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99357. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99358. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99359. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99360. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99361. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99362. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99363. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99364. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99365. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99366. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99367. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99368. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99369. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99370. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99371. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99372. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99373. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99374. 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);
  99375. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99376. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99377. #if FLAC__HAS_OGG
  99378. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99379. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99380. #endif
  99381. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99382. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99383. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99384. #if FLAC__HAS_OGG
  99385. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99386. #endif
  99387. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99388. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99389. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99390. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99391. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99392. /***********************************************************************
  99393. *
  99394. * Private class data
  99395. *
  99396. ***********************************************************************/
  99397. typedef struct FLAC__StreamDecoderPrivate {
  99398. #if FLAC__HAS_OGG
  99399. FLAC__bool is_ogg;
  99400. #endif
  99401. FLAC__StreamDecoderReadCallback read_callback;
  99402. FLAC__StreamDecoderSeekCallback seek_callback;
  99403. FLAC__StreamDecoderTellCallback tell_callback;
  99404. FLAC__StreamDecoderLengthCallback length_callback;
  99405. FLAC__StreamDecoderEofCallback eof_callback;
  99406. FLAC__StreamDecoderWriteCallback write_callback;
  99407. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99408. FLAC__StreamDecoderErrorCallback error_callback;
  99409. /* generic 32-bit datapath: */
  99410. 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[]);
  99411. /* generic 64-bit datapath: */
  99412. 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[]);
  99413. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99414. 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[]);
  99415. /* 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: */
  99416. 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[]);
  99417. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99418. void *client_data;
  99419. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99420. FLAC__BitReader *input;
  99421. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99422. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99423. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99424. unsigned output_capacity, output_channels;
  99425. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99426. FLAC__uint64 samples_decoded;
  99427. FLAC__bool has_stream_info, has_seek_table;
  99428. FLAC__StreamMetadata stream_info;
  99429. FLAC__StreamMetadata seek_table;
  99430. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99431. FLAC__byte *metadata_filter_ids;
  99432. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99433. FLAC__Frame frame;
  99434. FLAC__bool cached; /* true if there is a byte in lookahead */
  99435. FLAC__CPUInfo cpuinfo;
  99436. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99437. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99438. /* unaligned (original) pointers to allocated data */
  99439. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99440. 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 */
  99441. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99442. FLAC__bool is_seeking;
  99443. FLAC__MD5Context md5context;
  99444. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99445. /* (the rest of these are only used for seeking) */
  99446. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99447. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99448. FLAC__uint64 target_sample;
  99449. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99450. #if FLAC__HAS_OGG
  99451. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99452. #endif
  99453. } FLAC__StreamDecoderPrivate;
  99454. /***********************************************************************
  99455. *
  99456. * Public static class data
  99457. *
  99458. ***********************************************************************/
  99459. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99460. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99461. "FLAC__STREAM_DECODER_READ_METADATA",
  99462. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99463. "FLAC__STREAM_DECODER_READ_FRAME",
  99464. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99465. "FLAC__STREAM_DECODER_OGG_ERROR",
  99466. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99467. "FLAC__STREAM_DECODER_ABORTED",
  99468. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99469. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99470. };
  99471. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99472. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99473. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99474. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99475. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99476. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99477. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99478. };
  99479. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99480. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99481. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99482. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99483. };
  99484. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99485. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99486. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99487. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99488. };
  99489. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99490. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99491. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99492. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99493. };
  99494. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99495. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99496. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99497. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99498. };
  99499. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99500. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99501. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99502. };
  99503. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99504. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99505. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99506. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99507. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99508. };
  99509. /***********************************************************************
  99510. *
  99511. * Class constructor/destructor
  99512. *
  99513. ***********************************************************************/
  99514. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99515. {
  99516. FLAC__StreamDecoder *decoder;
  99517. unsigned i;
  99518. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99519. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99520. if(decoder == 0) {
  99521. return 0;
  99522. }
  99523. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99524. if(decoder->protected_ == 0) {
  99525. free(decoder);
  99526. return 0;
  99527. }
  99528. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99529. if(decoder->private_ == 0) {
  99530. free(decoder->protected_);
  99531. free(decoder);
  99532. return 0;
  99533. }
  99534. decoder->private_->input = FLAC__bitreader_new();
  99535. if(decoder->private_->input == 0) {
  99536. free(decoder->private_);
  99537. free(decoder->protected_);
  99538. free(decoder);
  99539. return 0;
  99540. }
  99541. decoder->private_->metadata_filter_ids_capacity = 16;
  99542. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99543. FLAC__bitreader_delete(decoder->private_->input);
  99544. free(decoder->private_);
  99545. free(decoder->protected_);
  99546. free(decoder);
  99547. return 0;
  99548. }
  99549. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99550. decoder->private_->output[i] = 0;
  99551. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99552. }
  99553. decoder->private_->output_capacity = 0;
  99554. decoder->private_->output_channels = 0;
  99555. decoder->private_->has_seek_table = false;
  99556. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99557. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99558. decoder->private_->file = 0;
  99559. set_defaults_dec(decoder);
  99560. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99561. return decoder;
  99562. }
  99563. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99564. {
  99565. unsigned i;
  99566. FLAC__ASSERT(0 != decoder);
  99567. FLAC__ASSERT(0 != decoder->protected_);
  99568. FLAC__ASSERT(0 != decoder->private_);
  99569. FLAC__ASSERT(0 != decoder->private_->input);
  99570. (void)FLAC__stream_decoder_finish(decoder);
  99571. if(0 != decoder->private_->metadata_filter_ids)
  99572. free(decoder->private_->metadata_filter_ids);
  99573. FLAC__bitreader_delete(decoder->private_->input);
  99574. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99575. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99576. free(decoder->private_);
  99577. free(decoder->protected_);
  99578. free(decoder);
  99579. }
  99580. /***********************************************************************
  99581. *
  99582. * Public class methods
  99583. *
  99584. ***********************************************************************/
  99585. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99586. FLAC__StreamDecoder *decoder,
  99587. FLAC__StreamDecoderReadCallback read_callback,
  99588. FLAC__StreamDecoderSeekCallback seek_callback,
  99589. FLAC__StreamDecoderTellCallback tell_callback,
  99590. FLAC__StreamDecoderLengthCallback length_callback,
  99591. FLAC__StreamDecoderEofCallback eof_callback,
  99592. FLAC__StreamDecoderWriteCallback write_callback,
  99593. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99594. FLAC__StreamDecoderErrorCallback error_callback,
  99595. void *client_data,
  99596. FLAC__bool is_ogg
  99597. )
  99598. {
  99599. FLAC__ASSERT(0 != decoder);
  99600. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99601. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99602. #if !FLAC__HAS_OGG
  99603. if(is_ogg)
  99604. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99605. #endif
  99606. if(
  99607. 0 == read_callback ||
  99608. 0 == write_callback ||
  99609. 0 == error_callback ||
  99610. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99611. )
  99612. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99613. #if FLAC__HAS_OGG
  99614. decoder->private_->is_ogg = is_ogg;
  99615. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99616. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99617. #endif
  99618. /*
  99619. * get the CPU info and set the function pointers
  99620. */
  99621. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99622. /* first default to the non-asm routines */
  99623. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99624. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99625. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99626. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99627. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99628. /* now override with asm where appropriate */
  99629. #ifndef FLAC__NO_ASM
  99630. if(decoder->private_->cpuinfo.use_asm) {
  99631. #ifdef FLAC__CPU_IA32
  99632. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99633. #ifdef FLAC__HAS_NASM
  99634. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99635. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99636. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99637. #endif
  99638. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99639. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99640. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99641. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99642. }
  99643. else {
  99644. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99645. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99646. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99647. }
  99648. #endif
  99649. #elif defined FLAC__CPU_PPC
  99650. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99651. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99652. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99653. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99654. }
  99655. #endif
  99656. }
  99657. #endif
  99658. /* from here on, errors are fatal */
  99659. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99660. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99661. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99662. }
  99663. decoder->private_->read_callback = read_callback;
  99664. decoder->private_->seek_callback = seek_callback;
  99665. decoder->private_->tell_callback = tell_callback;
  99666. decoder->private_->length_callback = length_callback;
  99667. decoder->private_->eof_callback = eof_callback;
  99668. decoder->private_->write_callback = write_callback;
  99669. decoder->private_->metadata_callback = metadata_callback;
  99670. decoder->private_->error_callback = error_callback;
  99671. decoder->private_->client_data = client_data;
  99672. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99673. decoder->private_->samples_decoded = 0;
  99674. decoder->private_->has_stream_info = false;
  99675. decoder->private_->cached = false;
  99676. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99677. decoder->private_->is_seeking = false;
  99678. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99679. if(!FLAC__stream_decoder_reset(decoder)) {
  99680. /* above call sets the state for us */
  99681. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99682. }
  99683. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99684. }
  99685. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99686. FLAC__StreamDecoder *decoder,
  99687. FLAC__StreamDecoderReadCallback read_callback,
  99688. FLAC__StreamDecoderSeekCallback seek_callback,
  99689. FLAC__StreamDecoderTellCallback tell_callback,
  99690. FLAC__StreamDecoderLengthCallback length_callback,
  99691. FLAC__StreamDecoderEofCallback eof_callback,
  99692. FLAC__StreamDecoderWriteCallback write_callback,
  99693. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99694. FLAC__StreamDecoderErrorCallback error_callback,
  99695. void *client_data
  99696. )
  99697. {
  99698. return init_stream_internal_dec(
  99699. decoder,
  99700. read_callback,
  99701. seek_callback,
  99702. tell_callback,
  99703. length_callback,
  99704. eof_callback,
  99705. write_callback,
  99706. metadata_callback,
  99707. error_callback,
  99708. client_data,
  99709. /*is_ogg=*/false
  99710. );
  99711. }
  99712. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99713. FLAC__StreamDecoder *decoder,
  99714. FLAC__StreamDecoderReadCallback read_callback,
  99715. FLAC__StreamDecoderSeekCallback seek_callback,
  99716. FLAC__StreamDecoderTellCallback tell_callback,
  99717. FLAC__StreamDecoderLengthCallback length_callback,
  99718. FLAC__StreamDecoderEofCallback eof_callback,
  99719. FLAC__StreamDecoderWriteCallback write_callback,
  99720. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99721. FLAC__StreamDecoderErrorCallback error_callback,
  99722. void *client_data
  99723. )
  99724. {
  99725. return init_stream_internal_dec(
  99726. decoder,
  99727. read_callback,
  99728. seek_callback,
  99729. tell_callback,
  99730. length_callback,
  99731. eof_callback,
  99732. write_callback,
  99733. metadata_callback,
  99734. error_callback,
  99735. client_data,
  99736. /*is_ogg=*/true
  99737. );
  99738. }
  99739. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99740. FLAC__StreamDecoder *decoder,
  99741. FILE *file,
  99742. FLAC__StreamDecoderWriteCallback write_callback,
  99743. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99744. FLAC__StreamDecoderErrorCallback error_callback,
  99745. void *client_data,
  99746. FLAC__bool is_ogg
  99747. )
  99748. {
  99749. FLAC__ASSERT(0 != decoder);
  99750. FLAC__ASSERT(0 != file);
  99751. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99752. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99753. if(0 == write_callback || 0 == error_callback)
  99754. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99755. /*
  99756. * To make sure that our file does not go unclosed after an error, we
  99757. * must assign the FILE pointer before any further error can occur in
  99758. * this routine.
  99759. */
  99760. if(file == stdin)
  99761. file = get_binary_stdin_(); /* just to be safe */
  99762. decoder->private_->file = file;
  99763. return init_stream_internal_dec(
  99764. decoder,
  99765. file_read_callback_dec,
  99766. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99767. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99768. decoder->private_->file == stdin? 0: file_length_callback_,
  99769. file_eof_callback_,
  99770. write_callback,
  99771. metadata_callback,
  99772. error_callback,
  99773. client_data,
  99774. is_ogg
  99775. );
  99776. }
  99777. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99778. FLAC__StreamDecoder *decoder,
  99779. FILE *file,
  99780. FLAC__StreamDecoderWriteCallback write_callback,
  99781. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99782. FLAC__StreamDecoderErrorCallback error_callback,
  99783. void *client_data
  99784. )
  99785. {
  99786. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99787. }
  99788. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99789. FLAC__StreamDecoder *decoder,
  99790. FILE *file,
  99791. FLAC__StreamDecoderWriteCallback write_callback,
  99792. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99793. FLAC__StreamDecoderErrorCallback error_callback,
  99794. void *client_data
  99795. )
  99796. {
  99797. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99798. }
  99799. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99800. FLAC__StreamDecoder *decoder,
  99801. const char *filename,
  99802. FLAC__StreamDecoderWriteCallback write_callback,
  99803. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99804. FLAC__StreamDecoderErrorCallback error_callback,
  99805. void *client_data,
  99806. FLAC__bool is_ogg
  99807. )
  99808. {
  99809. FILE *file;
  99810. FLAC__ASSERT(0 != decoder);
  99811. /*
  99812. * To make sure that our file does not go unclosed after an error, we
  99813. * have to do the same entrance checks here that are later performed
  99814. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99815. */
  99816. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99817. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99818. if(0 == write_callback || 0 == error_callback)
  99819. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99820. file = filename? fopen(filename, "rb") : stdin;
  99821. if(0 == file)
  99822. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99823. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99824. }
  99825. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99826. FLAC__StreamDecoder *decoder,
  99827. const char *filename,
  99828. FLAC__StreamDecoderWriteCallback write_callback,
  99829. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99830. FLAC__StreamDecoderErrorCallback error_callback,
  99831. void *client_data
  99832. )
  99833. {
  99834. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99835. }
  99836. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99837. FLAC__StreamDecoder *decoder,
  99838. const char *filename,
  99839. FLAC__StreamDecoderWriteCallback write_callback,
  99840. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99841. FLAC__StreamDecoderErrorCallback error_callback,
  99842. void *client_data
  99843. )
  99844. {
  99845. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99846. }
  99847. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99848. {
  99849. FLAC__bool md5_failed = false;
  99850. unsigned i;
  99851. FLAC__ASSERT(0 != decoder);
  99852. FLAC__ASSERT(0 != decoder->private_);
  99853. FLAC__ASSERT(0 != decoder->protected_);
  99854. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99855. return true;
  99856. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99857. * always call FLAC__MD5Final()
  99858. */
  99859. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99860. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99861. free(decoder->private_->seek_table.data.seek_table.points);
  99862. decoder->private_->seek_table.data.seek_table.points = 0;
  99863. decoder->private_->has_seek_table = false;
  99864. }
  99865. FLAC__bitreader_free(decoder->private_->input);
  99866. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99867. /* WATCHOUT:
  99868. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99869. * output arrays have a buffer of up to 3 zeroes in front
  99870. * (at negative indices) for alignment purposes; we use 4
  99871. * to keep the data well-aligned.
  99872. */
  99873. if(0 != decoder->private_->output[i]) {
  99874. free(decoder->private_->output[i]-4);
  99875. decoder->private_->output[i] = 0;
  99876. }
  99877. if(0 != decoder->private_->residual_unaligned[i]) {
  99878. free(decoder->private_->residual_unaligned[i]);
  99879. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99880. }
  99881. }
  99882. decoder->private_->output_capacity = 0;
  99883. decoder->private_->output_channels = 0;
  99884. #if FLAC__HAS_OGG
  99885. if(decoder->private_->is_ogg)
  99886. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99887. #endif
  99888. if(0 != decoder->private_->file) {
  99889. if(decoder->private_->file != stdin)
  99890. fclose(decoder->private_->file);
  99891. decoder->private_->file = 0;
  99892. }
  99893. if(decoder->private_->do_md5_checking) {
  99894. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99895. md5_failed = true;
  99896. }
  99897. decoder->private_->is_seeking = false;
  99898. set_defaults_dec(decoder);
  99899. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99900. return !md5_failed;
  99901. }
  99902. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99903. {
  99904. FLAC__ASSERT(0 != decoder);
  99905. FLAC__ASSERT(0 != decoder->private_);
  99906. FLAC__ASSERT(0 != decoder->protected_);
  99907. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99908. return false;
  99909. #if FLAC__HAS_OGG
  99910. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99911. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99912. return true;
  99913. #else
  99914. (void)value;
  99915. return false;
  99916. #endif
  99917. }
  99918. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99919. {
  99920. FLAC__ASSERT(0 != decoder);
  99921. FLAC__ASSERT(0 != decoder->protected_);
  99922. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99923. return false;
  99924. decoder->protected_->md5_checking = value;
  99925. return true;
  99926. }
  99927. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99928. {
  99929. FLAC__ASSERT(0 != decoder);
  99930. FLAC__ASSERT(0 != decoder->private_);
  99931. FLAC__ASSERT(0 != decoder->protected_);
  99932. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99933. /* double protection */
  99934. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99935. return false;
  99936. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99937. return false;
  99938. decoder->private_->metadata_filter[type] = true;
  99939. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99940. decoder->private_->metadata_filter_ids_count = 0;
  99941. return true;
  99942. }
  99943. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99944. {
  99945. FLAC__ASSERT(0 != decoder);
  99946. FLAC__ASSERT(0 != decoder->private_);
  99947. FLAC__ASSERT(0 != decoder->protected_);
  99948. FLAC__ASSERT(0 != id);
  99949. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99950. return false;
  99951. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99952. return true;
  99953. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99954. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99955. 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))) {
  99956. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99957. return false;
  99958. }
  99959. decoder->private_->metadata_filter_ids_capacity *= 2;
  99960. }
  99961. 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));
  99962. decoder->private_->metadata_filter_ids_count++;
  99963. return true;
  99964. }
  99965. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99966. {
  99967. unsigned i;
  99968. FLAC__ASSERT(0 != decoder);
  99969. FLAC__ASSERT(0 != decoder->private_);
  99970. FLAC__ASSERT(0 != decoder->protected_);
  99971. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99972. return false;
  99973. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99974. decoder->private_->metadata_filter[i] = true;
  99975. decoder->private_->metadata_filter_ids_count = 0;
  99976. return true;
  99977. }
  99978. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99979. {
  99980. FLAC__ASSERT(0 != decoder);
  99981. FLAC__ASSERT(0 != decoder->private_);
  99982. FLAC__ASSERT(0 != decoder->protected_);
  99983. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99984. /* double protection */
  99985. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99986. return false;
  99987. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99988. return false;
  99989. decoder->private_->metadata_filter[type] = false;
  99990. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99991. decoder->private_->metadata_filter_ids_count = 0;
  99992. return true;
  99993. }
  99994. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99995. {
  99996. FLAC__ASSERT(0 != decoder);
  99997. FLAC__ASSERT(0 != decoder->private_);
  99998. FLAC__ASSERT(0 != decoder->protected_);
  99999. FLAC__ASSERT(0 != id);
  100000. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100001. return false;
  100002. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  100003. return true;
  100004. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  100005. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  100006. 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))) {
  100007. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100008. return false;
  100009. }
  100010. decoder->private_->metadata_filter_ids_capacity *= 2;
  100011. }
  100012. 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));
  100013. decoder->private_->metadata_filter_ids_count++;
  100014. return true;
  100015. }
  100016. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  100017. {
  100018. FLAC__ASSERT(0 != decoder);
  100019. FLAC__ASSERT(0 != decoder->private_);
  100020. FLAC__ASSERT(0 != decoder->protected_);
  100021. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100022. return false;
  100023. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100024. decoder->private_->metadata_filter_ids_count = 0;
  100025. return true;
  100026. }
  100027. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  100028. {
  100029. FLAC__ASSERT(0 != decoder);
  100030. FLAC__ASSERT(0 != decoder->protected_);
  100031. return decoder->protected_->state;
  100032. }
  100033. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  100034. {
  100035. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  100036. }
  100037. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  100038. {
  100039. FLAC__ASSERT(0 != decoder);
  100040. FLAC__ASSERT(0 != decoder->protected_);
  100041. return decoder->protected_->md5_checking;
  100042. }
  100043. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  100044. {
  100045. FLAC__ASSERT(0 != decoder);
  100046. FLAC__ASSERT(0 != decoder->protected_);
  100047. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  100048. }
  100049. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  100050. {
  100051. FLAC__ASSERT(0 != decoder);
  100052. FLAC__ASSERT(0 != decoder->protected_);
  100053. return decoder->protected_->channels;
  100054. }
  100055. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  100056. {
  100057. FLAC__ASSERT(0 != decoder);
  100058. FLAC__ASSERT(0 != decoder->protected_);
  100059. return decoder->protected_->channel_assignment;
  100060. }
  100061. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  100062. {
  100063. FLAC__ASSERT(0 != decoder);
  100064. FLAC__ASSERT(0 != decoder->protected_);
  100065. return decoder->protected_->bits_per_sample;
  100066. }
  100067. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  100068. {
  100069. FLAC__ASSERT(0 != decoder);
  100070. FLAC__ASSERT(0 != decoder->protected_);
  100071. return decoder->protected_->sample_rate;
  100072. }
  100073. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  100074. {
  100075. FLAC__ASSERT(0 != decoder);
  100076. FLAC__ASSERT(0 != decoder->protected_);
  100077. return decoder->protected_->blocksize;
  100078. }
  100079. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  100080. {
  100081. FLAC__ASSERT(0 != decoder);
  100082. FLAC__ASSERT(0 != decoder->private_);
  100083. FLAC__ASSERT(0 != position);
  100084. #if FLAC__HAS_OGG
  100085. if(decoder->private_->is_ogg)
  100086. return false;
  100087. #endif
  100088. if(0 == decoder->private_->tell_callback)
  100089. return false;
  100090. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  100091. return false;
  100092. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  100093. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  100094. return false;
  100095. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  100096. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  100097. return true;
  100098. }
  100099. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  100100. {
  100101. FLAC__ASSERT(0 != decoder);
  100102. FLAC__ASSERT(0 != decoder->private_);
  100103. FLAC__ASSERT(0 != decoder->protected_);
  100104. decoder->private_->samples_decoded = 0;
  100105. decoder->private_->do_md5_checking = false;
  100106. #if FLAC__HAS_OGG
  100107. if(decoder->private_->is_ogg)
  100108. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  100109. #endif
  100110. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  100111. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100112. return false;
  100113. }
  100114. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100115. return true;
  100116. }
  100117. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  100118. {
  100119. FLAC__ASSERT(0 != decoder);
  100120. FLAC__ASSERT(0 != decoder->private_);
  100121. FLAC__ASSERT(0 != decoder->protected_);
  100122. if(!FLAC__stream_decoder_flush(decoder)) {
  100123. /* above call sets the state for us */
  100124. return false;
  100125. }
  100126. #if FLAC__HAS_OGG
  100127. /*@@@ could go in !internal_reset_hack block below */
  100128. if(decoder->private_->is_ogg)
  100129. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  100130. #endif
  100131. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  100132. * (internal_reset_hack) don't try to rewind since we are already at
  100133. * the beginning of the stream and don't want to fail if the input is
  100134. * not seekable.
  100135. */
  100136. if(!decoder->private_->internal_reset_hack) {
  100137. if(decoder->private_->file == stdin)
  100138. return false; /* can't rewind stdin, reset fails */
  100139. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  100140. return false; /* seekable and seek fails, reset fails */
  100141. }
  100142. else
  100143. decoder->private_->internal_reset_hack = false;
  100144. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  100145. decoder->private_->has_stream_info = false;
  100146. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  100147. free(decoder->private_->seek_table.data.seek_table.points);
  100148. decoder->private_->seek_table.data.seek_table.points = 0;
  100149. decoder->private_->has_seek_table = false;
  100150. }
  100151. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  100152. /*
  100153. * This goes in reset() and not flush() because according to the spec, a
  100154. * fixed-blocksize stream must stay that way through the whole stream.
  100155. */
  100156. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  100157. /* We initialize the FLAC__MD5Context even though we may never use it. This
  100158. * is because md5 checking may be turned on to start and then turned off if
  100159. * a seek occurs. So we init the context here and finalize it in
  100160. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  100161. * properly.
  100162. */
  100163. FLAC__MD5Init(&decoder->private_->md5context);
  100164. decoder->private_->first_frame_offset = 0;
  100165. decoder->private_->unparseable_frame_count = 0;
  100166. return true;
  100167. }
  100168. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  100169. {
  100170. FLAC__bool got_a_frame;
  100171. FLAC__ASSERT(0 != decoder);
  100172. FLAC__ASSERT(0 != decoder->protected_);
  100173. while(1) {
  100174. switch(decoder->protected_->state) {
  100175. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100176. if(!find_metadata_(decoder))
  100177. return false; /* above function sets the status for us */
  100178. break;
  100179. case FLAC__STREAM_DECODER_READ_METADATA:
  100180. if(!read_metadata_(decoder))
  100181. return false; /* above function sets the status for us */
  100182. else
  100183. return true;
  100184. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100185. if(!frame_sync_(decoder))
  100186. return true; /* above function sets the status for us */
  100187. break;
  100188. case FLAC__STREAM_DECODER_READ_FRAME:
  100189. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  100190. return false; /* above function sets the status for us */
  100191. if(got_a_frame)
  100192. return true; /* above function sets the status for us */
  100193. break;
  100194. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100195. case FLAC__STREAM_DECODER_ABORTED:
  100196. return true;
  100197. default:
  100198. FLAC__ASSERT(0);
  100199. return false;
  100200. }
  100201. }
  100202. }
  100203. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  100204. {
  100205. FLAC__ASSERT(0 != decoder);
  100206. FLAC__ASSERT(0 != decoder->protected_);
  100207. while(1) {
  100208. switch(decoder->protected_->state) {
  100209. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100210. if(!find_metadata_(decoder))
  100211. return false; /* above function sets the status for us */
  100212. break;
  100213. case FLAC__STREAM_DECODER_READ_METADATA:
  100214. if(!read_metadata_(decoder))
  100215. return false; /* above function sets the status for us */
  100216. break;
  100217. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100218. case FLAC__STREAM_DECODER_READ_FRAME:
  100219. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100220. case FLAC__STREAM_DECODER_ABORTED:
  100221. return true;
  100222. default:
  100223. FLAC__ASSERT(0);
  100224. return false;
  100225. }
  100226. }
  100227. }
  100228. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100229. {
  100230. FLAC__bool dummy;
  100231. FLAC__ASSERT(0 != decoder);
  100232. FLAC__ASSERT(0 != decoder->protected_);
  100233. while(1) {
  100234. switch(decoder->protected_->state) {
  100235. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100236. if(!find_metadata_(decoder))
  100237. return false; /* above function sets the status for us */
  100238. break;
  100239. case FLAC__STREAM_DECODER_READ_METADATA:
  100240. if(!read_metadata_(decoder))
  100241. return false; /* above function sets the status for us */
  100242. break;
  100243. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100244. if(!frame_sync_(decoder))
  100245. return true; /* above function sets the status for us */
  100246. break;
  100247. case FLAC__STREAM_DECODER_READ_FRAME:
  100248. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100249. return false; /* above function sets the status for us */
  100250. break;
  100251. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100252. case FLAC__STREAM_DECODER_ABORTED:
  100253. return true;
  100254. default:
  100255. FLAC__ASSERT(0);
  100256. return false;
  100257. }
  100258. }
  100259. }
  100260. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100261. {
  100262. FLAC__bool got_a_frame;
  100263. FLAC__ASSERT(0 != decoder);
  100264. FLAC__ASSERT(0 != decoder->protected_);
  100265. while(1) {
  100266. switch(decoder->protected_->state) {
  100267. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100268. case FLAC__STREAM_DECODER_READ_METADATA:
  100269. return false; /* above function sets the status for us */
  100270. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100271. if(!frame_sync_(decoder))
  100272. return true; /* above function sets the status for us */
  100273. break;
  100274. case FLAC__STREAM_DECODER_READ_FRAME:
  100275. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100276. return false; /* above function sets the status for us */
  100277. if(got_a_frame)
  100278. return true; /* above function sets the status for us */
  100279. break;
  100280. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100281. case FLAC__STREAM_DECODER_ABORTED:
  100282. return true;
  100283. default:
  100284. FLAC__ASSERT(0);
  100285. return false;
  100286. }
  100287. }
  100288. }
  100289. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100290. {
  100291. FLAC__uint64 length;
  100292. FLAC__ASSERT(0 != decoder);
  100293. if(
  100294. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100295. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100296. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100297. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100298. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100299. )
  100300. return false;
  100301. if(0 == decoder->private_->seek_callback)
  100302. return false;
  100303. FLAC__ASSERT(decoder->private_->seek_callback);
  100304. FLAC__ASSERT(decoder->private_->tell_callback);
  100305. FLAC__ASSERT(decoder->private_->length_callback);
  100306. FLAC__ASSERT(decoder->private_->eof_callback);
  100307. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100308. return false;
  100309. decoder->private_->is_seeking = true;
  100310. /* turn off md5 checking if a seek is attempted */
  100311. decoder->private_->do_md5_checking = false;
  100312. /* 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) */
  100313. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100314. decoder->private_->is_seeking = false;
  100315. return false;
  100316. }
  100317. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100318. if(
  100319. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100320. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100321. ) {
  100322. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100323. /* above call sets the state for us */
  100324. decoder->private_->is_seeking = false;
  100325. return false;
  100326. }
  100327. /* check this again in case we didn't know total_samples the first time */
  100328. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100329. decoder->private_->is_seeking = false;
  100330. return false;
  100331. }
  100332. }
  100333. {
  100334. const FLAC__bool ok =
  100335. #if FLAC__HAS_OGG
  100336. decoder->private_->is_ogg?
  100337. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100338. #endif
  100339. seek_to_absolute_sample_(decoder, length, sample)
  100340. ;
  100341. decoder->private_->is_seeking = false;
  100342. return ok;
  100343. }
  100344. }
  100345. /***********************************************************************
  100346. *
  100347. * Protected class methods
  100348. *
  100349. ***********************************************************************/
  100350. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100351. {
  100352. FLAC__ASSERT(0 != decoder);
  100353. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100354. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100355. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100356. }
  100357. /***********************************************************************
  100358. *
  100359. * Private class methods
  100360. *
  100361. ***********************************************************************/
  100362. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100363. {
  100364. #if FLAC__HAS_OGG
  100365. decoder->private_->is_ogg = false;
  100366. #endif
  100367. decoder->private_->read_callback = 0;
  100368. decoder->private_->seek_callback = 0;
  100369. decoder->private_->tell_callback = 0;
  100370. decoder->private_->length_callback = 0;
  100371. decoder->private_->eof_callback = 0;
  100372. decoder->private_->write_callback = 0;
  100373. decoder->private_->metadata_callback = 0;
  100374. decoder->private_->error_callback = 0;
  100375. decoder->private_->client_data = 0;
  100376. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100377. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100378. decoder->private_->metadata_filter_ids_count = 0;
  100379. decoder->protected_->md5_checking = false;
  100380. #if FLAC__HAS_OGG
  100381. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100382. #endif
  100383. }
  100384. /*
  100385. * This will forcibly set stdin to binary mode (for OSes that require it)
  100386. */
  100387. FILE *get_binary_stdin_(void)
  100388. {
  100389. /* if something breaks here it is probably due to the presence or
  100390. * absence of an underscore before the identifiers 'setmode',
  100391. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100392. */
  100393. #if defined _MSC_VER || defined __MINGW32__
  100394. _setmode(_fileno(stdin), _O_BINARY);
  100395. #elif defined __CYGWIN__
  100396. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100397. setmode(_fileno(stdin), _O_BINARY);
  100398. #elif defined __EMX__
  100399. setmode(fileno(stdin), O_BINARY);
  100400. #endif
  100401. return stdin;
  100402. }
  100403. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100404. {
  100405. unsigned i;
  100406. FLAC__int32 *tmp;
  100407. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100408. return true;
  100409. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100410. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100411. if(0 != decoder->private_->output[i]) {
  100412. free(decoder->private_->output[i]-4);
  100413. decoder->private_->output[i] = 0;
  100414. }
  100415. if(0 != decoder->private_->residual_unaligned[i]) {
  100416. free(decoder->private_->residual_unaligned[i]);
  100417. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100418. }
  100419. }
  100420. for(i = 0; i < channels; i++) {
  100421. /* WATCHOUT:
  100422. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100423. * output arrays have a buffer of up to 3 zeroes in front
  100424. * (at negative indices) for alignment purposes; we use 4
  100425. * to keep the data well-aligned.
  100426. */
  100427. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100428. if(tmp == 0) {
  100429. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100430. return false;
  100431. }
  100432. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100433. decoder->private_->output[i] = tmp + 4;
  100434. /* WATCHOUT:
  100435. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100436. */
  100437. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100438. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100439. return false;
  100440. }
  100441. }
  100442. decoder->private_->output_capacity = size;
  100443. decoder->private_->output_channels = channels;
  100444. return true;
  100445. }
  100446. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100447. {
  100448. size_t i;
  100449. FLAC__ASSERT(0 != decoder);
  100450. FLAC__ASSERT(0 != decoder->private_);
  100451. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100452. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100453. return true;
  100454. return false;
  100455. }
  100456. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100457. {
  100458. FLAC__uint32 x;
  100459. unsigned i, id_;
  100460. FLAC__bool first = true;
  100461. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100462. for(i = id_ = 0; i < 4; ) {
  100463. if(decoder->private_->cached) {
  100464. x = (FLAC__uint32)decoder->private_->lookahead;
  100465. decoder->private_->cached = false;
  100466. }
  100467. else {
  100468. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100469. return false; /* read_callback_ sets the state for us */
  100470. }
  100471. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100472. first = true;
  100473. i++;
  100474. id_ = 0;
  100475. continue;
  100476. }
  100477. if(x == ID3V2_TAG_[id_]) {
  100478. id_++;
  100479. i = 0;
  100480. if(id_ == 3) {
  100481. if(!skip_id3v2_tag_(decoder))
  100482. return false; /* skip_id3v2_tag_ sets the state for us */
  100483. }
  100484. continue;
  100485. }
  100486. id_ = 0;
  100487. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100488. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100489. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100490. return false; /* read_callback_ sets the state for us */
  100491. /* 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 */
  100492. /* else we have to check if the second byte is the end of a sync code */
  100493. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100494. decoder->private_->lookahead = (FLAC__byte)x;
  100495. decoder->private_->cached = true;
  100496. }
  100497. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100498. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100499. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100500. return true;
  100501. }
  100502. }
  100503. i = 0;
  100504. if(first) {
  100505. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100506. first = false;
  100507. }
  100508. }
  100509. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100510. return true;
  100511. }
  100512. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100513. {
  100514. FLAC__bool is_last;
  100515. FLAC__uint32 i, x, type, length;
  100516. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100517. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100518. return false; /* read_callback_ sets the state for us */
  100519. is_last = x? true : false;
  100520. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100521. return false; /* read_callback_ sets the state for us */
  100522. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100523. return false; /* read_callback_ sets the state for us */
  100524. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100525. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100526. return false;
  100527. decoder->private_->has_stream_info = true;
  100528. 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))
  100529. decoder->private_->do_md5_checking = false;
  100530. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100531. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100532. }
  100533. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100534. if(!read_metadata_seektable_(decoder, is_last, length))
  100535. return false;
  100536. decoder->private_->has_seek_table = true;
  100537. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100538. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100539. }
  100540. else {
  100541. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100542. unsigned real_length = length;
  100543. FLAC__StreamMetadata block;
  100544. block.is_last = is_last;
  100545. block.type = (FLAC__MetadataType)type;
  100546. block.length = length;
  100547. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100548. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100549. return false; /* read_callback_ sets the state for us */
  100550. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100551. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100552. return false;
  100553. }
  100554. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100555. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100556. skip_it = !skip_it;
  100557. }
  100558. if(skip_it) {
  100559. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100560. return false; /* read_callback_ sets the state for us */
  100561. }
  100562. else {
  100563. switch(type) {
  100564. case FLAC__METADATA_TYPE_PADDING:
  100565. /* skip the padding bytes */
  100566. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100567. return false; /* read_callback_ sets the state for us */
  100568. break;
  100569. case FLAC__METADATA_TYPE_APPLICATION:
  100570. /* remember, we read the ID already */
  100571. if(real_length > 0) {
  100572. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100573. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100574. return false;
  100575. }
  100576. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100577. return false; /* read_callback_ sets the state for us */
  100578. }
  100579. else
  100580. block.data.application.data = 0;
  100581. break;
  100582. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100583. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100584. return false;
  100585. break;
  100586. case FLAC__METADATA_TYPE_CUESHEET:
  100587. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100588. return false;
  100589. break;
  100590. case FLAC__METADATA_TYPE_PICTURE:
  100591. if(!read_metadata_picture_(decoder, &block.data.picture))
  100592. return false;
  100593. break;
  100594. case FLAC__METADATA_TYPE_STREAMINFO:
  100595. case FLAC__METADATA_TYPE_SEEKTABLE:
  100596. FLAC__ASSERT(0);
  100597. break;
  100598. default:
  100599. if(real_length > 0) {
  100600. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100601. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100602. return false;
  100603. }
  100604. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100605. return false; /* read_callback_ sets the state for us */
  100606. }
  100607. else
  100608. block.data.unknown.data = 0;
  100609. break;
  100610. }
  100611. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100612. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100613. /* now we have to free any malloc()ed data in the block */
  100614. switch(type) {
  100615. case FLAC__METADATA_TYPE_PADDING:
  100616. break;
  100617. case FLAC__METADATA_TYPE_APPLICATION:
  100618. if(0 != block.data.application.data)
  100619. free(block.data.application.data);
  100620. break;
  100621. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100622. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100623. free(block.data.vorbis_comment.vendor_string.entry);
  100624. if(block.data.vorbis_comment.num_comments > 0)
  100625. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100626. if(0 != block.data.vorbis_comment.comments[i].entry)
  100627. free(block.data.vorbis_comment.comments[i].entry);
  100628. if(0 != block.data.vorbis_comment.comments)
  100629. free(block.data.vorbis_comment.comments);
  100630. break;
  100631. case FLAC__METADATA_TYPE_CUESHEET:
  100632. if(block.data.cue_sheet.num_tracks > 0)
  100633. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100634. if(0 != block.data.cue_sheet.tracks[i].indices)
  100635. free(block.data.cue_sheet.tracks[i].indices);
  100636. if(0 != block.data.cue_sheet.tracks)
  100637. free(block.data.cue_sheet.tracks);
  100638. break;
  100639. case FLAC__METADATA_TYPE_PICTURE:
  100640. if(0 != block.data.picture.mime_type)
  100641. free(block.data.picture.mime_type);
  100642. if(0 != block.data.picture.description)
  100643. free(block.data.picture.description);
  100644. if(0 != block.data.picture.data)
  100645. free(block.data.picture.data);
  100646. break;
  100647. case FLAC__METADATA_TYPE_STREAMINFO:
  100648. case FLAC__METADATA_TYPE_SEEKTABLE:
  100649. FLAC__ASSERT(0);
  100650. default:
  100651. if(0 != block.data.unknown.data)
  100652. free(block.data.unknown.data);
  100653. break;
  100654. }
  100655. }
  100656. }
  100657. if(is_last) {
  100658. /* if this fails, it's OK, it's just a hint for the seek routine */
  100659. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100660. decoder->private_->first_frame_offset = 0;
  100661. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100662. }
  100663. return true;
  100664. }
  100665. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100666. {
  100667. FLAC__uint32 x;
  100668. unsigned bits, used_bits = 0;
  100669. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100670. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100671. decoder->private_->stream_info.is_last = is_last;
  100672. decoder->private_->stream_info.length = length;
  100673. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100674. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100675. return false; /* read_callback_ sets the state for us */
  100676. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100677. used_bits += bits;
  100678. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100679. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100680. return false; /* read_callback_ sets the state for us */
  100681. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100682. used_bits += bits;
  100683. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100684. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100685. return false; /* read_callback_ sets the state for us */
  100686. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100687. used_bits += bits;
  100688. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100689. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100690. return false; /* read_callback_ sets the state for us */
  100691. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100692. used_bits += bits;
  100693. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100694. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100695. return false; /* read_callback_ sets the state for us */
  100696. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100697. used_bits += bits;
  100698. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100699. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100700. return false; /* read_callback_ sets the state for us */
  100701. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100702. used_bits += bits;
  100703. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100704. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100705. return false; /* read_callback_ sets the state for us */
  100706. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100707. used_bits += bits;
  100708. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100709. 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))
  100710. return false; /* read_callback_ sets the state for us */
  100711. used_bits += bits;
  100712. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100713. return false; /* read_callback_ sets the state for us */
  100714. used_bits += 16*8;
  100715. /* skip the rest of the block */
  100716. FLAC__ASSERT(used_bits % 8 == 0);
  100717. length -= (used_bits / 8);
  100718. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100719. return false; /* read_callback_ sets the state for us */
  100720. return true;
  100721. }
  100722. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100723. {
  100724. FLAC__uint32 i, x;
  100725. FLAC__uint64 xx;
  100726. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100727. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100728. decoder->private_->seek_table.is_last = is_last;
  100729. decoder->private_->seek_table.length = length;
  100730. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100731. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100732. 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)))) {
  100733. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100734. return false;
  100735. }
  100736. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100737. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100738. return false; /* read_callback_ sets the state for us */
  100739. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100740. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100741. return false; /* read_callback_ sets the state for us */
  100742. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100743. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100744. return false; /* read_callback_ sets the state for us */
  100745. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100746. }
  100747. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100748. /* if there is a partial point left, skip over it */
  100749. if(length > 0) {
  100750. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100751. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100752. return false; /* read_callback_ sets the state for us */
  100753. }
  100754. return true;
  100755. }
  100756. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100757. {
  100758. FLAC__uint32 i;
  100759. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100760. /* read vendor string */
  100761. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100762. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100763. return false; /* read_callback_ sets the state for us */
  100764. if(obj->vendor_string.length > 0) {
  100765. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100766. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100767. return false;
  100768. }
  100769. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100770. return false; /* read_callback_ sets the state for us */
  100771. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100772. }
  100773. else
  100774. obj->vendor_string.entry = 0;
  100775. /* read num comments */
  100776. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100777. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100778. return false; /* read_callback_ sets the state for us */
  100779. /* read comments */
  100780. if(obj->num_comments > 0) {
  100781. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100782. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100783. return false;
  100784. }
  100785. for(i = 0; i < obj->num_comments; i++) {
  100786. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100787. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100788. return false; /* read_callback_ sets the state for us */
  100789. if(obj->comments[i].length > 0) {
  100790. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100791. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100792. return false;
  100793. }
  100794. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100795. return false; /* read_callback_ sets the state for us */
  100796. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100797. }
  100798. else
  100799. obj->comments[i].entry = 0;
  100800. }
  100801. }
  100802. else {
  100803. obj->comments = 0;
  100804. }
  100805. return true;
  100806. }
  100807. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100808. {
  100809. FLAC__uint32 i, j, x;
  100810. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100811. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100812. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100813. 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))
  100814. return false; /* read_callback_ sets the state for us */
  100815. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100816. return false; /* read_callback_ sets the state for us */
  100817. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100818. return false; /* read_callback_ sets the state for us */
  100819. obj->is_cd = x? true : false;
  100820. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100821. return false; /* read_callback_ sets the state for us */
  100822. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100823. return false; /* read_callback_ sets the state for us */
  100824. obj->num_tracks = x;
  100825. if(obj->num_tracks > 0) {
  100826. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100827. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100828. return false;
  100829. }
  100830. for(i = 0; i < obj->num_tracks; i++) {
  100831. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100832. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100833. return false; /* read_callback_ sets the state for us */
  100834. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100835. return false; /* read_callback_ sets the state for us */
  100836. track->number = (FLAC__byte)x;
  100837. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100838. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100839. return false; /* read_callback_ sets the state for us */
  100840. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100841. return false; /* read_callback_ sets the state for us */
  100842. track->type = x;
  100843. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100844. return false; /* read_callback_ sets the state for us */
  100845. track->pre_emphasis = x;
  100846. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100847. return false; /* read_callback_ sets the state for us */
  100848. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100849. return false; /* read_callback_ sets the state for us */
  100850. track->num_indices = (FLAC__byte)x;
  100851. if(track->num_indices > 0) {
  100852. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100853. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100854. return false;
  100855. }
  100856. for(j = 0; j < track->num_indices; j++) {
  100857. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100858. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100859. return false; /* read_callback_ sets the state for us */
  100860. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100861. return false; /* read_callback_ sets the state for us */
  100862. index->number = (FLAC__byte)x;
  100863. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100864. return false; /* read_callback_ sets the state for us */
  100865. }
  100866. }
  100867. }
  100868. }
  100869. return true;
  100870. }
  100871. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100872. {
  100873. FLAC__uint32 x;
  100874. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100875. /* read type */
  100876. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100877. return false; /* read_callback_ sets the state for us */
  100878. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100879. /* read MIME type */
  100880. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100881. return false; /* read_callback_ sets the state for us */
  100882. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100883. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100884. return false;
  100885. }
  100886. if(x > 0) {
  100887. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100888. return false; /* read_callback_ sets the state for us */
  100889. }
  100890. obj->mime_type[x] = '\0';
  100891. /* read description */
  100892. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100893. return false; /* read_callback_ sets the state for us */
  100894. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100895. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100896. return false;
  100897. }
  100898. if(x > 0) {
  100899. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100900. return false; /* read_callback_ sets the state for us */
  100901. }
  100902. obj->description[x] = '\0';
  100903. /* read width */
  100904. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100905. return false; /* read_callback_ sets the state for us */
  100906. /* read height */
  100907. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100908. return false; /* read_callback_ sets the state for us */
  100909. /* read depth */
  100910. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100911. return false; /* read_callback_ sets the state for us */
  100912. /* read colors */
  100913. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100914. return false; /* read_callback_ sets the state for us */
  100915. /* read data */
  100916. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100917. return false; /* read_callback_ sets the state for us */
  100918. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100919. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100920. return false;
  100921. }
  100922. if(obj->data_length > 0) {
  100923. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100924. return false; /* read_callback_ sets the state for us */
  100925. }
  100926. return true;
  100927. }
  100928. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100929. {
  100930. FLAC__uint32 x;
  100931. unsigned i, skip;
  100932. /* skip the version and flags bytes */
  100933. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100934. return false; /* read_callback_ sets the state for us */
  100935. /* get the size (in bytes) to skip */
  100936. skip = 0;
  100937. for(i = 0; i < 4; i++) {
  100938. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100939. return false; /* read_callback_ sets the state for us */
  100940. skip <<= 7;
  100941. skip |= (x & 0x7f);
  100942. }
  100943. /* skip the rest of the tag */
  100944. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100945. return false; /* read_callback_ sets the state for us */
  100946. return true;
  100947. }
  100948. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100949. {
  100950. FLAC__uint32 x;
  100951. FLAC__bool first = true;
  100952. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100953. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100954. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100955. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100956. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100957. return true;
  100958. }
  100959. }
  100960. /* make sure we're byte aligned */
  100961. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100962. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100963. return false; /* read_callback_ sets the state for us */
  100964. }
  100965. while(1) {
  100966. if(decoder->private_->cached) {
  100967. x = (FLAC__uint32)decoder->private_->lookahead;
  100968. decoder->private_->cached = false;
  100969. }
  100970. else {
  100971. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100972. return false; /* read_callback_ sets the state for us */
  100973. }
  100974. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100975. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100976. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100977. return false; /* read_callback_ sets the state for us */
  100978. /* 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 */
  100979. /* else we have to check if the second byte is the end of a sync code */
  100980. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100981. decoder->private_->lookahead = (FLAC__byte)x;
  100982. decoder->private_->cached = true;
  100983. }
  100984. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100985. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100986. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100987. return true;
  100988. }
  100989. }
  100990. if(first) {
  100991. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100992. first = false;
  100993. }
  100994. }
  100995. return true;
  100996. }
  100997. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100998. {
  100999. unsigned channel;
  101000. unsigned i;
  101001. FLAC__int32 mid, side;
  101002. unsigned frame_crc; /* the one we calculate from the input stream */
  101003. FLAC__uint32 x;
  101004. *got_a_frame = false;
  101005. /* init the CRC */
  101006. frame_crc = 0;
  101007. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  101008. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  101009. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  101010. if(!read_frame_header_(decoder))
  101011. return false;
  101012. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  101013. return true;
  101014. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  101015. return false;
  101016. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101017. /*
  101018. * first figure the correct bits-per-sample of the subframe
  101019. */
  101020. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  101021. switch(decoder->private_->frame.header.channel_assignment) {
  101022. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101023. /* no adjustment needed */
  101024. break;
  101025. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101026. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101027. if(channel == 1)
  101028. bps++;
  101029. break;
  101030. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101031. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101032. if(channel == 0)
  101033. bps++;
  101034. break;
  101035. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101036. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101037. if(channel == 1)
  101038. bps++;
  101039. break;
  101040. default:
  101041. FLAC__ASSERT(0);
  101042. }
  101043. /*
  101044. * now read it
  101045. */
  101046. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  101047. return false;
  101048. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101049. return true;
  101050. }
  101051. if(!read_zero_padding_(decoder))
  101052. return false;
  101053. 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) */
  101054. return true;
  101055. /*
  101056. * Read the frame CRC-16 from the footer and check
  101057. */
  101058. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  101059. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  101060. return false; /* read_callback_ sets the state for us */
  101061. if(frame_crc == x) {
  101062. if(do_full_decode) {
  101063. /* Undo any special channel coding */
  101064. switch(decoder->private_->frame.header.channel_assignment) {
  101065. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101066. /* do nothing */
  101067. break;
  101068. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101069. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101070. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101071. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  101072. break;
  101073. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101074. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101075. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101076. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  101077. break;
  101078. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101079. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101080. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101081. #if 1
  101082. mid = decoder->private_->output[0][i];
  101083. side = decoder->private_->output[1][i];
  101084. mid <<= 1;
  101085. mid |= (side & 1); /* i.e. if 'side' is odd... */
  101086. decoder->private_->output[0][i] = (mid + side) >> 1;
  101087. decoder->private_->output[1][i] = (mid - side) >> 1;
  101088. #else
  101089. /* OPT: without 'side' temp variable */
  101090. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  101091. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  101092. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  101093. #endif
  101094. }
  101095. break;
  101096. default:
  101097. FLAC__ASSERT(0);
  101098. break;
  101099. }
  101100. }
  101101. }
  101102. else {
  101103. /* Bad frame, emit error and zero the output signal */
  101104. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  101105. if(do_full_decode) {
  101106. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101107. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101108. }
  101109. }
  101110. }
  101111. *got_a_frame = true;
  101112. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  101113. if(decoder->private_->next_fixed_block_size)
  101114. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  101115. /* put the latest values into the public section of the decoder instance */
  101116. decoder->protected_->channels = decoder->private_->frame.header.channels;
  101117. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  101118. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  101119. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  101120. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  101121. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101122. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  101123. /* write it */
  101124. if(do_full_decode) {
  101125. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  101126. return false;
  101127. }
  101128. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101129. return true;
  101130. }
  101131. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  101132. {
  101133. FLAC__uint32 x;
  101134. FLAC__uint64 xx;
  101135. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  101136. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  101137. unsigned raw_header_len;
  101138. FLAC__bool is_unparseable = false;
  101139. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  101140. /* init the raw header with the saved bits from synchronization */
  101141. raw_header[0] = decoder->private_->header_warmup[0];
  101142. raw_header[1] = decoder->private_->header_warmup[1];
  101143. raw_header_len = 2;
  101144. /* check to make sure that reserved bit is 0 */
  101145. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  101146. is_unparseable = true;
  101147. /*
  101148. * Note that along the way as we read the header, we look for a sync
  101149. * code inside. If we find one it would indicate that our original
  101150. * sync was bad since there cannot be a sync code in a valid header.
  101151. *
  101152. * Three kinds of things can go wrong when reading the frame header:
  101153. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  101154. * If we don't find a sync code, it can end up looking like we read
  101155. * a valid but unparseable header, until getting to the frame header
  101156. * CRC. Even then we could get a false positive on the CRC.
  101157. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  101158. * future encoder).
  101159. * 3) We may be on a damaged frame which appears valid but unparseable.
  101160. *
  101161. * For all these reasons, we try and read a complete frame header as
  101162. * long as it seems valid, even if unparseable, up until the frame
  101163. * header CRC.
  101164. */
  101165. /*
  101166. * read in the raw header as bytes so we can CRC it, and parse it on the way
  101167. */
  101168. for(i = 0; i < 2; i++) {
  101169. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101170. return false; /* read_callback_ sets the state for us */
  101171. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101172. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  101173. decoder->private_->lookahead = (FLAC__byte)x;
  101174. decoder->private_->cached = true;
  101175. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101176. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101177. return true;
  101178. }
  101179. raw_header[raw_header_len++] = (FLAC__byte)x;
  101180. }
  101181. switch(x = raw_header[2] >> 4) {
  101182. case 0:
  101183. is_unparseable = true;
  101184. break;
  101185. case 1:
  101186. decoder->private_->frame.header.blocksize = 192;
  101187. break;
  101188. case 2:
  101189. case 3:
  101190. case 4:
  101191. case 5:
  101192. decoder->private_->frame.header.blocksize = 576 << (x-2);
  101193. break;
  101194. case 6:
  101195. case 7:
  101196. blocksize_hint = x;
  101197. break;
  101198. case 8:
  101199. case 9:
  101200. case 10:
  101201. case 11:
  101202. case 12:
  101203. case 13:
  101204. case 14:
  101205. case 15:
  101206. decoder->private_->frame.header.blocksize = 256 << (x-8);
  101207. break;
  101208. default:
  101209. FLAC__ASSERT(0);
  101210. break;
  101211. }
  101212. switch(x = raw_header[2] & 0x0f) {
  101213. case 0:
  101214. if(decoder->private_->has_stream_info)
  101215. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101216. else
  101217. is_unparseable = true;
  101218. break;
  101219. case 1:
  101220. decoder->private_->frame.header.sample_rate = 88200;
  101221. break;
  101222. case 2:
  101223. decoder->private_->frame.header.sample_rate = 176400;
  101224. break;
  101225. case 3:
  101226. decoder->private_->frame.header.sample_rate = 192000;
  101227. break;
  101228. case 4:
  101229. decoder->private_->frame.header.sample_rate = 8000;
  101230. break;
  101231. case 5:
  101232. decoder->private_->frame.header.sample_rate = 16000;
  101233. break;
  101234. case 6:
  101235. decoder->private_->frame.header.sample_rate = 22050;
  101236. break;
  101237. case 7:
  101238. decoder->private_->frame.header.sample_rate = 24000;
  101239. break;
  101240. case 8:
  101241. decoder->private_->frame.header.sample_rate = 32000;
  101242. break;
  101243. case 9:
  101244. decoder->private_->frame.header.sample_rate = 44100;
  101245. break;
  101246. case 10:
  101247. decoder->private_->frame.header.sample_rate = 48000;
  101248. break;
  101249. case 11:
  101250. decoder->private_->frame.header.sample_rate = 96000;
  101251. break;
  101252. case 12:
  101253. case 13:
  101254. case 14:
  101255. sample_rate_hint = x;
  101256. break;
  101257. case 15:
  101258. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101259. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101260. return true;
  101261. default:
  101262. FLAC__ASSERT(0);
  101263. }
  101264. x = (unsigned)(raw_header[3] >> 4);
  101265. if(x & 8) {
  101266. decoder->private_->frame.header.channels = 2;
  101267. switch(x & 7) {
  101268. case 0:
  101269. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101270. break;
  101271. case 1:
  101272. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101273. break;
  101274. case 2:
  101275. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101276. break;
  101277. default:
  101278. is_unparseable = true;
  101279. break;
  101280. }
  101281. }
  101282. else {
  101283. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101284. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101285. }
  101286. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101287. case 0:
  101288. if(decoder->private_->has_stream_info)
  101289. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101290. else
  101291. is_unparseable = true;
  101292. break;
  101293. case 1:
  101294. decoder->private_->frame.header.bits_per_sample = 8;
  101295. break;
  101296. case 2:
  101297. decoder->private_->frame.header.bits_per_sample = 12;
  101298. break;
  101299. case 4:
  101300. decoder->private_->frame.header.bits_per_sample = 16;
  101301. break;
  101302. case 5:
  101303. decoder->private_->frame.header.bits_per_sample = 20;
  101304. break;
  101305. case 6:
  101306. decoder->private_->frame.header.bits_per_sample = 24;
  101307. break;
  101308. case 3:
  101309. case 7:
  101310. is_unparseable = true;
  101311. break;
  101312. default:
  101313. FLAC__ASSERT(0);
  101314. break;
  101315. }
  101316. /* check to make sure that reserved bit is 0 */
  101317. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101318. is_unparseable = true;
  101319. /* read the frame's starting sample number (or frame number as the case may be) */
  101320. if(
  101321. raw_header[1] & 0x01 ||
  101322. /*@@@ 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 */
  101323. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101324. ) { /* variable blocksize */
  101325. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101326. return false; /* read_callback_ sets the state for us */
  101327. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101328. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101329. decoder->private_->cached = true;
  101330. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101331. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101332. return true;
  101333. }
  101334. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101335. decoder->private_->frame.header.number.sample_number = xx;
  101336. }
  101337. else { /* fixed blocksize */
  101338. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101339. return false; /* read_callback_ sets the state for us */
  101340. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101341. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101342. decoder->private_->cached = true;
  101343. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101344. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101345. return true;
  101346. }
  101347. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101348. decoder->private_->frame.header.number.frame_number = x;
  101349. }
  101350. if(blocksize_hint) {
  101351. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101352. return false; /* read_callback_ sets the state for us */
  101353. raw_header[raw_header_len++] = (FLAC__byte)x;
  101354. if(blocksize_hint == 7) {
  101355. FLAC__uint32 _x;
  101356. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101357. return false; /* read_callback_ sets the state for us */
  101358. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101359. x = (x << 8) | _x;
  101360. }
  101361. decoder->private_->frame.header.blocksize = x+1;
  101362. }
  101363. if(sample_rate_hint) {
  101364. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101365. return false; /* read_callback_ sets the state for us */
  101366. raw_header[raw_header_len++] = (FLAC__byte)x;
  101367. if(sample_rate_hint != 12) {
  101368. FLAC__uint32 _x;
  101369. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101370. return false; /* read_callback_ sets the state for us */
  101371. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101372. x = (x << 8) | _x;
  101373. }
  101374. if(sample_rate_hint == 12)
  101375. decoder->private_->frame.header.sample_rate = x*1000;
  101376. else if(sample_rate_hint == 13)
  101377. decoder->private_->frame.header.sample_rate = x;
  101378. else
  101379. decoder->private_->frame.header.sample_rate = x*10;
  101380. }
  101381. /* read the CRC-8 byte */
  101382. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101383. return false; /* read_callback_ sets the state for us */
  101384. crc8 = (FLAC__byte)x;
  101385. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101386. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101387. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101388. return true;
  101389. }
  101390. /* calculate the sample number from the frame number if needed */
  101391. decoder->private_->next_fixed_block_size = 0;
  101392. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101393. x = decoder->private_->frame.header.number.frame_number;
  101394. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101395. if(decoder->private_->fixed_block_size)
  101396. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101397. else if(decoder->private_->has_stream_info) {
  101398. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101399. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101400. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101401. }
  101402. else
  101403. is_unparseable = true;
  101404. }
  101405. else if(x == 0) {
  101406. decoder->private_->frame.header.number.sample_number = 0;
  101407. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101408. }
  101409. else {
  101410. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101411. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101412. }
  101413. }
  101414. if(is_unparseable) {
  101415. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101416. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101417. return true;
  101418. }
  101419. return true;
  101420. }
  101421. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101422. {
  101423. FLAC__uint32 x;
  101424. FLAC__bool wasted_bits;
  101425. unsigned i;
  101426. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101427. return false; /* read_callback_ sets the state for us */
  101428. wasted_bits = (x & 1);
  101429. x &= 0xfe;
  101430. if(wasted_bits) {
  101431. unsigned u;
  101432. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101433. return false; /* read_callback_ sets the state for us */
  101434. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101435. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101436. }
  101437. else
  101438. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101439. /*
  101440. * Lots of magic numbers here
  101441. */
  101442. if(x & 0x80) {
  101443. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101444. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101445. return true;
  101446. }
  101447. else if(x == 0) {
  101448. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101449. return false;
  101450. }
  101451. else if(x == 2) {
  101452. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101453. return false;
  101454. }
  101455. else if(x < 16) {
  101456. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101457. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101458. return true;
  101459. }
  101460. else if(x <= 24) {
  101461. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101462. return false;
  101463. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101464. return true;
  101465. }
  101466. else if(x < 64) {
  101467. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101468. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101469. return true;
  101470. }
  101471. else {
  101472. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101473. return false;
  101474. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101475. return true;
  101476. }
  101477. if(wasted_bits && do_full_decode) {
  101478. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101479. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101480. decoder->private_->output[channel][i] <<= x;
  101481. }
  101482. return true;
  101483. }
  101484. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101485. {
  101486. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101487. FLAC__int32 x;
  101488. unsigned i;
  101489. FLAC__int32 *output = decoder->private_->output[channel];
  101490. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101491. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101492. return false; /* read_callback_ sets the state for us */
  101493. subframe->value = x;
  101494. /* decode the subframe */
  101495. if(do_full_decode) {
  101496. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101497. output[i] = x;
  101498. }
  101499. return true;
  101500. }
  101501. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101502. {
  101503. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101504. FLAC__int32 i32;
  101505. FLAC__uint32 u32;
  101506. unsigned u;
  101507. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101508. subframe->residual = decoder->private_->residual[channel];
  101509. subframe->order = order;
  101510. /* read warm-up samples */
  101511. for(u = 0; u < order; u++) {
  101512. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101513. return false; /* read_callback_ sets the state for us */
  101514. subframe->warmup[u] = i32;
  101515. }
  101516. /* read entropy coding method info */
  101517. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101518. return false; /* read_callback_ sets the state for us */
  101519. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101520. switch(subframe->entropy_coding_method.type) {
  101521. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101522. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101523. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101524. return false; /* read_callback_ sets the state for us */
  101525. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101526. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101527. break;
  101528. default:
  101529. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101530. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101531. return true;
  101532. }
  101533. /* read residual */
  101534. switch(subframe->entropy_coding_method.type) {
  101535. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101536. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101537. 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))
  101538. return false;
  101539. break;
  101540. default:
  101541. FLAC__ASSERT(0);
  101542. }
  101543. /* decode the subframe */
  101544. if(do_full_decode) {
  101545. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101546. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101547. }
  101548. return true;
  101549. }
  101550. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101551. {
  101552. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101553. FLAC__int32 i32;
  101554. FLAC__uint32 u32;
  101555. unsigned u;
  101556. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101557. subframe->residual = decoder->private_->residual[channel];
  101558. subframe->order = order;
  101559. /* read warm-up samples */
  101560. for(u = 0; u < order; u++) {
  101561. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101562. return false; /* read_callback_ sets the state for us */
  101563. subframe->warmup[u] = i32;
  101564. }
  101565. /* read qlp coeff precision */
  101566. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101567. return false; /* read_callback_ sets the state for us */
  101568. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101569. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101570. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101571. return true;
  101572. }
  101573. subframe->qlp_coeff_precision = u32+1;
  101574. /* read qlp shift */
  101575. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101576. return false; /* read_callback_ sets the state for us */
  101577. subframe->quantization_level = i32;
  101578. /* read quantized lp coefficiencts */
  101579. for(u = 0; u < order; u++) {
  101580. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101581. return false; /* read_callback_ sets the state for us */
  101582. subframe->qlp_coeff[u] = i32;
  101583. }
  101584. /* read entropy coding method info */
  101585. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101586. return false; /* read_callback_ sets the state for us */
  101587. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101588. switch(subframe->entropy_coding_method.type) {
  101589. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101590. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101591. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101592. return false; /* read_callback_ sets the state for us */
  101593. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101594. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101595. break;
  101596. default:
  101597. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101598. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101599. return true;
  101600. }
  101601. /* read residual */
  101602. switch(subframe->entropy_coding_method.type) {
  101603. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101604. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101605. 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))
  101606. return false;
  101607. break;
  101608. default:
  101609. FLAC__ASSERT(0);
  101610. }
  101611. /* decode the subframe */
  101612. if(do_full_decode) {
  101613. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101614. /*@@@@@@ technically not pessimistic enough, should be more like
  101615. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101616. */
  101617. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101618. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101619. if(order <= 8)
  101620. 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);
  101621. else
  101622. 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);
  101623. }
  101624. else
  101625. 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);
  101626. else
  101627. 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);
  101628. }
  101629. return true;
  101630. }
  101631. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101632. {
  101633. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101634. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101635. unsigned i;
  101636. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101637. subframe->data = residual;
  101638. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101639. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101640. return false; /* read_callback_ sets the state for us */
  101641. residual[i] = x;
  101642. }
  101643. /* decode the subframe */
  101644. if(do_full_decode)
  101645. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101646. return true;
  101647. }
  101648. 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)
  101649. {
  101650. FLAC__uint32 rice_parameter;
  101651. int i;
  101652. unsigned partition, sample, u;
  101653. const unsigned partitions = 1u << partition_order;
  101654. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101655. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101656. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101657. /* sanity checks */
  101658. if(partition_order == 0) {
  101659. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101660. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101661. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101662. return true;
  101663. }
  101664. }
  101665. else {
  101666. if(partition_samples < predictor_order) {
  101667. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101668. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101669. return true;
  101670. }
  101671. }
  101672. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101673. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101674. return false;
  101675. }
  101676. sample = 0;
  101677. for(partition = 0; partition < partitions; partition++) {
  101678. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101679. return false; /* read_callback_ sets the state for us */
  101680. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101681. if(rice_parameter < pesc) {
  101682. partitioned_rice_contents->raw_bits[partition] = 0;
  101683. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101684. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101685. return false; /* read_callback_ sets the state for us */
  101686. sample += u;
  101687. }
  101688. else {
  101689. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101690. return false; /* read_callback_ sets the state for us */
  101691. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101692. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101693. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101694. return false; /* read_callback_ sets the state for us */
  101695. residual[sample] = i;
  101696. }
  101697. }
  101698. }
  101699. return true;
  101700. }
  101701. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101702. {
  101703. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101704. FLAC__uint32 zero = 0;
  101705. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101706. return false; /* read_callback_ sets the state for us */
  101707. if(zero != 0) {
  101708. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101709. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101710. }
  101711. }
  101712. return true;
  101713. }
  101714. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101715. {
  101716. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101717. if(
  101718. #if FLAC__HAS_OGG
  101719. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101720. !decoder->private_->is_ogg &&
  101721. #endif
  101722. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101723. ) {
  101724. *bytes = 0;
  101725. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101726. return false;
  101727. }
  101728. else if(*bytes > 0) {
  101729. /* While seeking, it is possible for our seek to land in the
  101730. * middle of audio data that looks exactly like a frame header
  101731. * from a future version of an encoder. When that happens, our
  101732. * error callback will get an
  101733. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101734. * unparseable_frame_count. But there is a remote possibility
  101735. * that it is properly synced at such a "future-codec frame",
  101736. * so to make sure, we wait to see many "unparseable" errors in
  101737. * a row before bailing out.
  101738. */
  101739. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101740. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101741. return false;
  101742. }
  101743. else {
  101744. const FLAC__StreamDecoderReadStatus status =
  101745. #if FLAC__HAS_OGG
  101746. decoder->private_->is_ogg?
  101747. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101748. #endif
  101749. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101750. ;
  101751. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101752. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101753. return false;
  101754. }
  101755. else if(*bytes == 0) {
  101756. if(
  101757. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101758. (
  101759. #if FLAC__HAS_OGG
  101760. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101761. !decoder->private_->is_ogg &&
  101762. #endif
  101763. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101764. )
  101765. ) {
  101766. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101767. return false;
  101768. }
  101769. else
  101770. return true;
  101771. }
  101772. else
  101773. return true;
  101774. }
  101775. }
  101776. else {
  101777. /* abort to avoid a deadlock */
  101778. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101779. return false;
  101780. }
  101781. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101782. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101783. * and at the same time hit the end of the stream (for example, seeking
  101784. * to a point that is after the beginning of the last Ogg page). There
  101785. * is no way to report an Ogg sync loss through the callbacks (see note
  101786. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101787. * So to keep the decoder from stopping at this point we gate the call
  101788. * to the eof_callback and let the Ogg decoder aspect set the
  101789. * end-of-stream state when it is needed.
  101790. */
  101791. }
  101792. #if FLAC__HAS_OGG
  101793. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101794. {
  101795. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101796. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101797. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101798. /* we don't really have a way to handle lost sync via read
  101799. * callback so we'll let it pass and let the underlying
  101800. * FLAC decoder catch the error
  101801. */
  101802. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101803. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101804. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101805. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101806. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101807. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101808. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101809. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101810. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101811. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101812. default:
  101813. FLAC__ASSERT(0);
  101814. /* double protection */
  101815. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101816. }
  101817. }
  101818. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101819. {
  101820. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101821. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101822. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101823. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101824. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101825. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101826. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101827. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101828. default:
  101829. /* double protection: */
  101830. FLAC__ASSERT(0);
  101831. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101832. }
  101833. }
  101834. #endif
  101835. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101836. {
  101837. if(decoder->private_->is_seeking) {
  101838. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101839. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101840. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101841. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101842. #if FLAC__HAS_OGG
  101843. decoder->private_->got_a_frame = true;
  101844. #endif
  101845. decoder->private_->last_frame = *frame; /* save the frame */
  101846. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101847. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101848. /* kick out of seek mode */
  101849. decoder->private_->is_seeking = false;
  101850. /* shift out the samples before target_sample */
  101851. if(delta > 0) {
  101852. unsigned channel;
  101853. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101854. for(channel = 0; channel < frame->header.channels; channel++)
  101855. newbuffer[channel] = buffer[channel] + delta;
  101856. decoder->private_->last_frame.header.blocksize -= delta;
  101857. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101858. /* write the relevant samples */
  101859. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101860. }
  101861. else {
  101862. /* write the relevant samples */
  101863. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101864. }
  101865. }
  101866. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101867. }
  101868. /*
  101869. * If we never got STREAMINFO, turn off MD5 checking to save
  101870. * cycles since we don't have a sum to compare to anyway
  101871. */
  101872. if(!decoder->private_->has_stream_info)
  101873. decoder->private_->do_md5_checking = false;
  101874. if(decoder->private_->do_md5_checking) {
  101875. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101876. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101877. }
  101878. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101879. }
  101880. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101881. {
  101882. if(!decoder->private_->is_seeking)
  101883. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101884. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101885. decoder->private_->unparseable_frame_count++;
  101886. }
  101887. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101888. {
  101889. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101890. FLAC__int64 pos = -1;
  101891. int i;
  101892. unsigned approx_bytes_per_frame;
  101893. FLAC__bool first_seek = true;
  101894. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101895. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101896. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101897. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101898. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101899. /* take these from the current frame in case they've changed mid-stream */
  101900. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101901. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101902. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101903. /* use values from stream info if we didn't decode a frame */
  101904. if(channels == 0)
  101905. channels = decoder->private_->stream_info.data.stream_info.channels;
  101906. if(bps == 0)
  101907. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101908. /* we are just guessing here */
  101909. if(max_framesize > 0)
  101910. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101911. /*
  101912. * Check if it's a known fixed-blocksize stream. Note that though
  101913. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101914. * never get a STREAMINFO block when decoding so the value of
  101915. * min_blocksize might be zero.
  101916. */
  101917. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101918. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101919. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101920. }
  101921. else
  101922. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101923. /*
  101924. * First, we set an upper and lower bound on where in the
  101925. * stream we will search. For now we assume the worst case
  101926. * scenario, which is our best guess at the beginning of
  101927. * the first frame and end of the stream.
  101928. */
  101929. lower_bound = first_frame_offset;
  101930. lower_bound_sample = 0;
  101931. upper_bound = stream_length;
  101932. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101933. /*
  101934. * Now we refine the bounds if we have a seektable with
  101935. * suitable points. Note that according to the spec they
  101936. * must be ordered by ascending sample number.
  101937. *
  101938. * Note: to protect against invalid seek tables we will ignore points
  101939. * that have frame_samples==0 or sample_number>=total_samples
  101940. */
  101941. if(seek_table) {
  101942. FLAC__uint64 new_lower_bound = lower_bound;
  101943. FLAC__uint64 new_upper_bound = upper_bound;
  101944. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101945. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101946. /* find the closest seek point <= target_sample, if it exists */
  101947. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101948. if(
  101949. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101950. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101951. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101952. seek_table->points[i].sample_number <= target_sample
  101953. )
  101954. break;
  101955. }
  101956. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101957. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101958. new_lower_bound_sample = seek_table->points[i].sample_number;
  101959. }
  101960. /* find the closest seek point > target_sample, if it exists */
  101961. for(i = 0; i < (int)seek_table->num_points; i++) {
  101962. if(
  101963. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101964. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101965. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101966. seek_table->points[i].sample_number > target_sample
  101967. )
  101968. break;
  101969. }
  101970. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101971. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101972. new_upper_bound_sample = seek_table->points[i].sample_number;
  101973. }
  101974. /* final protection against unsorted seek tables; keep original values if bogus */
  101975. if(new_upper_bound >= new_lower_bound) {
  101976. lower_bound = new_lower_bound;
  101977. upper_bound = new_upper_bound;
  101978. lower_bound_sample = new_lower_bound_sample;
  101979. upper_bound_sample = new_upper_bound_sample;
  101980. }
  101981. }
  101982. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101983. /* there are 2 insidious ways that the following equality occurs, which
  101984. * we need to fix:
  101985. * 1) total_samples is 0 (unknown) and target_sample is 0
  101986. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101987. * exactly equal to the last seek point in the seek table; this
  101988. * means there is no seek point above it, and upper_bound_samples
  101989. * remains equal to the estimate (of target_samples) we made above
  101990. * in either case it does not hurt to move upper_bound_sample up by 1
  101991. */
  101992. if(upper_bound_sample == lower_bound_sample)
  101993. upper_bound_sample++;
  101994. decoder->private_->target_sample = target_sample;
  101995. while(1) {
  101996. /* check if the bounds are still ok */
  101997. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101998. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101999. return false;
  102000. }
  102001. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102002. #if defined _MSC_VER || defined __MINGW32__
  102003. /* with VC++ you have to spoon feed it the casting */
  102004. 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;
  102005. #else
  102006. 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;
  102007. #endif
  102008. #else
  102009. /* a little less accurate: */
  102010. if(upper_bound - lower_bound < 0xffffffff)
  102011. 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;
  102012. else /* @@@ WATCHOUT, ~2TB limit */
  102013. 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;
  102014. #endif
  102015. if(pos >= (FLAC__int64)upper_bound)
  102016. pos = (FLAC__int64)upper_bound - 1;
  102017. if(pos < (FLAC__int64)lower_bound)
  102018. pos = (FLAC__int64)lower_bound;
  102019. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102020. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102021. return false;
  102022. }
  102023. if(!FLAC__stream_decoder_flush(decoder)) {
  102024. /* above call sets the state for us */
  102025. return false;
  102026. }
  102027. /* Now we need to get a frame. First we need to reset our
  102028. * unparseable_frame_count; if we get too many unparseable
  102029. * frames in a row, the read callback will return
  102030. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  102031. * FLAC__stream_decoder_process_single() to return false.
  102032. */
  102033. decoder->private_->unparseable_frame_count = 0;
  102034. if(!FLAC__stream_decoder_process_single(decoder)) {
  102035. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102036. return false;
  102037. }
  102038. /* our write callback will change the state when it gets to the target frame */
  102039. /* 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 */
  102040. #if 0
  102041. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  102042. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  102043. break;
  102044. #endif
  102045. if(!decoder->private_->is_seeking)
  102046. break;
  102047. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102048. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102049. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  102050. if (pos == (FLAC__int64)lower_bound) {
  102051. /* can't move back any more than the first frame, something is fatally wrong */
  102052. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102053. return false;
  102054. }
  102055. /* our last move backwards wasn't big enough, try again */
  102056. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  102057. continue;
  102058. }
  102059. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  102060. first_seek = false;
  102061. /* make sure we are not seeking in corrupted stream */
  102062. if (this_frame_sample < lower_bound_sample) {
  102063. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102064. return false;
  102065. }
  102066. /* we need to narrow the search */
  102067. if(target_sample < this_frame_sample) {
  102068. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102069. /*@@@@@@ what will decode position be if at end of stream? */
  102070. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  102071. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102072. return false;
  102073. }
  102074. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  102075. }
  102076. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  102077. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102078. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  102079. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102080. return false;
  102081. }
  102082. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  102083. }
  102084. }
  102085. return true;
  102086. }
  102087. #if FLAC__HAS_OGG
  102088. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  102089. {
  102090. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  102091. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  102092. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  102093. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  102094. FLAC__bool did_a_seek;
  102095. unsigned iteration = 0;
  102096. /* In the first iterations, we will calculate the target byte position
  102097. * by the distance from the target sample to left_sample and
  102098. * right_sample (let's call it "proportional search"). After that, we
  102099. * will switch to binary search.
  102100. */
  102101. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  102102. /* We will switch to a linear search once our current sample is less
  102103. * than this number of samples ahead of the target sample
  102104. */
  102105. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  102106. /* If the total number of samples is unknown, use a large value, and
  102107. * force binary search immediately.
  102108. */
  102109. if(right_sample == 0) {
  102110. right_sample = (FLAC__uint64)(-1);
  102111. BINARY_SEARCH_AFTER_ITERATION = 0;
  102112. }
  102113. decoder->private_->target_sample = target_sample;
  102114. for( ; ; iteration++) {
  102115. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  102116. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  102117. pos = (right_pos + left_pos) / 2;
  102118. }
  102119. else {
  102120. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102121. #if defined _MSC_VER || defined __MINGW32__
  102122. /* with MSVC you have to spoon feed it the casting */
  102123. 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));
  102124. #else
  102125. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  102126. #endif
  102127. #else
  102128. /* a little less accurate: */
  102129. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  102130. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  102131. else /* @@@ WATCHOUT, ~2TB limit */
  102132. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  102133. #endif
  102134. /* @@@ TODO: might want to limit pos to some distance
  102135. * before EOF, to make sure we land before the last frame,
  102136. * thereby getting a this_frame_sample and so having a better
  102137. * estimate.
  102138. */
  102139. }
  102140. /* physical seek */
  102141. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102142. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102143. return false;
  102144. }
  102145. if(!FLAC__stream_decoder_flush(decoder)) {
  102146. /* above call sets the state for us */
  102147. return false;
  102148. }
  102149. did_a_seek = true;
  102150. }
  102151. else
  102152. did_a_seek = false;
  102153. decoder->private_->got_a_frame = false;
  102154. if(!FLAC__stream_decoder_process_single(decoder)) {
  102155. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102156. return false;
  102157. }
  102158. if(!decoder->private_->got_a_frame) {
  102159. if(did_a_seek) {
  102160. /* this can happen if we seek to a point after the last frame; we drop
  102161. * to binary search right away in this case to avoid any wasted
  102162. * iterations of proportional search.
  102163. */
  102164. right_pos = pos;
  102165. BINARY_SEARCH_AFTER_ITERATION = 0;
  102166. }
  102167. else {
  102168. /* this can probably only happen if total_samples is unknown and the
  102169. * target_sample is past the end of the stream
  102170. */
  102171. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102172. return false;
  102173. }
  102174. }
  102175. /* our write callback will change the state when it gets to the target frame */
  102176. else if(!decoder->private_->is_seeking) {
  102177. break;
  102178. }
  102179. else {
  102180. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102181. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102182. if (did_a_seek) {
  102183. if (this_frame_sample <= target_sample) {
  102184. /* The 'equal' case should not happen, since
  102185. * FLAC__stream_decoder_process_single()
  102186. * should recognize that it has hit the
  102187. * target sample and we would exit through
  102188. * the 'break' above.
  102189. */
  102190. FLAC__ASSERT(this_frame_sample != target_sample);
  102191. left_sample = this_frame_sample;
  102192. /* sanity check to avoid infinite loop */
  102193. if (left_pos == pos) {
  102194. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102195. return false;
  102196. }
  102197. left_pos = pos;
  102198. }
  102199. else if(this_frame_sample > target_sample) {
  102200. right_sample = this_frame_sample;
  102201. /* sanity check to avoid infinite loop */
  102202. if (right_pos == pos) {
  102203. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102204. return false;
  102205. }
  102206. right_pos = pos;
  102207. }
  102208. }
  102209. }
  102210. }
  102211. return true;
  102212. }
  102213. #endif
  102214. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102215. {
  102216. (void)client_data;
  102217. if(*bytes > 0) {
  102218. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102219. if(ferror(decoder->private_->file))
  102220. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102221. else if(*bytes == 0)
  102222. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102223. else
  102224. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102225. }
  102226. else
  102227. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102228. }
  102229. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102230. {
  102231. (void)client_data;
  102232. if(decoder->private_->file == stdin)
  102233. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102234. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102235. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102236. else
  102237. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102238. }
  102239. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102240. {
  102241. off_t pos;
  102242. (void)client_data;
  102243. if(decoder->private_->file == stdin)
  102244. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102245. else if((pos = ftello(decoder->private_->file)) < 0)
  102246. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102247. else {
  102248. *absolute_byte_offset = (FLAC__uint64)pos;
  102249. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102250. }
  102251. }
  102252. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102253. {
  102254. struct stat filestats;
  102255. (void)client_data;
  102256. if(decoder->private_->file == stdin)
  102257. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102258. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102259. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102260. else {
  102261. *stream_length = (FLAC__uint64)filestats.st_size;
  102262. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102263. }
  102264. }
  102265. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102266. {
  102267. (void)client_data;
  102268. return feof(decoder->private_->file)? true : false;
  102269. }
  102270. #endif
  102271. /*** End of inlined file: stream_decoder.c ***/
  102272. /*** Start of inlined file: stream_encoder.c ***/
  102273. /*** Start of inlined file: juce_FlacHeader.h ***/
  102274. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102275. // tasks..
  102276. #define VERSION "1.2.1"
  102277. #define FLAC__NO_DLL 1
  102278. #if JUCE_MSVC
  102279. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102280. #endif
  102281. #if JUCE_MAC
  102282. #define FLAC__SYS_DARWIN 1
  102283. #endif
  102284. /*** End of inlined file: juce_FlacHeader.h ***/
  102285. #if JUCE_USE_FLAC
  102286. #if HAVE_CONFIG_H
  102287. # include <config.h>
  102288. #endif
  102289. #if defined _MSC_VER || defined __MINGW32__
  102290. #include <io.h> /* for _setmode() */
  102291. #include <fcntl.h> /* for _O_BINARY */
  102292. #endif
  102293. #if defined __CYGWIN__ || defined __EMX__
  102294. #include <io.h> /* for setmode(), O_BINARY */
  102295. #include <fcntl.h> /* for _O_BINARY */
  102296. #endif
  102297. #include <limits.h>
  102298. #include <stdio.h>
  102299. #include <stdlib.h> /* for malloc() */
  102300. #include <string.h> /* for memcpy() */
  102301. #include <sys/types.h> /* for off_t */
  102302. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102303. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102304. #define fseeko fseek
  102305. #define ftello ftell
  102306. #endif
  102307. #endif
  102308. /*** Start of inlined file: stream_encoder.h ***/
  102309. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102310. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102311. #if FLAC__HAS_OGG
  102312. #include "private/ogg_encoder_aspect.h"
  102313. #endif
  102314. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102315. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102316. typedef enum {
  102317. FLAC__APODIZATION_BARTLETT,
  102318. FLAC__APODIZATION_BARTLETT_HANN,
  102319. FLAC__APODIZATION_BLACKMAN,
  102320. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102321. FLAC__APODIZATION_CONNES,
  102322. FLAC__APODIZATION_FLATTOP,
  102323. FLAC__APODIZATION_GAUSS,
  102324. FLAC__APODIZATION_HAMMING,
  102325. FLAC__APODIZATION_HANN,
  102326. FLAC__APODIZATION_KAISER_BESSEL,
  102327. FLAC__APODIZATION_NUTTALL,
  102328. FLAC__APODIZATION_RECTANGLE,
  102329. FLAC__APODIZATION_TRIANGLE,
  102330. FLAC__APODIZATION_TUKEY,
  102331. FLAC__APODIZATION_WELCH
  102332. } FLAC__ApodizationFunction;
  102333. typedef struct {
  102334. FLAC__ApodizationFunction type;
  102335. union {
  102336. struct {
  102337. FLAC__real stddev;
  102338. } gauss;
  102339. struct {
  102340. FLAC__real p;
  102341. } tukey;
  102342. } parameters;
  102343. } FLAC__ApodizationSpecification;
  102344. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102345. typedef struct FLAC__StreamEncoderProtected {
  102346. FLAC__StreamEncoderState state;
  102347. FLAC__bool verify;
  102348. FLAC__bool streamable_subset;
  102349. FLAC__bool do_md5;
  102350. FLAC__bool do_mid_side_stereo;
  102351. FLAC__bool loose_mid_side_stereo;
  102352. unsigned channels;
  102353. unsigned bits_per_sample;
  102354. unsigned sample_rate;
  102355. unsigned blocksize;
  102356. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102357. unsigned num_apodizations;
  102358. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102359. #endif
  102360. unsigned max_lpc_order;
  102361. unsigned qlp_coeff_precision;
  102362. FLAC__bool do_qlp_coeff_prec_search;
  102363. FLAC__bool do_exhaustive_model_search;
  102364. FLAC__bool do_escape_coding;
  102365. unsigned min_residual_partition_order;
  102366. unsigned max_residual_partition_order;
  102367. unsigned rice_parameter_search_dist;
  102368. FLAC__uint64 total_samples_estimate;
  102369. FLAC__StreamMetadata **metadata;
  102370. unsigned num_metadata_blocks;
  102371. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102372. #if FLAC__HAS_OGG
  102373. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102374. #endif
  102375. } FLAC__StreamEncoderProtected;
  102376. #endif
  102377. /*** End of inlined file: stream_encoder.h ***/
  102378. #if FLAC__HAS_OGG
  102379. #include "include/private/ogg_helper.h"
  102380. #include "include/private/ogg_mapping.h"
  102381. #endif
  102382. /*** Start of inlined file: stream_encoder_framing.h ***/
  102383. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102384. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102385. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102386. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102387. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102388. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102389. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102390. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102391. #endif
  102392. /*** End of inlined file: stream_encoder_framing.h ***/
  102393. /*** Start of inlined file: window.h ***/
  102394. #ifndef FLAC__PRIVATE__WINDOW_H
  102395. #define FLAC__PRIVATE__WINDOW_H
  102396. #ifdef HAVE_CONFIG_H
  102397. #include <config.h>
  102398. #endif
  102399. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102400. /*
  102401. * FLAC__window_*()
  102402. * --------------------------------------------------------------------
  102403. * Calculates window coefficients according to different apodization
  102404. * functions.
  102405. *
  102406. * OUT window[0,L-1]
  102407. * IN L (number of points in window)
  102408. */
  102409. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102410. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102411. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102412. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102413. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102414. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102415. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102416. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102417. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102418. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102419. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102420. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102421. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102422. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102423. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102424. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102425. #endif
  102426. /*** End of inlined file: window.h ***/
  102427. #ifndef FLaC__INLINE
  102428. #define FLaC__INLINE
  102429. #endif
  102430. #ifdef min
  102431. #undef min
  102432. #endif
  102433. #define min(x,y) ((x)<(y)?(x):(y))
  102434. #ifdef max
  102435. #undef max
  102436. #endif
  102437. #define max(x,y) ((x)>(y)?(x):(y))
  102438. /* Exact Rice codeword length calculation is off by default. The simple
  102439. * (and fast) estimation (of how many bits a residual value will be
  102440. * encoded with) in this encoder is very good, almost always yielding
  102441. * compression within 0.1% of exact calculation.
  102442. */
  102443. #undef EXACT_RICE_BITS_CALCULATION
  102444. /* Rice parameter searching is off by default. The simple (and fast)
  102445. * parameter estimation in this encoder is very good, almost always
  102446. * yielding compression within 0.1% of the optimal parameters.
  102447. */
  102448. #undef ENABLE_RICE_PARAMETER_SEARCH
  102449. typedef struct {
  102450. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102451. unsigned size; /* of each data[] in samples */
  102452. unsigned tail;
  102453. } verify_input_fifo;
  102454. typedef struct {
  102455. const FLAC__byte *data;
  102456. unsigned capacity;
  102457. unsigned bytes;
  102458. } verify_output;
  102459. typedef enum {
  102460. ENCODER_IN_MAGIC = 0,
  102461. ENCODER_IN_METADATA = 1,
  102462. ENCODER_IN_AUDIO = 2
  102463. } EncoderStateHint;
  102464. static struct CompressionLevels {
  102465. FLAC__bool do_mid_side_stereo;
  102466. FLAC__bool loose_mid_side_stereo;
  102467. unsigned max_lpc_order;
  102468. unsigned qlp_coeff_precision;
  102469. FLAC__bool do_qlp_coeff_prec_search;
  102470. FLAC__bool do_escape_coding;
  102471. FLAC__bool do_exhaustive_model_search;
  102472. unsigned min_residual_partition_order;
  102473. unsigned max_residual_partition_order;
  102474. unsigned rice_parameter_search_dist;
  102475. } compression_levels_[] = {
  102476. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102477. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102478. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102479. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102480. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102481. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102482. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102483. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102484. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102485. };
  102486. /***********************************************************************
  102487. *
  102488. * Private class method prototypes
  102489. *
  102490. ***********************************************************************/
  102491. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102492. static void free_(FLAC__StreamEncoder *encoder);
  102493. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102494. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102495. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102496. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102497. #if FLAC__HAS_OGG
  102498. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102499. #endif
  102500. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102501. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102502. static FLAC__bool process_subframe_(
  102503. FLAC__StreamEncoder *encoder,
  102504. unsigned min_partition_order,
  102505. unsigned max_partition_order,
  102506. const FLAC__FrameHeader *frame_header,
  102507. unsigned subframe_bps,
  102508. const FLAC__int32 integer_signal[],
  102509. FLAC__Subframe *subframe[2],
  102510. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102511. FLAC__int32 *residual[2],
  102512. unsigned *best_subframe,
  102513. unsigned *best_bits
  102514. );
  102515. static FLAC__bool add_subframe_(
  102516. FLAC__StreamEncoder *encoder,
  102517. unsigned blocksize,
  102518. unsigned subframe_bps,
  102519. const FLAC__Subframe *subframe,
  102520. FLAC__BitWriter *frame
  102521. );
  102522. static unsigned evaluate_constant_subframe_(
  102523. FLAC__StreamEncoder *encoder,
  102524. const FLAC__int32 signal,
  102525. unsigned blocksize,
  102526. unsigned subframe_bps,
  102527. FLAC__Subframe *subframe
  102528. );
  102529. static unsigned evaluate_fixed_subframe_(
  102530. FLAC__StreamEncoder *encoder,
  102531. const FLAC__int32 signal[],
  102532. FLAC__int32 residual[],
  102533. FLAC__uint64 abs_residual_partition_sums[],
  102534. unsigned raw_bits_per_partition[],
  102535. unsigned blocksize,
  102536. unsigned subframe_bps,
  102537. unsigned order,
  102538. unsigned rice_parameter,
  102539. unsigned rice_parameter_limit,
  102540. unsigned min_partition_order,
  102541. unsigned max_partition_order,
  102542. FLAC__bool do_escape_coding,
  102543. unsigned rice_parameter_search_dist,
  102544. FLAC__Subframe *subframe,
  102545. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102546. );
  102547. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102548. static unsigned evaluate_lpc_subframe_(
  102549. FLAC__StreamEncoder *encoder,
  102550. const FLAC__int32 signal[],
  102551. FLAC__int32 residual[],
  102552. FLAC__uint64 abs_residual_partition_sums[],
  102553. unsigned raw_bits_per_partition[],
  102554. const FLAC__real lp_coeff[],
  102555. unsigned blocksize,
  102556. unsigned subframe_bps,
  102557. unsigned order,
  102558. unsigned qlp_coeff_precision,
  102559. unsigned rice_parameter,
  102560. unsigned rice_parameter_limit,
  102561. unsigned min_partition_order,
  102562. unsigned max_partition_order,
  102563. FLAC__bool do_escape_coding,
  102564. unsigned rice_parameter_search_dist,
  102565. FLAC__Subframe *subframe,
  102566. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102567. );
  102568. #endif
  102569. static unsigned evaluate_verbatim_subframe_(
  102570. FLAC__StreamEncoder *encoder,
  102571. const FLAC__int32 signal[],
  102572. unsigned blocksize,
  102573. unsigned subframe_bps,
  102574. FLAC__Subframe *subframe
  102575. );
  102576. static unsigned find_best_partition_order_(
  102577. struct FLAC__StreamEncoderPrivate *private_,
  102578. const FLAC__int32 residual[],
  102579. FLAC__uint64 abs_residual_partition_sums[],
  102580. unsigned raw_bits_per_partition[],
  102581. unsigned residual_samples,
  102582. unsigned predictor_order,
  102583. unsigned rice_parameter,
  102584. unsigned rice_parameter_limit,
  102585. unsigned min_partition_order,
  102586. unsigned max_partition_order,
  102587. unsigned bps,
  102588. FLAC__bool do_escape_coding,
  102589. unsigned rice_parameter_search_dist,
  102590. FLAC__EntropyCodingMethod *best_ecm
  102591. );
  102592. static void precompute_partition_info_sums_(
  102593. const FLAC__int32 residual[],
  102594. FLAC__uint64 abs_residual_partition_sums[],
  102595. unsigned residual_samples,
  102596. unsigned predictor_order,
  102597. unsigned min_partition_order,
  102598. unsigned max_partition_order,
  102599. unsigned bps
  102600. );
  102601. static void precompute_partition_info_escapes_(
  102602. const FLAC__int32 residual[],
  102603. unsigned raw_bits_per_partition[],
  102604. unsigned residual_samples,
  102605. unsigned predictor_order,
  102606. unsigned min_partition_order,
  102607. unsigned max_partition_order
  102608. );
  102609. static FLAC__bool set_partitioned_rice_(
  102610. #ifdef EXACT_RICE_BITS_CALCULATION
  102611. const FLAC__int32 residual[],
  102612. #endif
  102613. const FLAC__uint64 abs_residual_partition_sums[],
  102614. const unsigned raw_bits_per_partition[],
  102615. const unsigned residual_samples,
  102616. const unsigned predictor_order,
  102617. const unsigned suggested_rice_parameter,
  102618. const unsigned rice_parameter_limit,
  102619. const unsigned rice_parameter_search_dist,
  102620. const unsigned partition_order,
  102621. const FLAC__bool search_for_escapes,
  102622. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102623. unsigned *bits
  102624. );
  102625. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102626. /* verify-related routines: */
  102627. static void append_to_verify_fifo_(
  102628. verify_input_fifo *fifo,
  102629. const FLAC__int32 * const input[],
  102630. unsigned input_offset,
  102631. unsigned channels,
  102632. unsigned wide_samples
  102633. );
  102634. static void append_to_verify_fifo_interleaved_(
  102635. verify_input_fifo *fifo,
  102636. const FLAC__int32 input[],
  102637. unsigned input_offset,
  102638. unsigned channels,
  102639. unsigned wide_samples
  102640. );
  102641. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102642. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102643. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102644. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102645. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102646. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102647. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102648. 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);
  102649. static FILE *get_binary_stdout_(void);
  102650. /***********************************************************************
  102651. *
  102652. * Private class data
  102653. *
  102654. ***********************************************************************/
  102655. typedef struct FLAC__StreamEncoderPrivate {
  102656. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102657. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102658. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102659. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102660. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102661. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102662. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102663. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102664. #endif
  102665. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102666. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102667. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102668. FLAC__int32 *residual_workspace_mid_side[2][2];
  102669. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102670. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102671. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102672. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102673. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102674. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102675. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102676. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102677. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102678. unsigned best_subframe_mid_side[2];
  102679. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102680. unsigned best_subframe_bits_mid_side[2];
  102681. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102682. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102683. FLAC__BitWriter *frame; /* the current frame being worked on */
  102684. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102685. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102686. FLAC__ChannelAssignment last_channel_assignment;
  102687. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102688. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102689. unsigned current_sample_number;
  102690. unsigned current_frame_number;
  102691. FLAC__MD5Context md5context;
  102692. FLAC__CPUInfo cpuinfo;
  102693. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102694. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102695. #else
  102696. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102697. #endif
  102698. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102699. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102700. 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[]);
  102701. 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[]);
  102702. 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[]);
  102703. #endif
  102704. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102705. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102706. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102707. FLAC__bool disable_constant_subframes;
  102708. FLAC__bool disable_fixed_subframes;
  102709. FLAC__bool disable_verbatim_subframes;
  102710. #if FLAC__HAS_OGG
  102711. FLAC__bool is_ogg;
  102712. #endif
  102713. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102714. FLAC__StreamEncoderSeekCallback seek_callback;
  102715. FLAC__StreamEncoderTellCallback tell_callback;
  102716. FLAC__StreamEncoderWriteCallback write_callback;
  102717. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102718. FLAC__StreamEncoderProgressCallback progress_callback;
  102719. void *client_data;
  102720. unsigned first_seekpoint_to_check;
  102721. FILE *file; /* only used when encoding to a file */
  102722. FLAC__uint64 bytes_written;
  102723. FLAC__uint64 samples_written;
  102724. unsigned frames_written;
  102725. unsigned total_frames_estimate;
  102726. /* unaligned (original) pointers to allocated data */
  102727. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102728. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102729. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102730. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102731. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102732. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102733. FLAC__real *windowed_signal_unaligned;
  102734. #endif
  102735. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102736. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102737. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102738. unsigned *raw_bits_per_partition_unaligned;
  102739. /*
  102740. * These fields have been moved here from private function local
  102741. * declarations merely to save stack space during encoding.
  102742. */
  102743. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102744. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102745. #endif
  102746. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102747. /*
  102748. * The data for the verify section
  102749. */
  102750. struct {
  102751. FLAC__StreamDecoder *decoder;
  102752. EncoderStateHint state_hint;
  102753. FLAC__bool needs_magic_hack;
  102754. verify_input_fifo input_fifo;
  102755. verify_output output;
  102756. struct {
  102757. FLAC__uint64 absolute_sample;
  102758. unsigned frame_number;
  102759. unsigned channel;
  102760. unsigned sample;
  102761. FLAC__int32 expected;
  102762. FLAC__int32 got;
  102763. } error_stats;
  102764. } verify;
  102765. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102766. } FLAC__StreamEncoderPrivate;
  102767. /***********************************************************************
  102768. *
  102769. * Public static class data
  102770. *
  102771. ***********************************************************************/
  102772. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102773. "FLAC__STREAM_ENCODER_OK",
  102774. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102775. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102776. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102777. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102778. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102779. "FLAC__STREAM_ENCODER_IO_ERROR",
  102780. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102781. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102782. };
  102783. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102784. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102785. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102786. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102787. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102788. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102789. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102790. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102791. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102792. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102793. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102794. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102795. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102796. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102797. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102798. };
  102799. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102800. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102801. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102802. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102803. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102804. };
  102805. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102806. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102807. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102808. };
  102809. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102810. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102811. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102812. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102813. };
  102814. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102815. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102816. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102817. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102818. };
  102819. /* Number of samples that will be overread to watch for end of stream. By
  102820. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102821. * always try to read blocksize+1 samples before encoding a block, so that
  102822. * even if the stream has a total sample count that is an integral multiple
  102823. * of the blocksize, we will still notice when we are encoding the last
  102824. * block. This is needed, for example, to correctly set the end-of-stream
  102825. * marker in Ogg FLAC.
  102826. *
  102827. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102828. * not really any reason to change it.
  102829. */
  102830. static const unsigned OVERREAD_ = 1;
  102831. /***********************************************************************
  102832. *
  102833. * Class constructor/destructor
  102834. *
  102835. */
  102836. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102837. {
  102838. FLAC__StreamEncoder *encoder;
  102839. unsigned i;
  102840. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102841. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102842. if(encoder == 0) {
  102843. return 0;
  102844. }
  102845. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102846. if(encoder->protected_ == 0) {
  102847. free(encoder);
  102848. return 0;
  102849. }
  102850. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102851. if(encoder->private_ == 0) {
  102852. free(encoder->protected_);
  102853. free(encoder);
  102854. return 0;
  102855. }
  102856. encoder->private_->frame = FLAC__bitwriter_new();
  102857. if(encoder->private_->frame == 0) {
  102858. free(encoder->private_);
  102859. free(encoder->protected_);
  102860. free(encoder);
  102861. return 0;
  102862. }
  102863. encoder->private_->file = 0;
  102864. set_defaults_enc(encoder);
  102865. encoder->private_->is_being_deleted = false;
  102866. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102867. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102868. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102869. }
  102870. for(i = 0; i < 2; i++) {
  102871. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102872. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102873. }
  102874. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102875. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102876. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102877. }
  102878. for(i = 0; i < 2; i++) {
  102879. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102880. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102881. }
  102882. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102883. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102884. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102885. }
  102886. for(i = 0; i < 2; i++) {
  102887. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102888. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102889. }
  102890. for(i = 0; i < 2; i++)
  102891. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102892. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102893. return encoder;
  102894. }
  102895. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102896. {
  102897. unsigned i;
  102898. FLAC__ASSERT(0 != encoder);
  102899. FLAC__ASSERT(0 != encoder->protected_);
  102900. FLAC__ASSERT(0 != encoder->private_);
  102901. FLAC__ASSERT(0 != encoder->private_->frame);
  102902. encoder->private_->is_being_deleted = true;
  102903. (void)FLAC__stream_encoder_finish(encoder);
  102904. if(0 != encoder->private_->verify.decoder)
  102905. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102906. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102907. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102908. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102909. }
  102910. for(i = 0; i < 2; i++) {
  102911. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102912. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102913. }
  102914. for(i = 0; i < 2; i++)
  102915. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102916. FLAC__bitwriter_delete(encoder->private_->frame);
  102917. free(encoder->private_);
  102918. free(encoder->protected_);
  102919. free(encoder);
  102920. }
  102921. /***********************************************************************
  102922. *
  102923. * Public class methods
  102924. *
  102925. ***********************************************************************/
  102926. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102927. FLAC__StreamEncoder *encoder,
  102928. FLAC__StreamEncoderReadCallback read_callback,
  102929. FLAC__StreamEncoderWriteCallback write_callback,
  102930. FLAC__StreamEncoderSeekCallback seek_callback,
  102931. FLAC__StreamEncoderTellCallback tell_callback,
  102932. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102933. void *client_data,
  102934. FLAC__bool is_ogg
  102935. )
  102936. {
  102937. unsigned i;
  102938. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102939. FLAC__ASSERT(0 != encoder);
  102940. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102941. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102942. #if !FLAC__HAS_OGG
  102943. if(is_ogg)
  102944. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102945. #endif
  102946. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102947. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102948. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102949. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102950. if(encoder->protected_->channels != 2) {
  102951. encoder->protected_->do_mid_side_stereo = false;
  102952. encoder->protected_->loose_mid_side_stereo = false;
  102953. }
  102954. else if(!encoder->protected_->do_mid_side_stereo)
  102955. encoder->protected_->loose_mid_side_stereo = false;
  102956. if(encoder->protected_->bits_per_sample >= 32)
  102957. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102958. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102959. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102960. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102961. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102962. if(encoder->protected_->blocksize == 0) {
  102963. if(encoder->protected_->max_lpc_order == 0)
  102964. encoder->protected_->blocksize = 1152;
  102965. else
  102966. encoder->protected_->blocksize = 4096;
  102967. }
  102968. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102969. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102970. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102971. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102972. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102973. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102974. if(encoder->protected_->qlp_coeff_precision == 0) {
  102975. if(encoder->protected_->bits_per_sample < 16) {
  102976. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102977. /* @@@ until then we'll make a guess */
  102978. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102979. }
  102980. else if(encoder->protected_->bits_per_sample == 16) {
  102981. if(encoder->protected_->blocksize <= 192)
  102982. encoder->protected_->qlp_coeff_precision = 7;
  102983. else if(encoder->protected_->blocksize <= 384)
  102984. encoder->protected_->qlp_coeff_precision = 8;
  102985. else if(encoder->protected_->blocksize <= 576)
  102986. encoder->protected_->qlp_coeff_precision = 9;
  102987. else if(encoder->protected_->blocksize <= 1152)
  102988. encoder->protected_->qlp_coeff_precision = 10;
  102989. else if(encoder->protected_->blocksize <= 2304)
  102990. encoder->protected_->qlp_coeff_precision = 11;
  102991. else if(encoder->protected_->blocksize <= 4608)
  102992. encoder->protected_->qlp_coeff_precision = 12;
  102993. else
  102994. encoder->protected_->qlp_coeff_precision = 13;
  102995. }
  102996. else {
  102997. if(encoder->protected_->blocksize <= 384)
  102998. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102999. else if(encoder->protected_->blocksize <= 1152)
  103000. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  103001. else
  103002. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  103003. }
  103004. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  103005. }
  103006. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  103007. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  103008. if(encoder->protected_->streamable_subset) {
  103009. if(
  103010. encoder->protected_->blocksize != 192 &&
  103011. encoder->protected_->blocksize != 576 &&
  103012. encoder->protected_->blocksize != 1152 &&
  103013. encoder->protected_->blocksize != 2304 &&
  103014. encoder->protected_->blocksize != 4608 &&
  103015. encoder->protected_->blocksize != 256 &&
  103016. encoder->protected_->blocksize != 512 &&
  103017. encoder->protected_->blocksize != 1024 &&
  103018. encoder->protected_->blocksize != 2048 &&
  103019. encoder->protected_->blocksize != 4096 &&
  103020. encoder->protected_->blocksize != 8192 &&
  103021. encoder->protected_->blocksize != 16384
  103022. )
  103023. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103024. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  103025. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103026. if(
  103027. encoder->protected_->bits_per_sample != 8 &&
  103028. encoder->protected_->bits_per_sample != 12 &&
  103029. encoder->protected_->bits_per_sample != 16 &&
  103030. encoder->protected_->bits_per_sample != 20 &&
  103031. encoder->protected_->bits_per_sample != 24
  103032. )
  103033. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103034. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  103035. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103036. if(
  103037. encoder->protected_->sample_rate <= 48000 &&
  103038. (
  103039. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  103040. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  103041. )
  103042. ) {
  103043. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103044. }
  103045. }
  103046. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  103047. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  103048. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  103049. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  103050. #if FLAC__HAS_OGG
  103051. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  103052. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  103053. unsigned i;
  103054. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  103055. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103056. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  103057. for( ; i > 0; i--)
  103058. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  103059. encoder->protected_->metadata[0] = vc;
  103060. break;
  103061. }
  103062. }
  103063. }
  103064. #endif
  103065. /* keep track of any SEEKTABLE block */
  103066. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  103067. unsigned i;
  103068. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103069. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103070. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  103071. break; /* take only the first one */
  103072. }
  103073. }
  103074. }
  103075. /* validate metadata */
  103076. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  103077. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103078. metadata_has_seektable = false;
  103079. metadata_has_vorbis_comment = false;
  103080. metadata_picture_has_type1 = false;
  103081. metadata_picture_has_type2 = false;
  103082. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103083. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  103084. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  103085. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103086. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103087. if(metadata_has_seektable) /* only one is allowed */
  103088. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103089. metadata_has_seektable = true;
  103090. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  103091. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103092. }
  103093. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103094. if(metadata_has_vorbis_comment) /* only one is allowed */
  103095. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103096. metadata_has_vorbis_comment = true;
  103097. }
  103098. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  103099. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  103100. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103101. }
  103102. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  103103. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  103104. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103105. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  103106. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  103107. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103108. metadata_picture_has_type1 = true;
  103109. /* standard icon must be 32x32 pixel PNG */
  103110. if(
  103111. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  103112. (
  103113. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  103114. m->data.picture.width != 32 ||
  103115. m->data.picture.height != 32
  103116. )
  103117. )
  103118. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103119. }
  103120. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  103121. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  103122. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103123. metadata_picture_has_type2 = true;
  103124. }
  103125. }
  103126. }
  103127. encoder->private_->input_capacity = 0;
  103128. for(i = 0; i < encoder->protected_->channels; i++) {
  103129. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  103130. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103131. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  103132. #endif
  103133. }
  103134. for(i = 0; i < 2; i++) {
  103135. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  103136. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103137. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  103138. #endif
  103139. }
  103140. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103141. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  103142. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  103143. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  103144. #endif
  103145. for(i = 0; i < encoder->protected_->channels; i++) {
  103146. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  103147. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  103148. encoder->private_->best_subframe[i] = 0;
  103149. }
  103150. for(i = 0; i < 2; i++) {
  103151. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  103152. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  103153. encoder->private_->best_subframe_mid_side[i] = 0;
  103154. }
  103155. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  103156. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  103157. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103158. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  103159. #else
  103160. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  103161. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  103162. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  103163. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  103164. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  103165. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  103166. 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);
  103167. #endif
  103168. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  103169. encoder->private_->loose_mid_side_stereo_frames = 1;
  103170. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103171. encoder->private_->current_sample_number = 0;
  103172. encoder->private_->current_frame_number = 0;
  103173. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  103174. 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? */
  103175. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  103176. /*
  103177. * get the CPU info and set the function pointers
  103178. */
  103179. FLAC__cpu_info(&encoder->private_->cpuinfo);
  103180. /* first default to the non-asm routines */
  103181. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103182. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  103183. #endif
  103184. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  103185. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103186. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103187. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  103188. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103189. #endif
  103190. /* now override with asm where appropriate */
  103191. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103192. # ifndef FLAC__NO_ASM
  103193. if(encoder->private_->cpuinfo.use_asm) {
  103194. # ifdef FLAC__CPU_IA32
  103195. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  103196. # ifdef FLAC__HAS_NASM
  103197. if(encoder->private_->cpuinfo.data.ia32.sse) {
  103198. if(encoder->protected_->max_lpc_order < 4)
  103199. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  103200. else if(encoder->protected_->max_lpc_order < 8)
  103201. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  103202. else if(encoder->protected_->max_lpc_order < 12)
  103203. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  103204. else
  103205. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103206. }
  103207. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103208. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103209. else
  103210. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103211. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103212. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103213. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103214. }
  103215. else {
  103216. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103217. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103218. }
  103219. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103220. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103221. # endif /* FLAC__HAS_NASM */
  103222. # endif /* FLAC__CPU_IA32 */
  103223. }
  103224. # endif /* !FLAC__NO_ASM */
  103225. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103226. /* finally override based on wide-ness if necessary */
  103227. if(encoder->private_->use_wide_by_block) {
  103228. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103229. }
  103230. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103231. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103232. #if FLAC__HAS_OGG
  103233. encoder->private_->is_ogg = is_ogg;
  103234. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103235. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103236. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103237. }
  103238. #endif
  103239. encoder->private_->read_callback = read_callback;
  103240. encoder->private_->write_callback = write_callback;
  103241. encoder->private_->seek_callback = seek_callback;
  103242. encoder->private_->tell_callback = tell_callback;
  103243. encoder->private_->metadata_callback = metadata_callback;
  103244. encoder->private_->client_data = client_data;
  103245. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103246. /* the above function sets the state for us in case of an error */
  103247. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103248. }
  103249. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103250. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103251. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103252. }
  103253. /*
  103254. * Set up the verify stuff if necessary
  103255. */
  103256. if(encoder->protected_->verify) {
  103257. /*
  103258. * First, set up the fifo which will hold the
  103259. * original signal to compare against
  103260. */
  103261. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103262. for(i = 0; i < encoder->protected_->channels; i++) {
  103263. 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))) {
  103264. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103265. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103266. }
  103267. }
  103268. encoder->private_->verify.input_fifo.tail = 0;
  103269. /*
  103270. * Now set up a stream decoder for verification
  103271. */
  103272. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103273. if(0 == encoder->private_->verify.decoder) {
  103274. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103275. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103276. }
  103277. 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) {
  103278. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103279. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103280. }
  103281. }
  103282. encoder->private_->verify.error_stats.absolute_sample = 0;
  103283. encoder->private_->verify.error_stats.frame_number = 0;
  103284. encoder->private_->verify.error_stats.channel = 0;
  103285. encoder->private_->verify.error_stats.sample = 0;
  103286. encoder->private_->verify.error_stats.expected = 0;
  103287. encoder->private_->verify.error_stats.got = 0;
  103288. /*
  103289. * These must be done before we write any metadata, because that
  103290. * calls the write_callback, which uses these values.
  103291. */
  103292. encoder->private_->first_seekpoint_to_check = 0;
  103293. encoder->private_->samples_written = 0;
  103294. encoder->protected_->streaminfo_offset = 0;
  103295. encoder->protected_->seektable_offset = 0;
  103296. encoder->protected_->audio_offset = 0;
  103297. /*
  103298. * write the stream header
  103299. */
  103300. if(encoder->protected_->verify)
  103301. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103302. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103303. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103304. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103305. }
  103306. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103307. /* the above function sets the state for us in case of an error */
  103308. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103309. }
  103310. /*
  103311. * write the STREAMINFO metadata block
  103312. */
  103313. if(encoder->protected_->verify)
  103314. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103315. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103316. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103317. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103318. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103319. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103320. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103321. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103322. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103323. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103324. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103325. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103326. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103327. if(encoder->protected_->do_md5)
  103328. FLAC__MD5Init(&encoder->private_->md5context);
  103329. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103330. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103331. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103332. }
  103333. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103334. /* the above function sets the state for us in case of an error */
  103335. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103336. }
  103337. /*
  103338. * Now that the STREAMINFO block is written, we can init this to an
  103339. * absurdly-high value...
  103340. */
  103341. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103342. /* ... and clear this to 0 */
  103343. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103344. /*
  103345. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103346. * if not, we will write an empty one (FLAC__add_metadata_block()
  103347. * automatically supplies the vendor string).
  103348. *
  103349. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103350. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103351. * true it will have already insured that the metadata list is properly
  103352. * ordered.)
  103353. */
  103354. if(!metadata_has_vorbis_comment) {
  103355. FLAC__StreamMetadata vorbis_comment;
  103356. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103357. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103358. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103359. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103360. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103361. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103362. vorbis_comment.data.vorbis_comment.comments = 0;
  103363. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103364. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103365. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103366. }
  103367. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103368. /* the above function sets the state for us in case of an error */
  103369. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103370. }
  103371. }
  103372. /*
  103373. * write the user's metadata blocks
  103374. */
  103375. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103376. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103377. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103378. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103379. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103380. }
  103381. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103382. /* the above function sets the state for us in case of an error */
  103383. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103384. }
  103385. }
  103386. /* now that all the metadata is written, we save the stream offset */
  103387. 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 */
  103388. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103389. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103390. }
  103391. if(encoder->protected_->verify)
  103392. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103393. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103394. }
  103395. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103396. FLAC__StreamEncoder *encoder,
  103397. FLAC__StreamEncoderWriteCallback write_callback,
  103398. FLAC__StreamEncoderSeekCallback seek_callback,
  103399. FLAC__StreamEncoderTellCallback tell_callback,
  103400. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103401. void *client_data
  103402. )
  103403. {
  103404. return init_stream_internal_enc(
  103405. encoder,
  103406. /*read_callback=*/0,
  103407. write_callback,
  103408. seek_callback,
  103409. tell_callback,
  103410. metadata_callback,
  103411. client_data,
  103412. /*is_ogg=*/false
  103413. );
  103414. }
  103415. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103416. FLAC__StreamEncoder *encoder,
  103417. FLAC__StreamEncoderReadCallback read_callback,
  103418. FLAC__StreamEncoderWriteCallback write_callback,
  103419. FLAC__StreamEncoderSeekCallback seek_callback,
  103420. FLAC__StreamEncoderTellCallback tell_callback,
  103421. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103422. void *client_data
  103423. )
  103424. {
  103425. return init_stream_internal_enc(
  103426. encoder,
  103427. read_callback,
  103428. write_callback,
  103429. seek_callback,
  103430. tell_callback,
  103431. metadata_callback,
  103432. client_data,
  103433. /*is_ogg=*/true
  103434. );
  103435. }
  103436. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103437. FLAC__StreamEncoder *encoder,
  103438. FILE *file,
  103439. FLAC__StreamEncoderProgressCallback progress_callback,
  103440. void *client_data,
  103441. FLAC__bool is_ogg
  103442. )
  103443. {
  103444. FLAC__StreamEncoderInitStatus init_status;
  103445. FLAC__ASSERT(0 != encoder);
  103446. FLAC__ASSERT(0 != file);
  103447. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103448. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103449. /* double protection */
  103450. if(file == 0) {
  103451. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103452. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103453. }
  103454. /*
  103455. * To make sure that our file does not go unclosed after an error, we
  103456. * must assign the FILE pointer before any further error can occur in
  103457. * this routine.
  103458. */
  103459. if(file == stdout)
  103460. file = get_binary_stdout_(); /* just to be safe */
  103461. encoder->private_->file = file;
  103462. encoder->private_->progress_callback = progress_callback;
  103463. encoder->private_->bytes_written = 0;
  103464. encoder->private_->samples_written = 0;
  103465. encoder->private_->frames_written = 0;
  103466. init_status = init_stream_internal_enc(
  103467. encoder,
  103468. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103469. file_write_callback_,
  103470. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103471. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103472. /*metadata_callback=*/0,
  103473. client_data,
  103474. is_ogg
  103475. );
  103476. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103477. /* the above function sets the state for us in case of an error */
  103478. return init_status;
  103479. }
  103480. {
  103481. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103482. FLAC__ASSERT(blocksize != 0);
  103483. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103484. }
  103485. return init_status;
  103486. }
  103487. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103488. FLAC__StreamEncoder *encoder,
  103489. FILE *file,
  103490. FLAC__StreamEncoderProgressCallback progress_callback,
  103491. void *client_data
  103492. )
  103493. {
  103494. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103495. }
  103496. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103497. FLAC__StreamEncoder *encoder,
  103498. FILE *file,
  103499. FLAC__StreamEncoderProgressCallback progress_callback,
  103500. void *client_data
  103501. )
  103502. {
  103503. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103504. }
  103505. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103506. FLAC__StreamEncoder *encoder,
  103507. const char *filename,
  103508. FLAC__StreamEncoderProgressCallback progress_callback,
  103509. void *client_data,
  103510. FLAC__bool is_ogg
  103511. )
  103512. {
  103513. FILE *file;
  103514. FLAC__ASSERT(0 != encoder);
  103515. /*
  103516. * To make sure that our file does not go unclosed after an error, we
  103517. * have to do the same entrance checks here that are later performed
  103518. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103519. */
  103520. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103521. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103522. file = filename? fopen(filename, "w+b") : stdout;
  103523. if(file == 0) {
  103524. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103525. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103526. }
  103527. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103528. }
  103529. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103530. FLAC__StreamEncoder *encoder,
  103531. const char *filename,
  103532. FLAC__StreamEncoderProgressCallback progress_callback,
  103533. void *client_data
  103534. )
  103535. {
  103536. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103537. }
  103538. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103539. FLAC__StreamEncoder *encoder,
  103540. const char *filename,
  103541. FLAC__StreamEncoderProgressCallback progress_callback,
  103542. void *client_data
  103543. )
  103544. {
  103545. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103546. }
  103547. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103548. {
  103549. FLAC__bool error = false;
  103550. FLAC__ASSERT(0 != encoder);
  103551. FLAC__ASSERT(0 != encoder->private_);
  103552. FLAC__ASSERT(0 != encoder->protected_);
  103553. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103554. return true;
  103555. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103556. if(encoder->private_->current_sample_number != 0) {
  103557. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103558. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103559. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103560. error = true;
  103561. }
  103562. }
  103563. if(encoder->protected_->do_md5)
  103564. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103565. if(!encoder->private_->is_being_deleted) {
  103566. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103567. if(encoder->private_->seek_callback) {
  103568. #if FLAC__HAS_OGG
  103569. if(encoder->private_->is_ogg)
  103570. update_ogg_metadata_(encoder);
  103571. else
  103572. #endif
  103573. update_metadata_(encoder);
  103574. /* check if an error occurred while updating metadata */
  103575. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103576. error = true;
  103577. }
  103578. if(encoder->private_->metadata_callback)
  103579. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103580. }
  103581. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103582. if(!error)
  103583. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103584. error = true;
  103585. }
  103586. }
  103587. if(0 != encoder->private_->file) {
  103588. if(encoder->private_->file != stdout)
  103589. fclose(encoder->private_->file);
  103590. encoder->private_->file = 0;
  103591. }
  103592. #if FLAC__HAS_OGG
  103593. if(encoder->private_->is_ogg)
  103594. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103595. #endif
  103596. free_(encoder);
  103597. set_defaults_enc(encoder);
  103598. if(!error)
  103599. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103600. return !error;
  103601. }
  103602. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103603. {
  103604. FLAC__ASSERT(0 != encoder);
  103605. FLAC__ASSERT(0 != encoder->private_);
  103606. FLAC__ASSERT(0 != encoder->protected_);
  103607. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103608. return false;
  103609. #if FLAC__HAS_OGG
  103610. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103611. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103612. return true;
  103613. #else
  103614. (void)value;
  103615. return false;
  103616. #endif
  103617. }
  103618. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103619. {
  103620. FLAC__ASSERT(0 != encoder);
  103621. FLAC__ASSERT(0 != encoder->private_);
  103622. FLAC__ASSERT(0 != encoder->protected_);
  103623. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103624. return false;
  103625. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103626. encoder->protected_->verify = value;
  103627. #endif
  103628. return true;
  103629. }
  103630. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103631. {
  103632. FLAC__ASSERT(0 != encoder);
  103633. FLAC__ASSERT(0 != encoder->private_);
  103634. FLAC__ASSERT(0 != encoder->protected_);
  103635. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103636. return false;
  103637. encoder->protected_->streamable_subset = value;
  103638. return true;
  103639. }
  103640. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(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->protected_->do_md5 = value;
  103648. return true;
  103649. }
  103650. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned 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->protected_->channels = value;
  103658. return true;
  103659. }
  103660. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned 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->protected_->bits_per_sample = value;
  103668. return true;
  103669. }
  103670. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103671. {
  103672. FLAC__ASSERT(0 != encoder);
  103673. FLAC__ASSERT(0 != encoder->private_);
  103674. FLAC__ASSERT(0 != encoder->protected_);
  103675. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103676. return false;
  103677. encoder->protected_->sample_rate = value;
  103678. return true;
  103679. }
  103680. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103681. {
  103682. FLAC__bool ok = true;
  103683. FLAC__ASSERT(0 != encoder);
  103684. FLAC__ASSERT(0 != encoder->private_);
  103685. FLAC__ASSERT(0 != encoder->protected_);
  103686. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103687. return false;
  103688. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103689. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103690. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103691. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103692. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103693. #if 0
  103694. /* was: */
  103695. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103696. /* but it's too hard to specify the string in a locale-specific way */
  103697. #else
  103698. encoder->protected_->num_apodizations = 1;
  103699. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103700. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103701. #endif
  103702. #endif
  103703. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103704. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103705. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103706. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103707. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103708. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103709. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103710. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103711. return ok;
  103712. }
  103713. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103714. {
  103715. FLAC__ASSERT(0 != encoder);
  103716. FLAC__ASSERT(0 != encoder->private_);
  103717. FLAC__ASSERT(0 != encoder->protected_);
  103718. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103719. return false;
  103720. encoder->protected_->blocksize = value;
  103721. return true;
  103722. }
  103723. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103724. {
  103725. FLAC__ASSERT(0 != encoder);
  103726. FLAC__ASSERT(0 != encoder->private_);
  103727. FLAC__ASSERT(0 != encoder->protected_);
  103728. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103729. return false;
  103730. encoder->protected_->do_mid_side_stereo = value;
  103731. return true;
  103732. }
  103733. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103734. {
  103735. FLAC__ASSERT(0 != encoder);
  103736. FLAC__ASSERT(0 != encoder->private_);
  103737. FLAC__ASSERT(0 != encoder->protected_);
  103738. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103739. return false;
  103740. encoder->protected_->loose_mid_side_stereo = value;
  103741. return true;
  103742. }
  103743. /*@@@@add to tests*/
  103744. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103745. {
  103746. FLAC__ASSERT(0 != encoder);
  103747. FLAC__ASSERT(0 != encoder->private_);
  103748. FLAC__ASSERT(0 != encoder->protected_);
  103749. FLAC__ASSERT(0 != specification);
  103750. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103751. return false;
  103752. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103753. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103754. #else
  103755. encoder->protected_->num_apodizations = 0;
  103756. while(1) {
  103757. const char *s = strchr(specification, ';');
  103758. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103759. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103760. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103761. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103762. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103763. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103764. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103765. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103766. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103767. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103768. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103769. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103770. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103771. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103772. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103773. if (stddev > 0.0 && stddev <= 0.5) {
  103774. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103775. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103776. }
  103777. }
  103778. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103779. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103780. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103781. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103782. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103783. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103784. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103785. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103786. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103787. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103788. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103789. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103790. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103791. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103792. if (p >= 0.0 && p <= 1.0) {
  103793. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103794. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103795. }
  103796. }
  103797. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103798. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103799. if (encoder->protected_->num_apodizations == 32)
  103800. break;
  103801. if (s)
  103802. specification = s+1;
  103803. else
  103804. break;
  103805. }
  103806. if(encoder->protected_->num_apodizations == 0) {
  103807. encoder->protected_->num_apodizations = 1;
  103808. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103809. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103810. }
  103811. #endif
  103812. return true;
  103813. }
  103814. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103815. {
  103816. FLAC__ASSERT(0 != encoder);
  103817. FLAC__ASSERT(0 != encoder->private_);
  103818. FLAC__ASSERT(0 != encoder->protected_);
  103819. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103820. return false;
  103821. encoder->protected_->max_lpc_order = value;
  103822. return true;
  103823. }
  103824. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103825. {
  103826. FLAC__ASSERT(0 != encoder);
  103827. FLAC__ASSERT(0 != encoder->private_);
  103828. FLAC__ASSERT(0 != encoder->protected_);
  103829. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103830. return false;
  103831. encoder->protected_->qlp_coeff_precision = value;
  103832. return true;
  103833. }
  103834. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103835. {
  103836. FLAC__ASSERT(0 != encoder);
  103837. FLAC__ASSERT(0 != encoder->private_);
  103838. FLAC__ASSERT(0 != encoder->protected_);
  103839. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103840. return false;
  103841. encoder->protected_->do_qlp_coeff_prec_search = value;
  103842. return true;
  103843. }
  103844. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103845. {
  103846. FLAC__ASSERT(0 != encoder);
  103847. FLAC__ASSERT(0 != encoder->private_);
  103848. FLAC__ASSERT(0 != encoder->protected_);
  103849. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103850. return false;
  103851. #if 0
  103852. /*@@@ deprecated: */
  103853. encoder->protected_->do_escape_coding = value;
  103854. #else
  103855. (void)value;
  103856. #endif
  103857. return true;
  103858. }
  103859. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103860. {
  103861. FLAC__ASSERT(0 != encoder);
  103862. FLAC__ASSERT(0 != encoder->private_);
  103863. FLAC__ASSERT(0 != encoder->protected_);
  103864. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103865. return false;
  103866. encoder->protected_->do_exhaustive_model_search = value;
  103867. return true;
  103868. }
  103869. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103870. {
  103871. FLAC__ASSERT(0 != encoder);
  103872. FLAC__ASSERT(0 != encoder->private_);
  103873. FLAC__ASSERT(0 != encoder->protected_);
  103874. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103875. return false;
  103876. encoder->protected_->min_residual_partition_order = value;
  103877. return true;
  103878. }
  103879. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103880. {
  103881. FLAC__ASSERT(0 != encoder);
  103882. FLAC__ASSERT(0 != encoder->private_);
  103883. FLAC__ASSERT(0 != encoder->protected_);
  103884. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103885. return false;
  103886. encoder->protected_->max_residual_partition_order = value;
  103887. return true;
  103888. }
  103889. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103890. {
  103891. FLAC__ASSERT(0 != encoder);
  103892. FLAC__ASSERT(0 != encoder->private_);
  103893. FLAC__ASSERT(0 != encoder->protected_);
  103894. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103895. return false;
  103896. #if 0
  103897. /*@@@ deprecated: */
  103898. encoder->protected_->rice_parameter_search_dist = value;
  103899. #else
  103900. (void)value;
  103901. #endif
  103902. return true;
  103903. }
  103904. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103905. {
  103906. FLAC__ASSERT(0 != encoder);
  103907. FLAC__ASSERT(0 != encoder->private_);
  103908. FLAC__ASSERT(0 != encoder->protected_);
  103909. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103910. return false;
  103911. encoder->protected_->total_samples_estimate = value;
  103912. return true;
  103913. }
  103914. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103915. {
  103916. FLAC__ASSERT(0 != encoder);
  103917. FLAC__ASSERT(0 != encoder->private_);
  103918. FLAC__ASSERT(0 != encoder->protected_);
  103919. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103920. return false;
  103921. if(0 == metadata)
  103922. num_blocks = 0;
  103923. if(0 == num_blocks)
  103924. metadata = 0;
  103925. /* realloc() does not do exactly what we want so... */
  103926. if(encoder->protected_->metadata) {
  103927. free(encoder->protected_->metadata);
  103928. encoder->protected_->metadata = 0;
  103929. encoder->protected_->num_metadata_blocks = 0;
  103930. }
  103931. if(num_blocks) {
  103932. FLAC__StreamMetadata **m;
  103933. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103934. return false;
  103935. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103936. encoder->protected_->metadata = m;
  103937. encoder->protected_->num_metadata_blocks = num_blocks;
  103938. }
  103939. #if FLAC__HAS_OGG
  103940. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103941. return false;
  103942. #endif
  103943. return true;
  103944. }
  103945. /*
  103946. * These three functions are not static, but not publically exposed in
  103947. * include/FLAC/ either. They are used by the test suite.
  103948. */
  103949. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103950. {
  103951. FLAC__ASSERT(0 != encoder);
  103952. FLAC__ASSERT(0 != encoder->private_);
  103953. FLAC__ASSERT(0 != encoder->protected_);
  103954. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103955. return false;
  103956. encoder->private_->disable_constant_subframes = value;
  103957. return true;
  103958. }
  103959. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103960. {
  103961. FLAC__ASSERT(0 != encoder);
  103962. FLAC__ASSERT(0 != encoder->private_);
  103963. FLAC__ASSERT(0 != encoder->protected_);
  103964. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103965. return false;
  103966. encoder->private_->disable_fixed_subframes = value;
  103967. return true;
  103968. }
  103969. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103970. {
  103971. FLAC__ASSERT(0 != encoder);
  103972. FLAC__ASSERT(0 != encoder->private_);
  103973. FLAC__ASSERT(0 != encoder->protected_);
  103974. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103975. return false;
  103976. encoder->private_->disable_verbatim_subframes = value;
  103977. return true;
  103978. }
  103979. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103980. {
  103981. FLAC__ASSERT(0 != encoder);
  103982. FLAC__ASSERT(0 != encoder->private_);
  103983. FLAC__ASSERT(0 != encoder->protected_);
  103984. return encoder->protected_->state;
  103985. }
  103986. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103987. {
  103988. FLAC__ASSERT(0 != encoder);
  103989. FLAC__ASSERT(0 != encoder->private_);
  103990. FLAC__ASSERT(0 != encoder->protected_);
  103991. if(encoder->protected_->verify)
  103992. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103993. else
  103994. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103995. }
  103996. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103997. {
  103998. FLAC__ASSERT(0 != encoder);
  103999. FLAC__ASSERT(0 != encoder->private_);
  104000. FLAC__ASSERT(0 != encoder->protected_);
  104001. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  104002. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  104003. else
  104004. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  104005. }
  104006. 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)
  104007. {
  104008. FLAC__ASSERT(0 != encoder);
  104009. FLAC__ASSERT(0 != encoder->private_);
  104010. FLAC__ASSERT(0 != encoder->protected_);
  104011. if(0 != absolute_sample)
  104012. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  104013. if(0 != frame_number)
  104014. *frame_number = encoder->private_->verify.error_stats.frame_number;
  104015. if(0 != channel)
  104016. *channel = encoder->private_->verify.error_stats.channel;
  104017. if(0 != sample)
  104018. *sample = encoder->private_->verify.error_stats.sample;
  104019. if(0 != expected)
  104020. *expected = encoder->private_->verify.error_stats.expected;
  104021. if(0 != got)
  104022. *got = encoder->private_->verify.error_stats.got;
  104023. }
  104024. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  104025. {
  104026. FLAC__ASSERT(0 != encoder);
  104027. FLAC__ASSERT(0 != encoder->private_);
  104028. FLAC__ASSERT(0 != encoder->protected_);
  104029. return encoder->protected_->verify;
  104030. }
  104031. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  104032. {
  104033. FLAC__ASSERT(0 != encoder);
  104034. FLAC__ASSERT(0 != encoder->private_);
  104035. FLAC__ASSERT(0 != encoder->protected_);
  104036. return encoder->protected_->streamable_subset;
  104037. }
  104038. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  104039. {
  104040. FLAC__ASSERT(0 != encoder);
  104041. FLAC__ASSERT(0 != encoder->private_);
  104042. FLAC__ASSERT(0 != encoder->protected_);
  104043. return encoder->protected_->do_md5;
  104044. }
  104045. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  104046. {
  104047. FLAC__ASSERT(0 != encoder);
  104048. FLAC__ASSERT(0 != encoder->private_);
  104049. FLAC__ASSERT(0 != encoder->protected_);
  104050. return encoder->protected_->channels;
  104051. }
  104052. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  104053. {
  104054. FLAC__ASSERT(0 != encoder);
  104055. FLAC__ASSERT(0 != encoder->private_);
  104056. FLAC__ASSERT(0 != encoder->protected_);
  104057. return encoder->protected_->bits_per_sample;
  104058. }
  104059. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  104060. {
  104061. FLAC__ASSERT(0 != encoder);
  104062. FLAC__ASSERT(0 != encoder->private_);
  104063. FLAC__ASSERT(0 != encoder->protected_);
  104064. return encoder->protected_->sample_rate;
  104065. }
  104066. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  104067. {
  104068. FLAC__ASSERT(0 != encoder);
  104069. FLAC__ASSERT(0 != encoder->private_);
  104070. FLAC__ASSERT(0 != encoder->protected_);
  104071. return encoder->protected_->blocksize;
  104072. }
  104073. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104074. {
  104075. FLAC__ASSERT(0 != encoder);
  104076. FLAC__ASSERT(0 != encoder->private_);
  104077. FLAC__ASSERT(0 != encoder->protected_);
  104078. return encoder->protected_->do_mid_side_stereo;
  104079. }
  104080. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104081. {
  104082. FLAC__ASSERT(0 != encoder);
  104083. FLAC__ASSERT(0 != encoder->private_);
  104084. FLAC__ASSERT(0 != encoder->protected_);
  104085. return encoder->protected_->loose_mid_side_stereo;
  104086. }
  104087. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  104088. {
  104089. FLAC__ASSERT(0 != encoder);
  104090. FLAC__ASSERT(0 != encoder->private_);
  104091. FLAC__ASSERT(0 != encoder->protected_);
  104092. return encoder->protected_->max_lpc_order;
  104093. }
  104094. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  104095. {
  104096. FLAC__ASSERT(0 != encoder);
  104097. FLAC__ASSERT(0 != encoder->private_);
  104098. FLAC__ASSERT(0 != encoder->protected_);
  104099. return encoder->protected_->qlp_coeff_precision;
  104100. }
  104101. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  104102. {
  104103. FLAC__ASSERT(0 != encoder);
  104104. FLAC__ASSERT(0 != encoder->private_);
  104105. FLAC__ASSERT(0 != encoder->protected_);
  104106. return encoder->protected_->do_qlp_coeff_prec_search;
  104107. }
  104108. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  104109. {
  104110. FLAC__ASSERT(0 != encoder);
  104111. FLAC__ASSERT(0 != encoder->private_);
  104112. FLAC__ASSERT(0 != encoder->protected_);
  104113. return encoder->protected_->do_escape_coding;
  104114. }
  104115. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  104116. {
  104117. FLAC__ASSERT(0 != encoder);
  104118. FLAC__ASSERT(0 != encoder->private_);
  104119. FLAC__ASSERT(0 != encoder->protected_);
  104120. return encoder->protected_->do_exhaustive_model_search;
  104121. }
  104122. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104123. {
  104124. FLAC__ASSERT(0 != encoder);
  104125. FLAC__ASSERT(0 != encoder->private_);
  104126. FLAC__ASSERT(0 != encoder->protected_);
  104127. return encoder->protected_->min_residual_partition_order;
  104128. }
  104129. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104130. {
  104131. FLAC__ASSERT(0 != encoder);
  104132. FLAC__ASSERT(0 != encoder->private_);
  104133. FLAC__ASSERT(0 != encoder->protected_);
  104134. return encoder->protected_->max_residual_partition_order;
  104135. }
  104136. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  104137. {
  104138. FLAC__ASSERT(0 != encoder);
  104139. FLAC__ASSERT(0 != encoder->private_);
  104140. FLAC__ASSERT(0 != encoder->protected_);
  104141. return encoder->protected_->rice_parameter_search_dist;
  104142. }
  104143. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  104144. {
  104145. FLAC__ASSERT(0 != encoder);
  104146. FLAC__ASSERT(0 != encoder->private_);
  104147. FLAC__ASSERT(0 != encoder->protected_);
  104148. return encoder->protected_->total_samples_estimate;
  104149. }
  104150. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  104151. {
  104152. unsigned i, j = 0, channel;
  104153. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104154. FLAC__ASSERT(0 != encoder);
  104155. FLAC__ASSERT(0 != encoder->private_);
  104156. FLAC__ASSERT(0 != encoder->protected_);
  104157. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104158. do {
  104159. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  104160. if(encoder->protected_->verify)
  104161. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  104162. for(channel = 0; channel < channels; channel++)
  104163. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  104164. if(encoder->protected_->do_mid_side_stereo) {
  104165. FLAC__ASSERT(channels == 2);
  104166. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104167. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104168. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  104169. 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' ! */
  104170. }
  104171. }
  104172. else
  104173. j += n;
  104174. encoder->private_->current_sample_number += n;
  104175. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104176. if(encoder->private_->current_sample_number > blocksize) {
  104177. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  104178. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104179. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104180. return false;
  104181. /* move unprocessed overread samples to beginnings of arrays */
  104182. for(channel = 0; channel < channels; channel++)
  104183. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104184. if(encoder->protected_->do_mid_side_stereo) {
  104185. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104186. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104187. }
  104188. encoder->private_->current_sample_number = 1;
  104189. }
  104190. } while(j < samples);
  104191. return true;
  104192. }
  104193. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  104194. {
  104195. unsigned i, j, k, channel;
  104196. FLAC__int32 x, mid, side;
  104197. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104198. FLAC__ASSERT(0 != encoder);
  104199. FLAC__ASSERT(0 != encoder->private_);
  104200. FLAC__ASSERT(0 != encoder->protected_);
  104201. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104202. j = k = 0;
  104203. /*
  104204. * we have several flavors of the same basic loop, optimized for
  104205. * different conditions:
  104206. */
  104207. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104208. /*
  104209. * stereo coding: unroll channel loop
  104210. */
  104211. do {
  104212. if(encoder->protected_->verify)
  104213. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104214. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104215. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104216. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  104217. x = buffer[k++];
  104218. encoder->private_->integer_signal[1][i] = x;
  104219. mid += x;
  104220. side -= x;
  104221. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104222. encoder->private_->integer_signal_mid_side[1][i] = side;
  104223. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104224. }
  104225. encoder->private_->current_sample_number = i;
  104226. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104227. if(i > blocksize) {
  104228. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104229. return false;
  104230. /* move unprocessed overread samples to beginnings of arrays */
  104231. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104232. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104233. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104234. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104235. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104236. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104237. encoder->private_->current_sample_number = 1;
  104238. }
  104239. } while(j < samples);
  104240. }
  104241. else {
  104242. /*
  104243. * independent channel coding: buffer each channel in inner loop
  104244. */
  104245. do {
  104246. if(encoder->protected_->verify)
  104247. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104248. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104249. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104250. for(channel = 0; channel < channels; channel++)
  104251. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104252. }
  104253. encoder->private_->current_sample_number = i;
  104254. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104255. if(i > blocksize) {
  104256. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104257. return false;
  104258. /* move unprocessed overread samples to beginnings of arrays */
  104259. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104260. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104261. for(channel = 0; channel < channels; channel++)
  104262. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104263. encoder->private_->current_sample_number = 1;
  104264. }
  104265. } while(j < samples);
  104266. }
  104267. return true;
  104268. }
  104269. /***********************************************************************
  104270. *
  104271. * Private class methods
  104272. *
  104273. ***********************************************************************/
  104274. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104275. {
  104276. FLAC__ASSERT(0 != encoder);
  104277. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104278. encoder->protected_->verify = true;
  104279. #else
  104280. encoder->protected_->verify = false;
  104281. #endif
  104282. encoder->protected_->streamable_subset = true;
  104283. encoder->protected_->do_md5 = true;
  104284. encoder->protected_->do_mid_side_stereo = false;
  104285. encoder->protected_->loose_mid_side_stereo = false;
  104286. encoder->protected_->channels = 2;
  104287. encoder->protected_->bits_per_sample = 16;
  104288. encoder->protected_->sample_rate = 44100;
  104289. encoder->protected_->blocksize = 0;
  104290. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104291. encoder->protected_->num_apodizations = 1;
  104292. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104293. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104294. #endif
  104295. encoder->protected_->max_lpc_order = 0;
  104296. encoder->protected_->qlp_coeff_precision = 0;
  104297. encoder->protected_->do_qlp_coeff_prec_search = false;
  104298. encoder->protected_->do_exhaustive_model_search = false;
  104299. encoder->protected_->do_escape_coding = false;
  104300. encoder->protected_->min_residual_partition_order = 0;
  104301. encoder->protected_->max_residual_partition_order = 0;
  104302. encoder->protected_->rice_parameter_search_dist = 0;
  104303. encoder->protected_->total_samples_estimate = 0;
  104304. encoder->protected_->metadata = 0;
  104305. encoder->protected_->num_metadata_blocks = 0;
  104306. encoder->private_->seek_table = 0;
  104307. encoder->private_->disable_constant_subframes = false;
  104308. encoder->private_->disable_fixed_subframes = false;
  104309. encoder->private_->disable_verbatim_subframes = false;
  104310. #if FLAC__HAS_OGG
  104311. encoder->private_->is_ogg = false;
  104312. #endif
  104313. encoder->private_->read_callback = 0;
  104314. encoder->private_->write_callback = 0;
  104315. encoder->private_->seek_callback = 0;
  104316. encoder->private_->tell_callback = 0;
  104317. encoder->private_->metadata_callback = 0;
  104318. encoder->private_->progress_callback = 0;
  104319. encoder->private_->client_data = 0;
  104320. #if FLAC__HAS_OGG
  104321. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104322. #endif
  104323. }
  104324. void free_(FLAC__StreamEncoder *encoder)
  104325. {
  104326. unsigned i, channel;
  104327. FLAC__ASSERT(0 != encoder);
  104328. if(encoder->protected_->metadata) {
  104329. free(encoder->protected_->metadata);
  104330. encoder->protected_->metadata = 0;
  104331. encoder->protected_->num_metadata_blocks = 0;
  104332. }
  104333. for(i = 0; i < encoder->protected_->channels; i++) {
  104334. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104335. free(encoder->private_->integer_signal_unaligned[i]);
  104336. encoder->private_->integer_signal_unaligned[i] = 0;
  104337. }
  104338. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104339. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104340. free(encoder->private_->real_signal_unaligned[i]);
  104341. encoder->private_->real_signal_unaligned[i] = 0;
  104342. }
  104343. #endif
  104344. }
  104345. for(i = 0; i < 2; i++) {
  104346. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104347. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104348. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104349. }
  104350. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104351. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104352. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104353. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104354. }
  104355. #endif
  104356. }
  104357. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104358. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104359. if(0 != encoder->private_->window_unaligned[i]) {
  104360. free(encoder->private_->window_unaligned[i]);
  104361. encoder->private_->window_unaligned[i] = 0;
  104362. }
  104363. }
  104364. if(0 != encoder->private_->windowed_signal_unaligned) {
  104365. free(encoder->private_->windowed_signal_unaligned);
  104366. encoder->private_->windowed_signal_unaligned = 0;
  104367. }
  104368. #endif
  104369. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104370. for(i = 0; i < 2; i++) {
  104371. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104372. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104373. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104374. }
  104375. }
  104376. }
  104377. for(channel = 0; channel < 2; channel++) {
  104378. for(i = 0; i < 2; i++) {
  104379. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104380. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104381. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104382. }
  104383. }
  104384. }
  104385. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104386. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104387. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104388. }
  104389. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104390. free(encoder->private_->raw_bits_per_partition_unaligned);
  104391. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104392. }
  104393. if(encoder->protected_->verify) {
  104394. for(i = 0; i < encoder->protected_->channels; i++) {
  104395. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104396. free(encoder->private_->verify.input_fifo.data[i]);
  104397. encoder->private_->verify.input_fifo.data[i] = 0;
  104398. }
  104399. }
  104400. }
  104401. FLAC__bitwriter_free(encoder->private_->frame);
  104402. }
  104403. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104404. {
  104405. FLAC__bool ok;
  104406. unsigned i, channel;
  104407. FLAC__ASSERT(new_blocksize > 0);
  104408. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104409. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104410. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104411. if(new_blocksize <= encoder->private_->input_capacity)
  104412. return true;
  104413. ok = true;
  104414. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104415. * requires that the input arrays (in our case the integer signals)
  104416. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104417. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104418. */
  104419. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104420. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104421. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104422. encoder->private_->integer_signal[i] += 4;
  104423. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104424. #if 0 /* @@@ currently unused */
  104425. if(encoder->protected_->max_lpc_order > 0)
  104426. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104427. #endif
  104428. #endif
  104429. }
  104430. for(i = 0; ok && i < 2; i++) {
  104431. 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]);
  104432. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104433. encoder->private_->integer_signal_mid_side[i] += 4;
  104434. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104435. #if 0 /* @@@ currently unused */
  104436. if(encoder->protected_->max_lpc_order > 0)
  104437. 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]);
  104438. #endif
  104439. #endif
  104440. }
  104441. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104442. if(ok && encoder->protected_->max_lpc_order > 0) {
  104443. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104444. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104445. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104446. }
  104447. #endif
  104448. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104449. for(i = 0; ok && i < 2; i++) {
  104450. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104451. }
  104452. }
  104453. for(channel = 0; ok && channel < 2; channel++) {
  104454. for(i = 0; ok && i < 2; i++) {
  104455. 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]);
  104456. }
  104457. }
  104458. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104459. /*@@@ 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) */
  104460. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104461. if(encoder->protected_->do_escape_coding)
  104462. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104463. /* now adjust the windows if the blocksize has changed */
  104464. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104465. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104466. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104467. switch(encoder->protected_->apodizations[i].type) {
  104468. case FLAC__APODIZATION_BARTLETT:
  104469. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104470. break;
  104471. case FLAC__APODIZATION_BARTLETT_HANN:
  104472. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104473. break;
  104474. case FLAC__APODIZATION_BLACKMAN:
  104475. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104476. break;
  104477. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104478. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104479. break;
  104480. case FLAC__APODIZATION_CONNES:
  104481. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104482. break;
  104483. case FLAC__APODIZATION_FLATTOP:
  104484. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104485. break;
  104486. case FLAC__APODIZATION_GAUSS:
  104487. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104488. break;
  104489. case FLAC__APODIZATION_HAMMING:
  104490. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104491. break;
  104492. case FLAC__APODIZATION_HANN:
  104493. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104494. break;
  104495. case FLAC__APODIZATION_KAISER_BESSEL:
  104496. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104497. break;
  104498. case FLAC__APODIZATION_NUTTALL:
  104499. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104500. break;
  104501. case FLAC__APODIZATION_RECTANGLE:
  104502. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104503. break;
  104504. case FLAC__APODIZATION_TRIANGLE:
  104505. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104506. break;
  104507. case FLAC__APODIZATION_TUKEY:
  104508. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104509. break;
  104510. case FLAC__APODIZATION_WELCH:
  104511. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104512. break;
  104513. default:
  104514. FLAC__ASSERT(0);
  104515. /* double protection */
  104516. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104517. break;
  104518. }
  104519. }
  104520. }
  104521. #endif
  104522. if(ok)
  104523. encoder->private_->input_capacity = new_blocksize;
  104524. else
  104525. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104526. return ok;
  104527. }
  104528. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104529. {
  104530. const FLAC__byte *buffer;
  104531. size_t bytes;
  104532. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104533. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104534. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104535. return false;
  104536. }
  104537. if(encoder->protected_->verify) {
  104538. encoder->private_->verify.output.data = buffer;
  104539. encoder->private_->verify.output.bytes = bytes;
  104540. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104541. encoder->private_->verify.needs_magic_hack = true;
  104542. }
  104543. else {
  104544. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104545. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104546. FLAC__bitwriter_clear(encoder->private_->frame);
  104547. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104548. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104549. return false;
  104550. }
  104551. }
  104552. }
  104553. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104554. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104555. FLAC__bitwriter_clear(encoder->private_->frame);
  104556. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104557. return false;
  104558. }
  104559. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104560. FLAC__bitwriter_clear(encoder->private_->frame);
  104561. if(samples > 0) {
  104562. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104563. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104564. }
  104565. return true;
  104566. }
  104567. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104568. {
  104569. FLAC__StreamEncoderWriteStatus status;
  104570. FLAC__uint64 output_position = 0;
  104571. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104572. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104573. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104574. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104575. }
  104576. /*
  104577. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104578. */
  104579. if(samples == 0) {
  104580. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104581. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104582. encoder->protected_->streaminfo_offset = output_position;
  104583. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104584. encoder->protected_->seektable_offset = output_position;
  104585. }
  104586. /*
  104587. * Mark the current seek point if hit (if audio_offset == 0 that
  104588. * means we're still writing metadata and haven't hit the first
  104589. * frame yet)
  104590. */
  104591. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104592. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104593. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104594. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104595. FLAC__uint64 test_sample;
  104596. unsigned i;
  104597. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104598. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104599. if(test_sample > frame_last_sample) {
  104600. break;
  104601. }
  104602. else if(test_sample >= frame_first_sample) {
  104603. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104604. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104605. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104606. encoder->private_->first_seekpoint_to_check++;
  104607. /* DO NOT: "break;" and here's why:
  104608. * The seektable template may contain more than one target
  104609. * sample for any given frame; we will keep looping, generating
  104610. * duplicate seekpoints for them, and we'll clean it up later,
  104611. * just before writing the seektable back to the metadata.
  104612. */
  104613. }
  104614. else {
  104615. encoder->private_->first_seekpoint_to_check++;
  104616. }
  104617. }
  104618. }
  104619. #if FLAC__HAS_OGG
  104620. if(encoder->private_->is_ogg) {
  104621. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104622. &encoder->protected_->ogg_encoder_aspect,
  104623. buffer,
  104624. bytes,
  104625. samples,
  104626. encoder->private_->current_frame_number,
  104627. is_last_block,
  104628. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104629. encoder,
  104630. encoder->private_->client_data
  104631. );
  104632. }
  104633. else
  104634. #endif
  104635. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104636. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104637. encoder->private_->bytes_written += bytes;
  104638. encoder->private_->samples_written += samples;
  104639. /* we keep a high watermark on the number of frames written because
  104640. * when the encoder goes back to write metadata, 'current_frame'
  104641. * will drop back to 0.
  104642. */
  104643. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104644. }
  104645. else
  104646. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104647. return status;
  104648. }
  104649. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104650. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104651. {
  104652. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104653. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104654. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104655. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104656. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104657. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104658. FLAC__StreamEncoderSeekStatus seek_status;
  104659. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104660. /* All this is based on intimate knowledge of the stream header
  104661. * layout, but a change to the header format that would break this
  104662. * would also break all streams encoded in the previous format.
  104663. */
  104664. /*
  104665. * Write MD5 signature
  104666. */
  104667. {
  104668. const unsigned md5_offset =
  104669. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104670. (
  104671. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104672. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104673. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104674. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104675. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104676. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104677. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104678. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104679. ) / 8;
  104680. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104681. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104682. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104683. return;
  104684. }
  104685. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104686. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104687. return;
  104688. }
  104689. }
  104690. /*
  104691. * Write total samples
  104692. */
  104693. {
  104694. const unsigned total_samples_byte_offset =
  104695. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104696. (
  104697. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104698. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104699. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104700. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104701. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104702. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104703. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104704. - 4
  104705. ) / 8;
  104706. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104707. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104708. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104709. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104710. b[4] = (FLAC__byte)(samples & 0xFF);
  104711. 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) {
  104712. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104713. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104714. return;
  104715. }
  104716. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104717. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104718. return;
  104719. }
  104720. }
  104721. /*
  104722. * Write min/max framesize
  104723. */
  104724. {
  104725. const unsigned min_framesize_offset =
  104726. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104727. (
  104728. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104729. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104730. ) / 8;
  104731. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104732. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104733. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104734. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104735. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104736. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104737. 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) {
  104738. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104739. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104740. return;
  104741. }
  104742. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104743. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104744. return;
  104745. }
  104746. }
  104747. /*
  104748. * Write seektable
  104749. */
  104750. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104751. unsigned i;
  104752. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104753. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104754. 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) {
  104755. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104756. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104757. return;
  104758. }
  104759. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104760. FLAC__uint64 xx;
  104761. unsigned x;
  104762. xx = encoder->private_->seek_table->points[i].sample_number;
  104763. b[7] = (FLAC__byte)xx; xx >>= 8;
  104764. b[6] = (FLAC__byte)xx; xx >>= 8;
  104765. b[5] = (FLAC__byte)xx; xx >>= 8;
  104766. b[4] = (FLAC__byte)xx; xx >>= 8;
  104767. b[3] = (FLAC__byte)xx; xx >>= 8;
  104768. b[2] = (FLAC__byte)xx; xx >>= 8;
  104769. b[1] = (FLAC__byte)xx; xx >>= 8;
  104770. b[0] = (FLAC__byte)xx; xx >>= 8;
  104771. xx = encoder->private_->seek_table->points[i].stream_offset;
  104772. b[15] = (FLAC__byte)xx; xx >>= 8;
  104773. b[14] = (FLAC__byte)xx; xx >>= 8;
  104774. b[13] = (FLAC__byte)xx; xx >>= 8;
  104775. b[12] = (FLAC__byte)xx; xx >>= 8;
  104776. b[11] = (FLAC__byte)xx; xx >>= 8;
  104777. b[10] = (FLAC__byte)xx; xx >>= 8;
  104778. b[9] = (FLAC__byte)xx; xx >>= 8;
  104779. b[8] = (FLAC__byte)xx; xx >>= 8;
  104780. x = encoder->private_->seek_table->points[i].frame_samples;
  104781. b[17] = (FLAC__byte)x; x >>= 8;
  104782. b[16] = (FLAC__byte)x; x >>= 8;
  104783. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104784. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104785. return;
  104786. }
  104787. }
  104788. }
  104789. }
  104790. #if FLAC__HAS_OGG
  104791. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104792. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104793. {
  104794. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104795. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104796. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104797. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104798. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104799. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104800. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104801. FLAC__STREAM_SYNC_LENGTH
  104802. ;
  104803. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104804. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104805. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104806. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104807. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104808. ogg_page page;
  104809. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104810. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104811. /* Pre-check that client supports seeking, since we don't want the
  104812. * ogg_helper code to ever have to deal with this condition.
  104813. */
  104814. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104815. return;
  104816. /* All this is based on intimate knowledge of the stream header
  104817. * layout, but a change to the header format that would break this
  104818. * would also break all streams encoded in the previous format.
  104819. */
  104820. /**
  104821. ** Write STREAMINFO stats
  104822. **/
  104823. simple_ogg_page__init(&page);
  104824. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104825. simple_ogg_page__clear(&page);
  104826. return; /* state already set */
  104827. }
  104828. /*
  104829. * Write MD5 signature
  104830. */
  104831. {
  104832. const unsigned md5_offset =
  104833. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104834. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104835. (
  104836. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104837. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104838. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104839. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104840. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104841. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104842. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104843. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104844. ) / 8;
  104845. if(md5_offset + 16 > (unsigned)page.body_len) {
  104846. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104847. simple_ogg_page__clear(&page);
  104848. return;
  104849. }
  104850. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104851. }
  104852. /*
  104853. * Write total samples
  104854. */
  104855. {
  104856. const unsigned total_samples_byte_offset =
  104857. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104858. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104859. (
  104860. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104861. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104862. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104863. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104864. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104865. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104866. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104867. - 4
  104868. ) / 8;
  104869. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104870. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104871. simple_ogg_page__clear(&page);
  104872. return;
  104873. }
  104874. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104875. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104876. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104877. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104878. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104879. b[4] = (FLAC__byte)(samples & 0xFF);
  104880. memcpy(page.body + total_samples_byte_offset, b, 5);
  104881. }
  104882. /*
  104883. * Write min/max framesize
  104884. */
  104885. {
  104886. const unsigned min_framesize_offset =
  104887. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104888. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104889. (
  104890. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104891. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104892. ) / 8;
  104893. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104894. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104895. simple_ogg_page__clear(&page);
  104896. return;
  104897. }
  104898. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104899. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104900. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104901. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104902. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104903. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104904. memcpy(page.body + min_framesize_offset, b, 6);
  104905. }
  104906. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104907. simple_ogg_page__clear(&page);
  104908. return; /* state already set */
  104909. }
  104910. simple_ogg_page__clear(&page);
  104911. /*
  104912. * Write seektable
  104913. */
  104914. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104915. unsigned i;
  104916. FLAC__byte *p;
  104917. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104918. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104919. simple_ogg_page__init(&page);
  104920. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104921. simple_ogg_page__clear(&page);
  104922. return; /* state already set */
  104923. }
  104924. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104925. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104926. simple_ogg_page__clear(&page);
  104927. return;
  104928. }
  104929. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104930. FLAC__uint64 xx;
  104931. unsigned x;
  104932. xx = encoder->private_->seek_table->points[i].sample_number;
  104933. b[7] = (FLAC__byte)xx; xx >>= 8;
  104934. b[6] = (FLAC__byte)xx; xx >>= 8;
  104935. b[5] = (FLAC__byte)xx; xx >>= 8;
  104936. b[4] = (FLAC__byte)xx; xx >>= 8;
  104937. b[3] = (FLAC__byte)xx; xx >>= 8;
  104938. b[2] = (FLAC__byte)xx; xx >>= 8;
  104939. b[1] = (FLAC__byte)xx; xx >>= 8;
  104940. b[0] = (FLAC__byte)xx; xx >>= 8;
  104941. xx = encoder->private_->seek_table->points[i].stream_offset;
  104942. b[15] = (FLAC__byte)xx; xx >>= 8;
  104943. b[14] = (FLAC__byte)xx; xx >>= 8;
  104944. b[13] = (FLAC__byte)xx; xx >>= 8;
  104945. b[12] = (FLAC__byte)xx; xx >>= 8;
  104946. b[11] = (FLAC__byte)xx; xx >>= 8;
  104947. b[10] = (FLAC__byte)xx; xx >>= 8;
  104948. b[9] = (FLAC__byte)xx; xx >>= 8;
  104949. b[8] = (FLAC__byte)xx; xx >>= 8;
  104950. x = encoder->private_->seek_table->points[i].frame_samples;
  104951. b[17] = (FLAC__byte)x; x >>= 8;
  104952. b[16] = (FLAC__byte)x; x >>= 8;
  104953. memcpy(p, b, 18);
  104954. }
  104955. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104956. simple_ogg_page__clear(&page);
  104957. return; /* state already set */
  104958. }
  104959. simple_ogg_page__clear(&page);
  104960. }
  104961. }
  104962. #endif
  104963. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104964. {
  104965. FLAC__uint16 crc;
  104966. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104967. /*
  104968. * Accumulate raw signal to the MD5 signature
  104969. */
  104970. 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)) {
  104971. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104972. return false;
  104973. }
  104974. /*
  104975. * Process the frame header and subframes into the frame bitbuffer
  104976. */
  104977. if(!process_subframes_(encoder, is_fractional_block)) {
  104978. /* the above function sets the state for us in case of an error */
  104979. return false;
  104980. }
  104981. /*
  104982. * Zero-pad the frame to a byte_boundary
  104983. */
  104984. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104985. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104986. return false;
  104987. }
  104988. /*
  104989. * CRC-16 the whole thing
  104990. */
  104991. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104992. if(
  104993. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104994. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104995. ) {
  104996. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104997. return false;
  104998. }
  104999. /*
  105000. * Write it
  105001. */
  105002. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  105003. /* the above function sets the state for us in case of an error */
  105004. return false;
  105005. }
  105006. /*
  105007. * Get ready for the next frame
  105008. */
  105009. encoder->private_->current_sample_number = 0;
  105010. encoder->private_->current_frame_number++;
  105011. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  105012. return true;
  105013. }
  105014. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  105015. {
  105016. FLAC__FrameHeader frame_header;
  105017. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  105018. FLAC__bool do_independent, do_mid_side;
  105019. /*
  105020. * Calculate the min,max Rice partition orders
  105021. */
  105022. if(is_fractional_block) {
  105023. max_partition_order = 0;
  105024. }
  105025. else {
  105026. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  105027. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  105028. }
  105029. min_partition_order = min(min_partition_order, max_partition_order);
  105030. /*
  105031. * Setup the frame
  105032. */
  105033. frame_header.blocksize = encoder->protected_->blocksize;
  105034. frame_header.sample_rate = encoder->protected_->sample_rate;
  105035. frame_header.channels = encoder->protected_->channels;
  105036. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  105037. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  105038. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  105039. frame_header.number.frame_number = encoder->private_->current_frame_number;
  105040. /*
  105041. * Figure out what channel assignments to try
  105042. */
  105043. if(encoder->protected_->do_mid_side_stereo) {
  105044. if(encoder->protected_->loose_mid_side_stereo) {
  105045. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  105046. do_independent = true;
  105047. do_mid_side = true;
  105048. }
  105049. else {
  105050. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  105051. do_mid_side = !do_independent;
  105052. }
  105053. }
  105054. else {
  105055. do_independent = true;
  105056. do_mid_side = true;
  105057. }
  105058. }
  105059. else {
  105060. do_independent = true;
  105061. do_mid_side = false;
  105062. }
  105063. FLAC__ASSERT(do_independent || do_mid_side);
  105064. /*
  105065. * Check for wasted bits; set effective bps for each subframe
  105066. */
  105067. if(do_independent) {
  105068. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105069. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  105070. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  105071. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  105072. }
  105073. }
  105074. if(do_mid_side) {
  105075. FLAC__ASSERT(encoder->protected_->channels == 2);
  105076. for(channel = 0; channel < 2; channel++) {
  105077. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  105078. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  105079. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  105080. }
  105081. }
  105082. /*
  105083. * First do a normal encoding pass of each independent channel
  105084. */
  105085. if(do_independent) {
  105086. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105087. if(!
  105088. process_subframe_(
  105089. encoder,
  105090. min_partition_order,
  105091. max_partition_order,
  105092. &frame_header,
  105093. encoder->private_->subframe_bps[channel],
  105094. encoder->private_->integer_signal[channel],
  105095. encoder->private_->subframe_workspace_ptr[channel],
  105096. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  105097. encoder->private_->residual_workspace[channel],
  105098. encoder->private_->best_subframe+channel,
  105099. encoder->private_->best_subframe_bits+channel
  105100. )
  105101. )
  105102. return false;
  105103. }
  105104. }
  105105. /*
  105106. * Now do mid and side channels if requested
  105107. */
  105108. if(do_mid_side) {
  105109. FLAC__ASSERT(encoder->protected_->channels == 2);
  105110. for(channel = 0; channel < 2; channel++) {
  105111. if(!
  105112. process_subframe_(
  105113. encoder,
  105114. min_partition_order,
  105115. max_partition_order,
  105116. &frame_header,
  105117. encoder->private_->subframe_bps_mid_side[channel],
  105118. encoder->private_->integer_signal_mid_side[channel],
  105119. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  105120. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  105121. encoder->private_->residual_workspace_mid_side[channel],
  105122. encoder->private_->best_subframe_mid_side+channel,
  105123. encoder->private_->best_subframe_bits_mid_side+channel
  105124. )
  105125. )
  105126. return false;
  105127. }
  105128. }
  105129. /*
  105130. * Compose the frame bitbuffer
  105131. */
  105132. if(do_mid_side) {
  105133. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  105134. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  105135. FLAC__ChannelAssignment channel_assignment;
  105136. FLAC__ASSERT(encoder->protected_->channels == 2);
  105137. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  105138. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  105139. }
  105140. else {
  105141. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  105142. unsigned min_bits;
  105143. int ca;
  105144. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  105145. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  105146. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  105147. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  105148. FLAC__ASSERT(do_independent && do_mid_side);
  105149. /* We have to figure out which channel assignent results in the smallest frame */
  105150. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  105151. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  105152. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  105153. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  105154. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  105155. min_bits = bits[channel_assignment];
  105156. for(ca = 1; ca <= 3; ca++) {
  105157. if(bits[ca] < min_bits) {
  105158. min_bits = bits[ca];
  105159. channel_assignment = (FLAC__ChannelAssignment)ca;
  105160. }
  105161. }
  105162. }
  105163. frame_header.channel_assignment = channel_assignment;
  105164. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105165. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105166. return false;
  105167. }
  105168. switch(channel_assignment) {
  105169. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105170. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105171. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105172. break;
  105173. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105174. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105175. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105176. break;
  105177. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105178. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105179. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105180. break;
  105181. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105182. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  105183. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105184. break;
  105185. default:
  105186. FLAC__ASSERT(0);
  105187. }
  105188. switch(channel_assignment) {
  105189. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105190. left_bps = encoder->private_->subframe_bps [0];
  105191. right_bps = encoder->private_->subframe_bps [1];
  105192. break;
  105193. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105194. left_bps = encoder->private_->subframe_bps [0];
  105195. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105196. break;
  105197. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105198. left_bps = encoder->private_->subframe_bps_mid_side[1];
  105199. right_bps = encoder->private_->subframe_bps [1];
  105200. break;
  105201. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105202. left_bps = encoder->private_->subframe_bps_mid_side[0];
  105203. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105204. break;
  105205. default:
  105206. FLAC__ASSERT(0);
  105207. }
  105208. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105209. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105210. return false;
  105211. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105212. return false;
  105213. }
  105214. else {
  105215. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105216. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105217. return false;
  105218. }
  105219. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105220. 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)) {
  105221. /* the above function sets the state for us in case of an error */
  105222. return false;
  105223. }
  105224. }
  105225. }
  105226. if(encoder->protected_->loose_mid_side_stereo) {
  105227. encoder->private_->loose_mid_side_stereo_frame_count++;
  105228. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105229. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105230. }
  105231. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105232. return true;
  105233. }
  105234. FLAC__bool process_subframe_(
  105235. FLAC__StreamEncoder *encoder,
  105236. unsigned min_partition_order,
  105237. unsigned max_partition_order,
  105238. const FLAC__FrameHeader *frame_header,
  105239. unsigned subframe_bps,
  105240. const FLAC__int32 integer_signal[],
  105241. FLAC__Subframe *subframe[2],
  105242. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105243. FLAC__int32 *residual[2],
  105244. unsigned *best_subframe,
  105245. unsigned *best_bits
  105246. )
  105247. {
  105248. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105249. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105250. #else
  105251. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105252. #endif
  105253. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105254. FLAC__double lpc_residual_bits_per_sample;
  105255. 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 */
  105256. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105257. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105258. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105259. #endif
  105260. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105261. unsigned rice_parameter;
  105262. unsigned _candidate_bits, _best_bits;
  105263. unsigned _best_subframe;
  105264. /* only use RICE2 partitions if stream bps > 16 */
  105265. 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;
  105266. FLAC__ASSERT(frame_header->blocksize > 0);
  105267. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105268. _best_subframe = 0;
  105269. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105270. _best_bits = UINT_MAX;
  105271. else
  105272. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105273. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105274. unsigned signal_is_constant = false;
  105275. 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);
  105276. /* check for constant subframe */
  105277. if(
  105278. !encoder->private_->disable_constant_subframes &&
  105279. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105280. fixed_residual_bits_per_sample[1] == 0.0
  105281. #else
  105282. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105283. #endif
  105284. ) {
  105285. /* the above means it's possible all samples are the same value; now double-check it: */
  105286. unsigned i;
  105287. signal_is_constant = true;
  105288. for(i = 1; i < frame_header->blocksize; i++) {
  105289. if(integer_signal[0] != integer_signal[i]) {
  105290. signal_is_constant = false;
  105291. break;
  105292. }
  105293. }
  105294. }
  105295. if(signal_is_constant) {
  105296. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105297. if(_candidate_bits < _best_bits) {
  105298. _best_subframe = !_best_subframe;
  105299. _best_bits = _candidate_bits;
  105300. }
  105301. }
  105302. else {
  105303. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105304. /* encode fixed */
  105305. if(encoder->protected_->do_exhaustive_model_search) {
  105306. min_fixed_order = 0;
  105307. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105308. }
  105309. else {
  105310. min_fixed_order = max_fixed_order = guess_fixed_order;
  105311. }
  105312. if(max_fixed_order >= frame_header->blocksize)
  105313. max_fixed_order = frame_header->blocksize - 1;
  105314. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105315. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105316. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105317. continue; /* don't even try */
  105318. 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 */
  105319. #else
  105320. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105321. continue; /* don't even try */
  105322. 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 */
  105323. #endif
  105324. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105325. if(rice_parameter >= rice_parameter_limit) {
  105326. #ifdef DEBUG_VERBOSE
  105327. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105328. #endif
  105329. rice_parameter = rice_parameter_limit - 1;
  105330. }
  105331. _candidate_bits =
  105332. evaluate_fixed_subframe_(
  105333. encoder,
  105334. integer_signal,
  105335. residual[!_best_subframe],
  105336. encoder->private_->abs_residual_partition_sums,
  105337. encoder->private_->raw_bits_per_partition,
  105338. frame_header->blocksize,
  105339. subframe_bps,
  105340. fixed_order,
  105341. rice_parameter,
  105342. rice_parameter_limit,
  105343. min_partition_order,
  105344. max_partition_order,
  105345. encoder->protected_->do_escape_coding,
  105346. encoder->protected_->rice_parameter_search_dist,
  105347. subframe[!_best_subframe],
  105348. partitioned_rice_contents[!_best_subframe]
  105349. );
  105350. if(_candidate_bits < _best_bits) {
  105351. _best_subframe = !_best_subframe;
  105352. _best_bits = _candidate_bits;
  105353. }
  105354. }
  105355. }
  105356. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105357. /* encode lpc */
  105358. if(encoder->protected_->max_lpc_order > 0) {
  105359. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105360. max_lpc_order = frame_header->blocksize-1;
  105361. else
  105362. max_lpc_order = encoder->protected_->max_lpc_order;
  105363. if(max_lpc_order > 0) {
  105364. unsigned a;
  105365. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105366. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105367. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105368. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105369. if(autoc[0] != 0.0) {
  105370. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105371. if(encoder->protected_->do_exhaustive_model_search) {
  105372. min_lpc_order = 1;
  105373. }
  105374. else {
  105375. const unsigned guess_lpc_order =
  105376. FLAC__lpc_compute_best_order(
  105377. lpc_error,
  105378. max_lpc_order,
  105379. frame_header->blocksize,
  105380. subframe_bps + (
  105381. encoder->protected_->do_qlp_coeff_prec_search?
  105382. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105383. encoder->protected_->qlp_coeff_precision
  105384. )
  105385. );
  105386. min_lpc_order = max_lpc_order = guess_lpc_order;
  105387. }
  105388. if(max_lpc_order >= frame_header->blocksize)
  105389. max_lpc_order = frame_header->blocksize - 1;
  105390. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105391. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105392. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105393. continue; /* don't even try */
  105394. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105395. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105396. if(rice_parameter >= rice_parameter_limit) {
  105397. #ifdef DEBUG_VERBOSE
  105398. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105399. #endif
  105400. rice_parameter = rice_parameter_limit - 1;
  105401. }
  105402. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105403. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105404. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105405. if(subframe_bps <= 17) {
  105406. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105407. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105408. }
  105409. else
  105410. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105411. }
  105412. else {
  105413. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105414. }
  105415. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105416. _candidate_bits =
  105417. evaluate_lpc_subframe_(
  105418. encoder,
  105419. integer_signal,
  105420. residual[!_best_subframe],
  105421. encoder->private_->abs_residual_partition_sums,
  105422. encoder->private_->raw_bits_per_partition,
  105423. encoder->private_->lp_coeff[lpc_order-1],
  105424. frame_header->blocksize,
  105425. subframe_bps,
  105426. lpc_order,
  105427. qlp_coeff_precision,
  105428. rice_parameter,
  105429. rice_parameter_limit,
  105430. min_partition_order,
  105431. max_partition_order,
  105432. encoder->protected_->do_escape_coding,
  105433. encoder->protected_->rice_parameter_search_dist,
  105434. subframe[!_best_subframe],
  105435. partitioned_rice_contents[!_best_subframe]
  105436. );
  105437. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105438. if(_candidate_bits < _best_bits) {
  105439. _best_subframe = !_best_subframe;
  105440. _best_bits = _candidate_bits;
  105441. }
  105442. }
  105443. }
  105444. }
  105445. }
  105446. }
  105447. }
  105448. }
  105449. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105450. }
  105451. }
  105452. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105453. if(_best_bits == UINT_MAX) {
  105454. FLAC__ASSERT(_best_subframe == 0);
  105455. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105456. }
  105457. *best_subframe = _best_subframe;
  105458. *best_bits = _best_bits;
  105459. return true;
  105460. }
  105461. FLAC__bool add_subframe_(
  105462. FLAC__StreamEncoder *encoder,
  105463. unsigned blocksize,
  105464. unsigned subframe_bps,
  105465. const FLAC__Subframe *subframe,
  105466. FLAC__BitWriter *frame
  105467. )
  105468. {
  105469. switch(subframe->type) {
  105470. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105471. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105472. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105473. return false;
  105474. }
  105475. break;
  105476. case FLAC__SUBFRAME_TYPE_FIXED:
  105477. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105478. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105479. return false;
  105480. }
  105481. break;
  105482. case FLAC__SUBFRAME_TYPE_LPC:
  105483. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105484. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105485. return false;
  105486. }
  105487. break;
  105488. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105489. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105490. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105491. return false;
  105492. }
  105493. break;
  105494. default:
  105495. FLAC__ASSERT(0);
  105496. }
  105497. return true;
  105498. }
  105499. #define SPOTCHECK_ESTIMATE 0
  105500. #if SPOTCHECK_ESTIMATE
  105501. static void spotcheck_subframe_estimate_(
  105502. FLAC__StreamEncoder *encoder,
  105503. unsigned blocksize,
  105504. unsigned subframe_bps,
  105505. const FLAC__Subframe *subframe,
  105506. unsigned estimate
  105507. )
  105508. {
  105509. FLAC__bool ret;
  105510. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105511. if(frame == 0) {
  105512. fprintf(stderr, "EST: can't allocate frame\n");
  105513. return;
  105514. }
  105515. if(!FLAC__bitwriter_init(frame)) {
  105516. fprintf(stderr, "EST: can't init frame\n");
  105517. return;
  105518. }
  105519. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105520. FLAC__ASSERT(ret);
  105521. {
  105522. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105523. if(estimate != actual)
  105524. 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);
  105525. }
  105526. FLAC__bitwriter_delete(frame);
  105527. }
  105528. #endif
  105529. unsigned evaluate_constant_subframe_(
  105530. FLAC__StreamEncoder *encoder,
  105531. const FLAC__int32 signal,
  105532. unsigned blocksize,
  105533. unsigned subframe_bps,
  105534. FLAC__Subframe *subframe
  105535. )
  105536. {
  105537. unsigned estimate;
  105538. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105539. subframe->data.constant.value = signal;
  105540. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105541. #if SPOTCHECK_ESTIMATE
  105542. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105543. #else
  105544. (void)encoder, (void)blocksize;
  105545. #endif
  105546. return estimate;
  105547. }
  105548. unsigned evaluate_fixed_subframe_(
  105549. FLAC__StreamEncoder *encoder,
  105550. const FLAC__int32 signal[],
  105551. FLAC__int32 residual[],
  105552. FLAC__uint64 abs_residual_partition_sums[],
  105553. unsigned raw_bits_per_partition[],
  105554. unsigned blocksize,
  105555. unsigned subframe_bps,
  105556. unsigned order,
  105557. unsigned rice_parameter,
  105558. unsigned rice_parameter_limit,
  105559. unsigned min_partition_order,
  105560. unsigned max_partition_order,
  105561. FLAC__bool do_escape_coding,
  105562. unsigned rice_parameter_search_dist,
  105563. FLAC__Subframe *subframe,
  105564. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105565. )
  105566. {
  105567. unsigned i, residual_bits, estimate;
  105568. const unsigned residual_samples = blocksize - order;
  105569. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105570. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105571. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105572. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105573. subframe->data.fixed.residual = residual;
  105574. residual_bits =
  105575. find_best_partition_order_(
  105576. encoder->private_,
  105577. residual,
  105578. abs_residual_partition_sums,
  105579. raw_bits_per_partition,
  105580. residual_samples,
  105581. order,
  105582. rice_parameter,
  105583. rice_parameter_limit,
  105584. min_partition_order,
  105585. max_partition_order,
  105586. subframe_bps,
  105587. do_escape_coding,
  105588. rice_parameter_search_dist,
  105589. &subframe->data.fixed.entropy_coding_method
  105590. );
  105591. subframe->data.fixed.order = order;
  105592. for(i = 0; i < order; i++)
  105593. subframe->data.fixed.warmup[i] = signal[i];
  105594. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105595. #if SPOTCHECK_ESTIMATE
  105596. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105597. #endif
  105598. return estimate;
  105599. }
  105600. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105601. unsigned evaluate_lpc_subframe_(
  105602. FLAC__StreamEncoder *encoder,
  105603. const FLAC__int32 signal[],
  105604. FLAC__int32 residual[],
  105605. FLAC__uint64 abs_residual_partition_sums[],
  105606. unsigned raw_bits_per_partition[],
  105607. const FLAC__real lp_coeff[],
  105608. unsigned blocksize,
  105609. unsigned subframe_bps,
  105610. unsigned order,
  105611. unsigned qlp_coeff_precision,
  105612. unsigned rice_parameter,
  105613. unsigned rice_parameter_limit,
  105614. unsigned min_partition_order,
  105615. unsigned max_partition_order,
  105616. FLAC__bool do_escape_coding,
  105617. unsigned rice_parameter_search_dist,
  105618. FLAC__Subframe *subframe,
  105619. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105620. )
  105621. {
  105622. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105623. unsigned i, residual_bits, estimate;
  105624. int quantization, ret;
  105625. const unsigned residual_samples = blocksize - order;
  105626. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105627. if(subframe_bps <= 16) {
  105628. FLAC__ASSERT(order > 0);
  105629. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105630. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105631. }
  105632. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105633. if(ret != 0)
  105634. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105635. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105636. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105637. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105638. else
  105639. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105640. else
  105641. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105642. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105643. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105644. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105645. subframe->data.lpc.residual = residual;
  105646. residual_bits =
  105647. find_best_partition_order_(
  105648. encoder->private_,
  105649. residual,
  105650. abs_residual_partition_sums,
  105651. raw_bits_per_partition,
  105652. residual_samples,
  105653. order,
  105654. rice_parameter,
  105655. rice_parameter_limit,
  105656. min_partition_order,
  105657. max_partition_order,
  105658. subframe_bps,
  105659. do_escape_coding,
  105660. rice_parameter_search_dist,
  105661. &subframe->data.lpc.entropy_coding_method
  105662. );
  105663. subframe->data.lpc.order = order;
  105664. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105665. subframe->data.lpc.quantization_level = quantization;
  105666. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105667. for(i = 0; i < order; i++)
  105668. subframe->data.lpc.warmup[i] = signal[i];
  105669. 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;
  105670. #if SPOTCHECK_ESTIMATE
  105671. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105672. #endif
  105673. return estimate;
  105674. }
  105675. #endif
  105676. unsigned evaluate_verbatim_subframe_(
  105677. FLAC__StreamEncoder *encoder,
  105678. const FLAC__int32 signal[],
  105679. unsigned blocksize,
  105680. unsigned subframe_bps,
  105681. FLAC__Subframe *subframe
  105682. )
  105683. {
  105684. unsigned estimate;
  105685. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105686. subframe->data.verbatim.data = signal;
  105687. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105688. #if SPOTCHECK_ESTIMATE
  105689. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105690. #else
  105691. (void)encoder;
  105692. #endif
  105693. return estimate;
  105694. }
  105695. unsigned find_best_partition_order_(
  105696. FLAC__StreamEncoderPrivate *private_,
  105697. const FLAC__int32 residual[],
  105698. FLAC__uint64 abs_residual_partition_sums[],
  105699. unsigned raw_bits_per_partition[],
  105700. unsigned residual_samples,
  105701. unsigned predictor_order,
  105702. unsigned rice_parameter,
  105703. unsigned rice_parameter_limit,
  105704. unsigned min_partition_order,
  105705. unsigned max_partition_order,
  105706. unsigned bps,
  105707. FLAC__bool do_escape_coding,
  105708. unsigned rice_parameter_search_dist,
  105709. FLAC__EntropyCodingMethod *best_ecm
  105710. )
  105711. {
  105712. unsigned residual_bits, best_residual_bits = 0;
  105713. unsigned best_parameters_index = 0;
  105714. unsigned best_partition_order = 0;
  105715. const unsigned blocksize = residual_samples + predictor_order;
  105716. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105717. min_partition_order = min(min_partition_order, max_partition_order);
  105718. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105719. if(do_escape_coding)
  105720. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105721. {
  105722. int partition_order;
  105723. unsigned sum;
  105724. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105725. if(!
  105726. set_partitioned_rice_(
  105727. #ifdef EXACT_RICE_BITS_CALCULATION
  105728. residual,
  105729. #endif
  105730. abs_residual_partition_sums+sum,
  105731. raw_bits_per_partition+sum,
  105732. residual_samples,
  105733. predictor_order,
  105734. rice_parameter,
  105735. rice_parameter_limit,
  105736. rice_parameter_search_dist,
  105737. (unsigned)partition_order,
  105738. do_escape_coding,
  105739. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105740. &residual_bits
  105741. )
  105742. )
  105743. {
  105744. FLAC__ASSERT(best_residual_bits != 0);
  105745. break;
  105746. }
  105747. sum += 1u << partition_order;
  105748. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105749. best_residual_bits = residual_bits;
  105750. best_parameters_index = !best_parameters_index;
  105751. best_partition_order = partition_order;
  105752. }
  105753. }
  105754. }
  105755. best_ecm->data.partitioned_rice.order = best_partition_order;
  105756. {
  105757. /*
  105758. * We are allowed to de-const the pointer based on our special
  105759. * knowledge; it is const to the outside world.
  105760. */
  105761. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105762. unsigned partition;
  105763. /* save best parameters and raw_bits */
  105764. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105765. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105766. if(do_escape_coding)
  105767. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105768. /*
  105769. * Now need to check if the type should be changed to
  105770. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105771. * size of the rice parameters.
  105772. */
  105773. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105774. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105775. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105776. break;
  105777. }
  105778. }
  105779. }
  105780. return best_residual_bits;
  105781. }
  105782. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105783. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105784. const FLAC__int32 residual[],
  105785. FLAC__uint64 abs_residual_partition_sums[],
  105786. unsigned blocksize,
  105787. unsigned predictor_order,
  105788. unsigned min_partition_order,
  105789. unsigned max_partition_order
  105790. );
  105791. #endif
  105792. void precompute_partition_info_sums_(
  105793. const FLAC__int32 residual[],
  105794. FLAC__uint64 abs_residual_partition_sums[],
  105795. unsigned residual_samples,
  105796. unsigned predictor_order,
  105797. unsigned min_partition_order,
  105798. unsigned max_partition_order,
  105799. unsigned bps
  105800. )
  105801. {
  105802. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105803. unsigned partitions = 1u << max_partition_order;
  105804. FLAC__ASSERT(default_partition_samples > predictor_order);
  105805. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105806. /* slightly pessimistic but still catches all common cases */
  105807. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105808. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105809. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105810. return;
  105811. }
  105812. #endif
  105813. /* first do max_partition_order */
  105814. {
  105815. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105816. /* slightly pessimistic but still catches all common cases */
  105817. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105818. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105819. FLAC__uint32 abs_residual_partition_sum;
  105820. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105821. end += default_partition_samples;
  105822. abs_residual_partition_sum = 0;
  105823. for( ; residual_sample < end; residual_sample++)
  105824. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105825. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105826. }
  105827. }
  105828. else { /* have to pessimistically use 64 bits for accumulator */
  105829. FLAC__uint64 abs_residual_partition_sum;
  105830. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105831. end += default_partition_samples;
  105832. abs_residual_partition_sum = 0;
  105833. for( ; residual_sample < end; residual_sample++)
  105834. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105835. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105836. }
  105837. }
  105838. }
  105839. /* now merge partitions for lower orders */
  105840. {
  105841. unsigned from_partition = 0, to_partition = partitions;
  105842. int partition_order;
  105843. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105844. unsigned i;
  105845. partitions >>= 1;
  105846. for(i = 0; i < partitions; i++) {
  105847. abs_residual_partition_sums[to_partition++] =
  105848. abs_residual_partition_sums[from_partition ] +
  105849. abs_residual_partition_sums[from_partition+1];
  105850. from_partition += 2;
  105851. }
  105852. }
  105853. }
  105854. }
  105855. void precompute_partition_info_escapes_(
  105856. const FLAC__int32 residual[],
  105857. unsigned raw_bits_per_partition[],
  105858. unsigned residual_samples,
  105859. unsigned predictor_order,
  105860. unsigned min_partition_order,
  105861. unsigned max_partition_order
  105862. )
  105863. {
  105864. int partition_order;
  105865. unsigned from_partition, to_partition = 0;
  105866. const unsigned blocksize = residual_samples + predictor_order;
  105867. /* first do max_partition_order */
  105868. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105869. FLAC__int32 r;
  105870. FLAC__uint32 rmax;
  105871. unsigned partition, partition_sample, partition_samples, residual_sample;
  105872. const unsigned partitions = 1u << partition_order;
  105873. const unsigned default_partition_samples = blocksize >> partition_order;
  105874. FLAC__ASSERT(default_partition_samples > predictor_order);
  105875. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105876. partition_samples = default_partition_samples;
  105877. if(partition == 0)
  105878. partition_samples -= predictor_order;
  105879. rmax = 0;
  105880. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105881. r = residual[residual_sample++];
  105882. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105883. if(r < 0)
  105884. rmax |= ~r;
  105885. else
  105886. rmax |= r;
  105887. }
  105888. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105889. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105890. }
  105891. to_partition = partitions;
  105892. break; /*@@@ yuck, should remove the 'for' loop instead */
  105893. }
  105894. /* now merge partitions for lower orders */
  105895. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105896. unsigned m;
  105897. unsigned i;
  105898. const unsigned partitions = 1u << partition_order;
  105899. for(i = 0; i < partitions; i++) {
  105900. m = raw_bits_per_partition[from_partition];
  105901. from_partition++;
  105902. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105903. from_partition++;
  105904. to_partition++;
  105905. }
  105906. }
  105907. }
  105908. #ifdef EXACT_RICE_BITS_CALCULATION
  105909. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105910. const unsigned rice_parameter,
  105911. const unsigned partition_samples,
  105912. const FLAC__int32 *residual
  105913. )
  105914. {
  105915. unsigned i, partition_bits =
  105916. 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 */
  105917. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105918. ;
  105919. for(i = 0; i < partition_samples; i++)
  105920. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105921. return partition_bits;
  105922. }
  105923. #else
  105924. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105925. const unsigned rice_parameter,
  105926. const unsigned partition_samples,
  105927. const FLAC__uint64 abs_residual_partition_sum
  105928. )
  105929. {
  105930. return
  105931. 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 */
  105932. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105933. (
  105934. rice_parameter?
  105935. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105936. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105937. )
  105938. - (partition_samples >> 1)
  105939. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105940. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105941. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105942. * So the subtraction term tries to guess how many extra bits were contributed.
  105943. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105944. */
  105945. ;
  105946. }
  105947. #endif
  105948. FLAC__bool set_partitioned_rice_(
  105949. #ifdef EXACT_RICE_BITS_CALCULATION
  105950. const FLAC__int32 residual[],
  105951. #endif
  105952. const FLAC__uint64 abs_residual_partition_sums[],
  105953. const unsigned raw_bits_per_partition[],
  105954. const unsigned residual_samples,
  105955. const unsigned predictor_order,
  105956. const unsigned suggested_rice_parameter,
  105957. const unsigned rice_parameter_limit,
  105958. const unsigned rice_parameter_search_dist,
  105959. const unsigned partition_order,
  105960. const FLAC__bool search_for_escapes,
  105961. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105962. unsigned *bits
  105963. )
  105964. {
  105965. unsigned rice_parameter, partition_bits;
  105966. unsigned best_partition_bits, best_rice_parameter = 0;
  105967. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105968. unsigned *parameters, *raw_bits;
  105969. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105970. unsigned min_rice_parameter, max_rice_parameter;
  105971. #else
  105972. (void)rice_parameter_search_dist;
  105973. #endif
  105974. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105975. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105976. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105977. parameters = partitioned_rice_contents->parameters;
  105978. raw_bits = partitioned_rice_contents->raw_bits;
  105979. if(partition_order == 0) {
  105980. best_partition_bits = (unsigned)(-1);
  105981. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105982. if(rice_parameter_search_dist) {
  105983. if(suggested_rice_parameter < rice_parameter_search_dist)
  105984. min_rice_parameter = 0;
  105985. else
  105986. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105987. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105988. if(max_rice_parameter >= rice_parameter_limit) {
  105989. #ifdef DEBUG_VERBOSE
  105990. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105991. #endif
  105992. max_rice_parameter = rice_parameter_limit - 1;
  105993. }
  105994. }
  105995. else
  105996. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105997. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105998. #else
  105999. rice_parameter = suggested_rice_parameter;
  106000. #endif
  106001. #ifdef EXACT_RICE_BITS_CALCULATION
  106002. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  106003. #else
  106004. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  106005. #endif
  106006. if(partition_bits < best_partition_bits) {
  106007. best_rice_parameter = rice_parameter;
  106008. best_partition_bits = partition_bits;
  106009. }
  106010. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106011. }
  106012. #endif
  106013. if(search_for_escapes) {
  106014. 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;
  106015. if(partition_bits <= best_partition_bits) {
  106016. raw_bits[0] = raw_bits_per_partition[0];
  106017. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106018. best_partition_bits = partition_bits;
  106019. }
  106020. else
  106021. raw_bits[0] = 0;
  106022. }
  106023. parameters[0] = best_rice_parameter;
  106024. bits_ += best_partition_bits;
  106025. }
  106026. else {
  106027. unsigned partition, residual_sample;
  106028. unsigned partition_samples;
  106029. FLAC__uint64 mean, k;
  106030. const unsigned partitions = 1u << partition_order;
  106031. for(partition = residual_sample = 0; partition < partitions; partition++) {
  106032. partition_samples = (residual_samples+predictor_order) >> partition_order;
  106033. if(partition == 0) {
  106034. if(partition_samples <= predictor_order)
  106035. return false;
  106036. else
  106037. partition_samples -= predictor_order;
  106038. }
  106039. mean = abs_residual_partition_sums[partition];
  106040. /* we are basically calculating the size in bits of the
  106041. * average residual magnitude in the partition:
  106042. * rice_parameter = floor(log2(mean/partition_samples))
  106043. * 'mean' is not a good name for the variable, it is
  106044. * actually the sum of magnitudes of all residual values
  106045. * in the partition, so the actual mean is
  106046. * mean/partition_samples
  106047. */
  106048. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  106049. ;
  106050. if(rice_parameter >= rice_parameter_limit) {
  106051. #ifdef DEBUG_VERBOSE
  106052. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  106053. #endif
  106054. rice_parameter = rice_parameter_limit - 1;
  106055. }
  106056. best_partition_bits = (unsigned)(-1);
  106057. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106058. if(rice_parameter_search_dist) {
  106059. if(rice_parameter < rice_parameter_search_dist)
  106060. min_rice_parameter = 0;
  106061. else
  106062. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  106063. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  106064. if(max_rice_parameter >= rice_parameter_limit) {
  106065. #ifdef DEBUG_VERBOSE
  106066. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  106067. #endif
  106068. max_rice_parameter = rice_parameter_limit - 1;
  106069. }
  106070. }
  106071. else
  106072. min_rice_parameter = max_rice_parameter = rice_parameter;
  106073. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  106074. #endif
  106075. #ifdef EXACT_RICE_BITS_CALCULATION
  106076. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  106077. #else
  106078. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  106079. #endif
  106080. if(partition_bits < best_partition_bits) {
  106081. best_rice_parameter = rice_parameter;
  106082. best_partition_bits = partition_bits;
  106083. }
  106084. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106085. }
  106086. #endif
  106087. if(search_for_escapes) {
  106088. 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;
  106089. if(partition_bits <= best_partition_bits) {
  106090. raw_bits[partition] = raw_bits_per_partition[partition];
  106091. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106092. best_partition_bits = partition_bits;
  106093. }
  106094. else
  106095. raw_bits[partition] = 0;
  106096. }
  106097. parameters[partition] = best_rice_parameter;
  106098. bits_ += best_partition_bits;
  106099. residual_sample += partition_samples;
  106100. }
  106101. }
  106102. *bits = bits_;
  106103. return true;
  106104. }
  106105. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  106106. {
  106107. unsigned i, shift;
  106108. FLAC__int32 x = 0;
  106109. for(i = 0; i < samples && !(x&1); i++)
  106110. x |= signal[i];
  106111. if(x == 0) {
  106112. shift = 0;
  106113. }
  106114. else {
  106115. for(shift = 0; !(x&1); shift++)
  106116. x >>= 1;
  106117. }
  106118. if(shift > 0) {
  106119. for(i = 0; i < samples; i++)
  106120. signal[i] >>= shift;
  106121. }
  106122. return shift;
  106123. }
  106124. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106125. {
  106126. unsigned channel;
  106127. for(channel = 0; channel < channels; channel++)
  106128. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  106129. fifo->tail += wide_samples;
  106130. FLAC__ASSERT(fifo->tail <= fifo->size);
  106131. }
  106132. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106133. {
  106134. unsigned channel;
  106135. unsigned sample, wide_sample;
  106136. unsigned tail = fifo->tail;
  106137. sample = input_offset * channels;
  106138. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  106139. for(channel = 0; channel < channels; channel++)
  106140. fifo->data[channel][tail] = input[sample++];
  106141. tail++;
  106142. }
  106143. fifo->tail = tail;
  106144. FLAC__ASSERT(fifo->tail <= fifo->size);
  106145. }
  106146. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106147. {
  106148. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106149. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  106150. (void)decoder;
  106151. if(encoder->private_->verify.needs_magic_hack) {
  106152. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  106153. *bytes = FLAC__STREAM_SYNC_LENGTH;
  106154. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  106155. encoder->private_->verify.needs_magic_hack = false;
  106156. }
  106157. else {
  106158. if(encoded_bytes == 0) {
  106159. /*
  106160. * If we get here, a FIFO underflow has occurred,
  106161. * which means there is a bug somewhere.
  106162. */
  106163. FLAC__ASSERT(0);
  106164. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  106165. }
  106166. else if(encoded_bytes < *bytes)
  106167. *bytes = encoded_bytes;
  106168. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  106169. encoder->private_->verify.output.data += *bytes;
  106170. encoder->private_->verify.output.bytes -= *bytes;
  106171. }
  106172. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106173. }
  106174. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  106175. {
  106176. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  106177. unsigned channel;
  106178. const unsigned channels = frame->header.channels;
  106179. const unsigned blocksize = frame->header.blocksize;
  106180. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  106181. (void)decoder;
  106182. for(channel = 0; channel < channels; channel++) {
  106183. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  106184. unsigned i, sample = 0;
  106185. FLAC__int32 expect = 0, got = 0;
  106186. for(i = 0; i < blocksize; i++) {
  106187. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  106188. sample = i;
  106189. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  106190. got = (FLAC__int32)buffer[channel][i];
  106191. break;
  106192. }
  106193. }
  106194. FLAC__ASSERT(i < blocksize);
  106195. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  106196. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  106197. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  106198. encoder->private_->verify.error_stats.channel = channel;
  106199. encoder->private_->verify.error_stats.sample = sample;
  106200. encoder->private_->verify.error_stats.expected = expect;
  106201. encoder->private_->verify.error_stats.got = got;
  106202. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  106203. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  106204. }
  106205. }
  106206. /* dequeue the frame from the fifo */
  106207. encoder->private_->verify.input_fifo.tail -= blocksize;
  106208. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106209. for(channel = 0; channel < channels; channel++)
  106210. 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]));
  106211. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106212. }
  106213. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106214. {
  106215. (void)decoder, (void)metadata, (void)client_data;
  106216. }
  106217. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106218. {
  106219. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106220. (void)decoder, (void)status;
  106221. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106222. }
  106223. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106224. {
  106225. (void)client_data;
  106226. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106227. if (*bytes == 0) {
  106228. if (feof(encoder->private_->file))
  106229. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106230. else if (ferror(encoder->private_->file))
  106231. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106232. }
  106233. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106234. }
  106235. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106236. {
  106237. (void)client_data;
  106238. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106239. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106240. else
  106241. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106242. }
  106243. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106244. {
  106245. off_t offset;
  106246. (void)client_data;
  106247. offset = ftello(encoder->private_->file);
  106248. if(offset < 0) {
  106249. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106250. }
  106251. else {
  106252. *absolute_byte_offset = (FLAC__uint64)offset;
  106253. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106254. }
  106255. }
  106256. #ifdef FLAC__VALGRIND_TESTING
  106257. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106258. {
  106259. size_t ret = fwrite(ptr, size, nmemb, stream);
  106260. if(!ferror(stream))
  106261. fflush(stream);
  106262. return ret;
  106263. }
  106264. #else
  106265. #define local__fwrite fwrite
  106266. #endif
  106267. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106268. {
  106269. (void)client_data, (void)current_frame;
  106270. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106271. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106272. #if FLAC__HAS_OGG
  106273. /* We would like to be able to use 'samples > 0' in the
  106274. * clause here but currently because of the nature of our
  106275. * Ogg writing implementation, 'samples' is always 0 (see
  106276. * ogg_encoder_aspect.c). The downside is extra progress
  106277. * callbacks.
  106278. */
  106279. encoder->private_->is_ogg? true :
  106280. #endif
  106281. samples > 0
  106282. );
  106283. if(call_it) {
  106284. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106285. * because at this point in the callback chain, the stats
  106286. * have not been updated. Only after we return and control
  106287. * gets back to write_frame_() are the stats updated
  106288. */
  106289. 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);
  106290. }
  106291. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106292. }
  106293. else
  106294. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106295. }
  106296. /*
  106297. * This will forcibly set stdout to binary mode (for OSes that require it)
  106298. */
  106299. FILE *get_binary_stdout_(void)
  106300. {
  106301. /* if something breaks here it is probably due to the presence or
  106302. * absence of an underscore before the identifiers 'setmode',
  106303. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106304. */
  106305. #if defined _MSC_VER || defined __MINGW32__
  106306. _setmode(_fileno(stdout), _O_BINARY);
  106307. #elif defined __CYGWIN__
  106308. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106309. setmode(_fileno(stdout), _O_BINARY);
  106310. #elif defined __EMX__
  106311. setmode(fileno(stdout), O_BINARY);
  106312. #endif
  106313. return stdout;
  106314. }
  106315. #endif
  106316. /*** End of inlined file: stream_encoder.c ***/
  106317. /*** Start of inlined file: stream_encoder_framing.c ***/
  106318. /*** Start of inlined file: juce_FlacHeader.h ***/
  106319. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106320. // tasks..
  106321. #define VERSION "1.2.1"
  106322. #define FLAC__NO_DLL 1
  106323. #if JUCE_MSVC
  106324. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106325. #endif
  106326. #if JUCE_MAC
  106327. #define FLAC__SYS_DARWIN 1
  106328. #endif
  106329. /*** End of inlined file: juce_FlacHeader.h ***/
  106330. #if JUCE_USE_FLAC
  106331. #if HAVE_CONFIG_H
  106332. # include <config.h>
  106333. #endif
  106334. #include <stdio.h>
  106335. #include <string.h> /* for strlen() */
  106336. #ifdef max
  106337. #undef max
  106338. #endif
  106339. #define max(x,y) ((x)>(y)?(x):(y))
  106340. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106341. 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);
  106342. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106343. {
  106344. unsigned i, j;
  106345. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106346. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106347. return false;
  106348. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106349. return false;
  106350. /*
  106351. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106352. */
  106353. i = metadata->length;
  106354. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106355. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106356. i -= metadata->data.vorbis_comment.vendor_string.length;
  106357. i += vendor_string_length;
  106358. }
  106359. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106360. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106361. return false;
  106362. switch(metadata->type) {
  106363. case FLAC__METADATA_TYPE_STREAMINFO:
  106364. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106365. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106366. return false;
  106367. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106368. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106369. return false;
  106370. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106371. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106372. return false;
  106373. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106374. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106375. return false;
  106376. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106377. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106378. return false;
  106379. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106380. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106381. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106382. return false;
  106383. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106384. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106385. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106386. return false;
  106387. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106388. return false;
  106389. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106390. return false;
  106391. break;
  106392. case FLAC__METADATA_TYPE_PADDING:
  106393. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106394. return false;
  106395. break;
  106396. case FLAC__METADATA_TYPE_APPLICATION:
  106397. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106398. return false;
  106399. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106400. return false;
  106401. break;
  106402. case FLAC__METADATA_TYPE_SEEKTABLE:
  106403. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106404. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106405. return false;
  106406. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106407. return false;
  106408. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106409. return false;
  106410. }
  106411. break;
  106412. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106413. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106414. return false;
  106415. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106416. return false;
  106417. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106418. return false;
  106419. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106420. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106421. return false;
  106422. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106423. return false;
  106424. }
  106425. break;
  106426. case FLAC__METADATA_TYPE_CUESHEET:
  106427. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106428. 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))
  106429. return false;
  106430. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106431. return false;
  106432. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106433. return false;
  106434. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106435. return false;
  106436. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106437. return false;
  106438. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106439. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106440. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106441. return false;
  106442. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106443. return false;
  106444. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106445. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106446. return false;
  106447. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106448. return false;
  106449. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106450. return false;
  106451. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106452. return false;
  106453. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106454. return false;
  106455. for(j = 0; j < track->num_indices; j++) {
  106456. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106457. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106458. return false;
  106459. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106460. return false;
  106461. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106462. return false;
  106463. }
  106464. }
  106465. break;
  106466. case FLAC__METADATA_TYPE_PICTURE:
  106467. {
  106468. size_t len;
  106469. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106470. return false;
  106471. len = strlen(metadata->data.picture.mime_type);
  106472. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106473. return false;
  106474. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106475. return false;
  106476. len = strlen((const char *)metadata->data.picture.description);
  106477. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106478. return false;
  106479. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106480. return false;
  106481. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106482. return false;
  106483. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106484. return false;
  106485. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106486. return false;
  106487. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106488. return false;
  106489. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106490. return false;
  106491. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106492. return false;
  106493. }
  106494. break;
  106495. default:
  106496. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106497. return false;
  106498. break;
  106499. }
  106500. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106501. return true;
  106502. }
  106503. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106504. {
  106505. unsigned u, blocksize_hint, sample_rate_hint;
  106506. FLAC__byte crc;
  106507. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106508. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106509. return false;
  106510. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106511. return false;
  106512. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106513. return false;
  106514. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106515. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106516. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106517. blocksize_hint = 0;
  106518. switch(header->blocksize) {
  106519. case 192: u = 1; break;
  106520. case 576: u = 2; break;
  106521. case 1152: u = 3; break;
  106522. case 2304: u = 4; break;
  106523. case 4608: u = 5; break;
  106524. case 256: u = 8; break;
  106525. case 512: u = 9; break;
  106526. case 1024: u = 10; break;
  106527. case 2048: u = 11; break;
  106528. case 4096: u = 12; break;
  106529. case 8192: u = 13; break;
  106530. case 16384: u = 14; break;
  106531. case 32768: u = 15; break;
  106532. default:
  106533. if(header->blocksize <= 0x100)
  106534. blocksize_hint = u = 6;
  106535. else
  106536. blocksize_hint = u = 7;
  106537. break;
  106538. }
  106539. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106540. return false;
  106541. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106542. sample_rate_hint = 0;
  106543. switch(header->sample_rate) {
  106544. case 88200: u = 1; break;
  106545. case 176400: u = 2; break;
  106546. case 192000: u = 3; break;
  106547. case 8000: u = 4; break;
  106548. case 16000: u = 5; break;
  106549. case 22050: u = 6; break;
  106550. case 24000: u = 7; break;
  106551. case 32000: u = 8; break;
  106552. case 44100: u = 9; break;
  106553. case 48000: u = 10; break;
  106554. case 96000: u = 11; break;
  106555. default:
  106556. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106557. sample_rate_hint = u = 12;
  106558. else if(header->sample_rate % 10 == 0)
  106559. sample_rate_hint = u = 14;
  106560. else if(header->sample_rate <= 0xffff)
  106561. sample_rate_hint = u = 13;
  106562. else
  106563. u = 0;
  106564. break;
  106565. }
  106566. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106567. return false;
  106568. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106569. switch(header->channel_assignment) {
  106570. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106571. u = header->channels - 1;
  106572. break;
  106573. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106574. FLAC__ASSERT(header->channels == 2);
  106575. u = 8;
  106576. break;
  106577. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106578. FLAC__ASSERT(header->channels == 2);
  106579. u = 9;
  106580. break;
  106581. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106582. FLAC__ASSERT(header->channels == 2);
  106583. u = 10;
  106584. break;
  106585. default:
  106586. FLAC__ASSERT(0);
  106587. }
  106588. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106589. return false;
  106590. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106591. switch(header->bits_per_sample) {
  106592. case 8 : u = 1; break;
  106593. case 12: u = 2; break;
  106594. case 16: u = 4; break;
  106595. case 20: u = 5; break;
  106596. case 24: u = 6; break;
  106597. default: u = 0; break;
  106598. }
  106599. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106600. return false;
  106601. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106602. return false;
  106603. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106604. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106605. return false;
  106606. }
  106607. else {
  106608. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106609. return false;
  106610. }
  106611. if(blocksize_hint)
  106612. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106613. return false;
  106614. switch(sample_rate_hint) {
  106615. case 12:
  106616. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106617. return false;
  106618. break;
  106619. case 13:
  106620. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106621. return false;
  106622. break;
  106623. case 14:
  106624. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106625. return false;
  106626. break;
  106627. }
  106628. /* write the CRC */
  106629. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106630. return false;
  106631. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106632. return false;
  106633. return true;
  106634. }
  106635. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106636. {
  106637. FLAC__bool ok;
  106638. ok =
  106639. 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) &&
  106640. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106641. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106642. ;
  106643. return ok;
  106644. }
  106645. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106646. {
  106647. unsigned i;
  106648. 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))
  106649. return false;
  106650. if(wasted_bits)
  106651. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106652. return false;
  106653. for(i = 0; i < subframe->order; i++)
  106654. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106655. return false;
  106656. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106657. return false;
  106658. switch(subframe->entropy_coding_method.type) {
  106659. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106660. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106661. if(!add_residual_partitioned_rice_(
  106662. bw,
  106663. subframe->residual,
  106664. residual_samples,
  106665. subframe->order,
  106666. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106667. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106668. subframe->entropy_coding_method.data.partitioned_rice.order,
  106669. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106670. ))
  106671. return false;
  106672. break;
  106673. default:
  106674. FLAC__ASSERT(0);
  106675. }
  106676. return true;
  106677. }
  106678. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106679. {
  106680. unsigned i;
  106681. 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))
  106682. return false;
  106683. if(wasted_bits)
  106684. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106685. return false;
  106686. for(i = 0; i < subframe->order; i++)
  106687. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106688. return false;
  106689. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106690. return false;
  106691. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106692. return false;
  106693. for(i = 0; i < subframe->order; i++)
  106694. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106695. return false;
  106696. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106697. return false;
  106698. switch(subframe->entropy_coding_method.type) {
  106699. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106700. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106701. if(!add_residual_partitioned_rice_(
  106702. bw,
  106703. subframe->residual,
  106704. residual_samples,
  106705. subframe->order,
  106706. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106707. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106708. subframe->entropy_coding_method.data.partitioned_rice.order,
  106709. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106710. ))
  106711. return false;
  106712. break;
  106713. default:
  106714. FLAC__ASSERT(0);
  106715. }
  106716. return true;
  106717. }
  106718. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106719. {
  106720. unsigned i;
  106721. const FLAC__int32 *signal = subframe->data;
  106722. 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))
  106723. return false;
  106724. if(wasted_bits)
  106725. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106726. return false;
  106727. for(i = 0; i < samples; i++)
  106728. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106729. return false;
  106730. return true;
  106731. }
  106732. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106733. {
  106734. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106735. return false;
  106736. switch(method->type) {
  106737. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106738. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106739. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106740. return false;
  106741. break;
  106742. default:
  106743. FLAC__ASSERT(0);
  106744. }
  106745. return true;
  106746. }
  106747. 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)
  106748. {
  106749. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106750. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106751. if(partition_order == 0) {
  106752. unsigned i;
  106753. if(raw_bits[0] == 0) {
  106754. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106755. return false;
  106756. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106757. return false;
  106758. }
  106759. else {
  106760. FLAC__ASSERT(rice_parameters[0] == 0);
  106761. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106762. return false;
  106763. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106764. return false;
  106765. for(i = 0; i < residual_samples; i++) {
  106766. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106767. return false;
  106768. }
  106769. }
  106770. return true;
  106771. }
  106772. else {
  106773. unsigned i, j, k = 0, k_last = 0;
  106774. unsigned partition_samples;
  106775. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106776. for(i = 0; i < (1u<<partition_order); i++) {
  106777. partition_samples = default_partition_samples;
  106778. if(i == 0)
  106779. partition_samples -= predictor_order;
  106780. k += partition_samples;
  106781. if(raw_bits[i] == 0) {
  106782. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106783. return false;
  106784. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106785. return false;
  106786. }
  106787. else {
  106788. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106789. return false;
  106790. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106791. return false;
  106792. for(j = k_last; j < k; j++) {
  106793. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106794. return false;
  106795. }
  106796. }
  106797. k_last = k;
  106798. }
  106799. return true;
  106800. }
  106801. }
  106802. #endif
  106803. /*** End of inlined file: stream_encoder_framing.c ***/
  106804. /*** Start of inlined file: window_flac.c ***/
  106805. /*** Start of inlined file: juce_FlacHeader.h ***/
  106806. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106807. // tasks..
  106808. #define VERSION "1.2.1"
  106809. #define FLAC__NO_DLL 1
  106810. #if JUCE_MSVC
  106811. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106812. #endif
  106813. #if JUCE_MAC
  106814. #define FLAC__SYS_DARWIN 1
  106815. #endif
  106816. /*** End of inlined file: juce_FlacHeader.h ***/
  106817. #if JUCE_USE_FLAC
  106818. #if HAVE_CONFIG_H
  106819. # include <config.h>
  106820. #endif
  106821. #include <math.h>
  106822. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106823. #ifndef M_PI
  106824. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106825. #define M_PI 3.14159265358979323846
  106826. #endif
  106827. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106828. {
  106829. const FLAC__int32 N = L - 1;
  106830. FLAC__int32 n;
  106831. if (L & 1) {
  106832. for (n = 0; n <= N/2; n++)
  106833. window[n] = 2.0f * n / (float)N;
  106834. for (; n <= N; n++)
  106835. window[n] = 2.0f - 2.0f * n / (float)N;
  106836. }
  106837. else {
  106838. for (n = 0; n <= L/2-1; n++)
  106839. window[n] = 2.0f * n / (float)N;
  106840. for (; n <= N; n++)
  106841. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106842. }
  106843. }
  106844. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106845. {
  106846. const FLAC__int32 N = L - 1;
  106847. FLAC__int32 n;
  106848. for (n = 0; n < L; n++)
  106849. 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)));
  106850. }
  106851. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106852. {
  106853. const FLAC__int32 N = L - 1;
  106854. FLAC__int32 n;
  106855. for (n = 0; n < L; n++)
  106856. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106857. }
  106858. /* 4-term -92dB side-lobe */
  106859. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106860. {
  106861. const FLAC__int32 N = L - 1;
  106862. FLAC__int32 n;
  106863. for (n = 0; n <= N; n++)
  106864. 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));
  106865. }
  106866. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106867. {
  106868. const FLAC__int32 N = L - 1;
  106869. const double N2 = (double)N / 2.;
  106870. FLAC__int32 n;
  106871. for (n = 0; n <= N; n++) {
  106872. double k = ((double)n - N2) / N2;
  106873. k = 1.0f - k * k;
  106874. window[n] = (FLAC__real)(k * k);
  106875. }
  106876. }
  106877. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106878. {
  106879. const FLAC__int32 N = L - 1;
  106880. FLAC__int32 n;
  106881. for (n = 0; n < L; n++)
  106882. 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));
  106883. }
  106884. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106885. {
  106886. const FLAC__int32 N = L - 1;
  106887. const double N2 = (double)N / 2.;
  106888. FLAC__int32 n;
  106889. for (n = 0; n <= N; n++) {
  106890. const double k = ((double)n - N2) / (stddev * N2);
  106891. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106892. }
  106893. }
  106894. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106895. {
  106896. const FLAC__int32 N = L - 1;
  106897. FLAC__int32 n;
  106898. for (n = 0; n < L; n++)
  106899. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106900. }
  106901. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106902. {
  106903. const FLAC__int32 N = L - 1;
  106904. FLAC__int32 n;
  106905. for (n = 0; n < L; n++)
  106906. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106907. }
  106908. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106909. {
  106910. const FLAC__int32 N = L - 1;
  106911. FLAC__int32 n;
  106912. for (n = 0; n < L; n++)
  106913. 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));
  106914. }
  106915. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106916. {
  106917. const FLAC__int32 N = L - 1;
  106918. FLAC__int32 n;
  106919. for (n = 0; n < L; n++)
  106920. 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));
  106921. }
  106922. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106923. {
  106924. FLAC__int32 n;
  106925. for (n = 0; n < L; n++)
  106926. window[n] = 1.0f;
  106927. }
  106928. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106929. {
  106930. FLAC__int32 n;
  106931. if (L & 1) {
  106932. for (n = 1; n <= L+1/2; n++)
  106933. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106934. for (; n <= L; n++)
  106935. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106936. }
  106937. else {
  106938. for (n = 1; n <= L/2; n++)
  106939. window[n-1] = 2.0f * n / (float)L;
  106940. for (; n <= L; n++)
  106941. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106942. }
  106943. }
  106944. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106945. {
  106946. if (p <= 0.0)
  106947. FLAC__window_rectangle(window, L);
  106948. else if (p >= 1.0)
  106949. FLAC__window_hann(window, L);
  106950. else {
  106951. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106952. FLAC__int32 n;
  106953. /* start with rectangle... */
  106954. FLAC__window_rectangle(window, L);
  106955. /* ...replace ends with hann */
  106956. if (Np > 0) {
  106957. for (n = 0; n <= Np; n++) {
  106958. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106959. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106960. }
  106961. }
  106962. }
  106963. }
  106964. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106965. {
  106966. const FLAC__int32 N = L - 1;
  106967. const double N2 = (double)N / 2.;
  106968. FLAC__int32 n;
  106969. for (n = 0; n <= N; n++) {
  106970. const double k = ((double)n - N2) / N2;
  106971. window[n] = (FLAC__real)(1.0f - k * k);
  106972. }
  106973. }
  106974. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106975. #endif
  106976. /*** End of inlined file: window_flac.c ***/
  106977. #else
  106978. #include <FLAC/all.h>
  106979. #endif
  106980. }
  106981. #undef max
  106982. #undef min
  106983. BEGIN_JUCE_NAMESPACE
  106984. static const char* const flacFormatName = "FLAC file";
  106985. static const char* const flacExtensions[] = { ".flac", 0 };
  106986. class FlacReader : public AudioFormatReader
  106987. {
  106988. public:
  106989. FlacReader (InputStream* const in)
  106990. : AudioFormatReader (in, TRANS (flacFormatName)),
  106991. reservoir (2, 0),
  106992. reservoirStart (0),
  106993. samplesInReservoir (0),
  106994. scanningForLength (false)
  106995. {
  106996. using namespace FlacNamespace;
  106997. lengthInSamples = 0;
  106998. decoder = FLAC__stream_decoder_new();
  106999. ok = FLAC__stream_decoder_init_stream (decoder,
  107000. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  107001. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  107002. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  107003. if (ok)
  107004. {
  107005. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  107006. if (lengthInSamples == 0 && sampleRate > 0)
  107007. {
  107008. // the length hasn't been stored in the metadata, so we'll need to
  107009. // work it out the length the hard way, by scanning the whole file..
  107010. scanningForLength = true;
  107011. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  107012. scanningForLength = false;
  107013. const int64 tempLength = lengthInSamples;
  107014. FLAC__stream_decoder_reset (decoder);
  107015. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  107016. lengthInSamples = tempLength;
  107017. }
  107018. }
  107019. }
  107020. ~FlacReader()
  107021. {
  107022. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  107023. }
  107024. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  107025. {
  107026. sampleRate = info.sample_rate;
  107027. bitsPerSample = info.bits_per_sample;
  107028. lengthInSamples = (unsigned int) info.total_samples;
  107029. numChannels = info.channels;
  107030. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  107031. }
  107032. // returns the number of samples read
  107033. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  107034. int64 startSampleInFile, int numSamples)
  107035. {
  107036. using namespace FlacNamespace;
  107037. if (! ok)
  107038. return false;
  107039. while (numSamples > 0)
  107040. {
  107041. if (startSampleInFile >= reservoirStart
  107042. && startSampleInFile < reservoirStart + samplesInReservoir)
  107043. {
  107044. const int num = (int) jmin ((int64) numSamples,
  107045. reservoirStart + samplesInReservoir - startSampleInFile);
  107046. jassert (num > 0);
  107047. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  107048. if (destSamples[i] != 0)
  107049. memcpy (destSamples[i] + startOffsetInDestBuffer,
  107050. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  107051. sizeof (int) * num);
  107052. startOffsetInDestBuffer += num;
  107053. startSampleInFile += num;
  107054. numSamples -= num;
  107055. }
  107056. else
  107057. {
  107058. if (startSampleInFile >= (int) lengthInSamples)
  107059. {
  107060. samplesInReservoir = 0;
  107061. }
  107062. else if (startSampleInFile < reservoirStart
  107063. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  107064. {
  107065. // had some problems with flac crashing if the read pos is aligned more
  107066. // accurately than this. Probably fixed in newer versions of the library, though.
  107067. reservoirStart = (int) (startSampleInFile & ~511);
  107068. samplesInReservoir = 0;
  107069. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  107070. }
  107071. else
  107072. {
  107073. reservoirStart += samplesInReservoir;
  107074. samplesInReservoir = 0;
  107075. FLAC__stream_decoder_process_single (decoder);
  107076. }
  107077. if (samplesInReservoir == 0)
  107078. break;
  107079. }
  107080. }
  107081. if (numSamples > 0)
  107082. {
  107083. for (int i = numDestChannels; --i >= 0;)
  107084. if (destSamples[i] != 0)
  107085. zeromem (destSamples[i] + startOffsetInDestBuffer,
  107086. sizeof (int) * numSamples);
  107087. }
  107088. return true;
  107089. }
  107090. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  107091. {
  107092. if (scanningForLength)
  107093. {
  107094. lengthInSamples += numSamples;
  107095. }
  107096. else
  107097. {
  107098. if (numSamples > reservoir.getNumSamples())
  107099. reservoir.setSize (numChannels, numSamples, false, false, true);
  107100. const int bitsToShift = 32 - bitsPerSample;
  107101. for (int i = 0; i < (int) numChannels; ++i)
  107102. {
  107103. const FlacNamespace::FLAC__int32* src = buffer[i];
  107104. int n = i;
  107105. while (src == 0 && n > 0)
  107106. src = buffer [--n];
  107107. if (src != 0)
  107108. {
  107109. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  107110. for (int j = 0; j < numSamples; ++j)
  107111. dest[j] = src[j] << bitsToShift;
  107112. }
  107113. }
  107114. samplesInReservoir = numSamples;
  107115. }
  107116. }
  107117. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  107118. {
  107119. using namespace FlacNamespace;
  107120. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  107121. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  107122. }
  107123. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  107124. {
  107125. using namespace FlacNamespace;
  107126. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  107127. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  107128. }
  107129. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107130. {
  107131. using namespace FlacNamespace;
  107132. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  107133. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  107134. }
  107135. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  107136. {
  107137. using namespace FlacNamespace;
  107138. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  107139. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  107140. }
  107141. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  107142. {
  107143. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  107144. }
  107145. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107146. const FlacNamespace::FLAC__Frame* frame,
  107147. const FlacNamespace::FLAC__int32* const buffer[],
  107148. void* client_data)
  107149. {
  107150. using namespace FlacNamespace;
  107151. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  107152. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  107153. }
  107154. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107155. const FlacNamespace::FLAC__StreamMetadata* metadata,
  107156. void* client_data)
  107157. {
  107158. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  107159. }
  107160. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  107161. {
  107162. }
  107163. private:
  107164. FlacNamespace::FLAC__StreamDecoder* decoder;
  107165. AudioSampleBuffer reservoir;
  107166. int reservoirStart, samplesInReservoir;
  107167. bool ok, scanningForLength;
  107168. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  107169. };
  107170. class FlacWriter : public AudioFormatWriter
  107171. {
  107172. public:
  107173. FlacWriter (OutputStream* const out, double sampleRate_,
  107174. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  107175. : AudioFormatWriter (out, TRANS (flacFormatName),
  107176. sampleRate_, numChannels_, bitsPerSample_)
  107177. {
  107178. using namespace FlacNamespace;
  107179. encoder = FLAC__stream_encoder_new();
  107180. if (qualityOptionIndex > 0)
  107181. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  107182. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  107183. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  107184. FLAC__stream_encoder_set_channels (encoder, numChannels);
  107185. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  107186. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  107187. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  107188. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  107189. ok = FLAC__stream_encoder_init_stream (encoder,
  107190. encodeWriteCallback, encodeSeekCallback,
  107191. encodeTellCallback, encodeMetadataCallback,
  107192. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  107193. }
  107194. ~FlacWriter()
  107195. {
  107196. if (ok)
  107197. {
  107198. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  107199. output->flush();
  107200. }
  107201. else
  107202. {
  107203. output = 0; // to stop the base class deleting this, as it needs to be returned
  107204. // to the caller of createWriter()
  107205. }
  107206. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107207. }
  107208. bool write (const int** samplesToWrite, int numSamples)
  107209. {
  107210. using namespace FlacNamespace;
  107211. if (! ok)
  107212. return false;
  107213. int* buf[3];
  107214. HeapBlock<int> temp;
  107215. const int bitsToShift = 32 - bitsPerSample;
  107216. if (bitsToShift > 0)
  107217. {
  107218. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107219. temp.malloc (numSamples * numChannelsToWrite);
  107220. buf[0] = temp.getData();
  107221. buf[1] = temp.getData() + numSamples;
  107222. buf[2] = 0;
  107223. for (int i = numChannelsToWrite; --i >= 0;)
  107224. if (samplesToWrite[i] != 0)
  107225. for (int j = 0; j < numSamples; ++j)
  107226. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107227. samplesToWrite = const_cast<const int**> (buf);
  107228. }
  107229. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  107230. }
  107231. bool writeData (const void* const data, const int size) const
  107232. {
  107233. return output->write (data, size);
  107234. }
  107235. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107236. {
  107237. using namespace FlacNamespace;
  107238. b += bytes;
  107239. for (int i = 0; i < bytes; ++i)
  107240. {
  107241. *(--b) = (FLAC__byte) (val & 0xff);
  107242. val >>= 8;
  107243. }
  107244. }
  107245. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107246. {
  107247. using namespace FlacNamespace;
  107248. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107249. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107250. const unsigned int channelsMinus1 = info.channels - 1;
  107251. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107252. packUint32 (info.min_blocksize, buffer, 2);
  107253. packUint32 (info.max_blocksize, buffer + 2, 2);
  107254. packUint32 (info.min_framesize, buffer + 4, 3);
  107255. packUint32 (info.max_framesize, buffer + 7, 3);
  107256. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107257. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107258. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107259. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107260. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107261. memcpy (buffer + 18, info.md5sum, 16);
  107262. const bool seekOk = output->setPosition (4);
  107263. (void) seekOk;
  107264. // if this fails, you've given it an output stream that can't seek! It needs
  107265. // to be able to seek back to write the header
  107266. jassert (seekOk);
  107267. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107268. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107269. }
  107270. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107271. const FlacNamespace::FLAC__byte buffer[],
  107272. size_t bytes,
  107273. unsigned int /*samples*/,
  107274. unsigned int /*current_frame*/,
  107275. void* client_data)
  107276. {
  107277. using namespace FlacNamespace;
  107278. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107279. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107280. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107281. }
  107282. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107283. {
  107284. using namespace FlacNamespace;
  107285. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107286. }
  107287. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107288. {
  107289. using namespace FlacNamespace;
  107290. if (client_data == 0)
  107291. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107292. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107293. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107294. }
  107295. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107296. {
  107297. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107298. }
  107299. bool ok;
  107300. private:
  107301. FlacNamespace::FLAC__StreamEncoder* encoder;
  107302. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  107303. };
  107304. FlacAudioFormat::FlacAudioFormat()
  107305. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107306. {
  107307. }
  107308. FlacAudioFormat::~FlacAudioFormat()
  107309. {
  107310. }
  107311. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107312. {
  107313. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107314. return Array <int> (rates);
  107315. }
  107316. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107317. {
  107318. const int depths[] = { 16, 24, 0 };
  107319. return Array <int> (depths);
  107320. }
  107321. bool FlacAudioFormat::canDoStereo() { return true; }
  107322. bool FlacAudioFormat::canDoMono() { return true; }
  107323. bool FlacAudioFormat::isCompressed() { return true; }
  107324. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107325. const bool deleteStreamIfOpeningFails)
  107326. {
  107327. ScopedPointer<FlacReader> r (new FlacReader (in));
  107328. if (r->sampleRate != 0)
  107329. return r.release();
  107330. if (! deleteStreamIfOpeningFails)
  107331. r->input = 0;
  107332. return 0;
  107333. }
  107334. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107335. double sampleRate,
  107336. unsigned int numberOfChannels,
  107337. int bitsPerSample,
  107338. const StringPairArray& /*metadataValues*/,
  107339. int qualityOptionIndex)
  107340. {
  107341. if (getPossibleBitDepths().contains (bitsPerSample))
  107342. {
  107343. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107344. if (w->ok)
  107345. return w.release();
  107346. }
  107347. return 0;
  107348. }
  107349. END_JUCE_NAMESPACE
  107350. #endif
  107351. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107352. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107353. #if JUCE_USE_OGGVORBIS
  107354. #if JUCE_MAC
  107355. #define __MACOSX__ 1
  107356. #endif
  107357. namespace OggVorbisNamespace
  107358. {
  107359. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107360. /*** Start of inlined file: vorbisenc.h ***/
  107361. #ifndef _OV_ENC_H_
  107362. #define _OV_ENC_H_
  107363. #ifdef __cplusplus
  107364. extern "C"
  107365. {
  107366. #endif /* __cplusplus */
  107367. /*** Start of inlined file: codec.h ***/
  107368. #ifndef _vorbis_codec_h_
  107369. #define _vorbis_codec_h_
  107370. #ifdef __cplusplus
  107371. extern "C"
  107372. {
  107373. #endif /* __cplusplus */
  107374. /*** Start of inlined file: ogg.h ***/
  107375. #ifndef _OGG_H
  107376. #define _OGG_H
  107377. #ifdef __cplusplus
  107378. extern "C" {
  107379. #endif
  107380. /*** Start of inlined file: os_types.h ***/
  107381. #ifndef _OS_TYPES_H
  107382. #define _OS_TYPES_H
  107383. /* make it easy on the folks that want to compile the libs with a
  107384. different malloc than stdlib */
  107385. #define _ogg_malloc malloc
  107386. #define _ogg_calloc calloc
  107387. #define _ogg_realloc realloc
  107388. #define _ogg_free free
  107389. #if defined(_WIN32)
  107390. # if defined(__CYGWIN__)
  107391. # include <_G_config.h>
  107392. typedef _G_int64_t ogg_int64_t;
  107393. typedef _G_int32_t ogg_int32_t;
  107394. typedef _G_uint32_t ogg_uint32_t;
  107395. typedef _G_int16_t ogg_int16_t;
  107396. typedef _G_uint16_t ogg_uint16_t;
  107397. # elif defined(__MINGW32__)
  107398. typedef short ogg_int16_t;
  107399. typedef unsigned short ogg_uint16_t;
  107400. typedef int ogg_int32_t;
  107401. typedef unsigned int ogg_uint32_t;
  107402. typedef long long ogg_int64_t;
  107403. typedef unsigned long long ogg_uint64_t;
  107404. # elif defined(__MWERKS__)
  107405. typedef long long ogg_int64_t;
  107406. typedef int ogg_int32_t;
  107407. typedef unsigned int ogg_uint32_t;
  107408. typedef short ogg_int16_t;
  107409. typedef unsigned short ogg_uint16_t;
  107410. # else
  107411. /* MSVC/Borland */
  107412. typedef __int64 ogg_int64_t;
  107413. typedef __int32 ogg_int32_t;
  107414. typedef unsigned __int32 ogg_uint32_t;
  107415. typedef __int16 ogg_int16_t;
  107416. typedef unsigned __int16 ogg_uint16_t;
  107417. # endif
  107418. #elif defined(__MACOS__)
  107419. # include <sys/types.h>
  107420. typedef SInt16 ogg_int16_t;
  107421. typedef UInt16 ogg_uint16_t;
  107422. typedef SInt32 ogg_int32_t;
  107423. typedef UInt32 ogg_uint32_t;
  107424. typedef SInt64 ogg_int64_t;
  107425. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107426. # include <sys/types.h>
  107427. typedef int16_t ogg_int16_t;
  107428. typedef u_int16_t ogg_uint16_t;
  107429. typedef int32_t ogg_int32_t;
  107430. typedef u_int32_t ogg_uint32_t;
  107431. typedef int64_t ogg_int64_t;
  107432. #elif defined(__BEOS__)
  107433. /* Be */
  107434. # include <inttypes.h>
  107435. typedef int16_t ogg_int16_t;
  107436. typedef u_int16_t ogg_uint16_t;
  107437. typedef int32_t ogg_int32_t;
  107438. typedef u_int32_t ogg_uint32_t;
  107439. typedef int64_t ogg_int64_t;
  107440. #elif defined (__EMX__)
  107441. /* OS/2 GCC */
  107442. typedef short ogg_int16_t;
  107443. typedef unsigned short ogg_uint16_t;
  107444. typedef int ogg_int32_t;
  107445. typedef unsigned int ogg_uint32_t;
  107446. typedef long long ogg_int64_t;
  107447. #elif defined (DJGPP)
  107448. /* DJGPP */
  107449. typedef short ogg_int16_t;
  107450. typedef int ogg_int32_t;
  107451. typedef unsigned int ogg_uint32_t;
  107452. typedef long long ogg_int64_t;
  107453. #elif defined(R5900)
  107454. /* PS2 EE */
  107455. typedef long ogg_int64_t;
  107456. typedef int ogg_int32_t;
  107457. typedef unsigned ogg_uint32_t;
  107458. typedef short ogg_int16_t;
  107459. #elif defined(__SYMBIAN32__)
  107460. /* Symbian GCC */
  107461. typedef signed short ogg_int16_t;
  107462. typedef unsigned short ogg_uint16_t;
  107463. typedef signed int ogg_int32_t;
  107464. typedef unsigned int ogg_uint32_t;
  107465. typedef long long int ogg_int64_t;
  107466. #else
  107467. # include <sys/types.h>
  107468. /*** Start of inlined file: config_types.h ***/
  107469. #ifndef __CONFIG_TYPES_H__
  107470. #define __CONFIG_TYPES_H__
  107471. typedef int16_t ogg_int16_t;
  107472. typedef unsigned short ogg_uint16_t;
  107473. typedef int32_t ogg_int32_t;
  107474. typedef unsigned int ogg_uint32_t;
  107475. typedef int64_t ogg_int64_t;
  107476. #endif
  107477. /*** End of inlined file: config_types.h ***/
  107478. #endif
  107479. #endif /* _OS_TYPES_H */
  107480. /*** End of inlined file: os_types.h ***/
  107481. typedef struct {
  107482. long endbyte;
  107483. int endbit;
  107484. unsigned char *buffer;
  107485. unsigned char *ptr;
  107486. long storage;
  107487. } oggpack_buffer;
  107488. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107489. typedef struct {
  107490. unsigned char *header;
  107491. long header_len;
  107492. unsigned char *body;
  107493. long body_len;
  107494. } ogg_page;
  107495. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107496. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107497. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107498. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107499. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107500. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107501. }
  107502. /* ogg_stream_state contains the current encode/decode state of a logical
  107503. Ogg bitstream **********************************************************/
  107504. typedef struct {
  107505. unsigned char *body_data; /* bytes from packet bodies */
  107506. long body_storage; /* storage elements allocated */
  107507. long body_fill; /* elements stored; fill mark */
  107508. long body_returned; /* elements of fill returned */
  107509. int *lacing_vals; /* The values that will go to the segment table */
  107510. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107511. this way, but it is simple coupled to the
  107512. lacing fifo */
  107513. long lacing_storage;
  107514. long lacing_fill;
  107515. long lacing_packet;
  107516. long lacing_returned;
  107517. unsigned char header[282]; /* working space for header encode */
  107518. int header_fill;
  107519. int e_o_s; /* set when we have buffered the last packet in the
  107520. logical bitstream */
  107521. int b_o_s; /* set after we've written the initial page
  107522. of a logical bitstream */
  107523. long serialno;
  107524. long pageno;
  107525. ogg_int64_t packetno; /* sequence number for decode; the framing
  107526. knows where there's a hole in the data,
  107527. but we need coupling so that the codec
  107528. (which is in a seperate abstraction
  107529. layer) also knows about the gap */
  107530. ogg_int64_t granulepos;
  107531. } ogg_stream_state;
  107532. /* ogg_packet is used to encapsulate the data and metadata belonging
  107533. to a single raw Ogg/Vorbis packet *************************************/
  107534. typedef struct {
  107535. unsigned char *packet;
  107536. long bytes;
  107537. long b_o_s;
  107538. long e_o_s;
  107539. ogg_int64_t granulepos;
  107540. ogg_int64_t packetno; /* sequence number for decode; the framing
  107541. knows where there's a hole in the data,
  107542. but we need coupling so that the codec
  107543. (which is in a seperate abstraction
  107544. layer) also knows about the gap */
  107545. } ogg_packet;
  107546. typedef struct {
  107547. unsigned char *data;
  107548. int storage;
  107549. int fill;
  107550. int returned;
  107551. int unsynced;
  107552. int headerbytes;
  107553. int bodybytes;
  107554. } ogg_sync_state;
  107555. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107556. extern void oggpack_writeinit(oggpack_buffer *b);
  107557. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107558. extern void oggpack_writealign(oggpack_buffer *b);
  107559. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107560. extern void oggpack_reset(oggpack_buffer *b);
  107561. extern void oggpack_writeclear(oggpack_buffer *b);
  107562. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107563. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107564. extern long oggpack_look(oggpack_buffer *b,int bits);
  107565. extern long oggpack_look1(oggpack_buffer *b);
  107566. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107567. extern void oggpack_adv1(oggpack_buffer *b);
  107568. extern long oggpack_read(oggpack_buffer *b,int bits);
  107569. extern long oggpack_read1(oggpack_buffer *b);
  107570. extern long oggpack_bytes(oggpack_buffer *b);
  107571. extern long oggpack_bits(oggpack_buffer *b);
  107572. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107573. extern void oggpackB_writeinit(oggpack_buffer *b);
  107574. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107575. extern void oggpackB_writealign(oggpack_buffer *b);
  107576. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107577. extern void oggpackB_reset(oggpack_buffer *b);
  107578. extern void oggpackB_writeclear(oggpack_buffer *b);
  107579. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107580. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107581. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107582. extern long oggpackB_look1(oggpack_buffer *b);
  107583. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107584. extern void oggpackB_adv1(oggpack_buffer *b);
  107585. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107586. extern long oggpackB_read1(oggpack_buffer *b);
  107587. extern long oggpackB_bytes(oggpack_buffer *b);
  107588. extern long oggpackB_bits(oggpack_buffer *b);
  107589. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107590. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107591. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107592. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107593. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107594. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107595. extern int ogg_sync_init(ogg_sync_state *oy);
  107596. extern int ogg_sync_clear(ogg_sync_state *oy);
  107597. extern int ogg_sync_reset(ogg_sync_state *oy);
  107598. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107599. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107600. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107601. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107602. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107603. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107604. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107605. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107606. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107607. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107608. extern int ogg_stream_clear(ogg_stream_state *os);
  107609. extern int ogg_stream_reset(ogg_stream_state *os);
  107610. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107611. extern int ogg_stream_destroy(ogg_stream_state *os);
  107612. extern int ogg_stream_eos(ogg_stream_state *os);
  107613. extern void ogg_page_checksum_set(ogg_page *og);
  107614. extern int ogg_page_version(ogg_page *og);
  107615. extern int ogg_page_continued(ogg_page *og);
  107616. extern int ogg_page_bos(ogg_page *og);
  107617. extern int ogg_page_eos(ogg_page *og);
  107618. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107619. extern int ogg_page_serialno(ogg_page *og);
  107620. extern long ogg_page_pageno(ogg_page *og);
  107621. extern int ogg_page_packets(ogg_page *og);
  107622. extern void ogg_packet_clear(ogg_packet *op);
  107623. #ifdef __cplusplus
  107624. }
  107625. #endif
  107626. #endif /* _OGG_H */
  107627. /*** End of inlined file: ogg.h ***/
  107628. typedef struct vorbis_info{
  107629. int version;
  107630. int channels;
  107631. long rate;
  107632. /* The below bitrate declarations are *hints*.
  107633. Combinations of the three values carry the following implications:
  107634. all three set to the same value:
  107635. implies a fixed rate bitstream
  107636. only nominal set:
  107637. implies a VBR stream that averages the nominal bitrate. No hard
  107638. upper/lower limit
  107639. upper and or lower set:
  107640. implies a VBR bitstream that obeys the bitrate limits. nominal
  107641. may also be set to give a nominal rate.
  107642. none set:
  107643. the coder does not care to speculate.
  107644. */
  107645. long bitrate_upper;
  107646. long bitrate_nominal;
  107647. long bitrate_lower;
  107648. long bitrate_window;
  107649. void *codec_setup;
  107650. } vorbis_info;
  107651. /* vorbis_dsp_state buffers the current vorbis audio
  107652. analysis/synthesis state. The DSP state belongs to a specific
  107653. logical bitstream ****************************************************/
  107654. typedef struct vorbis_dsp_state{
  107655. int analysisp;
  107656. vorbis_info *vi;
  107657. float **pcm;
  107658. float **pcmret;
  107659. int pcm_storage;
  107660. int pcm_current;
  107661. int pcm_returned;
  107662. int preextrapolate;
  107663. int eofflag;
  107664. long lW;
  107665. long W;
  107666. long nW;
  107667. long centerW;
  107668. ogg_int64_t granulepos;
  107669. ogg_int64_t sequence;
  107670. ogg_int64_t glue_bits;
  107671. ogg_int64_t time_bits;
  107672. ogg_int64_t floor_bits;
  107673. ogg_int64_t res_bits;
  107674. void *backend_state;
  107675. } vorbis_dsp_state;
  107676. typedef struct vorbis_block{
  107677. /* necessary stream state for linking to the framing abstraction */
  107678. float **pcm; /* this is a pointer into local storage */
  107679. oggpack_buffer opb;
  107680. long lW;
  107681. long W;
  107682. long nW;
  107683. int pcmend;
  107684. int mode;
  107685. int eofflag;
  107686. ogg_int64_t granulepos;
  107687. ogg_int64_t sequence;
  107688. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107689. /* local storage to avoid remallocing; it's up to the mapping to
  107690. structure it */
  107691. void *localstore;
  107692. long localtop;
  107693. long localalloc;
  107694. long totaluse;
  107695. struct alloc_chain *reap;
  107696. /* bitmetrics for the frame */
  107697. long glue_bits;
  107698. long time_bits;
  107699. long floor_bits;
  107700. long res_bits;
  107701. void *internal;
  107702. } vorbis_block;
  107703. /* vorbis_block is a single block of data to be processed as part of
  107704. the analysis/synthesis stream; it belongs to a specific logical
  107705. bitstream, but is independant from other vorbis_blocks belonging to
  107706. that logical bitstream. *************************************************/
  107707. struct alloc_chain{
  107708. void *ptr;
  107709. struct alloc_chain *next;
  107710. };
  107711. /* vorbis_info contains all the setup information specific to the
  107712. specific compression/decompression mode in progress (eg,
  107713. psychoacoustic settings, channel setup, options, codebook
  107714. etc). vorbis_info and substructures are in backends.h.
  107715. *********************************************************************/
  107716. /* the comments are not part of vorbis_info so that vorbis_info can be
  107717. static storage */
  107718. typedef struct vorbis_comment{
  107719. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107720. whatever vendor is set to in encode */
  107721. char **user_comments;
  107722. int *comment_lengths;
  107723. int comments;
  107724. char *vendor;
  107725. } vorbis_comment;
  107726. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107727. and produce a packet (see docs/analysis.txt). The packet is then
  107728. coded into a framed OggSquish bitstream by the second layer (see
  107729. docs/framing.txt). Decode is the reverse process; we sync/frame
  107730. the bitstream and extract individual packets, then decode the
  107731. packet back into PCM audio.
  107732. The extra framing/packetizing is used in streaming formats, such as
  107733. files. Over the net (such as with UDP), the framing and
  107734. packetization aren't necessary as they're provided by the transport
  107735. and the streaming layer is not used */
  107736. /* Vorbis PRIMITIVES: general ***************************************/
  107737. extern void vorbis_info_init(vorbis_info *vi);
  107738. extern void vorbis_info_clear(vorbis_info *vi);
  107739. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107740. extern void vorbis_comment_init(vorbis_comment *vc);
  107741. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107742. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107743. const char *tag, char *contents);
  107744. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107745. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107746. extern void vorbis_comment_clear(vorbis_comment *vc);
  107747. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107748. extern int vorbis_block_clear(vorbis_block *vb);
  107749. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107750. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107751. ogg_int64_t granulepos);
  107752. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107753. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107754. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107755. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107756. vorbis_comment *vc,
  107757. ogg_packet *op,
  107758. ogg_packet *op_comm,
  107759. ogg_packet *op_code);
  107760. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107761. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107762. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107763. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107764. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107765. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107766. ogg_packet *op);
  107767. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107768. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107769. ogg_packet *op);
  107770. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107771. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107772. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107773. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107774. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107775. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107776. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107777. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107778. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107779. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107780. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107781. /* Vorbis ERRORS and return codes ***********************************/
  107782. #define OV_FALSE -1
  107783. #define OV_EOF -2
  107784. #define OV_HOLE -3
  107785. #define OV_EREAD -128
  107786. #define OV_EFAULT -129
  107787. #define OV_EIMPL -130
  107788. #define OV_EINVAL -131
  107789. #define OV_ENOTVORBIS -132
  107790. #define OV_EBADHEADER -133
  107791. #define OV_EVERSION -134
  107792. #define OV_ENOTAUDIO -135
  107793. #define OV_EBADPACKET -136
  107794. #define OV_EBADLINK -137
  107795. #define OV_ENOSEEK -138
  107796. #ifdef __cplusplus
  107797. }
  107798. #endif /* __cplusplus */
  107799. #endif
  107800. /*** End of inlined file: codec.h ***/
  107801. extern int vorbis_encode_init(vorbis_info *vi,
  107802. long channels,
  107803. long rate,
  107804. long max_bitrate,
  107805. long nominal_bitrate,
  107806. long min_bitrate);
  107807. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107808. long channels,
  107809. long rate,
  107810. long max_bitrate,
  107811. long nominal_bitrate,
  107812. long min_bitrate);
  107813. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107814. long channels,
  107815. long rate,
  107816. float quality /* quality level from 0. (lo) to 1. (hi) */
  107817. );
  107818. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107819. long channels,
  107820. long rate,
  107821. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107822. );
  107823. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107824. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107825. /* deprecated rate management supported only for compatability */
  107826. #define OV_ECTL_RATEMANAGE_GET 0x10
  107827. #define OV_ECTL_RATEMANAGE_SET 0x11
  107828. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107829. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107830. struct ovectl_ratemanage_arg {
  107831. int management_active;
  107832. long bitrate_hard_min;
  107833. long bitrate_hard_max;
  107834. double bitrate_hard_window;
  107835. long bitrate_av_lo;
  107836. long bitrate_av_hi;
  107837. double bitrate_av_window;
  107838. double bitrate_av_window_center;
  107839. };
  107840. /* new rate setup */
  107841. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107842. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107843. struct ovectl_ratemanage2_arg {
  107844. int management_active;
  107845. long bitrate_limit_min_kbps;
  107846. long bitrate_limit_max_kbps;
  107847. long bitrate_limit_reservoir_bits;
  107848. double bitrate_limit_reservoir_bias;
  107849. long bitrate_average_kbps;
  107850. double bitrate_average_damping;
  107851. };
  107852. #define OV_ECTL_LOWPASS_GET 0x20
  107853. #define OV_ECTL_LOWPASS_SET 0x21
  107854. #define OV_ECTL_IBLOCK_GET 0x30
  107855. #define OV_ECTL_IBLOCK_SET 0x31
  107856. #ifdef __cplusplus
  107857. }
  107858. #endif /* __cplusplus */
  107859. #endif
  107860. /*** End of inlined file: vorbisenc.h ***/
  107861. /*** Start of inlined file: vorbisfile.h ***/
  107862. #ifndef _OV_FILE_H_
  107863. #define _OV_FILE_H_
  107864. #ifdef __cplusplus
  107865. extern "C"
  107866. {
  107867. #endif /* __cplusplus */
  107868. #include <stdio.h>
  107869. /* The function prototypes for the callbacks are basically the same as for
  107870. * the stdio functions fread, fseek, fclose, ftell.
  107871. * The one difference is that the FILE * arguments have been replaced with
  107872. * a void * - this is to be used as a pointer to whatever internal data these
  107873. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107874. *
  107875. * If you use other functions, check the docs for these functions and return
  107876. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107877. * unseekable
  107878. */
  107879. typedef struct {
  107880. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107881. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107882. int (*close_func) (void *datasource);
  107883. long (*tell_func) (void *datasource);
  107884. } ov_callbacks;
  107885. #define NOTOPEN 0
  107886. #define PARTOPEN 1
  107887. #define OPENED 2
  107888. #define STREAMSET 3
  107889. #define INITSET 4
  107890. typedef struct OggVorbis_File {
  107891. void *datasource; /* Pointer to a FILE *, etc. */
  107892. int seekable;
  107893. ogg_int64_t offset;
  107894. ogg_int64_t end;
  107895. ogg_sync_state oy;
  107896. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107897. stream appears */
  107898. int links;
  107899. ogg_int64_t *offsets;
  107900. ogg_int64_t *dataoffsets;
  107901. long *serialnos;
  107902. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107903. compatability; x2 size, stores both
  107904. beginning and end values */
  107905. vorbis_info *vi;
  107906. vorbis_comment *vc;
  107907. /* Decoding working state local storage */
  107908. ogg_int64_t pcm_offset;
  107909. int ready_state;
  107910. long current_serialno;
  107911. int current_link;
  107912. double bittrack;
  107913. double samptrack;
  107914. ogg_stream_state os; /* take physical pages, weld into a logical
  107915. stream of packets */
  107916. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107917. vorbis_block vb; /* local working space for packet->PCM decode */
  107918. ov_callbacks callbacks;
  107919. } OggVorbis_File;
  107920. extern int ov_clear(OggVorbis_File *vf);
  107921. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107922. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107923. char *initial, long ibytes, ov_callbacks callbacks);
  107924. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107925. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107926. char *initial, long ibytes, ov_callbacks callbacks);
  107927. extern int ov_test_open(OggVorbis_File *vf);
  107928. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107929. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107930. extern long ov_streams(OggVorbis_File *vf);
  107931. extern long ov_seekable(OggVorbis_File *vf);
  107932. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107933. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107934. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107935. extern double ov_time_total(OggVorbis_File *vf,int i);
  107936. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107937. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107938. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107939. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107940. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107941. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107942. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107943. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107944. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107945. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107946. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107947. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107948. extern double ov_time_tell(OggVorbis_File *vf);
  107949. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107950. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107951. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107952. int *bitstream);
  107953. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107954. int bigendianp,int word,int sgned,int *bitstream);
  107955. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107956. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107957. extern int ov_halfrate_p(OggVorbis_File *vf);
  107958. #ifdef __cplusplus
  107959. }
  107960. #endif /* __cplusplus */
  107961. #endif
  107962. /*** End of inlined file: vorbisfile.h ***/
  107963. /*** Start of inlined file: bitwise.c ***/
  107964. /* We're 'LSb' endian; if we write a word but read individual bits,
  107965. then we'll read the lsb first */
  107966. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107967. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107968. // tasks..
  107969. #if JUCE_MSVC
  107970. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107971. #endif
  107972. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107973. #if JUCE_USE_OGGVORBIS
  107974. #include <string.h>
  107975. #include <stdlib.h>
  107976. #define BUFFER_INCREMENT 256
  107977. static const unsigned long mask[]=
  107978. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107979. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107980. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107981. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107982. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107983. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107984. 0x3fffffff,0x7fffffff,0xffffffff };
  107985. static const unsigned int mask8B[]=
  107986. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107987. void oggpack_writeinit(oggpack_buffer *b){
  107988. memset(b,0,sizeof(*b));
  107989. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107990. b->buffer[0]='\0';
  107991. b->storage=BUFFER_INCREMENT;
  107992. }
  107993. void oggpackB_writeinit(oggpack_buffer *b){
  107994. oggpack_writeinit(b);
  107995. }
  107996. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107997. long bytes=bits>>3;
  107998. bits-=bytes*8;
  107999. b->ptr=b->buffer+bytes;
  108000. b->endbit=bits;
  108001. b->endbyte=bytes;
  108002. *b->ptr&=mask[bits];
  108003. }
  108004. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  108005. long bytes=bits>>3;
  108006. bits-=bytes*8;
  108007. b->ptr=b->buffer+bytes;
  108008. b->endbit=bits;
  108009. b->endbyte=bytes;
  108010. *b->ptr&=mask8B[bits];
  108011. }
  108012. /* Takes only up to 32 bits. */
  108013. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  108014. if(b->endbyte+4>=b->storage){
  108015. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108016. b->storage+=BUFFER_INCREMENT;
  108017. b->ptr=b->buffer+b->endbyte;
  108018. }
  108019. value&=mask[bits];
  108020. bits+=b->endbit;
  108021. b->ptr[0]|=value<<b->endbit;
  108022. if(bits>=8){
  108023. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  108024. if(bits>=16){
  108025. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  108026. if(bits>=24){
  108027. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  108028. if(bits>=32){
  108029. if(b->endbit)
  108030. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  108031. else
  108032. b->ptr[4]=0;
  108033. }
  108034. }
  108035. }
  108036. }
  108037. b->endbyte+=bits/8;
  108038. b->ptr+=bits/8;
  108039. b->endbit=bits&7;
  108040. }
  108041. /* Takes only up to 32 bits. */
  108042. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  108043. if(b->endbyte+4>=b->storage){
  108044. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108045. b->storage+=BUFFER_INCREMENT;
  108046. b->ptr=b->buffer+b->endbyte;
  108047. }
  108048. value=(value&mask[bits])<<(32-bits);
  108049. bits+=b->endbit;
  108050. b->ptr[0]|=value>>(24+b->endbit);
  108051. if(bits>=8){
  108052. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  108053. if(bits>=16){
  108054. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  108055. if(bits>=24){
  108056. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  108057. if(bits>=32){
  108058. if(b->endbit)
  108059. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  108060. else
  108061. b->ptr[4]=0;
  108062. }
  108063. }
  108064. }
  108065. }
  108066. b->endbyte+=bits/8;
  108067. b->ptr+=bits/8;
  108068. b->endbit=bits&7;
  108069. }
  108070. void oggpack_writealign(oggpack_buffer *b){
  108071. int bits=8-b->endbit;
  108072. if(bits<8)
  108073. oggpack_write(b,0,bits);
  108074. }
  108075. void oggpackB_writealign(oggpack_buffer *b){
  108076. int bits=8-b->endbit;
  108077. if(bits<8)
  108078. oggpackB_write(b,0,bits);
  108079. }
  108080. static void oggpack_writecopy_helper(oggpack_buffer *b,
  108081. void *source,
  108082. long bits,
  108083. void (*w)(oggpack_buffer *,
  108084. unsigned long,
  108085. int),
  108086. int msb){
  108087. unsigned char *ptr=(unsigned char *)source;
  108088. long bytes=bits/8;
  108089. bits-=bytes*8;
  108090. if(b->endbit){
  108091. int i;
  108092. /* unaligned copy. Do it the hard way. */
  108093. for(i=0;i<bytes;i++)
  108094. w(b,(unsigned long)(ptr[i]),8);
  108095. }else{
  108096. /* aligned block copy */
  108097. if(b->endbyte+bytes+1>=b->storage){
  108098. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  108099. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  108100. b->ptr=b->buffer+b->endbyte;
  108101. }
  108102. memmove(b->ptr,source,bytes);
  108103. b->ptr+=bytes;
  108104. b->endbyte+=bytes;
  108105. *b->ptr=0;
  108106. }
  108107. if(bits){
  108108. if(msb)
  108109. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  108110. else
  108111. w(b,(unsigned long)(ptr[bytes]),bits);
  108112. }
  108113. }
  108114. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  108115. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  108116. }
  108117. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  108118. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  108119. }
  108120. void oggpack_reset(oggpack_buffer *b){
  108121. b->ptr=b->buffer;
  108122. b->buffer[0]=0;
  108123. b->endbit=b->endbyte=0;
  108124. }
  108125. void oggpackB_reset(oggpack_buffer *b){
  108126. oggpack_reset(b);
  108127. }
  108128. void oggpack_writeclear(oggpack_buffer *b){
  108129. _ogg_free(b->buffer);
  108130. memset(b,0,sizeof(*b));
  108131. }
  108132. void oggpackB_writeclear(oggpack_buffer *b){
  108133. oggpack_writeclear(b);
  108134. }
  108135. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108136. memset(b,0,sizeof(*b));
  108137. b->buffer=b->ptr=buf;
  108138. b->storage=bytes;
  108139. }
  108140. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108141. oggpack_readinit(b,buf,bytes);
  108142. }
  108143. /* Read in bits without advancing the bitptr; bits <= 32 */
  108144. long oggpack_look(oggpack_buffer *b,int bits){
  108145. unsigned long ret;
  108146. unsigned long m=mask[bits];
  108147. bits+=b->endbit;
  108148. if(b->endbyte+4>=b->storage){
  108149. /* not the main path */
  108150. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108151. }
  108152. ret=b->ptr[0]>>b->endbit;
  108153. if(bits>8){
  108154. ret|=b->ptr[1]<<(8-b->endbit);
  108155. if(bits>16){
  108156. ret|=b->ptr[2]<<(16-b->endbit);
  108157. if(bits>24){
  108158. ret|=b->ptr[3]<<(24-b->endbit);
  108159. if(bits>32 && b->endbit)
  108160. ret|=b->ptr[4]<<(32-b->endbit);
  108161. }
  108162. }
  108163. }
  108164. return(m&ret);
  108165. }
  108166. /* Read in bits without advancing the bitptr; bits <= 32 */
  108167. long oggpackB_look(oggpack_buffer *b,int bits){
  108168. unsigned long ret;
  108169. int m=32-bits;
  108170. bits+=b->endbit;
  108171. if(b->endbyte+4>=b->storage){
  108172. /* not the main path */
  108173. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108174. }
  108175. ret=b->ptr[0]<<(24+b->endbit);
  108176. if(bits>8){
  108177. ret|=b->ptr[1]<<(16+b->endbit);
  108178. if(bits>16){
  108179. ret|=b->ptr[2]<<(8+b->endbit);
  108180. if(bits>24){
  108181. ret|=b->ptr[3]<<(b->endbit);
  108182. if(bits>32 && b->endbit)
  108183. ret|=b->ptr[4]>>(8-b->endbit);
  108184. }
  108185. }
  108186. }
  108187. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  108188. }
  108189. long oggpack_look1(oggpack_buffer *b){
  108190. if(b->endbyte>=b->storage)return(-1);
  108191. return((b->ptr[0]>>b->endbit)&1);
  108192. }
  108193. long oggpackB_look1(oggpack_buffer *b){
  108194. if(b->endbyte>=b->storage)return(-1);
  108195. return((b->ptr[0]>>(7-b->endbit))&1);
  108196. }
  108197. void oggpack_adv(oggpack_buffer *b,int bits){
  108198. bits+=b->endbit;
  108199. b->ptr+=bits/8;
  108200. b->endbyte+=bits/8;
  108201. b->endbit=bits&7;
  108202. }
  108203. void oggpackB_adv(oggpack_buffer *b,int bits){
  108204. oggpack_adv(b,bits);
  108205. }
  108206. void oggpack_adv1(oggpack_buffer *b){
  108207. if(++(b->endbit)>7){
  108208. b->endbit=0;
  108209. b->ptr++;
  108210. b->endbyte++;
  108211. }
  108212. }
  108213. void oggpackB_adv1(oggpack_buffer *b){
  108214. oggpack_adv1(b);
  108215. }
  108216. /* bits <= 32 */
  108217. long oggpack_read(oggpack_buffer *b,int bits){
  108218. long ret;
  108219. unsigned long m=mask[bits];
  108220. bits+=b->endbit;
  108221. if(b->endbyte+4>=b->storage){
  108222. /* not the main path */
  108223. ret=-1L;
  108224. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108225. }
  108226. ret=b->ptr[0]>>b->endbit;
  108227. if(bits>8){
  108228. ret|=b->ptr[1]<<(8-b->endbit);
  108229. if(bits>16){
  108230. ret|=b->ptr[2]<<(16-b->endbit);
  108231. if(bits>24){
  108232. ret|=b->ptr[3]<<(24-b->endbit);
  108233. if(bits>32 && b->endbit){
  108234. ret|=b->ptr[4]<<(32-b->endbit);
  108235. }
  108236. }
  108237. }
  108238. }
  108239. ret&=m;
  108240. overflow:
  108241. b->ptr+=bits/8;
  108242. b->endbyte+=bits/8;
  108243. b->endbit=bits&7;
  108244. return(ret);
  108245. }
  108246. /* bits <= 32 */
  108247. long oggpackB_read(oggpack_buffer *b,int bits){
  108248. long ret;
  108249. long m=32-bits;
  108250. bits+=b->endbit;
  108251. if(b->endbyte+4>=b->storage){
  108252. /* not the main path */
  108253. ret=-1L;
  108254. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108255. }
  108256. ret=b->ptr[0]<<(24+b->endbit);
  108257. if(bits>8){
  108258. ret|=b->ptr[1]<<(16+b->endbit);
  108259. if(bits>16){
  108260. ret|=b->ptr[2]<<(8+b->endbit);
  108261. if(bits>24){
  108262. ret|=b->ptr[3]<<(b->endbit);
  108263. if(bits>32 && b->endbit)
  108264. ret|=b->ptr[4]>>(8-b->endbit);
  108265. }
  108266. }
  108267. }
  108268. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108269. overflow:
  108270. b->ptr+=bits/8;
  108271. b->endbyte+=bits/8;
  108272. b->endbit=bits&7;
  108273. return(ret);
  108274. }
  108275. long oggpack_read1(oggpack_buffer *b){
  108276. long ret;
  108277. if(b->endbyte>=b->storage){
  108278. /* not the main path */
  108279. ret=-1L;
  108280. goto overflow;
  108281. }
  108282. ret=(b->ptr[0]>>b->endbit)&1;
  108283. overflow:
  108284. b->endbit++;
  108285. if(b->endbit>7){
  108286. b->endbit=0;
  108287. b->ptr++;
  108288. b->endbyte++;
  108289. }
  108290. return(ret);
  108291. }
  108292. long oggpackB_read1(oggpack_buffer *b){
  108293. long ret;
  108294. if(b->endbyte>=b->storage){
  108295. /* not the main path */
  108296. ret=-1L;
  108297. goto overflow;
  108298. }
  108299. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108300. overflow:
  108301. b->endbit++;
  108302. if(b->endbit>7){
  108303. b->endbit=0;
  108304. b->ptr++;
  108305. b->endbyte++;
  108306. }
  108307. return(ret);
  108308. }
  108309. long oggpack_bytes(oggpack_buffer *b){
  108310. return(b->endbyte+(b->endbit+7)/8);
  108311. }
  108312. long oggpack_bits(oggpack_buffer *b){
  108313. return(b->endbyte*8+b->endbit);
  108314. }
  108315. long oggpackB_bytes(oggpack_buffer *b){
  108316. return oggpack_bytes(b);
  108317. }
  108318. long oggpackB_bits(oggpack_buffer *b){
  108319. return oggpack_bits(b);
  108320. }
  108321. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108322. return(b->buffer);
  108323. }
  108324. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108325. return oggpack_get_buffer(b);
  108326. }
  108327. /* Self test of the bitwise routines; everything else is based on
  108328. them, so they damned well better be solid. */
  108329. #ifdef _V_SELFTEST
  108330. #include <stdio.h>
  108331. static int ilog(unsigned int v){
  108332. int ret=0;
  108333. while(v){
  108334. ret++;
  108335. v>>=1;
  108336. }
  108337. return(ret);
  108338. }
  108339. oggpack_buffer o;
  108340. oggpack_buffer r;
  108341. void report(char *in){
  108342. fprintf(stderr,"%s",in);
  108343. exit(1);
  108344. }
  108345. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108346. long bytes,i;
  108347. unsigned char *buffer;
  108348. oggpack_reset(&o);
  108349. for(i=0;i<vals;i++)
  108350. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108351. buffer=oggpack_get_buffer(&o);
  108352. bytes=oggpack_bytes(&o);
  108353. if(bytes!=compsize)report("wrong number of bytes!\n");
  108354. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108355. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108356. report("wrote incorrect value!\n");
  108357. }
  108358. oggpack_readinit(&r,buffer,bytes);
  108359. for(i=0;i<vals;i++){
  108360. int tbit=bits?bits:ilog(b[i]);
  108361. if(oggpack_look(&r,tbit)==-1)
  108362. report("out of data!\n");
  108363. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108364. report("looked at incorrect value!\n");
  108365. if(tbit==1)
  108366. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108367. report("looked at single bit incorrect value!\n");
  108368. if(tbit==1){
  108369. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108370. report("read incorrect single bit value!\n");
  108371. }else{
  108372. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108373. report("read incorrect value!\n");
  108374. }
  108375. }
  108376. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108377. }
  108378. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108379. long bytes,i;
  108380. unsigned char *buffer;
  108381. oggpackB_reset(&o);
  108382. for(i=0;i<vals;i++)
  108383. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108384. buffer=oggpackB_get_buffer(&o);
  108385. bytes=oggpackB_bytes(&o);
  108386. if(bytes!=compsize)report("wrong number of bytes!\n");
  108387. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108388. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108389. report("wrote incorrect value!\n");
  108390. }
  108391. oggpackB_readinit(&r,buffer,bytes);
  108392. for(i=0;i<vals;i++){
  108393. int tbit=bits?bits:ilog(b[i]);
  108394. if(oggpackB_look(&r,tbit)==-1)
  108395. report("out of data!\n");
  108396. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108397. report("looked at incorrect value!\n");
  108398. if(tbit==1)
  108399. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108400. report("looked at single bit incorrect value!\n");
  108401. if(tbit==1){
  108402. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108403. report("read incorrect single bit value!\n");
  108404. }else{
  108405. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108406. report("read incorrect value!\n");
  108407. }
  108408. }
  108409. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108410. }
  108411. int main(void){
  108412. unsigned char *buffer;
  108413. long bytes,i;
  108414. static unsigned long testbuffer1[]=
  108415. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108416. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108417. int test1size=43;
  108418. static unsigned long testbuffer2[]=
  108419. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108420. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108421. 85525151,0,12321,1,349528352};
  108422. int test2size=21;
  108423. static unsigned long testbuffer3[]=
  108424. {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,
  108425. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108426. int test3size=56;
  108427. static unsigned long large[]=
  108428. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108429. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108430. 85525151,0,12321,1,2146528352};
  108431. int onesize=33;
  108432. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108433. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108434. 223,4};
  108435. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108436. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108437. 245,251,128};
  108438. int twosize=6;
  108439. static int two[6]={61,255,255,251,231,29};
  108440. static int twoB[6]={247,63,255,253,249,120};
  108441. int threesize=54;
  108442. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108443. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108444. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108445. 100,52,4,14,18,86,77,1};
  108446. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108447. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108448. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108449. 200,20,254,4,58,106,176,144,0};
  108450. int foursize=38;
  108451. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108452. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108453. 28,2,133,0,1};
  108454. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108455. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108456. 129,10,4,32};
  108457. int fivesize=45;
  108458. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108459. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108460. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108461. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108462. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108463. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108464. int sixsize=7;
  108465. static int six[7]={17,177,170,242,169,19,148};
  108466. static int sixB[7]={136,141,85,79,149,200,41};
  108467. /* Test read/write together */
  108468. /* Later we test against pregenerated bitstreams */
  108469. oggpack_writeinit(&o);
  108470. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108471. cliptest(testbuffer1,test1size,0,one,onesize);
  108472. fprintf(stderr,"ok.");
  108473. fprintf(stderr,"\nNull bit call (LSb): ");
  108474. cliptest(testbuffer3,test3size,0,two,twosize);
  108475. fprintf(stderr,"ok.");
  108476. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108477. cliptest(testbuffer2,test2size,0,three,threesize);
  108478. fprintf(stderr,"ok.");
  108479. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108480. oggpack_reset(&o);
  108481. for(i=0;i<test2size;i++)
  108482. oggpack_write(&o,large[i],32);
  108483. buffer=oggpack_get_buffer(&o);
  108484. bytes=oggpack_bytes(&o);
  108485. oggpack_readinit(&r,buffer,bytes);
  108486. for(i=0;i<test2size;i++){
  108487. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108488. if(oggpack_look(&r,32)!=large[i]){
  108489. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108490. oggpack_look(&r,32),large[i]);
  108491. report("read incorrect value!\n");
  108492. }
  108493. oggpack_adv(&r,32);
  108494. }
  108495. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108496. fprintf(stderr,"ok.");
  108497. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108498. cliptest(testbuffer1,test1size,7,four,foursize);
  108499. fprintf(stderr,"ok.");
  108500. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108501. cliptest(testbuffer2,test2size,17,five,fivesize);
  108502. fprintf(stderr,"ok.");
  108503. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108504. cliptest(testbuffer3,test3size,1,six,sixsize);
  108505. fprintf(stderr,"ok.");
  108506. fprintf(stderr,"\nTesting read past end (LSb): ");
  108507. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108508. for(i=0;i<64;i++){
  108509. if(oggpack_read(&r,1)!=0){
  108510. fprintf(stderr,"failed; got -1 prematurely.\n");
  108511. exit(1);
  108512. }
  108513. }
  108514. if(oggpack_look(&r,1)!=-1 ||
  108515. oggpack_read(&r,1)!=-1){
  108516. fprintf(stderr,"failed; read past end without -1.\n");
  108517. exit(1);
  108518. }
  108519. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108520. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108521. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108522. exit(1);
  108523. }
  108524. if(oggpack_look(&r,18)!=0 ||
  108525. oggpack_look(&r,18)!=0){
  108526. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108527. exit(1);
  108528. }
  108529. if(oggpack_look(&r,19)!=-1 ||
  108530. oggpack_look(&r,19)!=-1){
  108531. fprintf(stderr,"failed; read past end without -1.\n");
  108532. exit(1);
  108533. }
  108534. if(oggpack_look(&r,32)!=-1 ||
  108535. oggpack_look(&r,32)!=-1){
  108536. fprintf(stderr,"failed; read past end without -1.\n");
  108537. exit(1);
  108538. }
  108539. oggpack_writeclear(&o);
  108540. fprintf(stderr,"ok.\n");
  108541. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108542. /* Test read/write together */
  108543. /* Later we test against pregenerated bitstreams */
  108544. oggpackB_writeinit(&o);
  108545. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108546. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108547. fprintf(stderr,"ok.");
  108548. fprintf(stderr,"\nNull bit call (MSb): ");
  108549. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108550. fprintf(stderr,"ok.");
  108551. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108552. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108553. fprintf(stderr,"ok.");
  108554. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108555. oggpackB_reset(&o);
  108556. for(i=0;i<test2size;i++)
  108557. oggpackB_write(&o,large[i],32);
  108558. buffer=oggpackB_get_buffer(&o);
  108559. bytes=oggpackB_bytes(&o);
  108560. oggpackB_readinit(&r,buffer,bytes);
  108561. for(i=0;i<test2size;i++){
  108562. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108563. if(oggpackB_look(&r,32)!=large[i]){
  108564. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108565. oggpackB_look(&r,32),large[i]);
  108566. report("read incorrect value!\n");
  108567. }
  108568. oggpackB_adv(&r,32);
  108569. }
  108570. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108571. fprintf(stderr,"ok.");
  108572. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108573. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108574. fprintf(stderr,"ok.");
  108575. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108576. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108577. fprintf(stderr,"ok.");
  108578. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108579. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108580. fprintf(stderr,"ok.");
  108581. fprintf(stderr,"\nTesting read past end (MSb): ");
  108582. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108583. for(i=0;i<64;i++){
  108584. if(oggpackB_read(&r,1)!=0){
  108585. fprintf(stderr,"failed; got -1 prematurely.\n");
  108586. exit(1);
  108587. }
  108588. }
  108589. if(oggpackB_look(&r,1)!=-1 ||
  108590. oggpackB_read(&r,1)!=-1){
  108591. fprintf(stderr,"failed; read past end without -1.\n");
  108592. exit(1);
  108593. }
  108594. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108595. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108596. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108597. exit(1);
  108598. }
  108599. if(oggpackB_look(&r,18)!=0 ||
  108600. oggpackB_look(&r,18)!=0){
  108601. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108602. exit(1);
  108603. }
  108604. if(oggpackB_look(&r,19)!=-1 ||
  108605. oggpackB_look(&r,19)!=-1){
  108606. fprintf(stderr,"failed; read past end without -1.\n");
  108607. exit(1);
  108608. }
  108609. if(oggpackB_look(&r,32)!=-1 ||
  108610. oggpackB_look(&r,32)!=-1){
  108611. fprintf(stderr,"failed; read past end without -1.\n");
  108612. exit(1);
  108613. }
  108614. oggpackB_writeclear(&o);
  108615. fprintf(stderr,"ok.\n\n");
  108616. return(0);
  108617. }
  108618. #endif /* _V_SELFTEST */
  108619. #undef BUFFER_INCREMENT
  108620. #endif
  108621. /*** End of inlined file: bitwise.c ***/
  108622. /*** Start of inlined file: framing.c ***/
  108623. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108624. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108625. // tasks..
  108626. #if JUCE_MSVC
  108627. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108628. #endif
  108629. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108630. #if JUCE_USE_OGGVORBIS
  108631. #include <stdlib.h>
  108632. #include <string.h>
  108633. /* A complete description of Ogg framing exists in docs/framing.html */
  108634. int ogg_page_version(ogg_page *og){
  108635. return((int)(og->header[4]));
  108636. }
  108637. int ogg_page_continued(ogg_page *og){
  108638. return((int)(og->header[5]&0x01));
  108639. }
  108640. int ogg_page_bos(ogg_page *og){
  108641. return((int)(og->header[5]&0x02));
  108642. }
  108643. int ogg_page_eos(ogg_page *og){
  108644. return((int)(og->header[5]&0x04));
  108645. }
  108646. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108647. unsigned char *page=og->header;
  108648. ogg_int64_t granulepos=page[13]&(0xff);
  108649. granulepos= (granulepos<<8)|(page[12]&0xff);
  108650. granulepos= (granulepos<<8)|(page[11]&0xff);
  108651. granulepos= (granulepos<<8)|(page[10]&0xff);
  108652. granulepos= (granulepos<<8)|(page[9]&0xff);
  108653. granulepos= (granulepos<<8)|(page[8]&0xff);
  108654. granulepos= (granulepos<<8)|(page[7]&0xff);
  108655. granulepos= (granulepos<<8)|(page[6]&0xff);
  108656. return(granulepos);
  108657. }
  108658. int ogg_page_serialno(ogg_page *og){
  108659. return(og->header[14] |
  108660. (og->header[15]<<8) |
  108661. (og->header[16]<<16) |
  108662. (og->header[17]<<24));
  108663. }
  108664. long ogg_page_pageno(ogg_page *og){
  108665. return(og->header[18] |
  108666. (og->header[19]<<8) |
  108667. (og->header[20]<<16) |
  108668. (og->header[21]<<24));
  108669. }
  108670. /* returns the number of packets that are completed on this page (if
  108671. the leading packet is begun on a previous page, but ends on this
  108672. page, it's counted */
  108673. /* NOTE:
  108674. If a page consists of a packet begun on a previous page, and a new
  108675. packet begun (but not completed) on this page, the return will be:
  108676. ogg_page_packets(page) ==1,
  108677. ogg_page_continued(page) !=0
  108678. If a page happens to be a single packet that was begun on a
  108679. previous page, and spans to the next page (in the case of a three or
  108680. more page packet), the return will be:
  108681. ogg_page_packets(page) ==0,
  108682. ogg_page_continued(page) !=0
  108683. */
  108684. int ogg_page_packets(ogg_page *og){
  108685. int i,n=og->header[26],count=0;
  108686. for(i=0;i<n;i++)
  108687. if(og->header[27+i]<255)count++;
  108688. return(count);
  108689. }
  108690. #if 0
  108691. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108692. use the static init below) */
  108693. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108694. int i;
  108695. unsigned long r;
  108696. r = index << 24;
  108697. for (i=0; i<8; i++)
  108698. if (r & 0x80000000UL)
  108699. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108700. polynomial, although we use an
  108701. unreflected alg and an init/final
  108702. of 0, not 0xffffffff */
  108703. else
  108704. r<<=1;
  108705. return (r & 0xffffffffUL);
  108706. }
  108707. #endif
  108708. static const ogg_uint32_t crc_lookup[256]={
  108709. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108710. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108711. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108712. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108713. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108714. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108715. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108716. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108717. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108718. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108719. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108720. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108721. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108722. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108723. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108724. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108725. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108726. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108727. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108728. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108729. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108730. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108731. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108732. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108733. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108734. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108735. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108736. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108737. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108738. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108739. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108740. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108741. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108742. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108743. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108744. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108745. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108746. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108747. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108748. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108749. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108750. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108751. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108752. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108753. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108754. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108755. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108756. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108757. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108758. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108759. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108760. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108761. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108762. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108763. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108764. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108765. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108766. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108767. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108768. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108769. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108770. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108771. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108772. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108773. /* init the encode/decode logical stream state */
  108774. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108775. if(os){
  108776. memset(os,0,sizeof(*os));
  108777. os->body_storage=16*1024;
  108778. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108779. os->lacing_storage=1024;
  108780. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108781. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108782. os->serialno=serialno;
  108783. return(0);
  108784. }
  108785. return(-1);
  108786. }
  108787. /* _clear does not free os, only the non-flat storage within */
  108788. int ogg_stream_clear(ogg_stream_state *os){
  108789. if(os){
  108790. if(os->body_data)_ogg_free(os->body_data);
  108791. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108792. if(os->granule_vals)_ogg_free(os->granule_vals);
  108793. memset(os,0,sizeof(*os));
  108794. }
  108795. return(0);
  108796. }
  108797. int ogg_stream_destroy(ogg_stream_state *os){
  108798. if(os){
  108799. ogg_stream_clear(os);
  108800. _ogg_free(os);
  108801. }
  108802. return(0);
  108803. }
  108804. /* Helpers for ogg_stream_encode; this keeps the structure and
  108805. what's happening fairly clear */
  108806. static void _os_body_expand(ogg_stream_state *os,int needed){
  108807. if(os->body_storage<=os->body_fill+needed){
  108808. os->body_storage+=(needed+1024);
  108809. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108810. }
  108811. }
  108812. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108813. if(os->lacing_storage<=os->lacing_fill+needed){
  108814. os->lacing_storage+=(needed+32);
  108815. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108816. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108817. }
  108818. }
  108819. /* checksum the page */
  108820. /* Direct table CRC; note that this will be faster in the future if we
  108821. perform the checksum silmultaneously with other copies */
  108822. void ogg_page_checksum_set(ogg_page *og){
  108823. if(og){
  108824. ogg_uint32_t crc_reg=0;
  108825. int i;
  108826. /* safety; needed for API behavior, but not framing code */
  108827. og->header[22]=0;
  108828. og->header[23]=0;
  108829. og->header[24]=0;
  108830. og->header[25]=0;
  108831. for(i=0;i<og->header_len;i++)
  108832. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108833. for(i=0;i<og->body_len;i++)
  108834. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108835. og->header[22]=(unsigned char)(crc_reg&0xff);
  108836. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108837. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108838. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108839. }
  108840. }
  108841. /* submit data to the internal buffer of the framing engine */
  108842. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108843. int lacing_vals=op->bytes/255+1,i;
  108844. if(os->body_returned){
  108845. /* advance packet data according to the body_returned pointer. We
  108846. had to keep it around to return a pointer into the buffer last
  108847. call */
  108848. os->body_fill-=os->body_returned;
  108849. if(os->body_fill)
  108850. memmove(os->body_data,os->body_data+os->body_returned,
  108851. os->body_fill);
  108852. os->body_returned=0;
  108853. }
  108854. /* make sure we have the buffer storage */
  108855. _os_body_expand(os,op->bytes);
  108856. _os_lacing_expand(os,lacing_vals);
  108857. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108858. the liability of overly clean abstraction for the time being. It
  108859. will actually be fairly easy to eliminate the extra copy in the
  108860. future */
  108861. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108862. os->body_fill+=op->bytes;
  108863. /* Store lacing vals for this packet */
  108864. for(i=0;i<lacing_vals-1;i++){
  108865. os->lacing_vals[os->lacing_fill+i]=255;
  108866. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108867. }
  108868. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108869. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108870. /* flag the first segment as the beginning of the packet */
  108871. os->lacing_vals[os->lacing_fill]|= 0x100;
  108872. os->lacing_fill+=lacing_vals;
  108873. /* for the sake of completeness */
  108874. os->packetno++;
  108875. if(op->e_o_s)os->e_o_s=1;
  108876. return(0);
  108877. }
  108878. /* This will flush remaining packets into a page (returning nonzero),
  108879. even if there is not enough data to trigger a flush normally
  108880. (undersized page). If there are no packets or partial packets to
  108881. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108882. try to flush a normal sized page like ogg_stream_pageout; a call to
  108883. ogg_stream_flush does not guarantee that all packets have flushed.
  108884. Only a return value of 0 from ogg_stream_flush indicates all packet
  108885. data is flushed into pages.
  108886. since ogg_stream_flush will flush the last page in a stream even if
  108887. it's undersized, you almost certainly want to use ogg_stream_pageout
  108888. (and *not* ogg_stream_flush) unless you specifically need to flush
  108889. an page regardless of size in the middle of a stream. */
  108890. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108891. int i;
  108892. int vals=0;
  108893. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108894. int bytes=0;
  108895. long acc=0;
  108896. ogg_int64_t granule_pos=-1;
  108897. if(maxvals==0)return(0);
  108898. /* construct a page */
  108899. /* decide how many segments to include */
  108900. /* If this is the initial header case, the first page must only include
  108901. the initial header packet */
  108902. if(os->b_o_s==0){ /* 'initial header page' case */
  108903. granule_pos=0;
  108904. for(vals=0;vals<maxvals;vals++){
  108905. if((os->lacing_vals[vals]&0x0ff)<255){
  108906. vals++;
  108907. break;
  108908. }
  108909. }
  108910. }else{
  108911. for(vals=0;vals<maxvals;vals++){
  108912. if(acc>4096)break;
  108913. acc+=os->lacing_vals[vals]&0x0ff;
  108914. if((os->lacing_vals[vals]&0xff)<255)
  108915. granule_pos=os->granule_vals[vals];
  108916. }
  108917. }
  108918. /* construct the header in temp storage */
  108919. memcpy(os->header,"OggS",4);
  108920. /* stream structure version */
  108921. os->header[4]=0x00;
  108922. /* continued packet flag? */
  108923. os->header[5]=0x00;
  108924. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108925. /* first page flag? */
  108926. if(os->b_o_s==0)os->header[5]|=0x02;
  108927. /* last page flag? */
  108928. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108929. os->b_o_s=1;
  108930. /* 64 bits of PCM position */
  108931. for(i=6;i<14;i++){
  108932. os->header[i]=(unsigned char)(granule_pos&0xff);
  108933. granule_pos>>=8;
  108934. }
  108935. /* 32 bits of stream serial number */
  108936. {
  108937. long serialno=os->serialno;
  108938. for(i=14;i<18;i++){
  108939. os->header[i]=(unsigned char)(serialno&0xff);
  108940. serialno>>=8;
  108941. }
  108942. }
  108943. /* 32 bits of page counter (we have both counter and page header
  108944. because this val can roll over) */
  108945. if(os->pageno==-1)os->pageno=0; /* because someone called
  108946. stream_reset; this would be a
  108947. strange thing to do in an
  108948. encode stream, but it has
  108949. plausible uses */
  108950. {
  108951. long pageno=os->pageno++;
  108952. for(i=18;i<22;i++){
  108953. os->header[i]=(unsigned char)(pageno&0xff);
  108954. pageno>>=8;
  108955. }
  108956. }
  108957. /* zero for computation; filled in later */
  108958. os->header[22]=0;
  108959. os->header[23]=0;
  108960. os->header[24]=0;
  108961. os->header[25]=0;
  108962. /* segment table */
  108963. os->header[26]=(unsigned char)(vals&0xff);
  108964. for(i=0;i<vals;i++)
  108965. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108966. /* set pointers in the ogg_page struct */
  108967. og->header=os->header;
  108968. og->header_len=os->header_fill=vals+27;
  108969. og->body=os->body_data+os->body_returned;
  108970. og->body_len=bytes;
  108971. /* advance the lacing data and set the body_returned pointer */
  108972. os->lacing_fill-=vals;
  108973. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108974. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108975. os->body_returned+=bytes;
  108976. /* calculate the checksum */
  108977. ogg_page_checksum_set(og);
  108978. /* done */
  108979. return(1);
  108980. }
  108981. /* This constructs pages from buffered packet segments. The pointers
  108982. returned are to static buffers; do not free. The returned buffers are
  108983. good only until the next call (using the same ogg_stream_state) */
  108984. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108985. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108986. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108987. os->lacing_fill>=255 || /* 'segment table full' case */
  108988. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108989. return(ogg_stream_flush(os,og));
  108990. }
  108991. /* not enough data to construct a page and not end of stream */
  108992. return(0);
  108993. }
  108994. int ogg_stream_eos(ogg_stream_state *os){
  108995. return os->e_o_s;
  108996. }
  108997. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108998. /* This has two layers to place more of the multi-serialno and paging
  108999. control in the application's hands. First, we expose a data buffer
  109000. using ogg_sync_buffer(). The app either copies into the
  109001. buffer, or passes it directly to read(), etc. We then call
  109002. ogg_sync_wrote() to tell how many bytes we just added.
  109003. Pages are returned (pointers into the buffer in ogg_sync_state)
  109004. by ogg_sync_pageout(). The page is then submitted to
  109005. ogg_stream_pagein() along with the appropriate
  109006. ogg_stream_state* (ie, matching serialno). We then get raw
  109007. packets out calling ogg_stream_packetout() with a
  109008. ogg_stream_state. */
  109009. /* initialize the struct to a known state */
  109010. int ogg_sync_init(ogg_sync_state *oy){
  109011. if(oy){
  109012. memset(oy,0,sizeof(*oy));
  109013. }
  109014. return(0);
  109015. }
  109016. /* clear non-flat storage within */
  109017. int ogg_sync_clear(ogg_sync_state *oy){
  109018. if(oy){
  109019. if(oy->data)_ogg_free(oy->data);
  109020. ogg_sync_init(oy);
  109021. }
  109022. return(0);
  109023. }
  109024. int ogg_sync_destroy(ogg_sync_state *oy){
  109025. if(oy){
  109026. ogg_sync_clear(oy);
  109027. _ogg_free(oy);
  109028. }
  109029. return(0);
  109030. }
  109031. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  109032. /* first, clear out any space that has been previously returned */
  109033. if(oy->returned){
  109034. oy->fill-=oy->returned;
  109035. if(oy->fill>0)
  109036. memmove(oy->data,oy->data+oy->returned,oy->fill);
  109037. oy->returned=0;
  109038. }
  109039. if(size>oy->storage-oy->fill){
  109040. /* We need to extend the internal buffer */
  109041. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  109042. if(oy->data)
  109043. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  109044. else
  109045. oy->data=(unsigned char*) _ogg_malloc(newsize);
  109046. oy->storage=newsize;
  109047. }
  109048. /* expose a segment at least as large as requested at the fill mark */
  109049. return((char *)oy->data+oy->fill);
  109050. }
  109051. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  109052. if(oy->fill+bytes>oy->storage)return(-1);
  109053. oy->fill+=bytes;
  109054. return(0);
  109055. }
  109056. /* sync the stream. This is meant to be useful for finding page
  109057. boundaries.
  109058. return values for this:
  109059. -n) skipped n bytes
  109060. 0) page not ready; more data (no bytes skipped)
  109061. n) page synced at current location; page length n bytes
  109062. */
  109063. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  109064. unsigned char *page=oy->data+oy->returned;
  109065. unsigned char *next;
  109066. long bytes=oy->fill-oy->returned;
  109067. if(oy->headerbytes==0){
  109068. int headerbytes,i;
  109069. if(bytes<27)return(0); /* not enough for a header */
  109070. /* verify capture pattern */
  109071. if(memcmp(page,"OggS",4))goto sync_fail;
  109072. headerbytes=page[26]+27;
  109073. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  109074. /* count up body length in the segment table */
  109075. for(i=0;i<page[26];i++)
  109076. oy->bodybytes+=page[27+i];
  109077. oy->headerbytes=headerbytes;
  109078. }
  109079. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  109080. /* The whole test page is buffered. Verify the checksum */
  109081. {
  109082. /* Grab the checksum bytes, set the header field to zero */
  109083. char chksum[4];
  109084. ogg_page log;
  109085. memcpy(chksum,page+22,4);
  109086. memset(page+22,0,4);
  109087. /* set up a temp page struct and recompute the checksum */
  109088. log.header=page;
  109089. log.header_len=oy->headerbytes;
  109090. log.body=page+oy->headerbytes;
  109091. log.body_len=oy->bodybytes;
  109092. ogg_page_checksum_set(&log);
  109093. /* Compare */
  109094. if(memcmp(chksum,page+22,4)){
  109095. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  109096. at all) */
  109097. /* replace the computed checksum with the one actually read in */
  109098. memcpy(page+22,chksum,4);
  109099. /* Bad checksum. Lose sync */
  109100. goto sync_fail;
  109101. }
  109102. }
  109103. /* yes, have a whole page all ready to go */
  109104. {
  109105. unsigned char *page=oy->data+oy->returned;
  109106. long bytes;
  109107. if(og){
  109108. og->header=page;
  109109. og->header_len=oy->headerbytes;
  109110. og->body=page+oy->headerbytes;
  109111. og->body_len=oy->bodybytes;
  109112. }
  109113. oy->unsynced=0;
  109114. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  109115. oy->headerbytes=0;
  109116. oy->bodybytes=0;
  109117. return(bytes);
  109118. }
  109119. sync_fail:
  109120. oy->headerbytes=0;
  109121. oy->bodybytes=0;
  109122. /* search for possible capture */
  109123. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  109124. if(!next)
  109125. next=oy->data+oy->fill;
  109126. oy->returned=next-oy->data;
  109127. return(-(next-page));
  109128. }
  109129. /* sync the stream and get a page. Keep trying until we find a page.
  109130. Supress 'sync errors' after reporting the first.
  109131. return values:
  109132. -1) recapture (hole in data)
  109133. 0) need more data
  109134. 1) page returned
  109135. Returns pointers into buffered data; invalidated by next call to
  109136. _stream, _clear, _init, or _buffer */
  109137. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  109138. /* all we need to do is verify a page at the head of the stream
  109139. buffer. If it doesn't verify, we look for the next potential
  109140. frame */
  109141. for(;;){
  109142. long ret=ogg_sync_pageseek(oy,og);
  109143. if(ret>0){
  109144. /* have a page */
  109145. return(1);
  109146. }
  109147. if(ret==0){
  109148. /* need more data */
  109149. return(0);
  109150. }
  109151. /* head did not start a synced page... skipped some bytes */
  109152. if(!oy->unsynced){
  109153. oy->unsynced=1;
  109154. return(-1);
  109155. }
  109156. /* loop. keep looking */
  109157. }
  109158. }
  109159. /* add the incoming page to the stream state; we decompose the page
  109160. into packet segments here as well. */
  109161. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  109162. unsigned char *header=og->header;
  109163. unsigned char *body=og->body;
  109164. long bodysize=og->body_len;
  109165. int segptr=0;
  109166. int version=ogg_page_version(og);
  109167. int continued=ogg_page_continued(og);
  109168. int bos=ogg_page_bos(og);
  109169. int eos=ogg_page_eos(og);
  109170. ogg_int64_t granulepos=ogg_page_granulepos(og);
  109171. int serialno=ogg_page_serialno(og);
  109172. long pageno=ogg_page_pageno(og);
  109173. int segments=header[26];
  109174. /* clean up 'returned data' */
  109175. {
  109176. long lr=os->lacing_returned;
  109177. long br=os->body_returned;
  109178. /* body data */
  109179. if(br){
  109180. os->body_fill-=br;
  109181. if(os->body_fill)
  109182. memmove(os->body_data,os->body_data+br,os->body_fill);
  109183. os->body_returned=0;
  109184. }
  109185. if(lr){
  109186. /* segment table */
  109187. if(os->lacing_fill-lr){
  109188. memmove(os->lacing_vals,os->lacing_vals+lr,
  109189. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  109190. memmove(os->granule_vals,os->granule_vals+lr,
  109191. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  109192. }
  109193. os->lacing_fill-=lr;
  109194. os->lacing_packet-=lr;
  109195. os->lacing_returned=0;
  109196. }
  109197. }
  109198. /* check the serial number */
  109199. if(serialno!=os->serialno)return(-1);
  109200. if(version>0)return(-1);
  109201. _os_lacing_expand(os,segments+1);
  109202. /* are we in sequence? */
  109203. if(pageno!=os->pageno){
  109204. int i;
  109205. /* unroll previous partial packet (if any) */
  109206. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109207. os->body_fill-=os->lacing_vals[i]&0xff;
  109208. os->lacing_fill=os->lacing_packet;
  109209. /* make a note of dropped data in segment table */
  109210. if(os->pageno!=-1){
  109211. os->lacing_vals[os->lacing_fill++]=0x400;
  109212. os->lacing_packet++;
  109213. }
  109214. }
  109215. /* are we a 'continued packet' page? If so, we may need to skip
  109216. some segments */
  109217. if(continued){
  109218. if(os->lacing_fill<1 ||
  109219. os->lacing_vals[os->lacing_fill-1]==0x400){
  109220. bos=0;
  109221. for(;segptr<segments;segptr++){
  109222. int val=header[27+segptr];
  109223. body+=val;
  109224. bodysize-=val;
  109225. if(val<255){
  109226. segptr++;
  109227. break;
  109228. }
  109229. }
  109230. }
  109231. }
  109232. if(bodysize){
  109233. _os_body_expand(os,bodysize);
  109234. memcpy(os->body_data+os->body_fill,body,bodysize);
  109235. os->body_fill+=bodysize;
  109236. }
  109237. {
  109238. int saved=-1;
  109239. while(segptr<segments){
  109240. int val=header[27+segptr];
  109241. os->lacing_vals[os->lacing_fill]=val;
  109242. os->granule_vals[os->lacing_fill]=-1;
  109243. if(bos){
  109244. os->lacing_vals[os->lacing_fill]|=0x100;
  109245. bos=0;
  109246. }
  109247. if(val<255)saved=os->lacing_fill;
  109248. os->lacing_fill++;
  109249. segptr++;
  109250. if(val<255)os->lacing_packet=os->lacing_fill;
  109251. }
  109252. /* set the granulepos on the last granuleval of the last full packet */
  109253. if(saved!=-1){
  109254. os->granule_vals[saved]=granulepos;
  109255. }
  109256. }
  109257. if(eos){
  109258. os->e_o_s=1;
  109259. if(os->lacing_fill>0)
  109260. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109261. }
  109262. os->pageno=pageno+1;
  109263. return(0);
  109264. }
  109265. /* clear things to an initial state. Good to call, eg, before seeking */
  109266. int ogg_sync_reset(ogg_sync_state *oy){
  109267. oy->fill=0;
  109268. oy->returned=0;
  109269. oy->unsynced=0;
  109270. oy->headerbytes=0;
  109271. oy->bodybytes=0;
  109272. return(0);
  109273. }
  109274. int ogg_stream_reset(ogg_stream_state *os){
  109275. os->body_fill=0;
  109276. os->body_returned=0;
  109277. os->lacing_fill=0;
  109278. os->lacing_packet=0;
  109279. os->lacing_returned=0;
  109280. os->header_fill=0;
  109281. os->e_o_s=0;
  109282. os->b_o_s=0;
  109283. os->pageno=-1;
  109284. os->packetno=0;
  109285. os->granulepos=0;
  109286. return(0);
  109287. }
  109288. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109289. ogg_stream_reset(os);
  109290. os->serialno=serialno;
  109291. return(0);
  109292. }
  109293. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109294. /* The last part of decode. We have the stream broken into packet
  109295. segments. Now we need to group them into packets (or return the
  109296. out of sync markers) */
  109297. int ptr=os->lacing_returned;
  109298. if(os->lacing_packet<=ptr)return(0);
  109299. if(os->lacing_vals[ptr]&0x400){
  109300. /* we need to tell the codec there's a gap; it might need to
  109301. handle previous packet dependencies. */
  109302. os->lacing_returned++;
  109303. os->packetno++;
  109304. return(-1);
  109305. }
  109306. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109307. to ask if there's a whole packet
  109308. waiting */
  109309. /* Gather the whole packet. We'll have no holes or a partial packet */
  109310. {
  109311. int size=os->lacing_vals[ptr]&0xff;
  109312. int bytes=size;
  109313. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109314. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109315. while(size==255){
  109316. int val=os->lacing_vals[++ptr];
  109317. size=val&0xff;
  109318. if(val&0x200)eos=0x200;
  109319. bytes+=size;
  109320. }
  109321. if(op){
  109322. op->e_o_s=eos;
  109323. op->b_o_s=bos;
  109324. op->packet=os->body_data+os->body_returned;
  109325. op->packetno=os->packetno;
  109326. op->granulepos=os->granule_vals[ptr];
  109327. op->bytes=bytes;
  109328. }
  109329. if(adv){
  109330. os->body_returned+=bytes;
  109331. os->lacing_returned=ptr+1;
  109332. os->packetno++;
  109333. }
  109334. }
  109335. return(1);
  109336. }
  109337. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109338. return _packetout(os,op,1);
  109339. }
  109340. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109341. return _packetout(os,op,0);
  109342. }
  109343. void ogg_packet_clear(ogg_packet *op) {
  109344. _ogg_free(op->packet);
  109345. memset(op, 0, sizeof(*op));
  109346. }
  109347. #ifdef _V_SELFTEST
  109348. #include <stdio.h>
  109349. ogg_stream_state os_en, os_de;
  109350. ogg_sync_state oy;
  109351. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109352. long j;
  109353. static int sequence=0;
  109354. static int lastno=0;
  109355. if(op->bytes!=len){
  109356. fprintf(stderr,"incorrect packet length!\n");
  109357. exit(1);
  109358. }
  109359. if(op->granulepos!=pos){
  109360. fprintf(stderr,"incorrect packet position!\n");
  109361. exit(1);
  109362. }
  109363. /* packet number just follows sequence/gap; adjust the input number
  109364. for that */
  109365. if(no==0){
  109366. sequence=0;
  109367. }else{
  109368. sequence++;
  109369. if(no>lastno+1)
  109370. sequence++;
  109371. }
  109372. lastno=no;
  109373. if(op->packetno!=sequence){
  109374. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109375. (long)(op->packetno),sequence);
  109376. exit(1);
  109377. }
  109378. /* Test data */
  109379. for(j=0;j<op->bytes;j++)
  109380. if(op->packet[j]!=((j+no)&0xff)){
  109381. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109382. j,op->packet[j],(j+no)&0xff);
  109383. exit(1);
  109384. }
  109385. }
  109386. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109387. long j;
  109388. /* Test data */
  109389. for(j=0;j<og->body_len;j++)
  109390. if(og->body[j]!=data[j]){
  109391. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109392. j,data[j],og->body[j]);
  109393. exit(1);
  109394. }
  109395. /* Test header */
  109396. for(j=0;j<og->header_len;j++){
  109397. if(og->header[j]!=header[j]){
  109398. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109399. for(j=0;j<header[26]+27;j++)
  109400. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109401. fprintf(stderr,"\n");
  109402. exit(1);
  109403. }
  109404. }
  109405. if(og->header_len!=header[26]+27){
  109406. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109407. og->header_len,header[26]+27);
  109408. exit(1);
  109409. }
  109410. }
  109411. void print_header(ogg_page *og){
  109412. int j;
  109413. fprintf(stderr,"\nHEADER:\n");
  109414. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109415. og->header[0],og->header[1],og->header[2],og->header[3],
  109416. (int)og->header[4],(int)og->header[5]);
  109417. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109418. (og->header[9]<<24)|(og->header[8]<<16)|
  109419. (og->header[7]<<8)|og->header[6],
  109420. (og->header[17]<<24)|(og->header[16]<<16)|
  109421. (og->header[15]<<8)|og->header[14],
  109422. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109423. (og->header[19]<<8)|og->header[18]);
  109424. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109425. (int)og->header[22],(int)og->header[23],
  109426. (int)og->header[24],(int)og->header[25],
  109427. (int)og->header[26]);
  109428. for(j=27;j<og->header_len;j++)
  109429. fprintf(stderr,"%d ",(int)og->header[j]);
  109430. fprintf(stderr,")\n\n");
  109431. }
  109432. void copy_page(ogg_page *og){
  109433. unsigned char *temp=_ogg_malloc(og->header_len);
  109434. memcpy(temp,og->header,og->header_len);
  109435. og->header=temp;
  109436. temp=_ogg_malloc(og->body_len);
  109437. memcpy(temp,og->body,og->body_len);
  109438. og->body=temp;
  109439. }
  109440. void free_page(ogg_page *og){
  109441. _ogg_free (og->header);
  109442. _ogg_free (og->body);
  109443. }
  109444. void error(void){
  109445. fprintf(stderr,"error!\n");
  109446. exit(1);
  109447. }
  109448. /* 17 only */
  109449. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109450. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109451. 0x01,0x02,0x03,0x04,0,0,0,0,
  109452. 0x15,0xed,0xec,0x91,
  109453. 1,
  109454. 17};
  109455. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109456. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109457. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109458. 0x01,0x02,0x03,0x04,0,0,0,0,
  109459. 0x59,0x10,0x6c,0x2c,
  109460. 1,
  109461. 17};
  109462. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109463. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109464. 0x01,0x02,0x03,0x04,1,0,0,0,
  109465. 0x89,0x33,0x85,0xce,
  109466. 13,
  109467. 254,255,0,255,1,255,245,255,255,0,
  109468. 255,255,90};
  109469. /* nil packets; beginning,middle,end */
  109470. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109471. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109472. 0x01,0x02,0x03,0x04,0,0,0,0,
  109473. 0xff,0x7b,0x23,0x17,
  109474. 1,
  109475. 0};
  109476. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109477. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109478. 0x01,0x02,0x03,0x04,1,0,0,0,
  109479. 0x5c,0x3f,0x66,0xcb,
  109480. 17,
  109481. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109482. 255,255,90,0};
  109483. /* large initial packet */
  109484. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109485. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109486. 0x01,0x02,0x03,0x04,0,0,0,0,
  109487. 0x01,0x27,0x31,0xaa,
  109488. 18,
  109489. 255,255,255,255,255,255,255,255,
  109490. 255,255,255,255,255,255,255,255,255,10};
  109491. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109492. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109493. 0x01,0x02,0x03,0x04,1,0,0,0,
  109494. 0x7f,0x4e,0x8a,0xd2,
  109495. 4,
  109496. 255,4,255,0};
  109497. /* continuing packet test */
  109498. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109499. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109500. 0x01,0x02,0x03,0x04,0,0,0,0,
  109501. 0xff,0x7b,0x23,0x17,
  109502. 1,
  109503. 0};
  109504. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109505. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109506. 0x01,0x02,0x03,0x04,1,0,0,0,
  109507. 0x54,0x05,0x51,0xc8,
  109508. 17,
  109509. 255,255,255,255,255,255,255,255,
  109510. 255,255,255,255,255,255,255,255,255};
  109511. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109512. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109513. 0x01,0x02,0x03,0x04,2,0,0,0,
  109514. 0xc8,0xc3,0xcb,0xed,
  109515. 5,
  109516. 10,255,4,255,0};
  109517. /* page with the 255 segment limit */
  109518. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109519. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109520. 0x01,0x02,0x03,0x04,0,0,0,0,
  109521. 0xff,0x7b,0x23,0x17,
  109522. 1,
  109523. 0};
  109524. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109525. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109526. 0x01,0x02,0x03,0x04,1,0,0,0,
  109527. 0xed,0x2a,0x2e,0xa7,
  109528. 255,
  109529. 10,10,10,10,10,10,10,10,
  109530. 10,10,10,10,10,10,10,10,
  109531. 10,10,10,10,10,10,10,10,
  109532. 10,10,10,10,10,10,10,10,
  109533. 10,10,10,10,10,10,10,10,
  109534. 10,10,10,10,10,10,10,10,
  109535. 10,10,10,10,10,10,10,10,
  109536. 10,10,10,10,10,10,10,10,
  109537. 10,10,10,10,10,10,10,10,
  109538. 10,10,10,10,10,10,10,10,
  109539. 10,10,10,10,10,10,10,10,
  109540. 10,10,10,10,10,10,10,10,
  109541. 10,10,10,10,10,10,10,10,
  109542. 10,10,10,10,10,10,10,10,
  109543. 10,10,10,10,10,10,10,10,
  109544. 10,10,10,10,10,10,10,10,
  109545. 10,10,10,10,10,10,10,10,
  109546. 10,10,10,10,10,10,10,10,
  109547. 10,10,10,10,10,10,10,10,
  109548. 10,10,10,10,10,10,10,10,
  109549. 10,10,10,10,10,10,10,10,
  109550. 10,10,10,10,10,10,10,10,
  109551. 10,10,10,10,10,10,10,10,
  109552. 10,10,10,10,10,10,10,10,
  109553. 10,10,10,10,10,10,10,10,
  109554. 10,10,10,10,10,10,10,10,
  109555. 10,10,10,10,10,10,10,10,
  109556. 10,10,10,10,10,10,10,10,
  109557. 10,10,10,10,10,10,10,10,
  109558. 10,10,10,10,10,10,10,10,
  109559. 10,10,10,10,10,10,10,10,
  109560. 10,10,10,10,10,10,10};
  109561. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109562. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109563. 0x01,0x02,0x03,0x04,2,0,0,0,
  109564. 0x6c,0x3b,0x82,0x3d,
  109565. 1,
  109566. 50};
  109567. /* packet that overspans over an entire page */
  109568. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109569. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109570. 0x01,0x02,0x03,0x04,0,0,0,0,
  109571. 0xff,0x7b,0x23,0x17,
  109572. 1,
  109573. 0};
  109574. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109575. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109576. 0x01,0x02,0x03,0x04,1,0,0,0,
  109577. 0x3c,0xd9,0x4d,0x3f,
  109578. 17,
  109579. 100,255,255,255,255,255,255,255,255,
  109580. 255,255,255,255,255,255,255,255};
  109581. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109582. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109583. 0x01,0x02,0x03,0x04,2,0,0,0,
  109584. 0x01,0xd2,0xe5,0xe5,
  109585. 17,
  109586. 255,255,255,255,255,255,255,255,
  109587. 255,255,255,255,255,255,255,255,255};
  109588. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109589. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109590. 0x01,0x02,0x03,0x04,3,0,0,0,
  109591. 0xef,0xdd,0x88,0xde,
  109592. 7,
  109593. 255,255,75,255,4,255,0};
  109594. /* packet that overspans over an entire page */
  109595. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109596. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109597. 0x01,0x02,0x03,0x04,0,0,0,0,
  109598. 0xff,0x7b,0x23,0x17,
  109599. 1,
  109600. 0};
  109601. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109602. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109603. 0x01,0x02,0x03,0x04,1,0,0,0,
  109604. 0x3c,0xd9,0x4d,0x3f,
  109605. 17,
  109606. 100,255,255,255,255,255,255,255,255,
  109607. 255,255,255,255,255,255,255,255};
  109608. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109609. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109610. 0x01,0x02,0x03,0x04,2,0,0,0,
  109611. 0xd4,0xe0,0x60,0xe5,
  109612. 1,0};
  109613. void test_pack(const int *pl, const int **headers, int byteskip,
  109614. int pageskip, int packetskip){
  109615. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109616. long inptr=0;
  109617. long outptr=0;
  109618. long deptr=0;
  109619. long depacket=0;
  109620. long granule_pos=7,pageno=0;
  109621. int i,j,packets,pageout=pageskip;
  109622. int eosflag=0;
  109623. int bosflag=0;
  109624. int byteskipcount=0;
  109625. ogg_stream_reset(&os_en);
  109626. ogg_stream_reset(&os_de);
  109627. ogg_sync_reset(&oy);
  109628. for(packets=0;packets<packetskip;packets++)
  109629. depacket+=pl[packets];
  109630. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109631. for(i=0;i<packets;i++){
  109632. /* construct a test packet */
  109633. ogg_packet op;
  109634. int len=pl[i];
  109635. op.packet=data+inptr;
  109636. op.bytes=len;
  109637. op.e_o_s=(pl[i+1]<0?1:0);
  109638. op.granulepos=granule_pos;
  109639. granule_pos+=1024;
  109640. for(j=0;j<len;j++)data[inptr++]=i+j;
  109641. /* submit the test packet */
  109642. ogg_stream_packetin(&os_en,&op);
  109643. /* retrieve any finished pages */
  109644. {
  109645. ogg_page og;
  109646. while(ogg_stream_pageout(&os_en,&og)){
  109647. /* We have a page. Check it carefully */
  109648. fprintf(stderr,"%ld, ",pageno);
  109649. if(headers[pageno]==NULL){
  109650. fprintf(stderr,"coded too many pages!\n");
  109651. exit(1);
  109652. }
  109653. check_page(data+outptr,headers[pageno],&og);
  109654. outptr+=og.body_len;
  109655. pageno++;
  109656. if(pageskip){
  109657. bosflag=1;
  109658. pageskip--;
  109659. deptr+=og.body_len;
  109660. }
  109661. /* have a complete page; submit it to sync/decode */
  109662. {
  109663. ogg_page og_de;
  109664. ogg_packet op_de,op_de2;
  109665. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109666. char *next=buf;
  109667. byteskipcount+=og.header_len;
  109668. if(byteskipcount>byteskip){
  109669. memcpy(next,og.header,byteskipcount-byteskip);
  109670. next+=byteskipcount-byteskip;
  109671. byteskipcount=byteskip;
  109672. }
  109673. byteskipcount+=og.body_len;
  109674. if(byteskipcount>byteskip){
  109675. memcpy(next,og.body,byteskipcount-byteskip);
  109676. next+=byteskipcount-byteskip;
  109677. byteskipcount=byteskip;
  109678. }
  109679. ogg_sync_wrote(&oy,next-buf);
  109680. while(1){
  109681. int ret=ogg_sync_pageout(&oy,&og_de);
  109682. if(ret==0)break;
  109683. if(ret<0)continue;
  109684. /* got a page. Happy happy. Verify that it's good. */
  109685. fprintf(stderr,"(%ld), ",pageout);
  109686. check_page(data+deptr,headers[pageout],&og_de);
  109687. deptr+=og_de.body_len;
  109688. pageout++;
  109689. /* submit it to deconstitution */
  109690. ogg_stream_pagein(&os_de,&og_de);
  109691. /* packets out? */
  109692. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109693. ogg_stream_packetpeek(&os_de,NULL);
  109694. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109695. /* verify peek and out match */
  109696. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109697. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109698. depacket);
  109699. exit(1);
  109700. }
  109701. /* verify the packet! */
  109702. /* check data */
  109703. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109704. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109705. depacket);
  109706. exit(1);
  109707. }
  109708. /* check bos flag */
  109709. if(bosflag==0 && op_de.b_o_s==0){
  109710. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109711. exit(1);
  109712. }
  109713. if(bosflag && op_de.b_o_s){
  109714. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109715. exit(1);
  109716. }
  109717. bosflag=1;
  109718. depacket+=op_de.bytes;
  109719. /* check eos flag */
  109720. if(eosflag){
  109721. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109722. exit(1);
  109723. }
  109724. if(op_de.e_o_s)eosflag=1;
  109725. /* check granulepos flag */
  109726. if(op_de.granulepos!=-1){
  109727. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109728. }
  109729. }
  109730. }
  109731. }
  109732. }
  109733. }
  109734. }
  109735. _ogg_free(data);
  109736. if(headers[pageno]!=NULL){
  109737. fprintf(stderr,"did not write last page!\n");
  109738. exit(1);
  109739. }
  109740. if(headers[pageout]!=NULL){
  109741. fprintf(stderr,"did not decode last page!\n");
  109742. exit(1);
  109743. }
  109744. if(inptr!=outptr){
  109745. fprintf(stderr,"encoded page data incomplete!\n");
  109746. exit(1);
  109747. }
  109748. if(inptr!=deptr){
  109749. fprintf(stderr,"decoded page data incomplete!\n");
  109750. exit(1);
  109751. }
  109752. if(inptr!=depacket){
  109753. fprintf(stderr,"decoded packet data incomplete!\n");
  109754. exit(1);
  109755. }
  109756. if(!eosflag){
  109757. fprintf(stderr,"Never got a packet with EOS set!\n");
  109758. exit(1);
  109759. }
  109760. fprintf(stderr,"ok.\n");
  109761. }
  109762. int main(void){
  109763. ogg_stream_init(&os_en,0x04030201);
  109764. ogg_stream_init(&os_de,0x04030201);
  109765. ogg_sync_init(&oy);
  109766. /* Exercise each code path in the framing code. Also verify that
  109767. the checksums are working. */
  109768. {
  109769. /* 17 only */
  109770. const int packets[]={17, -1};
  109771. const int *headret[]={head1_0,NULL};
  109772. fprintf(stderr,"testing single page encoding... ");
  109773. test_pack(packets,headret,0,0,0);
  109774. }
  109775. {
  109776. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109777. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109778. const int *headret[]={head1_1,head2_1,NULL};
  109779. fprintf(stderr,"testing basic page encoding... ");
  109780. test_pack(packets,headret,0,0,0);
  109781. }
  109782. {
  109783. /* nil packets; beginning,middle,end */
  109784. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109785. const int *headret[]={head1_2,head2_2,NULL};
  109786. fprintf(stderr,"testing basic nil packets... ");
  109787. test_pack(packets,headret,0,0,0);
  109788. }
  109789. {
  109790. /* large initial packet */
  109791. const int packets[]={4345,259,255,-1};
  109792. const int *headret[]={head1_3,head2_3,NULL};
  109793. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109794. test_pack(packets,headret,0,0,0);
  109795. }
  109796. {
  109797. /* continuing packet test */
  109798. const int packets[]={0,4345,259,255,-1};
  109799. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109800. fprintf(stderr,"testing single packet page span... ");
  109801. test_pack(packets,headret,0,0,0);
  109802. }
  109803. /* page with the 255 segment limit */
  109804. {
  109805. const int packets[]={0,10,10,10,10,10,10,10,10,
  109806. 10,10,10,10,10,10,10,10,
  109807. 10,10,10,10,10,10,10,10,
  109808. 10,10,10,10,10,10,10,10,
  109809. 10,10,10,10,10,10,10,10,
  109810. 10,10,10,10,10,10,10,10,
  109811. 10,10,10,10,10,10,10,10,
  109812. 10,10,10,10,10,10,10,10,
  109813. 10,10,10,10,10,10,10,10,
  109814. 10,10,10,10,10,10,10,10,
  109815. 10,10,10,10,10,10,10,10,
  109816. 10,10,10,10,10,10,10,10,
  109817. 10,10,10,10,10,10,10,10,
  109818. 10,10,10,10,10,10,10,10,
  109819. 10,10,10,10,10,10,10,10,
  109820. 10,10,10,10,10,10,10,10,
  109821. 10,10,10,10,10,10,10,10,
  109822. 10,10,10,10,10,10,10,10,
  109823. 10,10,10,10,10,10,10,10,
  109824. 10,10,10,10,10,10,10,10,
  109825. 10,10,10,10,10,10,10,10,
  109826. 10,10,10,10,10,10,10,10,
  109827. 10,10,10,10,10,10,10,10,
  109828. 10,10,10,10,10,10,10,10,
  109829. 10,10,10,10,10,10,10,10,
  109830. 10,10,10,10,10,10,10,10,
  109831. 10,10,10,10,10,10,10,10,
  109832. 10,10,10,10,10,10,10,10,
  109833. 10,10,10,10,10,10,10,10,
  109834. 10,10,10,10,10,10,10,10,
  109835. 10,10,10,10,10,10,10,10,
  109836. 10,10,10,10,10,10,10,50,-1};
  109837. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109838. fprintf(stderr,"testing max packet segments... ");
  109839. test_pack(packets,headret,0,0,0);
  109840. }
  109841. {
  109842. /* packet that overspans over an entire page */
  109843. const int packets[]={0,100,9000,259,255,-1};
  109844. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109845. fprintf(stderr,"testing very large packets... ");
  109846. test_pack(packets,headret,0,0,0);
  109847. }
  109848. {
  109849. /* test for the libogg 1.1.1 resync in large continuation bug
  109850. found by Josh Coalson) */
  109851. const int packets[]={0,100,9000,259,255,-1};
  109852. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109853. fprintf(stderr,"testing continuation resync in very large packets... ");
  109854. test_pack(packets,headret,100,2,3);
  109855. }
  109856. {
  109857. /* term only page. why not? */
  109858. const int packets[]={0,100,4080,-1};
  109859. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109860. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109861. test_pack(packets,headret,0,0,0);
  109862. }
  109863. {
  109864. /* build a bunch of pages for testing */
  109865. unsigned char *data=_ogg_malloc(1024*1024);
  109866. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109867. int inptr=0,i,j;
  109868. ogg_page og[5];
  109869. ogg_stream_reset(&os_en);
  109870. for(i=0;pl[i]!=-1;i++){
  109871. ogg_packet op;
  109872. int len=pl[i];
  109873. op.packet=data+inptr;
  109874. op.bytes=len;
  109875. op.e_o_s=(pl[i+1]<0?1:0);
  109876. op.granulepos=(i+1)*1000;
  109877. for(j=0;j<len;j++)data[inptr++]=i+j;
  109878. ogg_stream_packetin(&os_en,&op);
  109879. }
  109880. _ogg_free(data);
  109881. /* retrieve finished pages */
  109882. for(i=0;i<5;i++){
  109883. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109884. fprintf(stderr,"Too few pages output building sync tests!\n");
  109885. exit(1);
  109886. }
  109887. copy_page(&og[i]);
  109888. }
  109889. /* Test lost pages on pagein/packetout: no rollback */
  109890. {
  109891. ogg_page temp;
  109892. ogg_packet test;
  109893. fprintf(stderr,"Testing loss of pages... ");
  109894. ogg_sync_reset(&oy);
  109895. ogg_stream_reset(&os_de);
  109896. for(i=0;i<5;i++){
  109897. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109898. og[i].header_len);
  109899. ogg_sync_wrote(&oy,og[i].header_len);
  109900. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109901. ogg_sync_wrote(&oy,og[i].body_len);
  109902. }
  109903. ogg_sync_pageout(&oy,&temp);
  109904. ogg_stream_pagein(&os_de,&temp);
  109905. ogg_sync_pageout(&oy,&temp);
  109906. ogg_stream_pagein(&os_de,&temp);
  109907. ogg_sync_pageout(&oy,&temp);
  109908. /* skip */
  109909. ogg_sync_pageout(&oy,&temp);
  109910. ogg_stream_pagein(&os_de,&temp);
  109911. /* do we get the expected results/packets? */
  109912. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109913. checkpacket(&test,0,0,0);
  109914. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109915. checkpacket(&test,100,1,-1);
  109916. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109917. checkpacket(&test,4079,2,3000);
  109918. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109919. fprintf(stderr,"Error: loss of page did not return error\n");
  109920. exit(1);
  109921. }
  109922. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109923. checkpacket(&test,76,5,-1);
  109924. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109925. checkpacket(&test,34,6,-1);
  109926. fprintf(stderr,"ok.\n");
  109927. }
  109928. /* Test lost pages on pagein/packetout: rollback with continuation */
  109929. {
  109930. ogg_page temp;
  109931. ogg_packet test;
  109932. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109933. ogg_sync_reset(&oy);
  109934. ogg_stream_reset(&os_de);
  109935. for(i=0;i<5;i++){
  109936. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109937. og[i].header_len);
  109938. ogg_sync_wrote(&oy,og[i].header_len);
  109939. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109940. ogg_sync_wrote(&oy,og[i].body_len);
  109941. }
  109942. ogg_sync_pageout(&oy,&temp);
  109943. ogg_stream_pagein(&os_de,&temp);
  109944. ogg_sync_pageout(&oy,&temp);
  109945. ogg_stream_pagein(&os_de,&temp);
  109946. ogg_sync_pageout(&oy,&temp);
  109947. ogg_stream_pagein(&os_de,&temp);
  109948. ogg_sync_pageout(&oy,&temp);
  109949. /* skip */
  109950. ogg_sync_pageout(&oy,&temp);
  109951. ogg_stream_pagein(&os_de,&temp);
  109952. /* do we get the expected results/packets? */
  109953. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109954. checkpacket(&test,0,0,0);
  109955. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109956. checkpacket(&test,100,1,-1);
  109957. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109958. checkpacket(&test,4079,2,3000);
  109959. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109960. checkpacket(&test,2956,3,4000);
  109961. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109962. fprintf(stderr,"Error: loss of page did not return error\n");
  109963. exit(1);
  109964. }
  109965. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109966. checkpacket(&test,300,13,14000);
  109967. fprintf(stderr,"ok.\n");
  109968. }
  109969. /* the rest only test sync */
  109970. {
  109971. ogg_page og_de;
  109972. /* Test fractional page inputs: incomplete capture */
  109973. fprintf(stderr,"Testing sync on partial inputs... ");
  109974. ogg_sync_reset(&oy);
  109975. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109976. 3);
  109977. ogg_sync_wrote(&oy,3);
  109978. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109979. /* Test fractional page inputs: incomplete fixed header */
  109980. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109981. 20);
  109982. ogg_sync_wrote(&oy,20);
  109983. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109984. /* Test fractional page inputs: incomplete header */
  109985. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109986. 5);
  109987. ogg_sync_wrote(&oy,5);
  109988. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109989. /* Test fractional page inputs: incomplete body */
  109990. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109991. og[1].header_len-28);
  109992. ogg_sync_wrote(&oy,og[1].header_len-28);
  109993. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109994. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109995. ogg_sync_wrote(&oy,1000);
  109996. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109997. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109998. og[1].body_len-1000);
  109999. ogg_sync_wrote(&oy,og[1].body_len-1000);
  110000. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110001. fprintf(stderr,"ok.\n");
  110002. }
  110003. /* Test fractional page inputs: page + incomplete capture */
  110004. {
  110005. ogg_page og_de;
  110006. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  110007. ogg_sync_reset(&oy);
  110008. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110009. og[1].header_len);
  110010. ogg_sync_wrote(&oy,og[1].header_len);
  110011. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110012. og[1].body_len);
  110013. ogg_sync_wrote(&oy,og[1].body_len);
  110014. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110015. 20);
  110016. ogg_sync_wrote(&oy,20);
  110017. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110018. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110019. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  110020. og[1].header_len-20);
  110021. ogg_sync_wrote(&oy,og[1].header_len-20);
  110022. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110023. og[1].body_len);
  110024. ogg_sync_wrote(&oy,og[1].body_len);
  110025. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110026. fprintf(stderr,"ok.\n");
  110027. }
  110028. /* Test recapture: garbage + page */
  110029. {
  110030. ogg_page og_de;
  110031. fprintf(stderr,"Testing search for capture... ");
  110032. ogg_sync_reset(&oy);
  110033. /* 'garbage' */
  110034. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110035. og[1].body_len);
  110036. ogg_sync_wrote(&oy,og[1].body_len);
  110037. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110038. og[1].header_len);
  110039. ogg_sync_wrote(&oy,og[1].header_len);
  110040. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110041. og[1].body_len);
  110042. ogg_sync_wrote(&oy,og[1].body_len);
  110043. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110044. 20);
  110045. ogg_sync_wrote(&oy,20);
  110046. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110047. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110048. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110049. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  110050. og[2].header_len-20);
  110051. ogg_sync_wrote(&oy,og[2].header_len-20);
  110052. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110053. og[2].body_len);
  110054. ogg_sync_wrote(&oy,og[2].body_len);
  110055. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110056. fprintf(stderr,"ok.\n");
  110057. }
  110058. /* Test recapture: page + garbage + page */
  110059. {
  110060. ogg_page og_de;
  110061. fprintf(stderr,"Testing recapture... ");
  110062. ogg_sync_reset(&oy);
  110063. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110064. og[1].header_len);
  110065. ogg_sync_wrote(&oy,og[1].header_len);
  110066. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110067. og[1].body_len);
  110068. ogg_sync_wrote(&oy,og[1].body_len);
  110069. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110070. og[2].header_len);
  110071. ogg_sync_wrote(&oy,og[2].header_len);
  110072. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110073. og[2].header_len);
  110074. ogg_sync_wrote(&oy,og[2].header_len);
  110075. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110076. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110077. og[2].body_len-5);
  110078. ogg_sync_wrote(&oy,og[2].body_len-5);
  110079. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  110080. og[3].header_len);
  110081. ogg_sync_wrote(&oy,og[3].header_len);
  110082. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  110083. og[3].body_len);
  110084. ogg_sync_wrote(&oy,og[3].body_len);
  110085. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110086. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110087. fprintf(stderr,"ok.\n");
  110088. }
  110089. /* Free page data that was previously copied */
  110090. {
  110091. for(i=0;i<5;i++){
  110092. free_page(&og[i]);
  110093. }
  110094. }
  110095. }
  110096. return(0);
  110097. }
  110098. #endif
  110099. #endif
  110100. /*** End of inlined file: framing.c ***/
  110101. /*** Start of inlined file: analysis.c ***/
  110102. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110103. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110104. // tasks..
  110105. #if JUCE_MSVC
  110106. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110107. #endif
  110108. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110109. #if JUCE_USE_OGGVORBIS
  110110. #include <stdio.h>
  110111. #include <string.h>
  110112. #include <math.h>
  110113. /*** Start of inlined file: codec_internal.h ***/
  110114. #ifndef _V_CODECI_H_
  110115. #define _V_CODECI_H_
  110116. /*** Start of inlined file: envelope.h ***/
  110117. #ifndef _V_ENVELOPE_
  110118. #define _V_ENVELOPE_
  110119. /*** Start of inlined file: mdct.h ***/
  110120. #ifndef _OGG_mdct_H_
  110121. #define _OGG_mdct_H_
  110122. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  110123. #ifdef MDCT_INTEGERIZED
  110124. #define DATA_TYPE int
  110125. #define REG_TYPE register int
  110126. #define TRIGBITS 14
  110127. #define cPI3_8 6270
  110128. #define cPI2_8 11585
  110129. #define cPI1_8 15137
  110130. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  110131. #define MULT_NORM(x) ((x)>>TRIGBITS)
  110132. #define HALVE(x) ((x)>>1)
  110133. #else
  110134. #define DATA_TYPE float
  110135. #define REG_TYPE float
  110136. #define cPI3_8 .38268343236508977175F
  110137. #define cPI2_8 .70710678118654752441F
  110138. #define cPI1_8 .92387953251128675613F
  110139. #define FLOAT_CONV(x) (x)
  110140. #define MULT_NORM(x) (x)
  110141. #define HALVE(x) ((x)*.5f)
  110142. #endif
  110143. typedef struct {
  110144. int n;
  110145. int log2n;
  110146. DATA_TYPE *trig;
  110147. int *bitrev;
  110148. DATA_TYPE scale;
  110149. } mdct_lookup;
  110150. extern void mdct_init(mdct_lookup *lookup,int n);
  110151. extern void mdct_clear(mdct_lookup *l);
  110152. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110153. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110154. #endif
  110155. /*** End of inlined file: mdct.h ***/
  110156. #define VE_PRE 16
  110157. #define VE_WIN 4
  110158. #define VE_POST 2
  110159. #define VE_AMP (VE_PRE+VE_POST-1)
  110160. #define VE_BANDS 7
  110161. #define VE_NEARDC 15
  110162. #define VE_MINSTRETCH 2 /* a bit less than short block */
  110163. #define VE_MAXSTRETCH 12 /* one-third full block */
  110164. typedef struct {
  110165. float ampbuf[VE_AMP];
  110166. int ampptr;
  110167. float nearDC[VE_NEARDC];
  110168. float nearDC_acc;
  110169. float nearDC_partialacc;
  110170. int nearptr;
  110171. } envelope_filter_state;
  110172. typedef struct {
  110173. int begin;
  110174. int end;
  110175. float *window;
  110176. float total;
  110177. } envelope_band;
  110178. typedef struct {
  110179. int ch;
  110180. int winlength;
  110181. int searchstep;
  110182. float minenergy;
  110183. mdct_lookup mdct;
  110184. float *mdct_win;
  110185. envelope_band band[VE_BANDS];
  110186. envelope_filter_state *filter;
  110187. int stretch;
  110188. int *mark;
  110189. long storage;
  110190. long current;
  110191. long curmark;
  110192. long cursor;
  110193. } envelope_lookup;
  110194. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  110195. extern void _ve_envelope_clear(envelope_lookup *e);
  110196. extern long _ve_envelope_search(vorbis_dsp_state *v);
  110197. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  110198. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110199. #endif
  110200. /*** End of inlined file: envelope.h ***/
  110201. /*** Start of inlined file: codebook.h ***/
  110202. #ifndef _V_CODEBOOK_H_
  110203. #define _V_CODEBOOK_H_
  110204. /* This structure encapsulates huffman and VQ style encoding books; it
  110205. doesn't do anything specific to either.
  110206. valuelist/quantlist are nonNULL (and q_* significant) only if
  110207. there's entry->value mapping to be done.
  110208. If encode-side mapping must be done (and thus the entry needs to be
  110209. hunted), the auxiliary encode pointer will point to a decision
  110210. tree. This is true of both VQ and huffman, but is mostly useful
  110211. with VQ.
  110212. */
  110213. typedef struct static_codebook{
  110214. long dim; /* codebook dimensions (elements per vector) */
  110215. long entries; /* codebook entries */
  110216. long *lengthlist; /* codeword lengths in bits */
  110217. /* mapping ***************************************************************/
  110218. int maptype; /* 0=none
  110219. 1=implicitly populated values from map column
  110220. 2=listed arbitrary values */
  110221. /* The below does a linear, single monotonic sequence mapping. */
  110222. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110223. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110224. int q_quant; /* bits: 0 < quant <= 16 */
  110225. int q_sequencep; /* bitflag */
  110226. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110227. map == 2: list of dim*entries quantized entry vals
  110228. */
  110229. /* encode helpers ********************************************************/
  110230. struct encode_aux_nearestmatch *nearest_tree;
  110231. struct encode_aux_threshmatch *thresh_tree;
  110232. struct encode_aux_pigeonhole *pigeon_tree;
  110233. int allocedp;
  110234. } static_codebook;
  110235. /* this structures an arbitrary trained book to quickly find the
  110236. nearest cell match */
  110237. typedef struct encode_aux_nearestmatch{
  110238. /* pre-calculated partitioning tree */
  110239. long *ptr0;
  110240. long *ptr1;
  110241. long *p; /* decision points (each is an entry) */
  110242. long *q; /* decision points (each is an entry) */
  110243. long aux; /* number of tree entries */
  110244. long alloc;
  110245. } encode_aux_nearestmatch;
  110246. /* assumes a maptype of 1; encode side only, so that's OK */
  110247. typedef struct encode_aux_threshmatch{
  110248. float *quantthresh;
  110249. long *quantmap;
  110250. int quantvals;
  110251. int threshvals;
  110252. } encode_aux_threshmatch;
  110253. typedef struct encode_aux_pigeonhole{
  110254. float min;
  110255. float del;
  110256. int mapentries;
  110257. int quantvals;
  110258. long *pigeonmap;
  110259. long fittotal;
  110260. long *fitlist;
  110261. long *fitmap;
  110262. long *fitlength;
  110263. } encode_aux_pigeonhole;
  110264. typedef struct codebook{
  110265. long dim; /* codebook dimensions (elements per vector) */
  110266. long entries; /* codebook entries */
  110267. long used_entries; /* populated codebook entries */
  110268. const static_codebook *c;
  110269. /* for encode, the below are entry-ordered, fully populated */
  110270. /* for decode, the below are ordered by bitreversed codeword and only
  110271. used entries are populated */
  110272. float *valuelist; /* list of dim*entries actual entry values */
  110273. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110274. int *dec_index; /* only used if sparseness collapsed */
  110275. char *dec_codelengths;
  110276. ogg_uint32_t *dec_firsttable;
  110277. int dec_firsttablen;
  110278. int dec_maxlength;
  110279. } codebook;
  110280. extern void vorbis_staticbook_clear(static_codebook *b);
  110281. extern void vorbis_staticbook_destroy(static_codebook *b);
  110282. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110283. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110284. extern void vorbis_book_clear(codebook *b);
  110285. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110286. extern float *_book_logdist(const static_codebook *b,float *vals);
  110287. extern float _float32_unpack(long val);
  110288. extern long _float32_pack(float val);
  110289. extern int _best(codebook *book, float *a, int step);
  110290. extern int _ilog(unsigned int v);
  110291. extern long _book_maptype1_quantvals(const static_codebook *b);
  110292. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110293. extern long vorbis_book_codeword(codebook *book,int entry);
  110294. extern long vorbis_book_codelen(codebook *book,int entry);
  110295. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110296. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110297. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110298. extern int vorbis_book_errorv(codebook *book, float *a);
  110299. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110300. oggpack_buffer *b);
  110301. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110302. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110303. oggpack_buffer *b,int n);
  110304. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110305. oggpack_buffer *b,int n);
  110306. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110307. oggpack_buffer *b,int n);
  110308. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110309. long off,int ch,
  110310. oggpack_buffer *b,int n);
  110311. #endif
  110312. /*** End of inlined file: codebook.h ***/
  110313. #define BLOCKTYPE_IMPULSE 0
  110314. #define BLOCKTYPE_PADDING 1
  110315. #define BLOCKTYPE_TRANSITION 0
  110316. #define BLOCKTYPE_LONG 1
  110317. #define PACKETBLOBS 15
  110318. typedef struct vorbis_block_internal{
  110319. float **pcmdelay; /* this is a pointer into local storage */
  110320. float ampmax;
  110321. int blocktype;
  110322. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110323. blob [PACKETBLOBS/2] points to
  110324. the oggpack_buffer in the
  110325. main vorbis_block */
  110326. } vorbis_block_internal;
  110327. typedef void vorbis_look_floor;
  110328. typedef void vorbis_look_residue;
  110329. typedef void vorbis_look_transform;
  110330. /* mode ************************************************************/
  110331. typedef struct {
  110332. int blockflag;
  110333. int windowtype;
  110334. int transformtype;
  110335. int mapping;
  110336. } vorbis_info_mode;
  110337. typedef void vorbis_info_floor;
  110338. typedef void vorbis_info_residue;
  110339. typedef void vorbis_info_mapping;
  110340. /*** Start of inlined file: psy.h ***/
  110341. #ifndef _V_PSY_H_
  110342. #define _V_PSY_H_
  110343. /*** Start of inlined file: smallft.h ***/
  110344. #ifndef _V_SMFT_H_
  110345. #define _V_SMFT_H_
  110346. typedef struct {
  110347. int n;
  110348. float *trigcache;
  110349. int *splitcache;
  110350. } drft_lookup;
  110351. extern void drft_forward(drft_lookup *l,float *data);
  110352. extern void drft_backward(drft_lookup *l,float *data);
  110353. extern void drft_init(drft_lookup *l,int n);
  110354. extern void drft_clear(drft_lookup *l);
  110355. #endif
  110356. /*** End of inlined file: smallft.h ***/
  110357. /*** Start of inlined file: backends.h ***/
  110358. /* this is exposed up here because we need it for static modes.
  110359. Lookups for each backend aren't exposed because there's no reason
  110360. to do so */
  110361. #ifndef _vorbis_backend_h_
  110362. #define _vorbis_backend_h_
  110363. /* this would all be simpler/shorter with templates, but.... */
  110364. /* Floor backend generic *****************************************/
  110365. typedef struct{
  110366. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110367. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110368. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110369. void (*free_info) (vorbis_info_floor *);
  110370. void (*free_look) (vorbis_look_floor *);
  110371. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110372. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110373. void *buffer,float *);
  110374. } vorbis_func_floor;
  110375. typedef struct{
  110376. int order;
  110377. long rate;
  110378. long barkmap;
  110379. int ampbits;
  110380. int ampdB;
  110381. int numbooks; /* <= 16 */
  110382. int books[16];
  110383. float lessthan; /* encode-only config setting hacks for libvorbis */
  110384. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110385. } vorbis_info_floor0;
  110386. #define VIF_POSIT 63
  110387. #define VIF_CLASS 16
  110388. #define VIF_PARTS 31
  110389. typedef struct{
  110390. int partitions; /* 0 to 31 */
  110391. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110392. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110393. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110394. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110395. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110396. int mult; /* 1 2 3 or 4 */
  110397. int postlist[VIF_POSIT+2]; /* first two implicit */
  110398. /* encode side analysis parameters */
  110399. float maxover;
  110400. float maxunder;
  110401. float maxerr;
  110402. float twofitweight;
  110403. float twofitatten;
  110404. int n;
  110405. } vorbis_info_floor1;
  110406. /* Residue backend generic *****************************************/
  110407. typedef struct{
  110408. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110409. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110410. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110411. vorbis_info_residue *);
  110412. void (*free_info) (vorbis_info_residue *);
  110413. void (*free_look) (vorbis_look_residue *);
  110414. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110415. float **,int *,int);
  110416. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110417. vorbis_look_residue *,
  110418. float **,float **,int *,int,long **);
  110419. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110420. float **,int *,int);
  110421. } vorbis_func_residue;
  110422. typedef struct vorbis_info_residue0{
  110423. /* block-partitioned VQ coded straight residue */
  110424. long begin;
  110425. long end;
  110426. /* first stage (lossless partitioning) */
  110427. int grouping; /* group n vectors per partition */
  110428. int partitions; /* possible codebooks for a partition */
  110429. int groupbook; /* huffbook for partitioning */
  110430. int secondstages[64]; /* expanded out to pointers in lookup */
  110431. int booklist[256]; /* list of second stage books */
  110432. float classmetric1[64];
  110433. float classmetric2[64];
  110434. } vorbis_info_residue0;
  110435. /* Mapping backend generic *****************************************/
  110436. typedef struct{
  110437. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110438. oggpack_buffer *);
  110439. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110440. void (*free_info) (vorbis_info_mapping *);
  110441. int (*forward) (struct vorbis_block *vb);
  110442. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110443. } vorbis_func_mapping;
  110444. typedef struct vorbis_info_mapping0{
  110445. int submaps; /* <= 16 */
  110446. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110447. int floorsubmap[16]; /* [mux] submap to floors */
  110448. int residuesubmap[16]; /* [mux] submap to residue */
  110449. int coupling_steps;
  110450. int coupling_mag[256];
  110451. int coupling_ang[256];
  110452. } vorbis_info_mapping0;
  110453. #endif
  110454. /*** End of inlined file: backends.h ***/
  110455. #ifndef EHMER_MAX
  110456. #define EHMER_MAX 56
  110457. #endif
  110458. /* psychoacoustic setup ********************************************/
  110459. #define P_BANDS 17 /* 62Hz to 16kHz */
  110460. #define P_LEVELS 8 /* 30dB to 100dB */
  110461. #define P_LEVEL_0 30. /* 30 dB */
  110462. #define P_NOISECURVES 3
  110463. #define NOISE_COMPAND_LEVELS 40
  110464. typedef struct vorbis_info_psy{
  110465. int blockflag;
  110466. float ath_adjatt;
  110467. float ath_maxatt;
  110468. float tone_masteratt[P_NOISECURVES];
  110469. float tone_centerboost;
  110470. float tone_decay;
  110471. float tone_abs_limit;
  110472. float toneatt[P_BANDS];
  110473. int noisemaskp;
  110474. float noisemaxsupp;
  110475. float noisewindowlo;
  110476. float noisewindowhi;
  110477. int noisewindowlomin;
  110478. int noisewindowhimin;
  110479. int noisewindowfixed;
  110480. float noiseoff[P_NOISECURVES][P_BANDS];
  110481. float noisecompand[NOISE_COMPAND_LEVELS];
  110482. float max_curve_dB;
  110483. int normal_channel_p;
  110484. int normal_point_p;
  110485. int normal_start;
  110486. int normal_partition;
  110487. double normal_thresh;
  110488. } vorbis_info_psy;
  110489. typedef struct{
  110490. int eighth_octave_lines;
  110491. /* for block long/short tuning; encode only */
  110492. float preecho_thresh[VE_BANDS];
  110493. float postecho_thresh[VE_BANDS];
  110494. float stretch_penalty;
  110495. float preecho_minenergy;
  110496. float ampmax_att_per_sec;
  110497. /* channel coupling config */
  110498. int coupling_pkHz[PACKETBLOBS];
  110499. int coupling_pointlimit[2][PACKETBLOBS];
  110500. int coupling_prepointamp[PACKETBLOBS];
  110501. int coupling_postpointamp[PACKETBLOBS];
  110502. int sliding_lowpass[2][PACKETBLOBS];
  110503. } vorbis_info_psy_global;
  110504. typedef struct {
  110505. float ampmax;
  110506. int channels;
  110507. vorbis_info_psy_global *gi;
  110508. int coupling_pointlimit[2][P_NOISECURVES];
  110509. } vorbis_look_psy_global;
  110510. typedef struct {
  110511. int n;
  110512. struct vorbis_info_psy *vi;
  110513. float ***tonecurves;
  110514. float **noiseoffset;
  110515. float *ath;
  110516. long *octave; /* in n.ocshift format */
  110517. long *bark;
  110518. long firstoc;
  110519. long shiftoc;
  110520. int eighth_octave_lines; /* power of two, please */
  110521. int total_octave_lines;
  110522. long rate; /* cache it */
  110523. float m_val; /* Masking compensation value */
  110524. } vorbis_look_psy;
  110525. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110526. vorbis_info_psy_global *gi,int n,long rate);
  110527. extern void _vp_psy_clear(vorbis_look_psy *p);
  110528. extern void *_vi_psy_dup(void *source);
  110529. extern void _vi_psy_free(vorbis_info_psy *i);
  110530. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110531. extern void _vp_remove_floor(vorbis_look_psy *p,
  110532. float *mdct,
  110533. int *icodedflr,
  110534. float *residue,
  110535. int sliding_lowpass);
  110536. extern void _vp_noisemask(vorbis_look_psy *p,
  110537. float *logmdct,
  110538. float *logmask);
  110539. extern void _vp_tonemask(vorbis_look_psy *p,
  110540. float *logfft,
  110541. float *logmask,
  110542. float global_specmax,
  110543. float local_specmax);
  110544. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110545. float *noise,
  110546. float *tone,
  110547. int offset_select,
  110548. float *logmask,
  110549. float *mdct,
  110550. float *logmdct);
  110551. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110552. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110553. vorbis_info_psy_global *g,
  110554. vorbis_look_psy *p,
  110555. vorbis_info_mapping0 *vi,
  110556. float **mdct);
  110557. extern void _vp_couple(int blobno,
  110558. vorbis_info_psy_global *g,
  110559. vorbis_look_psy *p,
  110560. vorbis_info_mapping0 *vi,
  110561. float **res,
  110562. float **mag_memo,
  110563. int **mag_sort,
  110564. int **ifloor,
  110565. int *nonzero,
  110566. int sliding_lowpass);
  110567. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110568. float *in,float *out,int *sortedindex);
  110569. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110570. float *magnitudes,int *sortedindex);
  110571. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110572. vorbis_look_psy *p,
  110573. vorbis_info_mapping0 *vi,
  110574. float **mags);
  110575. extern void hf_reduction(vorbis_info_psy_global *g,
  110576. vorbis_look_psy *p,
  110577. vorbis_info_mapping0 *vi,
  110578. float **mdct);
  110579. #endif
  110580. /*** End of inlined file: psy.h ***/
  110581. /*** Start of inlined file: bitrate.h ***/
  110582. #ifndef _V_BITRATE_H_
  110583. #define _V_BITRATE_H_
  110584. /*** Start of inlined file: os.h ***/
  110585. #ifndef _OS_H
  110586. #define _OS_H
  110587. /********************************************************************
  110588. * *
  110589. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110590. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110591. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110592. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110593. * *
  110594. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110595. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110596. * *
  110597. ********************************************************************
  110598. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110599. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110600. ********************************************************************/
  110601. #ifdef HAVE_CONFIG_H
  110602. #include "config.h"
  110603. #endif
  110604. #include <math.h>
  110605. /*** Start of inlined file: misc.h ***/
  110606. #ifndef _V_RANDOM_H_
  110607. #define _V_RANDOM_H_
  110608. extern int analysis_noisy;
  110609. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110610. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110611. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110612. ogg_int64_t off);
  110613. #ifdef DEBUG_MALLOC
  110614. #define _VDBG_GRAPHFILE "malloc.m"
  110615. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110616. extern void _VDBG_free(void *ptr,char *file,long line);
  110617. #ifndef MISC_C
  110618. #undef _ogg_malloc
  110619. #undef _ogg_calloc
  110620. #undef _ogg_realloc
  110621. #undef _ogg_free
  110622. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110623. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110624. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110625. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110626. #endif
  110627. #endif
  110628. #endif
  110629. /*** End of inlined file: misc.h ***/
  110630. #ifndef _V_IFDEFJAIL_H_
  110631. # define _V_IFDEFJAIL_H_
  110632. # ifdef __GNUC__
  110633. # define STIN static __inline__
  110634. # elif _WIN32
  110635. # define STIN static __inline
  110636. # else
  110637. # define STIN static
  110638. # endif
  110639. #ifdef DJGPP
  110640. # define rint(x) (floor((x)+0.5f))
  110641. #endif
  110642. #ifndef M_PI
  110643. # define M_PI (3.1415926536f)
  110644. #endif
  110645. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110646. # include <malloc.h>
  110647. # define rint(x) (floor((x)+0.5f))
  110648. # define NO_FLOAT_MATH_LIB
  110649. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110650. #endif
  110651. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110652. void *_alloca(size_t size);
  110653. # define alloca _alloca
  110654. #endif
  110655. #ifndef FAST_HYPOT
  110656. # define FAST_HYPOT hypot
  110657. #endif
  110658. #endif
  110659. #ifdef HAVE_ALLOCA_H
  110660. # include <alloca.h>
  110661. #endif
  110662. #ifdef USE_MEMORY_H
  110663. # include <memory.h>
  110664. #endif
  110665. #ifndef min
  110666. # define min(x,y) ((x)>(y)?(y):(x))
  110667. #endif
  110668. #ifndef max
  110669. # define max(x,y) ((x)<(y)?(y):(x))
  110670. #endif
  110671. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110672. # define VORBIS_FPU_CONTROL
  110673. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110674. Because of encapsulation constraints (GCC can't see inside the asm
  110675. block and so we end up doing stupid things like a store/load that
  110676. is collectively a noop), we do it this way */
  110677. /* we must set up the fpu before this works!! */
  110678. typedef ogg_int16_t vorbis_fpu_control;
  110679. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110680. ogg_int16_t ret;
  110681. ogg_int16_t temp;
  110682. __asm__ __volatile__("fnstcw %0\n\t"
  110683. "movw %0,%%dx\n\t"
  110684. "orw $62463,%%dx\n\t"
  110685. "movw %%dx,%1\n\t"
  110686. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110687. *fpu=ret;
  110688. }
  110689. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110690. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110691. }
  110692. /* assumes the FPU is in round mode! */
  110693. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110694. we get extra fst/fld to
  110695. truncate precision */
  110696. int i;
  110697. __asm__("fistl %0": "=m"(i) : "t"(f));
  110698. return(i);
  110699. }
  110700. #endif
  110701. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110702. # define VORBIS_FPU_CONTROL
  110703. typedef ogg_int16_t vorbis_fpu_control;
  110704. static __inline int vorbis_ftoi(double f){
  110705. int i;
  110706. __asm{
  110707. fld f
  110708. fistp i
  110709. }
  110710. return i;
  110711. }
  110712. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110713. }
  110714. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110715. }
  110716. #endif
  110717. #ifndef VORBIS_FPU_CONTROL
  110718. typedef int vorbis_fpu_control;
  110719. static int vorbis_ftoi(double f){
  110720. return (int)(f+.5);
  110721. }
  110722. /* We don't have special code for this compiler/arch, so do it the slow way */
  110723. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110724. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110725. #endif
  110726. #endif /* _OS_H */
  110727. /*** End of inlined file: os.h ***/
  110728. /* encode side bitrate tracking */
  110729. typedef struct bitrate_manager_state {
  110730. int managed;
  110731. long avg_reservoir;
  110732. long minmax_reservoir;
  110733. long avg_bitsper;
  110734. long min_bitsper;
  110735. long max_bitsper;
  110736. long short_per_long;
  110737. double avgfloat;
  110738. vorbis_block *vb;
  110739. int choice;
  110740. } bitrate_manager_state;
  110741. typedef struct bitrate_manager_info{
  110742. long avg_rate;
  110743. long min_rate;
  110744. long max_rate;
  110745. long reservoir_bits;
  110746. double reservoir_bias;
  110747. double slew_damp;
  110748. } bitrate_manager_info;
  110749. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110750. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110751. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110752. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110753. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110754. #endif
  110755. /*** End of inlined file: bitrate.h ***/
  110756. static int ilog(unsigned int v){
  110757. int ret=0;
  110758. while(v){
  110759. ret++;
  110760. v>>=1;
  110761. }
  110762. return(ret);
  110763. }
  110764. static int ilog2(unsigned int v){
  110765. int ret=0;
  110766. if(v)--v;
  110767. while(v){
  110768. ret++;
  110769. v>>=1;
  110770. }
  110771. return(ret);
  110772. }
  110773. typedef struct private_state {
  110774. /* local lookup storage */
  110775. envelope_lookup *ve; /* envelope lookup */
  110776. int window[2];
  110777. vorbis_look_transform **transform[2]; /* block, type */
  110778. drft_lookup fft_look[2];
  110779. int modebits;
  110780. vorbis_look_floor **flr;
  110781. vorbis_look_residue **residue;
  110782. vorbis_look_psy *psy;
  110783. vorbis_look_psy_global *psy_g_look;
  110784. /* local storage, only used on the encoding side. This way the
  110785. application does not need to worry about freeing some packets'
  110786. memory and not others'; packet storage is always tracked.
  110787. Cleared next call to a _dsp_ function */
  110788. unsigned char *header;
  110789. unsigned char *header1;
  110790. unsigned char *header2;
  110791. bitrate_manager_state bms;
  110792. ogg_int64_t sample_count;
  110793. } private_state;
  110794. /* codec_setup_info contains all the setup information specific to the
  110795. specific compression/decompression mode in progress (eg,
  110796. psychoacoustic settings, channel setup, options, codebook
  110797. etc).
  110798. *********************************************************************/
  110799. /*** Start of inlined file: highlevel.h ***/
  110800. typedef struct highlevel_byblocktype {
  110801. double tone_mask_setting;
  110802. double tone_peaklimit_setting;
  110803. double noise_bias_setting;
  110804. double noise_compand_setting;
  110805. } highlevel_byblocktype;
  110806. typedef struct highlevel_encode_setup {
  110807. void *setup;
  110808. int set_in_stone;
  110809. double base_setting;
  110810. double long_setting;
  110811. double short_setting;
  110812. double impulse_noisetune;
  110813. int managed;
  110814. long bitrate_min;
  110815. long bitrate_av;
  110816. double bitrate_av_damp;
  110817. long bitrate_max;
  110818. long bitrate_reservoir;
  110819. double bitrate_reservoir_bias;
  110820. int impulse_block_p;
  110821. int noise_normalize_p;
  110822. double stereo_point_setting;
  110823. double lowpass_kHz;
  110824. double ath_floating_dB;
  110825. double ath_absolute_dB;
  110826. double amplitude_track_dBpersec;
  110827. double trigger_setting;
  110828. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110829. } highlevel_encode_setup;
  110830. /*** End of inlined file: highlevel.h ***/
  110831. typedef struct codec_setup_info {
  110832. /* Vorbis supports only short and long blocks, but allows the
  110833. encoder to choose the sizes */
  110834. long blocksizes[2];
  110835. /* modes are the primary means of supporting on-the-fly different
  110836. blocksizes, different channel mappings (LR or M/A),
  110837. different residue backends, etc. Each mode consists of a
  110838. blocksize flag and a mapping (along with the mapping setup */
  110839. int modes;
  110840. int maps;
  110841. int floors;
  110842. int residues;
  110843. int books;
  110844. int psys; /* encode only */
  110845. vorbis_info_mode *mode_param[64];
  110846. int map_type[64];
  110847. vorbis_info_mapping *map_param[64];
  110848. int floor_type[64];
  110849. vorbis_info_floor *floor_param[64];
  110850. int residue_type[64];
  110851. vorbis_info_residue *residue_param[64];
  110852. static_codebook *book_param[256];
  110853. codebook *fullbooks;
  110854. vorbis_info_psy *psy_param[4]; /* encode only */
  110855. vorbis_info_psy_global psy_g_param;
  110856. bitrate_manager_info bi;
  110857. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110858. highly redundant structure, but
  110859. improves clarity of program flow. */
  110860. int halfrate_flag; /* painless downsample for decode */
  110861. } codec_setup_info;
  110862. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110863. extern void _vp_global_free(vorbis_look_psy_global *look);
  110864. #endif
  110865. /*** End of inlined file: codec_internal.h ***/
  110866. /*** Start of inlined file: registry.h ***/
  110867. #ifndef _V_REG_H_
  110868. #define _V_REG_H_
  110869. #define VI_TRANSFORMB 1
  110870. #define VI_WINDOWB 1
  110871. #define VI_TIMEB 1
  110872. #define VI_FLOORB 2
  110873. #define VI_RESB 3
  110874. #define VI_MAPB 1
  110875. extern vorbis_func_floor *_floor_P[];
  110876. extern vorbis_func_residue *_residue_P[];
  110877. extern vorbis_func_mapping *_mapping_P[];
  110878. #endif
  110879. /*** End of inlined file: registry.h ***/
  110880. /*** Start of inlined file: scales.h ***/
  110881. #ifndef _V_SCALES_H_
  110882. #define _V_SCALES_H_
  110883. #include <math.h>
  110884. /* 20log10(x) */
  110885. #define VORBIS_IEEE_FLOAT32 1
  110886. #ifdef VORBIS_IEEE_FLOAT32
  110887. static float unitnorm(float x){
  110888. union {
  110889. ogg_uint32_t i;
  110890. float f;
  110891. } ix;
  110892. ix.f = x;
  110893. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110894. return ix.f;
  110895. }
  110896. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110897. static float todB(const float *x){
  110898. union {
  110899. ogg_uint32_t i;
  110900. float f;
  110901. } ix;
  110902. ix.f = *x;
  110903. ix.i = ix.i&0x7fffffff;
  110904. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110905. }
  110906. #define todB_nn(x) todB(x)
  110907. #else
  110908. static float unitnorm(float x){
  110909. if(x<0)return(-1.f);
  110910. return(1.f);
  110911. }
  110912. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110913. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110914. #endif
  110915. #define fromdB(x) (exp((x)*.11512925f))
  110916. /* The bark scale equations are approximations, since the original
  110917. table was somewhat hand rolled. The below are chosen to have the
  110918. best possible fit to the rolled tables, thus their somewhat odd
  110919. appearance (these are more accurate and over a longer range than
  110920. the oft-quoted bark equations found in the texts I have). The
  110921. approximations are valid from 0 - 30kHz (nyquist) or so.
  110922. all f in Hz, z in Bark */
  110923. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110924. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110925. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110926. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110927. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110928. 0.0 */
  110929. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110930. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110931. #endif
  110932. /*** End of inlined file: scales.h ***/
  110933. int analysis_noisy=1;
  110934. /* decides between modes, dispatches to the appropriate mapping. */
  110935. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110936. int ret,i;
  110937. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110938. vb->glue_bits=0;
  110939. vb->time_bits=0;
  110940. vb->floor_bits=0;
  110941. vb->res_bits=0;
  110942. /* first things first. Make sure encode is ready */
  110943. for(i=0;i<PACKETBLOBS;i++)
  110944. oggpack_reset(vbi->packetblob[i]);
  110945. /* we only have one mapping type (0), and we let the mapping code
  110946. itself figure out what soft mode to use. This allows easier
  110947. bitrate management */
  110948. if((ret=_mapping_P[0]->forward(vb)))
  110949. return(ret);
  110950. if(op){
  110951. if(vorbis_bitrate_managed(vb))
  110952. /* The app is using a bitmanaged mode... but not using the
  110953. bitrate management interface. */
  110954. return(OV_EINVAL);
  110955. op->packet=oggpack_get_buffer(&vb->opb);
  110956. op->bytes=oggpack_bytes(&vb->opb);
  110957. op->b_o_s=0;
  110958. op->e_o_s=vb->eofflag;
  110959. op->granulepos=vb->granulepos;
  110960. op->packetno=vb->sequence; /* for sake of completeness */
  110961. }
  110962. return(0);
  110963. }
  110964. /* there was no great place to put this.... */
  110965. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110966. int j;
  110967. FILE *of;
  110968. char buffer[80];
  110969. /* if(i==5870){*/
  110970. sprintf(buffer,"%s_%d.m",base,i);
  110971. of=fopen(buffer,"w");
  110972. if(!of)perror("failed to open data dump file");
  110973. for(j=0;j<n;j++){
  110974. if(bark){
  110975. float b=toBARK((4000.f*j/n)+.25);
  110976. fprintf(of,"%f ",b);
  110977. }else
  110978. if(off!=0)
  110979. fprintf(of,"%f ",(double)(j+off)/8000.);
  110980. else
  110981. fprintf(of,"%f ",(double)j);
  110982. if(dB){
  110983. float val;
  110984. if(v[j]==0.)
  110985. val=-140.;
  110986. else
  110987. val=todB(v+j);
  110988. fprintf(of,"%f\n",val);
  110989. }else{
  110990. fprintf(of,"%f\n",v[j]);
  110991. }
  110992. }
  110993. fclose(of);
  110994. /* } */
  110995. }
  110996. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110997. ogg_int64_t off){
  110998. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110999. }
  111000. #endif
  111001. /*** End of inlined file: analysis.c ***/
  111002. /*** Start of inlined file: bitrate.c ***/
  111003. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111004. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111005. // tasks..
  111006. #if JUCE_MSVC
  111007. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111008. #endif
  111009. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111010. #if JUCE_USE_OGGVORBIS
  111011. #include <stdlib.h>
  111012. #include <string.h>
  111013. #include <math.h>
  111014. /* compute bitrate tracking setup */
  111015. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  111016. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111017. bitrate_manager_info *bi=&ci->bi;
  111018. memset(bm,0,sizeof(*bm));
  111019. if(bi && (bi->reservoir_bits>0)){
  111020. long ratesamples=vi->rate;
  111021. int halfsamples=ci->blocksizes[0]>>1;
  111022. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  111023. bm->managed=1;
  111024. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  111025. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  111026. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  111027. bm->avgfloat=PACKETBLOBS/2;
  111028. /* not a necessary fix, but one that leads to a more balanced
  111029. typical initialization */
  111030. {
  111031. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111032. bm->minmax_reservoir=desired_fill;
  111033. bm->avg_reservoir=desired_fill;
  111034. }
  111035. }
  111036. }
  111037. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  111038. memset(bm,0,sizeof(*bm));
  111039. return;
  111040. }
  111041. int vorbis_bitrate_managed(vorbis_block *vb){
  111042. vorbis_dsp_state *vd=vb->vd;
  111043. private_state *b=(private_state*)vd->backend_state;
  111044. bitrate_manager_state *bm=&b->bms;
  111045. if(bm && bm->managed)return(1);
  111046. return(0);
  111047. }
  111048. /* finish taking in the block we just processed */
  111049. int vorbis_bitrate_addblock(vorbis_block *vb){
  111050. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111051. vorbis_dsp_state *vd=vb->vd;
  111052. private_state *b=(private_state*)vd->backend_state;
  111053. bitrate_manager_state *bm=&b->bms;
  111054. vorbis_info *vi=vd->vi;
  111055. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111056. bitrate_manager_info *bi=&ci->bi;
  111057. int choice=rint(bm->avgfloat);
  111058. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111059. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  111060. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  111061. int samples=ci->blocksizes[vb->W]>>1;
  111062. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111063. if(!bm->managed){
  111064. /* not a bitrate managed stream, but for API simplicity, we'll
  111065. buffer the packet to keep the code path clean */
  111066. if(bm->vb)return(-1); /* one has been submitted without
  111067. being claimed */
  111068. bm->vb=vb;
  111069. return(0);
  111070. }
  111071. bm->vb=vb;
  111072. /* look ahead for avg floater */
  111073. if(bm->avg_bitsper>0){
  111074. double slew=0.;
  111075. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111076. double slewlimit= 15./bi->slew_damp;
  111077. /* choosing a new floater:
  111078. if we're over target, we slew down
  111079. if we're under target, we slew up
  111080. choose slew as follows: look through packetblobs of this frame
  111081. and set slew as the first in the appropriate direction that
  111082. gives us the slew we want. This may mean no slew if delta is
  111083. already favorable.
  111084. Then limit slew to slew max */
  111085. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111086. while(choice>0 && this_bits>avg_target_bits &&
  111087. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111088. choice--;
  111089. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111090. }
  111091. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111092. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  111093. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111094. choice++;
  111095. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111096. }
  111097. }
  111098. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  111099. if(slew<-slewlimit)slew=-slewlimit;
  111100. if(slew>slewlimit)slew=slewlimit;
  111101. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  111102. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111103. }
  111104. /* enforce min(if used) on the current floater (if used) */
  111105. if(bm->min_bitsper>0){
  111106. /* do we need to force the bitrate up? */
  111107. if(this_bits<min_target_bits){
  111108. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  111109. choice++;
  111110. if(choice>=PACKETBLOBS)break;
  111111. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111112. }
  111113. }
  111114. }
  111115. /* enforce max (if used) on the current floater (if used) */
  111116. if(bm->max_bitsper>0){
  111117. /* do we need to force the bitrate down? */
  111118. if(this_bits>max_target_bits){
  111119. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  111120. choice--;
  111121. if(choice<0)break;
  111122. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111123. }
  111124. }
  111125. }
  111126. /* Choice of packetblobs now made based on floater, and min/max
  111127. requirements. Now boundary check extreme choices */
  111128. if(choice<0){
  111129. /* choosing a smaller packetblob is insufficient to trim bitrate.
  111130. frame will need to be truncated */
  111131. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  111132. bm->choice=choice=0;
  111133. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  111134. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  111135. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111136. }
  111137. }else{
  111138. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  111139. if(choice>=PACKETBLOBS)
  111140. choice=PACKETBLOBS-1;
  111141. bm->choice=choice;
  111142. /* prop up bitrate according to demand. pad this frame out with zeroes */
  111143. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  111144. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  111145. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111146. }
  111147. /* now we have the final packet and the final packet size. Update statistics */
  111148. /* min and max reservoir */
  111149. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  111150. if(max_target_bits>0 && this_bits>max_target_bits){
  111151. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111152. }else if(min_target_bits>0 && this_bits<min_target_bits){
  111153. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111154. }else{
  111155. /* inbetween; we want to take reservoir toward but not past desired_fill */
  111156. if(bm->minmax_reservoir>desired_fill){
  111157. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  111158. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111159. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  111160. }else{
  111161. bm->minmax_reservoir=desired_fill;
  111162. }
  111163. }else{
  111164. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  111165. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111166. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  111167. }else{
  111168. bm->minmax_reservoir=desired_fill;
  111169. }
  111170. }
  111171. }
  111172. }
  111173. /* avg reservoir */
  111174. if(bm->avg_bitsper>0){
  111175. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111176. bm->avg_reservoir+=this_bits-avg_target_bits;
  111177. }
  111178. return(0);
  111179. }
  111180. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  111181. private_state *b=(private_state*)vd->backend_state;
  111182. bitrate_manager_state *bm=&b->bms;
  111183. vorbis_block *vb=bm->vb;
  111184. int choice=PACKETBLOBS/2;
  111185. if(!vb)return 0;
  111186. if(op){
  111187. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111188. if(vorbis_bitrate_managed(vb))
  111189. choice=bm->choice;
  111190. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  111191. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  111192. op->b_o_s=0;
  111193. op->e_o_s=vb->eofflag;
  111194. op->granulepos=vb->granulepos;
  111195. op->packetno=vb->sequence; /* for sake of completeness */
  111196. }
  111197. bm->vb=0;
  111198. return(1);
  111199. }
  111200. #endif
  111201. /*** End of inlined file: bitrate.c ***/
  111202. /*** Start of inlined file: block.c ***/
  111203. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111204. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111205. // tasks..
  111206. #if JUCE_MSVC
  111207. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111208. #endif
  111209. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111210. #if JUCE_USE_OGGVORBIS
  111211. #include <stdio.h>
  111212. #include <stdlib.h>
  111213. #include <string.h>
  111214. /*** Start of inlined file: window.h ***/
  111215. #ifndef _V_WINDOW_
  111216. #define _V_WINDOW_
  111217. extern float *_vorbis_window_get(int n);
  111218. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111219. int lW,int W,int nW);
  111220. #endif
  111221. /*** End of inlined file: window.h ***/
  111222. /*** Start of inlined file: lpc.h ***/
  111223. #ifndef _V_LPC_H_
  111224. #define _V_LPC_H_
  111225. /* simple linear scale LPC code */
  111226. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111227. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111228. float *data,long n);
  111229. #endif
  111230. /*** End of inlined file: lpc.h ***/
  111231. /* pcm accumulator examples (not exhaustive):
  111232. <-------------- lW ---------------->
  111233. <--------------- W ---------------->
  111234. : .....|..... _______________ |
  111235. : .''' | '''_--- | |\ |
  111236. :.....''' |_____--- '''......| | \_______|
  111237. :.................|__________________|_______|__|______|
  111238. |<------ Sl ------>| > Sr < |endW
  111239. |beginSl |endSl | |endSr
  111240. |beginW |endlW |beginSr
  111241. |< lW >|
  111242. <--------------- W ---------------->
  111243. | | .. ______________ |
  111244. | | ' `/ | ---_ |
  111245. |___.'___/`. | ---_____|
  111246. |_______|__|_______|_________________|
  111247. | >|Sl|< |<------ Sr ----->|endW
  111248. | | |endSl |beginSr |endSr
  111249. |beginW | |endlW
  111250. mult[0] |beginSl mult[n]
  111251. <-------------- lW ----------------->
  111252. |<--W-->|
  111253. : .............. ___ | |
  111254. : .''' |`/ \ | |
  111255. :.....''' |/`....\|...|
  111256. :.........................|___|___|___|
  111257. |Sl |Sr |endW
  111258. | | |endSr
  111259. | |beginSr
  111260. | |endSl
  111261. |beginSl
  111262. |beginW
  111263. */
  111264. /* block abstraction setup *********************************************/
  111265. #ifndef WORD_ALIGN
  111266. #define WORD_ALIGN 8
  111267. #endif
  111268. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111269. int i;
  111270. memset(vb,0,sizeof(*vb));
  111271. vb->vd=v;
  111272. vb->localalloc=0;
  111273. vb->localstore=NULL;
  111274. if(v->analysisp){
  111275. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111276. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111277. vbi->ampmax=-9999;
  111278. for(i=0;i<PACKETBLOBS;i++){
  111279. if(i==PACKETBLOBS/2){
  111280. vbi->packetblob[i]=&vb->opb;
  111281. }else{
  111282. vbi->packetblob[i]=
  111283. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111284. }
  111285. oggpack_writeinit(vbi->packetblob[i]);
  111286. }
  111287. }
  111288. return(0);
  111289. }
  111290. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111291. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111292. if(bytes+vb->localtop>vb->localalloc){
  111293. /* can't just _ogg_realloc... there are outstanding pointers */
  111294. if(vb->localstore){
  111295. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111296. vb->totaluse+=vb->localtop;
  111297. link->next=vb->reap;
  111298. link->ptr=vb->localstore;
  111299. vb->reap=link;
  111300. }
  111301. /* highly conservative */
  111302. vb->localalloc=bytes;
  111303. vb->localstore=_ogg_malloc(vb->localalloc);
  111304. vb->localtop=0;
  111305. }
  111306. {
  111307. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111308. vb->localtop+=bytes;
  111309. return ret;
  111310. }
  111311. }
  111312. /* reap the chain, pull the ripcord */
  111313. void _vorbis_block_ripcord(vorbis_block *vb){
  111314. /* reap the chain */
  111315. struct alloc_chain *reap=vb->reap;
  111316. while(reap){
  111317. struct alloc_chain *next=reap->next;
  111318. _ogg_free(reap->ptr);
  111319. memset(reap,0,sizeof(*reap));
  111320. _ogg_free(reap);
  111321. reap=next;
  111322. }
  111323. /* consolidate storage */
  111324. if(vb->totaluse){
  111325. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111326. vb->localalloc+=vb->totaluse;
  111327. vb->totaluse=0;
  111328. }
  111329. /* pull the ripcord */
  111330. vb->localtop=0;
  111331. vb->reap=NULL;
  111332. }
  111333. int vorbis_block_clear(vorbis_block *vb){
  111334. int i;
  111335. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111336. _vorbis_block_ripcord(vb);
  111337. if(vb->localstore)_ogg_free(vb->localstore);
  111338. if(vbi){
  111339. for(i=0;i<PACKETBLOBS;i++){
  111340. oggpack_writeclear(vbi->packetblob[i]);
  111341. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111342. }
  111343. _ogg_free(vbi);
  111344. }
  111345. memset(vb,0,sizeof(*vb));
  111346. return(0);
  111347. }
  111348. /* Analysis side code, but directly related to blocking. Thus it's
  111349. here and not in analysis.c (which is for analysis transforms only).
  111350. The init is here because some of it is shared */
  111351. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111352. int i;
  111353. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111354. private_state *b=NULL;
  111355. int hs;
  111356. if(ci==NULL) return 1;
  111357. hs=ci->halfrate_flag;
  111358. memset(v,0,sizeof(*v));
  111359. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111360. v->vi=vi;
  111361. b->modebits=ilog2(ci->modes);
  111362. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111363. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111364. /* MDCT is tranform 0 */
  111365. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111366. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111367. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111368. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111369. /* Vorbis I uses only window type 0 */
  111370. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111371. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111372. if(encp){ /* encode/decode differ here */
  111373. /* analysis always needs an fft */
  111374. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111375. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111376. /* finish the codebooks */
  111377. if(!ci->fullbooks){
  111378. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111379. for(i=0;i<ci->books;i++)
  111380. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111381. }
  111382. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111383. for(i=0;i<ci->psys;i++){
  111384. _vp_psy_init(b->psy+i,
  111385. ci->psy_param[i],
  111386. &ci->psy_g_param,
  111387. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111388. vi->rate);
  111389. }
  111390. v->analysisp=1;
  111391. }else{
  111392. /* finish the codebooks */
  111393. if(!ci->fullbooks){
  111394. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111395. for(i=0;i<ci->books;i++){
  111396. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111397. /* decode codebooks are now standalone after init */
  111398. vorbis_staticbook_destroy(ci->book_param[i]);
  111399. ci->book_param[i]=NULL;
  111400. }
  111401. }
  111402. }
  111403. /* initialize the storage vectors. blocksize[1] is small for encode,
  111404. but the correct size for decode */
  111405. v->pcm_storage=ci->blocksizes[1];
  111406. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111407. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111408. {
  111409. int i;
  111410. for(i=0;i<vi->channels;i++)
  111411. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111412. }
  111413. /* all 1 (large block) or 0 (small block) */
  111414. /* explicitly set for the sake of clarity */
  111415. v->lW=0; /* previous window size */
  111416. v->W=0; /* current window size */
  111417. /* all vector indexes */
  111418. v->centerW=ci->blocksizes[1]/2;
  111419. v->pcm_current=v->centerW;
  111420. /* initialize all the backend lookups */
  111421. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111422. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111423. for(i=0;i<ci->floors;i++)
  111424. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111425. look(v,ci->floor_param[i]);
  111426. for(i=0;i<ci->residues;i++)
  111427. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111428. look(v,ci->residue_param[i]);
  111429. return 0;
  111430. }
  111431. /* arbitrary settings and spec-mandated numbers get filled in here */
  111432. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111433. private_state *b=NULL;
  111434. if(_vds_shared_init(v,vi,1))return 1;
  111435. b=(private_state*)v->backend_state;
  111436. b->psy_g_look=_vp_global_look(vi);
  111437. /* Initialize the envelope state storage */
  111438. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111439. _ve_envelope_init(b->ve,vi);
  111440. vorbis_bitrate_init(vi,&b->bms);
  111441. /* compressed audio packets start after the headers
  111442. with sequence number 3 */
  111443. v->sequence=3;
  111444. return(0);
  111445. }
  111446. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111447. int i;
  111448. if(v){
  111449. vorbis_info *vi=v->vi;
  111450. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111451. private_state *b=(private_state*)v->backend_state;
  111452. if(b){
  111453. if(b->ve){
  111454. _ve_envelope_clear(b->ve);
  111455. _ogg_free(b->ve);
  111456. }
  111457. if(b->transform[0]){
  111458. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111459. _ogg_free(b->transform[0][0]);
  111460. _ogg_free(b->transform[0]);
  111461. }
  111462. if(b->transform[1]){
  111463. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111464. _ogg_free(b->transform[1][0]);
  111465. _ogg_free(b->transform[1]);
  111466. }
  111467. if(b->flr){
  111468. for(i=0;i<ci->floors;i++)
  111469. _floor_P[ci->floor_type[i]]->
  111470. free_look(b->flr[i]);
  111471. _ogg_free(b->flr);
  111472. }
  111473. if(b->residue){
  111474. for(i=0;i<ci->residues;i++)
  111475. _residue_P[ci->residue_type[i]]->
  111476. free_look(b->residue[i]);
  111477. _ogg_free(b->residue);
  111478. }
  111479. if(b->psy){
  111480. for(i=0;i<ci->psys;i++)
  111481. _vp_psy_clear(b->psy+i);
  111482. _ogg_free(b->psy);
  111483. }
  111484. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111485. vorbis_bitrate_clear(&b->bms);
  111486. drft_clear(&b->fft_look[0]);
  111487. drft_clear(&b->fft_look[1]);
  111488. }
  111489. if(v->pcm){
  111490. for(i=0;i<vi->channels;i++)
  111491. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111492. _ogg_free(v->pcm);
  111493. if(v->pcmret)_ogg_free(v->pcmret);
  111494. }
  111495. if(b){
  111496. /* free header, header1, header2 */
  111497. if(b->header)_ogg_free(b->header);
  111498. if(b->header1)_ogg_free(b->header1);
  111499. if(b->header2)_ogg_free(b->header2);
  111500. _ogg_free(b);
  111501. }
  111502. memset(v,0,sizeof(*v));
  111503. }
  111504. }
  111505. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111506. int i;
  111507. vorbis_info *vi=v->vi;
  111508. private_state *b=(private_state*)v->backend_state;
  111509. /* free header, header1, header2 */
  111510. if(b->header)_ogg_free(b->header);b->header=NULL;
  111511. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111512. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111513. /* Do we have enough storage space for the requested buffer? If not,
  111514. expand the PCM (and envelope) storage */
  111515. if(v->pcm_current+vals>=v->pcm_storage){
  111516. v->pcm_storage=v->pcm_current+vals*2;
  111517. for(i=0;i<vi->channels;i++){
  111518. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111519. }
  111520. }
  111521. for(i=0;i<vi->channels;i++)
  111522. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111523. return(v->pcmret);
  111524. }
  111525. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111526. int i;
  111527. int order=32;
  111528. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111529. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111530. long j;
  111531. v->preextrapolate=1;
  111532. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111533. for(i=0;i<v->vi->channels;i++){
  111534. /* need to run the extrapolation in reverse! */
  111535. for(j=0;j<v->pcm_current;j++)
  111536. work[j]=v->pcm[i][v->pcm_current-j-1];
  111537. /* prime as above */
  111538. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111539. /* run the predictor filter */
  111540. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111541. order,
  111542. work+v->pcm_current-v->centerW,
  111543. v->centerW);
  111544. for(j=0;j<v->pcm_current;j++)
  111545. v->pcm[i][v->pcm_current-j-1]=work[j];
  111546. }
  111547. }
  111548. }
  111549. /* call with val<=0 to set eof */
  111550. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111551. vorbis_info *vi=v->vi;
  111552. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111553. if(vals<=0){
  111554. int order=32;
  111555. int i;
  111556. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111557. /* if it wasn't done earlier (very short sample) */
  111558. if(!v->preextrapolate)
  111559. _preextrapolate_helper(v);
  111560. /* We're encoding the end of the stream. Just make sure we have
  111561. [at least] a few full blocks of zeroes at the end. */
  111562. /* actually, we don't want zeroes; that could drop a large
  111563. amplitude off a cliff, creating spread spectrum noise that will
  111564. suck to encode. Extrapolate for the sake of cleanliness. */
  111565. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111566. v->eofflag=v->pcm_current;
  111567. v->pcm_current+=ci->blocksizes[1]*3;
  111568. for(i=0;i<vi->channels;i++){
  111569. if(v->eofflag>order*2){
  111570. /* extrapolate with LPC to fill in */
  111571. long n;
  111572. /* make a predictor filter */
  111573. n=v->eofflag;
  111574. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111575. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111576. /* run the predictor filter */
  111577. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111578. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111579. }else{
  111580. /* not enough data to extrapolate (unlikely to happen due to
  111581. guarding the overlap, but bulletproof in case that
  111582. assumtion goes away). zeroes will do. */
  111583. memset(v->pcm[i]+v->eofflag,0,
  111584. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111585. }
  111586. }
  111587. }else{
  111588. if(v->pcm_current+vals>v->pcm_storage)
  111589. return(OV_EINVAL);
  111590. v->pcm_current+=vals;
  111591. /* we may want to reverse extrapolate the beginning of a stream
  111592. too... in case we're beginning on a cliff! */
  111593. /* clumsy, but simple. It only runs once, so simple is good. */
  111594. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111595. _preextrapolate_helper(v);
  111596. }
  111597. return(0);
  111598. }
  111599. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111600. the next block on which to continue analysis */
  111601. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111602. int i;
  111603. vorbis_info *vi=v->vi;
  111604. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111605. private_state *b=(private_state*)v->backend_state;
  111606. vorbis_look_psy_global *g=b->psy_g_look;
  111607. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111608. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111609. /* check to see if we're started... */
  111610. if(!v->preextrapolate)return(0);
  111611. /* check to see if we're done... */
  111612. if(v->eofflag==-1)return(0);
  111613. /* By our invariant, we have lW, W and centerW set. Search for
  111614. the next boundary so we can determine nW (the next window size)
  111615. which lets us compute the shape of the current block's window */
  111616. /* we do an envelope search even on a single blocksize; we may still
  111617. be throwing more bits at impulses, and envelope search handles
  111618. marking impulses too. */
  111619. {
  111620. long bp=_ve_envelope_search(v);
  111621. if(bp==-1){
  111622. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111623. full long block */
  111624. v->nW=0;
  111625. }else{
  111626. if(ci->blocksizes[0]==ci->blocksizes[1])
  111627. v->nW=0;
  111628. else
  111629. v->nW=bp;
  111630. }
  111631. }
  111632. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111633. {
  111634. /* center of next block + next block maximum right side. */
  111635. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111636. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111637. although this check is
  111638. less strict that the
  111639. _ve_envelope_search,
  111640. the search is not run
  111641. if we only use one
  111642. block size */
  111643. }
  111644. /* fill in the block. Note that for a short window, lW and nW are *short*
  111645. regardless of actual settings in the stream */
  111646. _vorbis_block_ripcord(vb);
  111647. vb->lW=v->lW;
  111648. vb->W=v->W;
  111649. vb->nW=v->nW;
  111650. if(v->W){
  111651. if(!v->lW || !v->nW){
  111652. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111653. /*fprintf(stderr,"-");*/
  111654. }else{
  111655. vbi->blocktype=BLOCKTYPE_LONG;
  111656. /*fprintf(stderr,"_");*/
  111657. }
  111658. }else{
  111659. if(_ve_envelope_mark(v)){
  111660. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111661. /*fprintf(stderr,"|");*/
  111662. }else{
  111663. vbi->blocktype=BLOCKTYPE_PADDING;
  111664. /*fprintf(stderr,".");*/
  111665. }
  111666. }
  111667. vb->vd=v;
  111668. vb->sequence=v->sequence++;
  111669. vb->granulepos=v->granulepos;
  111670. vb->pcmend=ci->blocksizes[v->W];
  111671. /* copy the vectors; this uses the local storage in vb */
  111672. /* this tracks 'strongest peak' for later psychoacoustics */
  111673. /* moved to the global psy state; clean this mess up */
  111674. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111675. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111676. vbi->ampmax=g->ampmax;
  111677. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111678. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111679. for(i=0;i<vi->channels;i++){
  111680. vbi->pcmdelay[i]=
  111681. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111682. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111683. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111684. /* before we added the delay
  111685. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111686. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111687. */
  111688. }
  111689. /* handle eof detection: eof==0 means that we've not yet received EOF
  111690. eof>0 marks the last 'real' sample in pcm[]
  111691. eof<0 'no more to do'; doesn't get here */
  111692. if(v->eofflag){
  111693. if(v->centerW>=v->eofflag){
  111694. v->eofflag=-1;
  111695. vb->eofflag=1;
  111696. return(1);
  111697. }
  111698. }
  111699. /* advance storage vectors and clean up */
  111700. {
  111701. int new_centerNext=ci->blocksizes[1]/2;
  111702. int movementW=centerNext-new_centerNext;
  111703. if(movementW>0){
  111704. _ve_envelope_shift(b->ve,movementW);
  111705. v->pcm_current-=movementW;
  111706. for(i=0;i<vi->channels;i++)
  111707. memmove(v->pcm[i],v->pcm[i]+movementW,
  111708. v->pcm_current*sizeof(*v->pcm[i]));
  111709. v->lW=v->W;
  111710. v->W=v->nW;
  111711. v->centerW=new_centerNext;
  111712. if(v->eofflag){
  111713. v->eofflag-=movementW;
  111714. if(v->eofflag<=0)v->eofflag=-1;
  111715. /* do not add padding to end of stream! */
  111716. if(v->centerW>=v->eofflag){
  111717. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111718. }else{
  111719. v->granulepos+=movementW;
  111720. }
  111721. }else{
  111722. v->granulepos+=movementW;
  111723. }
  111724. }
  111725. }
  111726. /* done */
  111727. return(1);
  111728. }
  111729. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111730. vorbis_info *vi=v->vi;
  111731. codec_setup_info *ci;
  111732. int hs;
  111733. if(!v->backend_state)return -1;
  111734. if(!vi)return -1;
  111735. ci=(codec_setup_info*) vi->codec_setup;
  111736. if(!ci)return -1;
  111737. hs=ci->halfrate_flag;
  111738. v->centerW=ci->blocksizes[1]>>(hs+1);
  111739. v->pcm_current=v->centerW>>hs;
  111740. v->pcm_returned=-1;
  111741. v->granulepos=-1;
  111742. v->sequence=-1;
  111743. v->eofflag=0;
  111744. ((private_state *)(v->backend_state))->sample_count=-1;
  111745. return(0);
  111746. }
  111747. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111748. if(_vds_shared_init(v,vi,0)) return 1;
  111749. vorbis_synthesis_restart(v);
  111750. return 0;
  111751. }
  111752. /* Unlike in analysis, the window is only partially applied for each
  111753. block. The time domain envelope is not yet handled at the point of
  111754. calling (as it relies on the previous block). */
  111755. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111756. vorbis_info *vi=v->vi;
  111757. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111758. private_state *b=(private_state*)v->backend_state;
  111759. int hs=ci->halfrate_flag;
  111760. int i,j;
  111761. if(!vb)return(OV_EINVAL);
  111762. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111763. v->lW=v->W;
  111764. v->W=vb->W;
  111765. v->nW=-1;
  111766. if((v->sequence==-1)||
  111767. (v->sequence+1 != vb->sequence)){
  111768. v->granulepos=-1; /* out of sequence; lose count */
  111769. b->sample_count=-1;
  111770. }
  111771. v->sequence=vb->sequence;
  111772. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111773. was called on block */
  111774. int n=ci->blocksizes[v->W]>>(hs+1);
  111775. int n0=ci->blocksizes[0]>>(hs+1);
  111776. int n1=ci->blocksizes[1]>>(hs+1);
  111777. int thisCenter;
  111778. int prevCenter;
  111779. v->glue_bits+=vb->glue_bits;
  111780. v->time_bits+=vb->time_bits;
  111781. v->floor_bits+=vb->floor_bits;
  111782. v->res_bits+=vb->res_bits;
  111783. if(v->centerW){
  111784. thisCenter=n1;
  111785. prevCenter=0;
  111786. }else{
  111787. thisCenter=0;
  111788. prevCenter=n1;
  111789. }
  111790. /* v->pcm is now used like a two-stage double buffer. We don't want
  111791. to have to constantly shift *or* adjust memory usage. Don't
  111792. accept a new block until the old is shifted out */
  111793. for(j=0;j<vi->channels;j++){
  111794. /* the overlap/add section */
  111795. if(v->lW){
  111796. if(v->W){
  111797. /* large/large */
  111798. float *w=_vorbis_window_get(b->window[1]-hs);
  111799. float *pcm=v->pcm[j]+prevCenter;
  111800. float *p=vb->pcm[j];
  111801. for(i=0;i<n1;i++)
  111802. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111803. }else{
  111804. /* large/small */
  111805. float *w=_vorbis_window_get(b->window[0]-hs);
  111806. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111807. float *p=vb->pcm[j];
  111808. for(i=0;i<n0;i++)
  111809. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111810. }
  111811. }else{
  111812. if(v->W){
  111813. /* small/large */
  111814. float *w=_vorbis_window_get(b->window[0]-hs);
  111815. float *pcm=v->pcm[j]+prevCenter;
  111816. float *p=vb->pcm[j]+n1/2-n0/2;
  111817. for(i=0;i<n0;i++)
  111818. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111819. for(;i<n1/2+n0/2;i++)
  111820. pcm[i]=p[i];
  111821. }else{
  111822. /* small/small */
  111823. float *w=_vorbis_window_get(b->window[0]-hs);
  111824. float *pcm=v->pcm[j]+prevCenter;
  111825. float *p=vb->pcm[j];
  111826. for(i=0;i<n0;i++)
  111827. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111828. }
  111829. }
  111830. /* the copy section */
  111831. {
  111832. float *pcm=v->pcm[j]+thisCenter;
  111833. float *p=vb->pcm[j]+n;
  111834. for(i=0;i<n;i++)
  111835. pcm[i]=p[i];
  111836. }
  111837. }
  111838. if(v->centerW)
  111839. v->centerW=0;
  111840. else
  111841. v->centerW=n1;
  111842. /* deal with initial packet state; we do this using the explicit
  111843. pcm_returned==-1 flag otherwise we're sensitive to first block
  111844. being short or long */
  111845. if(v->pcm_returned==-1){
  111846. v->pcm_returned=thisCenter;
  111847. v->pcm_current=thisCenter;
  111848. }else{
  111849. v->pcm_returned=prevCenter;
  111850. v->pcm_current=prevCenter+
  111851. ((ci->blocksizes[v->lW]/4+
  111852. ci->blocksizes[v->W]/4)>>hs);
  111853. }
  111854. }
  111855. /* track the frame number... This is for convenience, but also
  111856. making sure our last packet doesn't end with added padding. If
  111857. the last packet is partial, the number of samples we'll have to
  111858. return will be past the vb->granulepos.
  111859. This is not foolproof! It will be confused if we begin
  111860. decoding at the last page after a seek or hole. In that case,
  111861. we don't have a starting point to judge where the last frame
  111862. is. For this reason, vorbisfile will always try to make sure
  111863. it reads the last two marked pages in proper sequence */
  111864. if(b->sample_count==-1){
  111865. b->sample_count=0;
  111866. }else{
  111867. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111868. }
  111869. if(v->granulepos==-1){
  111870. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111871. v->granulepos=vb->granulepos;
  111872. /* is this a short page? */
  111873. if(b->sample_count>v->granulepos){
  111874. /* corner case; if this is both the first and last audio page,
  111875. then spec says the end is cut, not beginning */
  111876. if(vb->eofflag){
  111877. /* trim the end */
  111878. /* no preceeding granulepos; assume we started at zero (we'd
  111879. have to in a short single-page stream) */
  111880. /* granulepos could be -1 due to a seek, but that would result
  111881. in a long count, not short count */
  111882. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111883. }else{
  111884. /* trim the beginning */
  111885. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111886. if(v->pcm_returned>v->pcm_current)
  111887. v->pcm_returned=v->pcm_current;
  111888. }
  111889. }
  111890. }
  111891. }else{
  111892. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111893. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111894. if(v->granulepos>vb->granulepos){
  111895. long extra=v->granulepos-vb->granulepos;
  111896. if(extra)
  111897. if(vb->eofflag){
  111898. /* partial last frame. Strip the extra samples off */
  111899. v->pcm_current-=extra>>hs;
  111900. } /* else {Shouldn't happen *unless* the bitstream is out of
  111901. spec. Either way, believe the bitstream } */
  111902. } /* else {Shouldn't happen *unless* the bitstream is out of
  111903. spec. Either way, believe the bitstream } */
  111904. v->granulepos=vb->granulepos;
  111905. }
  111906. }
  111907. /* Update, cleanup */
  111908. if(vb->eofflag)v->eofflag=1;
  111909. return(0);
  111910. }
  111911. /* pcm==NULL indicates we just want the pending samples, no more */
  111912. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111913. vorbis_info *vi=v->vi;
  111914. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111915. if(pcm){
  111916. int i;
  111917. for(i=0;i<vi->channels;i++)
  111918. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111919. *pcm=v->pcmret;
  111920. }
  111921. return(v->pcm_current-v->pcm_returned);
  111922. }
  111923. return(0);
  111924. }
  111925. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111926. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111927. v->pcm_returned+=n;
  111928. return(0);
  111929. }
  111930. /* intended for use with a specific vorbisfile feature; we want access
  111931. to the [usually synthetic/postextrapolated] buffer and lapping at
  111932. the end of a decode cycle, specifically, a half-short-block worth.
  111933. This funtion works like pcmout above, except it will also expose
  111934. this implicit buffer data not normally decoded. */
  111935. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111936. vorbis_info *vi=v->vi;
  111937. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111938. int hs=ci->halfrate_flag;
  111939. int n=ci->blocksizes[v->W]>>(hs+1);
  111940. int n0=ci->blocksizes[0]>>(hs+1);
  111941. int n1=ci->blocksizes[1]>>(hs+1);
  111942. int i,j;
  111943. if(v->pcm_returned<0)return 0;
  111944. /* our returned data ends at pcm_returned; because the synthesis pcm
  111945. buffer is a two-fragment ring, that means our data block may be
  111946. fragmented by buffering, wrapping or a short block not filling
  111947. out a buffer. To simplify things, we unfragment if it's at all
  111948. possibly needed. Otherwise, we'd need to call lapout more than
  111949. once as well as hold additional dsp state. Opt for
  111950. simplicity. */
  111951. /* centerW was advanced by blockin; it would be the center of the
  111952. *next* block */
  111953. if(v->centerW==n1){
  111954. /* the data buffer wraps; swap the halves */
  111955. /* slow, sure, small */
  111956. for(j=0;j<vi->channels;j++){
  111957. float *p=v->pcm[j];
  111958. for(i=0;i<n1;i++){
  111959. float temp=p[i];
  111960. p[i]=p[i+n1];
  111961. p[i+n1]=temp;
  111962. }
  111963. }
  111964. v->pcm_current-=n1;
  111965. v->pcm_returned-=n1;
  111966. v->centerW=0;
  111967. }
  111968. /* solidify buffer into contiguous space */
  111969. if((v->lW^v->W)==1){
  111970. /* long/short or short/long */
  111971. for(j=0;j<vi->channels;j++){
  111972. float *s=v->pcm[j];
  111973. float *d=v->pcm[j]+(n1-n0)/2;
  111974. for(i=(n1+n0)/2-1;i>=0;--i)
  111975. d[i]=s[i];
  111976. }
  111977. v->pcm_returned+=(n1-n0)/2;
  111978. v->pcm_current+=(n1-n0)/2;
  111979. }else{
  111980. if(v->lW==0){
  111981. /* short/short */
  111982. for(j=0;j<vi->channels;j++){
  111983. float *s=v->pcm[j];
  111984. float *d=v->pcm[j]+n1-n0;
  111985. for(i=n0-1;i>=0;--i)
  111986. d[i]=s[i];
  111987. }
  111988. v->pcm_returned+=n1-n0;
  111989. v->pcm_current+=n1-n0;
  111990. }
  111991. }
  111992. if(pcm){
  111993. int i;
  111994. for(i=0;i<vi->channels;i++)
  111995. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111996. *pcm=v->pcmret;
  111997. }
  111998. return(n1+n-v->pcm_returned);
  111999. }
  112000. float *vorbis_window(vorbis_dsp_state *v,int W){
  112001. vorbis_info *vi=v->vi;
  112002. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  112003. int hs=ci->halfrate_flag;
  112004. private_state *b=(private_state*)v->backend_state;
  112005. if(b->window[W]-1<0)return NULL;
  112006. return _vorbis_window_get(b->window[W]-hs);
  112007. }
  112008. #endif
  112009. /*** End of inlined file: block.c ***/
  112010. /*** Start of inlined file: codebook.c ***/
  112011. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112012. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112013. // tasks..
  112014. #if JUCE_MSVC
  112015. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112016. #endif
  112017. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112018. #if JUCE_USE_OGGVORBIS
  112019. #include <stdlib.h>
  112020. #include <string.h>
  112021. #include <math.h>
  112022. /* packs the given codebook into the bitstream **************************/
  112023. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  112024. long i,j;
  112025. int ordered=0;
  112026. /* first the basic parameters */
  112027. oggpack_write(opb,0x564342,24);
  112028. oggpack_write(opb,c->dim,16);
  112029. oggpack_write(opb,c->entries,24);
  112030. /* pack the codewords. There are two packings; length ordered and
  112031. length random. Decide between the two now. */
  112032. for(i=1;i<c->entries;i++)
  112033. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  112034. if(i==c->entries)ordered=1;
  112035. if(ordered){
  112036. /* length ordered. We only need to say how many codewords of
  112037. each length. The actual codewords are generated
  112038. deterministically */
  112039. long count=0;
  112040. oggpack_write(opb,1,1); /* ordered */
  112041. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  112042. for(i=1;i<c->entries;i++){
  112043. long thisx=c->lengthlist[i];
  112044. long last=c->lengthlist[i-1];
  112045. if(thisx>last){
  112046. for(j=last;j<thisx;j++){
  112047. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112048. count=i;
  112049. }
  112050. }
  112051. }
  112052. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112053. }else{
  112054. /* length random. Again, we don't code the codeword itself, just
  112055. the length. This time, though, we have to encode each length */
  112056. oggpack_write(opb,0,1); /* unordered */
  112057. /* algortihmic mapping has use for 'unused entries', which we tag
  112058. here. The algorithmic mapping happens as usual, but the unused
  112059. entry has no codeword. */
  112060. for(i=0;i<c->entries;i++)
  112061. if(c->lengthlist[i]==0)break;
  112062. if(i==c->entries){
  112063. oggpack_write(opb,0,1); /* no unused entries */
  112064. for(i=0;i<c->entries;i++)
  112065. oggpack_write(opb,c->lengthlist[i]-1,5);
  112066. }else{
  112067. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  112068. for(i=0;i<c->entries;i++){
  112069. if(c->lengthlist[i]==0){
  112070. oggpack_write(opb,0,1);
  112071. }else{
  112072. oggpack_write(opb,1,1);
  112073. oggpack_write(opb,c->lengthlist[i]-1,5);
  112074. }
  112075. }
  112076. }
  112077. }
  112078. /* is the entry number the desired return value, or do we have a
  112079. mapping? If we have a mapping, what type? */
  112080. oggpack_write(opb,c->maptype,4);
  112081. switch(c->maptype){
  112082. case 0:
  112083. /* no mapping */
  112084. break;
  112085. case 1:case 2:
  112086. /* implicitly populated value mapping */
  112087. /* explicitly populated value mapping */
  112088. if(!c->quantlist){
  112089. /* no quantlist? error */
  112090. return(-1);
  112091. }
  112092. /* values that define the dequantization */
  112093. oggpack_write(opb,c->q_min,32);
  112094. oggpack_write(opb,c->q_delta,32);
  112095. oggpack_write(opb,c->q_quant-1,4);
  112096. oggpack_write(opb,c->q_sequencep,1);
  112097. {
  112098. int quantvals;
  112099. switch(c->maptype){
  112100. case 1:
  112101. /* a single column of (c->entries/c->dim) quantized values for
  112102. building a full value list algorithmically (square lattice) */
  112103. quantvals=_book_maptype1_quantvals(c);
  112104. break;
  112105. case 2:
  112106. /* every value (c->entries*c->dim total) specified explicitly */
  112107. quantvals=c->entries*c->dim;
  112108. break;
  112109. default: /* NOT_REACHABLE */
  112110. quantvals=-1;
  112111. }
  112112. /* quantized values */
  112113. for(i=0;i<quantvals;i++)
  112114. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  112115. }
  112116. break;
  112117. default:
  112118. /* error case; we don't have any other map types now */
  112119. return(-1);
  112120. }
  112121. return(0);
  112122. }
  112123. /* unpacks a codebook from the packet buffer into the codebook struct,
  112124. readies the codebook auxiliary structures for decode *************/
  112125. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  112126. long i,j;
  112127. memset(s,0,sizeof(*s));
  112128. s->allocedp=1;
  112129. /* make sure alignment is correct */
  112130. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  112131. /* first the basic parameters */
  112132. s->dim=oggpack_read(opb,16);
  112133. s->entries=oggpack_read(opb,24);
  112134. if(s->entries==-1)goto _eofout;
  112135. /* codeword ordering.... length ordered or unordered? */
  112136. switch((int)oggpack_read(opb,1)){
  112137. case 0:
  112138. /* unordered */
  112139. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112140. /* allocated but unused entries? */
  112141. if(oggpack_read(opb,1)){
  112142. /* yes, unused entries */
  112143. for(i=0;i<s->entries;i++){
  112144. if(oggpack_read(opb,1)){
  112145. long num=oggpack_read(opb,5);
  112146. if(num==-1)goto _eofout;
  112147. s->lengthlist[i]=num+1;
  112148. }else
  112149. s->lengthlist[i]=0;
  112150. }
  112151. }else{
  112152. /* all entries used; no tagging */
  112153. for(i=0;i<s->entries;i++){
  112154. long num=oggpack_read(opb,5);
  112155. if(num==-1)goto _eofout;
  112156. s->lengthlist[i]=num+1;
  112157. }
  112158. }
  112159. break;
  112160. case 1:
  112161. /* ordered */
  112162. {
  112163. long length=oggpack_read(opb,5)+1;
  112164. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112165. for(i=0;i<s->entries;){
  112166. long num=oggpack_read(opb,_ilog(s->entries-i));
  112167. if(num==-1)goto _eofout;
  112168. for(j=0;j<num && i<s->entries;j++,i++)
  112169. s->lengthlist[i]=length;
  112170. length++;
  112171. }
  112172. }
  112173. break;
  112174. default:
  112175. /* EOF */
  112176. return(-1);
  112177. }
  112178. /* Do we have a mapping to unpack? */
  112179. switch((s->maptype=oggpack_read(opb,4))){
  112180. case 0:
  112181. /* no mapping */
  112182. break;
  112183. case 1: case 2:
  112184. /* implicitly populated value mapping */
  112185. /* explicitly populated value mapping */
  112186. s->q_min=oggpack_read(opb,32);
  112187. s->q_delta=oggpack_read(opb,32);
  112188. s->q_quant=oggpack_read(opb,4)+1;
  112189. s->q_sequencep=oggpack_read(opb,1);
  112190. {
  112191. int quantvals=0;
  112192. switch(s->maptype){
  112193. case 1:
  112194. quantvals=_book_maptype1_quantvals(s);
  112195. break;
  112196. case 2:
  112197. quantvals=s->entries*s->dim;
  112198. break;
  112199. }
  112200. /* quantized values */
  112201. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112202. for(i=0;i<quantvals;i++)
  112203. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112204. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112205. }
  112206. break;
  112207. default:
  112208. goto _errout;
  112209. }
  112210. /* all set */
  112211. return(0);
  112212. _errout:
  112213. _eofout:
  112214. vorbis_staticbook_clear(s);
  112215. return(-1);
  112216. }
  112217. /* returns the number of bits ************************************************/
  112218. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112219. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112220. return(book->c->lengthlist[a]);
  112221. }
  112222. /* One the encode side, our vector writers are each designed for a
  112223. specific purpose, and the encoder is not flexible without modification:
  112224. The LSP vector coder uses a single stage nearest-match with no
  112225. interleave, so no step and no error return. This is specced by floor0
  112226. and doesn't change.
  112227. Residue0 encoding interleaves, uses multiple stages, and each stage
  112228. peels of a specific amount of resolution from a lattice (thus we want
  112229. to match by threshold, not nearest match). Residue doesn't *have* to
  112230. be encoded that way, but to change it, one will need to add more
  112231. infrastructure on the encode side (decode side is specced and simpler) */
  112232. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112233. /* returns entry number and *modifies a* to the quantization value *****/
  112234. int vorbis_book_errorv(codebook *book,float *a){
  112235. int dim=book->dim,k;
  112236. int best=_best(book,a,1);
  112237. for(k=0;k<dim;k++)
  112238. a[k]=(book->valuelist+best*dim)[k];
  112239. return(best);
  112240. }
  112241. /* returns the number of bits and *modifies a* to the quantization value *****/
  112242. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112243. int k,dim=book->dim;
  112244. for(k=0;k<dim;k++)
  112245. a[k]=(book->valuelist+best*dim)[k];
  112246. return(vorbis_book_encode(book,best,b));
  112247. }
  112248. /* the 'eliminate the decode tree' optimization actually requires the
  112249. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112250. (and one of the first places where carefully thought out design
  112251. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112252. to an MSb bitpacker), but not actually the huge hit it appears to
  112253. be. The first-stage decode table catches most words so that
  112254. bitreverse is not in the main execution path. */
  112255. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112256. int read=book->dec_maxlength;
  112257. long lo,hi;
  112258. long lok = oggpack_look(b,book->dec_firsttablen);
  112259. if (lok >= 0) {
  112260. long entry = book->dec_firsttable[lok];
  112261. if(entry&0x80000000UL){
  112262. lo=(entry>>15)&0x7fff;
  112263. hi=book->used_entries-(entry&0x7fff);
  112264. }else{
  112265. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112266. return(entry-1);
  112267. }
  112268. }else{
  112269. lo=0;
  112270. hi=book->used_entries;
  112271. }
  112272. lok = oggpack_look(b, read);
  112273. while(lok<0 && read>1)
  112274. lok = oggpack_look(b, --read);
  112275. if(lok<0)return -1;
  112276. /* bisect search for the codeword in the ordered list */
  112277. {
  112278. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112279. while(hi-lo>1){
  112280. long p=(hi-lo)>>1;
  112281. long test=book->codelist[lo+p]>testword;
  112282. lo+=p&(test-1);
  112283. hi-=p&(-test);
  112284. }
  112285. if(book->dec_codelengths[lo]<=read){
  112286. oggpack_adv(b, book->dec_codelengths[lo]);
  112287. return(lo);
  112288. }
  112289. }
  112290. oggpack_adv(b, read);
  112291. return(-1);
  112292. }
  112293. /* Decode side is specced and easier, because we don't need to find
  112294. matches using different criteria; we simply read and map. There are
  112295. two things we need to do 'depending':
  112296. We may need to support interleave. We don't really, but it's
  112297. convenient to do it here rather than rebuild the vector later.
  112298. Cascades may be additive or multiplicitive; this is not inherent in
  112299. the codebook, but set in the code using the codebook. Like
  112300. interleaving, it's easiest to do it here.
  112301. addmul==0 -> declarative (set the value)
  112302. addmul==1 -> additive
  112303. addmul==2 -> multiplicitive */
  112304. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112305. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112306. long packed_entry=decode_packed_entry_number(book,b);
  112307. if(packed_entry>=0)
  112308. return(book->dec_index[packed_entry]);
  112309. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112310. return(packed_entry);
  112311. }
  112312. /* returns 0 on OK or -1 on eof *************************************/
  112313. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112314. int step=n/book->dim;
  112315. long *entry = (long*)alloca(sizeof(*entry)*step);
  112316. float **t = (float**)alloca(sizeof(*t)*step);
  112317. int i,j,o;
  112318. for (i = 0; i < step; i++) {
  112319. entry[i]=decode_packed_entry_number(book,b);
  112320. if(entry[i]==-1)return(-1);
  112321. t[i] = book->valuelist+entry[i]*book->dim;
  112322. }
  112323. for(i=0,o=0;i<book->dim;i++,o+=step)
  112324. for (j=0;j<step;j++)
  112325. a[o+j]+=t[j][i];
  112326. return(0);
  112327. }
  112328. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112329. int i,j,entry;
  112330. float *t;
  112331. if(book->dim>8){
  112332. for(i=0;i<n;){
  112333. entry = decode_packed_entry_number(book,b);
  112334. if(entry==-1)return(-1);
  112335. t = book->valuelist+entry*book->dim;
  112336. for (j=0;j<book->dim;)
  112337. a[i++]+=t[j++];
  112338. }
  112339. }else{
  112340. for(i=0;i<n;){
  112341. entry = decode_packed_entry_number(book,b);
  112342. if(entry==-1)return(-1);
  112343. t = book->valuelist+entry*book->dim;
  112344. j=0;
  112345. switch((int)book->dim){
  112346. case 8:
  112347. a[i++]+=t[j++];
  112348. case 7:
  112349. a[i++]+=t[j++];
  112350. case 6:
  112351. a[i++]+=t[j++];
  112352. case 5:
  112353. a[i++]+=t[j++];
  112354. case 4:
  112355. a[i++]+=t[j++];
  112356. case 3:
  112357. a[i++]+=t[j++];
  112358. case 2:
  112359. a[i++]+=t[j++];
  112360. case 1:
  112361. a[i++]+=t[j++];
  112362. case 0:
  112363. break;
  112364. }
  112365. }
  112366. }
  112367. return(0);
  112368. }
  112369. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112370. int i,j,entry;
  112371. float *t;
  112372. for(i=0;i<n;){
  112373. entry = decode_packed_entry_number(book,b);
  112374. if(entry==-1)return(-1);
  112375. t = book->valuelist+entry*book->dim;
  112376. for (j=0;j<book->dim;)
  112377. a[i++]=t[j++];
  112378. }
  112379. return(0);
  112380. }
  112381. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112382. oggpack_buffer *b,int n){
  112383. long i,j,entry;
  112384. int chptr=0;
  112385. for(i=offset/ch;i<(offset+n)/ch;){
  112386. entry = decode_packed_entry_number(book,b);
  112387. if(entry==-1)return(-1);
  112388. {
  112389. const float *t = book->valuelist+entry*book->dim;
  112390. for (j=0;j<book->dim;j++){
  112391. a[chptr++][i]+=t[j];
  112392. if(chptr==ch){
  112393. chptr=0;
  112394. i++;
  112395. }
  112396. }
  112397. }
  112398. }
  112399. return(0);
  112400. }
  112401. #ifdef _V_SELFTEST
  112402. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112403. number of vectors through (keeping track of the quantized values),
  112404. and decode using the unpacked book. quantized version of in should
  112405. exactly equal out */
  112406. #include <stdio.h>
  112407. #include "vorbis/book/lsp20_0.vqh"
  112408. #include "vorbis/book/res0a_13.vqh"
  112409. #define TESTSIZE 40
  112410. float test1[TESTSIZE]={
  112411. 0.105939f,
  112412. 0.215373f,
  112413. 0.429117f,
  112414. 0.587974f,
  112415. 0.181173f,
  112416. 0.296583f,
  112417. 0.515707f,
  112418. 0.715261f,
  112419. 0.162327f,
  112420. 0.263834f,
  112421. 0.342876f,
  112422. 0.406025f,
  112423. 0.103571f,
  112424. 0.223561f,
  112425. 0.368513f,
  112426. 0.540313f,
  112427. 0.136672f,
  112428. 0.395882f,
  112429. 0.587183f,
  112430. 0.652476f,
  112431. 0.114338f,
  112432. 0.417300f,
  112433. 0.525486f,
  112434. 0.698679f,
  112435. 0.147492f,
  112436. 0.324481f,
  112437. 0.643089f,
  112438. 0.757582f,
  112439. 0.139556f,
  112440. 0.215795f,
  112441. 0.324559f,
  112442. 0.399387f,
  112443. 0.120236f,
  112444. 0.267420f,
  112445. 0.446940f,
  112446. 0.608760f,
  112447. 0.115587f,
  112448. 0.287234f,
  112449. 0.571081f,
  112450. 0.708603f,
  112451. };
  112452. float test3[TESTSIZE]={
  112453. 0,1,-2,3,4,-5,6,7,8,9,
  112454. 8,-2,7,-1,4,6,8,3,1,-9,
  112455. 10,11,12,13,14,15,26,17,18,19,
  112456. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112457. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112458. &_vq_book_res0a_13,NULL};
  112459. float *testvec[]={test1,test3};
  112460. int main(){
  112461. oggpack_buffer write;
  112462. oggpack_buffer read;
  112463. long ptr=0,i;
  112464. oggpack_writeinit(&write);
  112465. fprintf(stderr,"Testing codebook abstraction...:\n");
  112466. while(testlist[ptr]){
  112467. codebook c;
  112468. static_codebook s;
  112469. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112470. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112471. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112472. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112473. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112474. /* pack the codebook, write the testvector */
  112475. oggpack_reset(&write);
  112476. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112477. we can write */
  112478. vorbis_staticbook_pack(testlist[ptr],&write);
  112479. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112480. for(i=0;i<TESTSIZE;i+=c.dim){
  112481. int best=_best(&c,qv+i,1);
  112482. vorbis_book_encodev(&c,best,qv+i,&write);
  112483. }
  112484. vorbis_book_clear(&c);
  112485. fprintf(stderr,"OK.\n");
  112486. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112487. /* transfer the write data to a read buffer and unpack/read */
  112488. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112489. if(vorbis_staticbook_unpack(&read,&s)){
  112490. fprintf(stderr,"Error unpacking codebook.\n");
  112491. exit(1);
  112492. }
  112493. if(vorbis_book_init_decode(&c,&s)){
  112494. fprintf(stderr,"Error initializing codebook.\n");
  112495. exit(1);
  112496. }
  112497. for(i=0;i<TESTSIZE;i+=c.dim)
  112498. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112499. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112500. exit(1);
  112501. }
  112502. for(i=0;i<TESTSIZE;i++)
  112503. if(fabs(qv[i]-iv[i])>.000001){
  112504. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112505. iv[i],qv[i],i);
  112506. exit(1);
  112507. }
  112508. fprintf(stderr,"OK\n");
  112509. ptr++;
  112510. }
  112511. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112512. exit(0);
  112513. }
  112514. #endif
  112515. #endif
  112516. /*** End of inlined file: codebook.c ***/
  112517. /*** Start of inlined file: envelope.c ***/
  112518. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112519. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112520. // tasks..
  112521. #if JUCE_MSVC
  112522. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112523. #endif
  112524. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112525. #if JUCE_USE_OGGVORBIS
  112526. #include <stdlib.h>
  112527. #include <string.h>
  112528. #include <stdio.h>
  112529. #include <math.h>
  112530. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112531. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112532. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112533. int ch=vi->channels;
  112534. int i,j;
  112535. int n=e->winlength=128;
  112536. e->searchstep=64; /* not random */
  112537. e->minenergy=gi->preecho_minenergy;
  112538. e->ch=ch;
  112539. e->storage=128;
  112540. e->cursor=ci->blocksizes[1]/2;
  112541. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112542. mdct_init(&e->mdct,n);
  112543. for(i=0;i<n;i++){
  112544. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112545. e->mdct_win[i]*=e->mdct_win[i];
  112546. }
  112547. /* magic follows */
  112548. e->band[0].begin=2; e->band[0].end=4;
  112549. e->band[1].begin=4; e->band[1].end=5;
  112550. e->band[2].begin=6; e->band[2].end=6;
  112551. e->band[3].begin=9; e->band[3].end=8;
  112552. e->band[4].begin=13; e->band[4].end=8;
  112553. e->band[5].begin=17; e->band[5].end=8;
  112554. e->band[6].begin=22; e->band[6].end=8;
  112555. for(j=0;j<VE_BANDS;j++){
  112556. n=e->band[j].end;
  112557. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112558. for(i=0;i<n;i++){
  112559. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112560. e->band[j].total+=e->band[j].window[i];
  112561. }
  112562. e->band[j].total=1./e->band[j].total;
  112563. }
  112564. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112565. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112566. }
  112567. void _ve_envelope_clear(envelope_lookup *e){
  112568. int i;
  112569. mdct_clear(&e->mdct);
  112570. for(i=0;i<VE_BANDS;i++)
  112571. _ogg_free(e->band[i].window);
  112572. _ogg_free(e->mdct_win);
  112573. _ogg_free(e->filter);
  112574. _ogg_free(e->mark);
  112575. memset(e,0,sizeof(*e));
  112576. }
  112577. /* fairly straight threshhold-by-band based until we find something
  112578. that works better and isn't patented. */
  112579. static int _ve_amp(envelope_lookup *ve,
  112580. vorbis_info_psy_global *gi,
  112581. float *data,
  112582. envelope_band *bands,
  112583. envelope_filter_state *filters,
  112584. long pos){
  112585. long n=ve->winlength;
  112586. int ret=0;
  112587. long i,j;
  112588. float decay;
  112589. /* we want to have a 'minimum bar' for energy, else we're just
  112590. basing blocks on quantization noise that outweighs the signal
  112591. itself (for low power signals) */
  112592. float minV=ve->minenergy;
  112593. float *vec=(float*) alloca(n*sizeof(*vec));
  112594. /* stretch is used to gradually lengthen the number of windows
  112595. considered prevoius-to-potential-trigger */
  112596. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112597. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112598. if(penalty<0.f)penalty=0.f;
  112599. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112600. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112601. totalshift+pos*ve->searchstep);*/
  112602. /* window and transform */
  112603. for(i=0;i<n;i++)
  112604. vec[i]=data[i]*ve->mdct_win[i];
  112605. mdct_forward(&ve->mdct,vec,vec);
  112606. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112607. /* near-DC spreading function; this has nothing to do with
  112608. psychoacoustics, just sidelobe leakage and window size */
  112609. {
  112610. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112611. int ptr=filters->nearptr;
  112612. /* the accumulation is regularly refreshed from scratch to avoid
  112613. floating point creep */
  112614. if(ptr==0){
  112615. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112616. filters->nearDC_partialacc=temp;
  112617. }else{
  112618. decay=filters->nearDC_acc+=temp;
  112619. filters->nearDC_partialacc+=temp;
  112620. }
  112621. filters->nearDC_acc-=filters->nearDC[ptr];
  112622. filters->nearDC[ptr]=temp;
  112623. decay*=(1./(VE_NEARDC+1));
  112624. filters->nearptr++;
  112625. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112626. decay=todB(&decay)*.5-15.f;
  112627. }
  112628. /* perform spreading and limiting, also smooth the spectrum. yes,
  112629. the MDCT results in all real coefficients, but it still *behaves*
  112630. like real/imaginary pairs */
  112631. for(i=0;i<n/2;i+=2){
  112632. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112633. val=todB(&val)*.5f;
  112634. if(val<decay)val=decay;
  112635. if(val<minV)val=minV;
  112636. vec[i>>1]=val;
  112637. decay-=8.;
  112638. }
  112639. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112640. /* perform preecho/postecho triggering by band */
  112641. for(j=0;j<VE_BANDS;j++){
  112642. float acc=0.;
  112643. float valmax,valmin;
  112644. /* accumulate amplitude */
  112645. for(i=0;i<bands[j].end;i++)
  112646. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112647. acc*=bands[j].total;
  112648. /* convert amplitude to delta */
  112649. {
  112650. int p,thisx=filters[j].ampptr;
  112651. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112652. p=thisx;
  112653. p--;
  112654. if(p<0)p+=VE_AMP;
  112655. postmax=max(acc,filters[j].ampbuf[p]);
  112656. postmin=min(acc,filters[j].ampbuf[p]);
  112657. for(i=0;i<stretch;i++){
  112658. p--;
  112659. if(p<0)p+=VE_AMP;
  112660. premax=max(premax,filters[j].ampbuf[p]);
  112661. premin=min(premin,filters[j].ampbuf[p]);
  112662. }
  112663. valmin=postmin-premin;
  112664. valmax=postmax-premax;
  112665. /*filters[j].markers[pos]=valmax;*/
  112666. filters[j].ampbuf[thisx]=acc;
  112667. filters[j].ampptr++;
  112668. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112669. }
  112670. /* look at min/max, decide trigger */
  112671. if(valmax>gi->preecho_thresh[j]+penalty){
  112672. ret|=1;
  112673. ret|=4;
  112674. }
  112675. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112676. }
  112677. return(ret);
  112678. }
  112679. #if 0
  112680. static int seq=0;
  112681. static ogg_int64_t totalshift=-1024;
  112682. #endif
  112683. long _ve_envelope_search(vorbis_dsp_state *v){
  112684. vorbis_info *vi=v->vi;
  112685. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112686. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112687. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112688. long i,j;
  112689. int first=ve->current/ve->searchstep;
  112690. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112691. if(first<0)first=0;
  112692. /* make sure we have enough storage to match the PCM */
  112693. if(last+VE_WIN+VE_POST>ve->storage){
  112694. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112695. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112696. }
  112697. for(j=first;j<last;j++){
  112698. int ret=0;
  112699. ve->stretch++;
  112700. if(ve->stretch>VE_MAXSTRETCH*2)
  112701. ve->stretch=VE_MAXSTRETCH*2;
  112702. for(i=0;i<ve->ch;i++){
  112703. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112704. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112705. }
  112706. ve->mark[j+VE_POST]=0;
  112707. if(ret&1){
  112708. ve->mark[j]=1;
  112709. ve->mark[j+1]=1;
  112710. }
  112711. if(ret&2){
  112712. ve->mark[j]=1;
  112713. if(j>0)ve->mark[j-1]=1;
  112714. }
  112715. if(ret&4)ve->stretch=-1;
  112716. }
  112717. ve->current=last*ve->searchstep;
  112718. {
  112719. long centerW=v->centerW;
  112720. long testW=
  112721. centerW+
  112722. ci->blocksizes[v->W]/4+
  112723. ci->blocksizes[1]/2+
  112724. ci->blocksizes[0]/4;
  112725. j=ve->cursor;
  112726. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112727. working back one window */
  112728. if(j>=testW)return(1);
  112729. ve->cursor=j;
  112730. if(ve->mark[j/ve->searchstep]){
  112731. if(j>centerW){
  112732. #if 0
  112733. if(j>ve->curmark){
  112734. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112735. int l,m;
  112736. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112737. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112738. seq,
  112739. (totalshift+ve->cursor)/44100.,
  112740. (totalshift+j)/44100.);
  112741. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112742. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112743. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112744. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112745. for(m=0;m<VE_BANDS;m++){
  112746. char buf[80];
  112747. sprintf(buf,"delL%d",m);
  112748. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112749. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112750. }
  112751. for(m=0;m<VE_BANDS;m++){
  112752. char buf[80];
  112753. sprintf(buf,"delR%d",m);
  112754. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112755. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112756. }
  112757. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112758. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112759. seq++;
  112760. }
  112761. #endif
  112762. ve->curmark=j;
  112763. if(j>=testW)return(1);
  112764. return(0);
  112765. }
  112766. }
  112767. j+=ve->searchstep;
  112768. }
  112769. }
  112770. return(-1);
  112771. }
  112772. int _ve_envelope_mark(vorbis_dsp_state *v){
  112773. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112774. vorbis_info *vi=v->vi;
  112775. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112776. long centerW=v->centerW;
  112777. long beginW=centerW-ci->blocksizes[v->W]/4;
  112778. long endW=centerW+ci->blocksizes[v->W]/4;
  112779. if(v->W){
  112780. beginW-=ci->blocksizes[v->lW]/4;
  112781. endW+=ci->blocksizes[v->nW]/4;
  112782. }else{
  112783. beginW-=ci->blocksizes[0]/4;
  112784. endW+=ci->blocksizes[0]/4;
  112785. }
  112786. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112787. {
  112788. long first=beginW/ve->searchstep;
  112789. long last=endW/ve->searchstep;
  112790. long i;
  112791. for(i=first;i<last;i++)
  112792. if(ve->mark[i])return(1);
  112793. }
  112794. return(0);
  112795. }
  112796. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112797. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112798. ahead of ve->current */
  112799. int smallshift=shift/e->searchstep;
  112800. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112801. #if 0
  112802. for(i=0;i<VE_BANDS*e->ch;i++)
  112803. memmove(e->filter[i].markers,
  112804. e->filter[i].markers+smallshift,
  112805. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112806. totalshift+=shift;
  112807. #endif
  112808. e->current-=shift;
  112809. if(e->curmark>=0)
  112810. e->curmark-=shift;
  112811. e->cursor-=shift;
  112812. }
  112813. #endif
  112814. /*** End of inlined file: envelope.c ***/
  112815. /*** Start of inlined file: floor0.c ***/
  112816. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112817. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112818. // tasks..
  112819. #if JUCE_MSVC
  112820. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112821. #endif
  112822. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112823. #if JUCE_USE_OGGVORBIS
  112824. #include <stdlib.h>
  112825. #include <string.h>
  112826. #include <math.h>
  112827. /*** Start of inlined file: lsp.h ***/
  112828. #ifndef _V_LSP_H_
  112829. #define _V_LSP_H_
  112830. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112831. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112832. float *lsp,int m,
  112833. float amp,float ampoffset);
  112834. #endif
  112835. /*** End of inlined file: lsp.h ***/
  112836. #include <stdio.h>
  112837. typedef struct {
  112838. int ln;
  112839. int m;
  112840. int **linearmap;
  112841. int n[2];
  112842. vorbis_info_floor0 *vi;
  112843. long bits;
  112844. long frames;
  112845. } vorbis_look_floor0;
  112846. /***********************************************/
  112847. static void floor0_free_info(vorbis_info_floor *i){
  112848. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112849. if(info){
  112850. memset(info,0,sizeof(*info));
  112851. _ogg_free(info);
  112852. }
  112853. }
  112854. static void floor0_free_look(vorbis_look_floor *i){
  112855. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112856. if(look){
  112857. if(look->linearmap){
  112858. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112859. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112860. _ogg_free(look->linearmap);
  112861. }
  112862. memset(look,0,sizeof(*look));
  112863. _ogg_free(look);
  112864. }
  112865. }
  112866. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112867. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112868. int j;
  112869. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112870. info->order=oggpack_read(opb,8);
  112871. info->rate=oggpack_read(opb,16);
  112872. info->barkmap=oggpack_read(opb,16);
  112873. info->ampbits=oggpack_read(opb,6);
  112874. info->ampdB=oggpack_read(opb,8);
  112875. info->numbooks=oggpack_read(opb,4)+1;
  112876. if(info->order<1)goto err_out;
  112877. if(info->rate<1)goto err_out;
  112878. if(info->barkmap<1)goto err_out;
  112879. if(info->numbooks<1)goto err_out;
  112880. for(j=0;j<info->numbooks;j++){
  112881. info->books[j]=oggpack_read(opb,8);
  112882. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112883. }
  112884. return(info);
  112885. err_out:
  112886. floor0_free_info(info);
  112887. return(NULL);
  112888. }
  112889. /* initialize Bark scale and normalization lookups. We could do this
  112890. with static tables, but Vorbis allows a number of possible
  112891. combinations, so it's best to do it computationally.
  112892. The below is authoritative in terms of defining scale mapping.
  112893. Note that the scale depends on the sampling rate as well as the
  112894. linear block and mapping sizes */
  112895. static void floor0_map_lazy_init(vorbis_block *vb,
  112896. vorbis_info_floor *infoX,
  112897. vorbis_look_floor0 *look){
  112898. if(!look->linearmap[vb->W]){
  112899. vorbis_dsp_state *vd=vb->vd;
  112900. vorbis_info *vi=vd->vi;
  112901. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112902. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112903. int W=vb->W;
  112904. int n=ci->blocksizes[W]/2,j;
  112905. /* we choose a scaling constant so that:
  112906. floor(bark(rate/2-1)*C)=mapped-1
  112907. floor(bark(rate/2)*C)=mapped */
  112908. float scale=look->ln/toBARK(info->rate/2.f);
  112909. /* the mapping from a linear scale to a smaller bark scale is
  112910. straightforward. We do *not* make sure that the linear mapping
  112911. does not skip bark-scale bins; the decoder simply skips them and
  112912. the encoder may do what it wishes in filling them. They're
  112913. necessary in some mapping combinations to keep the scale spacing
  112914. accurate */
  112915. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112916. for(j=0;j<n;j++){
  112917. int val=floor( toBARK((info->rate/2.f)/n*j)
  112918. *scale); /* bark numbers represent band edges */
  112919. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112920. look->linearmap[W][j]=val;
  112921. }
  112922. look->linearmap[W][j]=-1;
  112923. look->n[W]=n;
  112924. }
  112925. }
  112926. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112927. vorbis_info_floor *i){
  112928. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112929. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112930. look->m=info->order;
  112931. look->ln=info->barkmap;
  112932. look->vi=info;
  112933. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112934. return look;
  112935. }
  112936. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112937. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112938. vorbis_info_floor0 *info=look->vi;
  112939. int j,k;
  112940. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112941. if(ampraw>0){ /* also handles the -1 out of data case */
  112942. long maxval=(1<<info->ampbits)-1;
  112943. float amp=(float)ampraw/maxval*info->ampdB;
  112944. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112945. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112946. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112947. codebook *b=ci->fullbooks+info->books[booknum];
  112948. float last=0.f;
  112949. /* the additional b->dim is a guard against any possible stack
  112950. smash; b->dim is provably more than we can overflow the
  112951. vector */
  112952. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112953. for(j=0;j<look->m;j+=b->dim)
  112954. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112955. for(j=0;j<look->m;){
  112956. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112957. last=lsp[j-1];
  112958. }
  112959. lsp[look->m]=amp;
  112960. return(lsp);
  112961. }
  112962. }
  112963. eop:
  112964. return(NULL);
  112965. }
  112966. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112967. void *memo,float *out){
  112968. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112969. vorbis_info_floor0 *info=look->vi;
  112970. floor0_map_lazy_init(vb,info,look);
  112971. if(memo){
  112972. float *lsp=(float *)memo;
  112973. float amp=lsp[look->m];
  112974. /* take the coefficients back to a spectral envelope curve */
  112975. vorbis_lsp_to_curve(out,
  112976. look->linearmap[vb->W],
  112977. look->n[vb->W],
  112978. look->ln,
  112979. lsp,look->m,amp,(float)info->ampdB);
  112980. return(1);
  112981. }
  112982. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112983. return(0);
  112984. }
  112985. /* export hooks */
  112986. vorbis_func_floor floor0_exportbundle={
  112987. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112988. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112989. };
  112990. #endif
  112991. /*** End of inlined file: floor0.c ***/
  112992. /*** Start of inlined file: floor1.c ***/
  112993. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112994. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112995. // tasks..
  112996. #if JUCE_MSVC
  112997. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112998. #endif
  112999. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113000. #if JUCE_USE_OGGVORBIS
  113001. #include <stdlib.h>
  113002. #include <string.h>
  113003. #include <math.h>
  113004. #include <stdio.h>
  113005. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  113006. typedef struct {
  113007. int sorted_index[VIF_POSIT+2];
  113008. int forward_index[VIF_POSIT+2];
  113009. int reverse_index[VIF_POSIT+2];
  113010. int hineighbor[VIF_POSIT];
  113011. int loneighbor[VIF_POSIT];
  113012. int posts;
  113013. int n;
  113014. int quant_q;
  113015. vorbis_info_floor1 *vi;
  113016. long phrasebits;
  113017. long postbits;
  113018. long frames;
  113019. } vorbis_look_floor1;
  113020. typedef struct lsfit_acc{
  113021. long x0;
  113022. long x1;
  113023. long xa;
  113024. long ya;
  113025. long x2a;
  113026. long y2a;
  113027. long xya;
  113028. long an;
  113029. } lsfit_acc;
  113030. /***********************************************/
  113031. static void floor1_free_info(vorbis_info_floor *i){
  113032. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113033. if(info){
  113034. memset(info,0,sizeof(*info));
  113035. _ogg_free(info);
  113036. }
  113037. }
  113038. static void floor1_free_look(vorbis_look_floor *i){
  113039. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  113040. if(look){
  113041. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  113042. (float)look->phrasebits/look->frames,
  113043. (float)look->postbits/look->frames,
  113044. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113045. memset(look,0,sizeof(*look));
  113046. _ogg_free(look);
  113047. }
  113048. }
  113049. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  113050. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113051. int j,k;
  113052. int count=0;
  113053. int rangebits;
  113054. int maxposit=info->postlist[1];
  113055. int maxclass=-1;
  113056. /* save out partitions */
  113057. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  113058. for(j=0;j<info->partitions;j++){
  113059. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  113060. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113061. }
  113062. /* save out partition classes */
  113063. for(j=0;j<maxclass+1;j++){
  113064. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  113065. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  113066. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  113067. for(k=0;k<(1<<info->class_subs[j]);k++)
  113068. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  113069. }
  113070. /* save out the post list */
  113071. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  113072. oggpack_write(opb,ilog2(maxposit),4);
  113073. rangebits=ilog2(maxposit);
  113074. for(j=0,k=0;j<info->partitions;j++){
  113075. count+=info->class_dim[info->partitionclass[j]];
  113076. for(;k<count;k++)
  113077. oggpack_write(opb,info->postlist[k+2],rangebits);
  113078. }
  113079. }
  113080. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  113081. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113082. int j,k,count=0,maxclass=-1,rangebits;
  113083. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  113084. /* read partitions */
  113085. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  113086. for(j=0;j<info->partitions;j++){
  113087. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  113088. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113089. }
  113090. /* read partition classes */
  113091. for(j=0;j<maxclass+1;j++){
  113092. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  113093. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  113094. if(info->class_subs[j]<0)
  113095. goto err_out;
  113096. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  113097. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  113098. goto err_out;
  113099. for(k=0;k<(1<<info->class_subs[j]);k++){
  113100. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  113101. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  113102. goto err_out;
  113103. }
  113104. }
  113105. /* read the post list */
  113106. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  113107. rangebits=oggpack_read(opb,4);
  113108. for(j=0,k=0;j<info->partitions;j++){
  113109. count+=info->class_dim[info->partitionclass[j]];
  113110. for(;k<count;k++){
  113111. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  113112. if(t<0 || t>=(1<<rangebits))
  113113. goto err_out;
  113114. }
  113115. }
  113116. info->postlist[0]=0;
  113117. info->postlist[1]=1<<rangebits;
  113118. return(info);
  113119. err_out:
  113120. floor1_free_info(info);
  113121. return(NULL);
  113122. }
  113123. static int JUCE_CDECL icomp(const void *a,const void *b){
  113124. return(**(int **)a-**(int **)b);
  113125. }
  113126. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  113127. vorbis_info_floor *in){
  113128. int *sortpointer[VIF_POSIT+2];
  113129. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  113130. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  113131. int i,j,n=0;
  113132. look->vi=info;
  113133. look->n=info->postlist[1];
  113134. /* we drop each position value in-between already decoded values,
  113135. and use linear interpolation to predict each new value past the
  113136. edges. The positions are read in the order of the position
  113137. list... we precompute the bounding positions in the lookup. Of
  113138. course, the neighbors can change (if a position is declined), but
  113139. this is an initial mapping */
  113140. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  113141. n+=2;
  113142. look->posts=n;
  113143. /* also store a sorted position index */
  113144. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  113145. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  113146. /* points from sort order back to range number */
  113147. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  113148. /* points from range order to sorted position */
  113149. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  113150. /* we actually need the post values too */
  113151. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  113152. /* quantize values to multiplier spec */
  113153. switch(info->mult){
  113154. case 1: /* 1024 -> 256 */
  113155. look->quant_q=256;
  113156. break;
  113157. case 2: /* 1024 -> 128 */
  113158. look->quant_q=128;
  113159. break;
  113160. case 3: /* 1024 -> 86 */
  113161. look->quant_q=86;
  113162. break;
  113163. case 4: /* 1024 -> 64 */
  113164. look->quant_q=64;
  113165. break;
  113166. }
  113167. /* discover our neighbors for decode where we don't use fit flags
  113168. (that would push the neighbors outward) */
  113169. for(i=0;i<n-2;i++){
  113170. int lo=0;
  113171. int hi=1;
  113172. int lx=0;
  113173. int hx=look->n;
  113174. int currentx=info->postlist[i+2];
  113175. for(j=0;j<i+2;j++){
  113176. int x=info->postlist[j];
  113177. if(x>lx && x<currentx){
  113178. lo=j;
  113179. lx=x;
  113180. }
  113181. if(x<hx && x>currentx){
  113182. hi=j;
  113183. hx=x;
  113184. }
  113185. }
  113186. look->loneighbor[i]=lo;
  113187. look->hineighbor[i]=hi;
  113188. }
  113189. return(look);
  113190. }
  113191. static int render_point(int x0,int x1,int y0,int y1,int x){
  113192. y0&=0x7fff; /* mask off flag */
  113193. y1&=0x7fff;
  113194. {
  113195. int dy=y1-y0;
  113196. int adx=x1-x0;
  113197. int ady=abs(dy);
  113198. int err=ady*(x-x0);
  113199. int off=err/adx;
  113200. if(dy<0)return(y0-off);
  113201. return(y0+off);
  113202. }
  113203. }
  113204. static int vorbis_dBquant(const float *x){
  113205. int i= *x*7.3142857f+1023.5f;
  113206. if(i>1023)return(1023);
  113207. if(i<0)return(0);
  113208. return i;
  113209. }
  113210. static float FLOOR1_fromdB_LOOKUP[256]={
  113211. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113212. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113213. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113214. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113215. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113216. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113217. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113218. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113219. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113220. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113221. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113222. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113223. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113224. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113225. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113226. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113227. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113228. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113229. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113230. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113231. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113232. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113233. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113234. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113235. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113236. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113237. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113238. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113239. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113240. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113241. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113242. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113243. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113244. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113245. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113246. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113247. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113248. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113249. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113250. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113251. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113252. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113253. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113254. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113255. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113256. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113257. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113258. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113259. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113260. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113261. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113262. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113263. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113264. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113265. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113266. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113267. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113268. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113269. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113270. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113271. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113272. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113273. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113274. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113275. };
  113276. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113277. int dy=y1-y0;
  113278. int adx=x1-x0;
  113279. int ady=abs(dy);
  113280. int base=dy/adx;
  113281. int sy=(dy<0?base-1:base+1);
  113282. int x=x0;
  113283. int y=y0;
  113284. int err=0;
  113285. ady-=abs(base*adx);
  113286. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113287. while(++x<x1){
  113288. err=err+ady;
  113289. if(err>=adx){
  113290. err-=adx;
  113291. y+=sy;
  113292. }else{
  113293. y+=base;
  113294. }
  113295. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113296. }
  113297. }
  113298. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113299. int dy=y1-y0;
  113300. int adx=x1-x0;
  113301. int ady=abs(dy);
  113302. int base=dy/adx;
  113303. int sy=(dy<0?base-1:base+1);
  113304. int x=x0;
  113305. int y=y0;
  113306. int err=0;
  113307. ady-=abs(base*adx);
  113308. d[x]=y;
  113309. while(++x<x1){
  113310. err=err+ady;
  113311. if(err>=adx){
  113312. err-=adx;
  113313. y+=sy;
  113314. }else{
  113315. y+=base;
  113316. }
  113317. d[x]=y;
  113318. }
  113319. }
  113320. /* the floor has already been filtered to only include relevant sections */
  113321. static int accumulate_fit(const float *flr,const float *mdct,
  113322. int x0, int x1,lsfit_acc *a,
  113323. int n,vorbis_info_floor1 *info){
  113324. long i;
  113325. 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;
  113326. memset(a,0,sizeof(*a));
  113327. a->x0=x0;
  113328. a->x1=x1;
  113329. if(x1>=n)x1=n-1;
  113330. for(i=x0;i<=x1;i++){
  113331. int quantized=vorbis_dBquant(flr+i);
  113332. if(quantized){
  113333. if(mdct[i]+info->twofitatten>=flr[i]){
  113334. xa += i;
  113335. ya += quantized;
  113336. x2a += i*i;
  113337. y2a += quantized*quantized;
  113338. xya += i*quantized;
  113339. na++;
  113340. }else{
  113341. xb += i;
  113342. yb += quantized;
  113343. x2b += i*i;
  113344. y2b += quantized*quantized;
  113345. xyb += i*quantized;
  113346. nb++;
  113347. }
  113348. }
  113349. }
  113350. xb+=xa;
  113351. yb+=ya;
  113352. x2b+=x2a;
  113353. y2b+=y2a;
  113354. xyb+=xya;
  113355. nb+=na;
  113356. /* weight toward the actually used frequencies if we meet the threshhold */
  113357. {
  113358. int weight=nb*info->twofitweight/(na+1);
  113359. a->xa=xa*weight+xb;
  113360. a->ya=ya*weight+yb;
  113361. a->x2a=x2a*weight+x2b;
  113362. a->y2a=y2a*weight+y2b;
  113363. a->xya=xya*weight+xyb;
  113364. a->an=na*weight+nb;
  113365. }
  113366. return(na);
  113367. }
  113368. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113369. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113370. long x0=a[0].x0;
  113371. long x1=a[fits-1].x1;
  113372. for(i=0;i<fits;i++){
  113373. x+=a[i].xa;
  113374. y+=a[i].ya;
  113375. x2+=a[i].x2a;
  113376. y2+=a[i].y2a;
  113377. xy+=a[i].xya;
  113378. an+=a[i].an;
  113379. }
  113380. if(*y0>=0){
  113381. x+= x0;
  113382. y+= *y0;
  113383. x2+= x0 * x0;
  113384. y2+= *y0 * *y0;
  113385. xy+= *y0 * x0;
  113386. an++;
  113387. }
  113388. if(*y1>=0){
  113389. x+= x1;
  113390. y+= *y1;
  113391. x2+= x1 * x1;
  113392. y2+= *y1 * *y1;
  113393. xy+= *y1 * x1;
  113394. an++;
  113395. }
  113396. if(an){
  113397. /* need 64 bit multiplies, which C doesn't give portably as int */
  113398. double fx=x;
  113399. double fy=y;
  113400. double fx2=x2;
  113401. double fxy=xy;
  113402. double denom=1./(an*fx2-fx*fx);
  113403. double a=(fy*fx2-fxy*fx)*denom;
  113404. double b=(an*fxy-fx*fy)*denom;
  113405. *y0=rint(a+b*x0);
  113406. *y1=rint(a+b*x1);
  113407. /* limit to our range! */
  113408. if(*y0>1023)*y0=1023;
  113409. if(*y1>1023)*y1=1023;
  113410. if(*y0<0)*y0=0;
  113411. if(*y1<0)*y1=0;
  113412. }else{
  113413. *y0=0;
  113414. *y1=0;
  113415. }
  113416. }
  113417. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113418. long y=0;
  113419. int i;
  113420. for(i=0;i<fits && y==0;i++)
  113421. y+=a[i].ya;
  113422. *y0=*y1=y;
  113423. }*/
  113424. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113425. const float *mdct,
  113426. vorbis_info_floor1 *info){
  113427. int dy=y1-y0;
  113428. int adx=x1-x0;
  113429. int ady=abs(dy);
  113430. int base=dy/adx;
  113431. int sy=(dy<0?base-1:base+1);
  113432. int x=x0;
  113433. int y=y0;
  113434. int err=0;
  113435. int val=vorbis_dBquant(mask+x);
  113436. int mse=0;
  113437. int n=0;
  113438. ady-=abs(base*adx);
  113439. mse=(y-val);
  113440. mse*=mse;
  113441. n++;
  113442. if(mdct[x]+info->twofitatten>=mask[x]){
  113443. if(y+info->maxover<val)return(1);
  113444. if(y-info->maxunder>val)return(1);
  113445. }
  113446. while(++x<x1){
  113447. err=err+ady;
  113448. if(err>=adx){
  113449. err-=adx;
  113450. y+=sy;
  113451. }else{
  113452. y+=base;
  113453. }
  113454. val=vorbis_dBquant(mask+x);
  113455. mse+=((y-val)*(y-val));
  113456. n++;
  113457. if(mdct[x]+info->twofitatten>=mask[x]){
  113458. if(val){
  113459. if(y+info->maxover<val)return(1);
  113460. if(y-info->maxunder>val)return(1);
  113461. }
  113462. }
  113463. }
  113464. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113465. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113466. if(mse/n>info->maxerr)return(1);
  113467. return(0);
  113468. }
  113469. static int post_Y(int *A,int *B,int pos){
  113470. if(A[pos]<0)
  113471. return B[pos];
  113472. if(B[pos]<0)
  113473. return A[pos];
  113474. return (A[pos]+B[pos])>>1;
  113475. }
  113476. int *floor1_fit(vorbis_block *vb,void *look_,
  113477. const float *logmdct, /* in */
  113478. const float *logmask){
  113479. long i,j;
  113480. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113481. vorbis_info_floor1 *info=look->vi;
  113482. long n=look->n;
  113483. long posts=look->posts;
  113484. long nonzero=0;
  113485. lsfit_acc fits[VIF_POSIT+1];
  113486. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113487. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113488. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113489. int hineighbor[VIF_POSIT+2];
  113490. int *output=NULL;
  113491. int memo[VIF_POSIT+2];
  113492. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113493. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113494. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113495. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113496. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113497. /* quantize the relevant floor points and collect them into line fit
  113498. structures (one per minimal division) at the same time */
  113499. if(posts==0){
  113500. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113501. }else{
  113502. for(i=0;i<posts-1;i++)
  113503. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113504. look->sorted_index[i+1],fits+i,
  113505. n,info);
  113506. }
  113507. if(nonzero){
  113508. /* start by fitting the implicit base case.... */
  113509. int y0=-200;
  113510. int y1=-200;
  113511. fit_line(fits,posts-1,&y0,&y1);
  113512. fit_valueA[0]=y0;
  113513. fit_valueB[0]=y0;
  113514. fit_valueB[1]=y1;
  113515. fit_valueA[1]=y1;
  113516. /* Non degenerate case */
  113517. /* start progressive splitting. This is a greedy, non-optimal
  113518. algorithm, but simple and close enough to the best
  113519. answer. */
  113520. for(i=2;i<posts;i++){
  113521. int sortpos=look->reverse_index[i];
  113522. int ln=loneighbor[sortpos];
  113523. int hn=hineighbor[sortpos];
  113524. /* eliminate repeat searches of a particular range with a memo */
  113525. if(memo[ln]!=hn){
  113526. /* haven't performed this error search yet */
  113527. int lsortpos=look->reverse_index[ln];
  113528. int hsortpos=look->reverse_index[hn];
  113529. memo[ln]=hn;
  113530. {
  113531. /* A note: we want to bound/minimize *local*, not global, error */
  113532. int lx=info->postlist[ln];
  113533. int hx=info->postlist[hn];
  113534. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113535. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113536. if(ly==-1 || hy==-1){
  113537. exit(1);
  113538. }
  113539. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113540. /* outside error bounds/begin search area. Split it. */
  113541. int ly0=-200;
  113542. int ly1=-200;
  113543. int hy0=-200;
  113544. int hy1=-200;
  113545. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113546. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113547. /* store new edge values */
  113548. fit_valueB[ln]=ly0;
  113549. if(ln==0)fit_valueA[ln]=ly0;
  113550. fit_valueA[i]=ly1;
  113551. fit_valueB[i]=hy0;
  113552. fit_valueA[hn]=hy1;
  113553. if(hn==1)fit_valueB[hn]=hy1;
  113554. if(ly1>=0 || hy0>=0){
  113555. /* store new neighbor values */
  113556. for(j=sortpos-1;j>=0;j--)
  113557. if(hineighbor[j]==hn)
  113558. hineighbor[j]=i;
  113559. else
  113560. break;
  113561. for(j=sortpos+1;j<posts;j++)
  113562. if(loneighbor[j]==ln)
  113563. loneighbor[j]=i;
  113564. else
  113565. break;
  113566. }
  113567. }else{
  113568. fit_valueA[i]=-200;
  113569. fit_valueB[i]=-200;
  113570. }
  113571. }
  113572. }
  113573. }
  113574. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113575. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113576. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113577. /* fill in posts marked as not using a fit; we will zero
  113578. back out to 'unused' when encoding them so long as curve
  113579. interpolation doesn't force them into use */
  113580. for(i=2;i<posts;i++){
  113581. int ln=look->loneighbor[i-2];
  113582. int hn=look->hineighbor[i-2];
  113583. int x0=info->postlist[ln];
  113584. int x1=info->postlist[hn];
  113585. int y0=output[ln];
  113586. int y1=output[hn];
  113587. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113588. int vx=post_Y(fit_valueA,fit_valueB,i);
  113589. if(vx>=0 && predicted!=vx){
  113590. output[i]=vx;
  113591. }else{
  113592. output[i]= predicted|0x8000;
  113593. }
  113594. }
  113595. }
  113596. return(output);
  113597. }
  113598. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113599. int *A,int *B,
  113600. int del){
  113601. long i;
  113602. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113603. long posts=look->posts;
  113604. int *output=NULL;
  113605. if(A && B){
  113606. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113607. for(i=0;i<posts;i++){
  113608. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113609. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113610. }
  113611. }
  113612. return(output);
  113613. }
  113614. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113615. void*look_,
  113616. int *post,int *ilogmask){
  113617. long i,j;
  113618. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113619. vorbis_info_floor1 *info=look->vi;
  113620. long posts=look->posts;
  113621. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113622. int out[VIF_POSIT+2];
  113623. static_codebook **sbooks=ci->book_param;
  113624. codebook *books=ci->fullbooks;
  113625. static long seq=0;
  113626. /* quantize values to multiplier spec */
  113627. if(post){
  113628. for(i=0;i<posts;i++){
  113629. int val=post[i]&0x7fff;
  113630. switch(info->mult){
  113631. case 1: /* 1024 -> 256 */
  113632. val>>=2;
  113633. break;
  113634. case 2: /* 1024 -> 128 */
  113635. val>>=3;
  113636. break;
  113637. case 3: /* 1024 -> 86 */
  113638. val/=12;
  113639. break;
  113640. case 4: /* 1024 -> 64 */
  113641. val>>=4;
  113642. break;
  113643. }
  113644. post[i]=val | (post[i]&0x8000);
  113645. }
  113646. out[0]=post[0];
  113647. out[1]=post[1];
  113648. /* find prediction values for each post and subtract them */
  113649. for(i=2;i<posts;i++){
  113650. int ln=look->loneighbor[i-2];
  113651. int hn=look->hineighbor[i-2];
  113652. int x0=info->postlist[ln];
  113653. int x1=info->postlist[hn];
  113654. int y0=post[ln];
  113655. int y1=post[hn];
  113656. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113657. if((post[i]&0x8000) || (predicted==post[i])){
  113658. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113659. in interpolation */
  113660. out[i]=0;
  113661. }else{
  113662. int headroom=(look->quant_q-predicted<predicted?
  113663. look->quant_q-predicted:predicted);
  113664. int val=post[i]-predicted;
  113665. /* at this point the 'deviation' value is in the range +/- max
  113666. range, but the real, unique range can always be mapped to
  113667. only [0-maxrange). So we want to wrap the deviation into
  113668. this limited range, but do it in the way that least screws
  113669. an essentially gaussian probability distribution. */
  113670. if(val<0)
  113671. if(val<-headroom)
  113672. val=headroom-val-1;
  113673. else
  113674. val=-1-(val<<1);
  113675. else
  113676. if(val>=headroom)
  113677. val= val+headroom;
  113678. else
  113679. val<<=1;
  113680. out[i]=val;
  113681. post[ln]&=0x7fff;
  113682. post[hn]&=0x7fff;
  113683. }
  113684. }
  113685. /* we have everything we need. pack it out */
  113686. /* mark nontrivial floor */
  113687. oggpack_write(opb,1,1);
  113688. /* beginning/end post */
  113689. look->frames++;
  113690. look->postbits+=ilog(look->quant_q-1)*2;
  113691. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113692. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113693. /* partition by partition */
  113694. for(i=0,j=2;i<info->partitions;i++){
  113695. int classx=info->partitionclass[i];
  113696. int cdim=info->class_dim[classx];
  113697. int csubbits=info->class_subs[classx];
  113698. int csub=1<<csubbits;
  113699. int bookas[8]={0,0,0,0,0,0,0,0};
  113700. int cval=0;
  113701. int cshift=0;
  113702. int k,l;
  113703. /* generate the partition's first stage cascade value */
  113704. if(csubbits){
  113705. int maxval[8];
  113706. for(k=0;k<csub;k++){
  113707. int booknum=info->class_subbook[classx][k];
  113708. if(booknum<0){
  113709. maxval[k]=1;
  113710. }else{
  113711. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113712. }
  113713. }
  113714. for(k=0;k<cdim;k++){
  113715. for(l=0;l<csub;l++){
  113716. int val=out[j+k];
  113717. if(val<maxval[l]){
  113718. bookas[k]=l;
  113719. break;
  113720. }
  113721. }
  113722. cval|= bookas[k]<<cshift;
  113723. cshift+=csubbits;
  113724. }
  113725. /* write it */
  113726. look->phrasebits+=
  113727. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113728. #ifdef TRAIN_FLOOR1
  113729. {
  113730. FILE *of;
  113731. char buffer[80];
  113732. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113733. vb->pcmend/2,posts-2,class);
  113734. of=fopen(buffer,"a");
  113735. fprintf(of,"%d\n",cval);
  113736. fclose(of);
  113737. }
  113738. #endif
  113739. }
  113740. /* write post values */
  113741. for(k=0;k<cdim;k++){
  113742. int book=info->class_subbook[classx][bookas[k]];
  113743. if(book>=0){
  113744. /* hack to allow training with 'bad' books */
  113745. if(out[j+k]<(books+book)->entries)
  113746. look->postbits+=vorbis_book_encode(books+book,
  113747. out[j+k],opb);
  113748. /*else
  113749. fprintf(stderr,"+!");*/
  113750. #ifdef TRAIN_FLOOR1
  113751. {
  113752. FILE *of;
  113753. char buffer[80];
  113754. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113755. vb->pcmend/2,posts-2,class,bookas[k]);
  113756. of=fopen(buffer,"a");
  113757. fprintf(of,"%d\n",out[j+k]);
  113758. fclose(of);
  113759. }
  113760. #endif
  113761. }
  113762. }
  113763. j+=cdim;
  113764. }
  113765. {
  113766. /* generate quantized floor equivalent to what we'd unpack in decode */
  113767. /* render the lines */
  113768. int hx=0;
  113769. int lx=0;
  113770. int ly=post[0]*info->mult;
  113771. for(j=1;j<look->posts;j++){
  113772. int current=look->forward_index[j];
  113773. int hy=post[current]&0x7fff;
  113774. if(hy==post[current]){
  113775. hy*=info->mult;
  113776. hx=info->postlist[current];
  113777. render_line0(lx,hx,ly,hy,ilogmask);
  113778. lx=hx;
  113779. ly=hy;
  113780. }
  113781. }
  113782. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113783. seq++;
  113784. return(1);
  113785. }
  113786. }else{
  113787. oggpack_write(opb,0,1);
  113788. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113789. seq++;
  113790. return(0);
  113791. }
  113792. }
  113793. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113794. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113795. vorbis_info_floor1 *info=look->vi;
  113796. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113797. int i,j,k;
  113798. codebook *books=ci->fullbooks;
  113799. /* unpack wrapped/predicted values from stream */
  113800. if(oggpack_read(&vb->opb,1)==1){
  113801. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113802. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113803. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113804. /* partition by partition */
  113805. for(i=0,j=2;i<info->partitions;i++){
  113806. int classx=info->partitionclass[i];
  113807. int cdim=info->class_dim[classx];
  113808. int csubbits=info->class_subs[classx];
  113809. int csub=1<<csubbits;
  113810. int cval=0;
  113811. /* decode the partition's first stage cascade value */
  113812. if(csubbits){
  113813. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113814. if(cval==-1)goto eop;
  113815. }
  113816. for(k=0;k<cdim;k++){
  113817. int book=info->class_subbook[classx][cval&(csub-1)];
  113818. cval>>=csubbits;
  113819. if(book>=0){
  113820. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113821. goto eop;
  113822. }else{
  113823. fit_value[j+k]=0;
  113824. }
  113825. }
  113826. j+=cdim;
  113827. }
  113828. /* unwrap positive values and reconsitute via linear interpolation */
  113829. for(i=2;i<look->posts;i++){
  113830. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113831. info->postlist[look->hineighbor[i-2]],
  113832. fit_value[look->loneighbor[i-2]],
  113833. fit_value[look->hineighbor[i-2]],
  113834. info->postlist[i]);
  113835. int hiroom=look->quant_q-predicted;
  113836. int loroom=predicted;
  113837. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113838. int val=fit_value[i];
  113839. if(val){
  113840. if(val>=room){
  113841. if(hiroom>loroom){
  113842. val = val-loroom;
  113843. }else{
  113844. val = -1-(val-hiroom);
  113845. }
  113846. }else{
  113847. if(val&1){
  113848. val= -((val+1)>>1);
  113849. }else{
  113850. val>>=1;
  113851. }
  113852. }
  113853. fit_value[i]=val+predicted;
  113854. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113855. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113856. }else{
  113857. fit_value[i]=predicted|0x8000;
  113858. }
  113859. }
  113860. return(fit_value);
  113861. }
  113862. eop:
  113863. return(NULL);
  113864. }
  113865. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113866. float *out){
  113867. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113868. vorbis_info_floor1 *info=look->vi;
  113869. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113870. int n=ci->blocksizes[vb->W]/2;
  113871. int j;
  113872. if(memo){
  113873. /* render the lines */
  113874. int *fit_value=(int *)memo;
  113875. int hx=0;
  113876. int lx=0;
  113877. int ly=fit_value[0]*info->mult;
  113878. for(j=1;j<look->posts;j++){
  113879. int current=look->forward_index[j];
  113880. int hy=fit_value[current]&0x7fff;
  113881. if(hy==fit_value[current]){
  113882. hy*=info->mult;
  113883. hx=info->postlist[current];
  113884. render_line(lx,hx,ly,hy,out);
  113885. lx=hx;
  113886. ly=hy;
  113887. }
  113888. }
  113889. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113890. return(1);
  113891. }
  113892. memset(out,0,sizeof(*out)*n);
  113893. return(0);
  113894. }
  113895. /* export hooks */
  113896. vorbis_func_floor floor1_exportbundle={
  113897. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113898. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113899. };
  113900. #endif
  113901. /*** End of inlined file: floor1.c ***/
  113902. /*** Start of inlined file: info.c ***/
  113903. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113904. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113905. // tasks..
  113906. #if JUCE_MSVC
  113907. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113908. #endif
  113909. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113910. #if JUCE_USE_OGGVORBIS
  113911. /* general handling of the header and the vorbis_info structure (and
  113912. substructures) */
  113913. #include <stdlib.h>
  113914. #include <string.h>
  113915. #include <ctype.h>
  113916. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113917. while(bytes--){
  113918. oggpack_write(o,*s++,8);
  113919. }
  113920. }
  113921. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113922. while(bytes--){
  113923. *buf++=oggpack_read(o,8);
  113924. }
  113925. }
  113926. void vorbis_comment_init(vorbis_comment *vc){
  113927. memset(vc,0,sizeof(*vc));
  113928. }
  113929. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113930. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113931. (vc->comments+2)*sizeof(*vc->user_comments));
  113932. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113933. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113934. vc->comment_lengths[vc->comments]=strlen(comment);
  113935. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113936. strcpy(vc->user_comments[vc->comments], comment);
  113937. vc->comments++;
  113938. vc->user_comments[vc->comments]=NULL;
  113939. }
  113940. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113941. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113942. strcpy(comment, tag);
  113943. strcat(comment, "=");
  113944. strcat(comment, contents);
  113945. vorbis_comment_add(vc, comment);
  113946. }
  113947. /* This is more or less the same as strncasecmp - but that doesn't exist
  113948. * everywhere, and this is a fairly trivial function, so we include it */
  113949. static int tagcompare(const char *s1, const char *s2, int n){
  113950. int c=0;
  113951. while(c < n){
  113952. if(toupper(s1[c]) != toupper(s2[c]))
  113953. return !0;
  113954. c++;
  113955. }
  113956. return 0;
  113957. }
  113958. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113959. long i;
  113960. int found = 0;
  113961. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113962. char *fulltag = (char*)alloca(taglen+ 1);
  113963. strcpy(fulltag, tag);
  113964. strcat(fulltag, "=");
  113965. for(i=0;i<vc->comments;i++){
  113966. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113967. if(count == found)
  113968. /* We return a pointer to the data, not a copy */
  113969. return vc->user_comments[i] + taglen;
  113970. else
  113971. found++;
  113972. }
  113973. }
  113974. return NULL; /* didn't find anything */
  113975. }
  113976. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113977. int i,count=0;
  113978. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113979. char *fulltag = (char*)alloca(taglen+1);
  113980. strcpy(fulltag,tag);
  113981. strcat(fulltag, "=");
  113982. for(i=0;i<vc->comments;i++){
  113983. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113984. count++;
  113985. }
  113986. return count;
  113987. }
  113988. void vorbis_comment_clear(vorbis_comment *vc){
  113989. if(vc){
  113990. long i;
  113991. for(i=0;i<vc->comments;i++)
  113992. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113993. if(vc->user_comments)_ogg_free(vc->user_comments);
  113994. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113995. if(vc->vendor)_ogg_free(vc->vendor);
  113996. }
  113997. memset(vc,0,sizeof(*vc));
  113998. }
  113999. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  114000. They may be equal, but short will never ge greater than long */
  114001. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  114002. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  114003. return ci ? ci->blocksizes[zo] : -1;
  114004. }
  114005. /* used by synthesis, which has a full, alloced vi */
  114006. void vorbis_info_init(vorbis_info *vi){
  114007. memset(vi,0,sizeof(*vi));
  114008. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  114009. }
  114010. void vorbis_info_clear(vorbis_info *vi){
  114011. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114012. int i;
  114013. if(ci){
  114014. for(i=0;i<ci->modes;i++)
  114015. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  114016. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  114017. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  114018. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  114019. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  114020. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  114021. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  114022. for(i=0;i<ci->books;i++){
  114023. if(ci->book_param[i]){
  114024. /* knows if the book was not alloced */
  114025. vorbis_staticbook_destroy(ci->book_param[i]);
  114026. }
  114027. if(ci->fullbooks)
  114028. vorbis_book_clear(ci->fullbooks+i);
  114029. }
  114030. if(ci->fullbooks)
  114031. _ogg_free(ci->fullbooks);
  114032. for(i=0;i<ci->psys;i++)
  114033. _vi_psy_free(ci->psy_param[i]);
  114034. _ogg_free(ci);
  114035. }
  114036. memset(vi,0,sizeof(*vi));
  114037. }
  114038. /* Header packing/unpacking ********************************************/
  114039. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  114040. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114041. if(!ci)return(OV_EFAULT);
  114042. vi->version=oggpack_read(opb,32);
  114043. if(vi->version!=0)return(OV_EVERSION);
  114044. vi->channels=oggpack_read(opb,8);
  114045. vi->rate=oggpack_read(opb,32);
  114046. vi->bitrate_upper=oggpack_read(opb,32);
  114047. vi->bitrate_nominal=oggpack_read(opb,32);
  114048. vi->bitrate_lower=oggpack_read(opb,32);
  114049. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  114050. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  114051. if(vi->rate<1)goto err_out;
  114052. if(vi->channels<1)goto err_out;
  114053. if(ci->blocksizes[0]<8)goto err_out;
  114054. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  114055. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114056. return(0);
  114057. err_out:
  114058. vorbis_info_clear(vi);
  114059. return(OV_EBADHEADER);
  114060. }
  114061. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  114062. int i;
  114063. int vendorlen=oggpack_read(opb,32);
  114064. if(vendorlen<0)goto err_out;
  114065. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  114066. _v_readstring(opb,vc->vendor,vendorlen);
  114067. vc->comments=oggpack_read(opb,32);
  114068. if(vc->comments<0)goto err_out;
  114069. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  114070. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  114071. for(i=0;i<vc->comments;i++){
  114072. int len=oggpack_read(opb,32);
  114073. if(len<0)goto err_out;
  114074. vc->comment_lengths[i]=len;
  114075. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  114076. _v_readstring(opb,vc->user_comments[i],len);
  114077. }
  114078. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114079. return(0);
  114080. err_out:
  114081. vorbis_comment_clear(vc);
  114082. return(OV_EBADHEADER);
  114083. }
  114084. /* all of the real encoding details are here. The modes, books,
  114085. everything */
  114086. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  114087. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114088. int i;
  114089. if(!ci)return(OV_EFAULT);
  114090. /* codebooks */
  114091. ci->books=oggpack_read(opb,8)+1;
  114092. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  114093. for(i=0;i<ci->books;i++){
  114094. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  114095. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  114096. }
  114097. /* time backend settings; hooks are unused */
  114098. {
  114099. int times=oggpack_read(opb,6)+1;
  114100. for(i=0;i<times;i++){
  114101. int test=oggpack_read(opb,16);
  114102. if(test<0 || test>=VI_TIMEB)goto err_out;
  114103. }
  114104. }
  114105. /* floor backend settings */
  114106. ci->floors=oggpack_read(opb,6)+1;
  114107. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  114108. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  114109. for(i=0;i<ci->floors;i++){
  114110. ci->floor_type[i]=oggpack_read(opb,16);
  114111. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  114112. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  114113. if(!ci->floor_param[i])goto err_out;
  114114. }
  114115. /* residue backend settings */
  114116. ci->residues=oggpack_read(opb,6)+1;
  114117. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  114118. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  114119. for(i=0;i<ci->residues;i++){
  114120. ci->residue_type[i]=oggpack_read(opb,16);
  114121. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  114122. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  114123. if(!ci->residue_param[i])goto err_out;
  114124. }
  114125. /* map backend settings */
  114126. ci->maps=oggpack_read(opb,6)+1;
  114127. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  114128. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  114129. for(i=0;i<ci->maps;i++){
  114130. ci->map_type[i]=oggpack_read(opb,16);
  114131. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  114132. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  114133. if(!ci->map_param[i])goto err_out;
  114134. }
  114135. /* mode settings */
  114136. ci->modes=oggpack_read(opb,6)+1;
  114137. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  114138. for(i=0;i<ci->modes;i++){
  114139. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  114140. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  114141. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  114142. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  114143. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  114144. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  114145. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  114146. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  114147. }
  114148. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  114149. return(0);
  114150. err_out:
  114151. vorbis_info_clear(vi);
  114152. return(OV_EBADHEADER);
  114153. }
  114154. /* The Vorbis header is in three packets; the initial small packet in
  114155. the first page that identifies basic parameters, a second packet
  114156. with bitstream comments and a third packet that holds the
  114157. codebook. */
  114158. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  114159. oggpack_buffer opb;
  114160. if(op){
  114161. oggpack_readinit(&opb,op->packet,op->bytes);
  114162. /* Which of the three types of header is this? */
  114163. /* Also verify header-ness, vorbis */
  114164. {
  114165. char buffer[6];
  114166. int packtype=oggpack_read(&opb,8);
  114167. memset(buffer,0,6);
  114168. _v_readstring(&opb,buffer,6);
  114169. if(memcmp(buffer,"vorbis",6)){
  114170. /* not a vorbis header */
  114171. return(OV_ENOTVORBIS);
  114172. }
  114173. switch(packtype){
  114174. case 0x01: /* least significant *bit* is read first */
  114175. if(!op->b_o_s){
  114176. /* Not the initial packet */
  114177. return(OV_EBADHEADER);
  114178. }
  114179. if(vi->rate!=0){
  114180. /* previously initialized info header */
  114181. return(OV_EBADHEADER);
  114182. }
  114183. return(_vorbis_unpack_info(vi,&opb));
  114184. case 0x03: /* least significant *bit* is read first */
  114185. if(vi->rate==0){
  114186. /* um... we didn't get the initial header */
  114187. return(OV_EBADHEADER);
  114188. }
  114189. return(_vorbis_unpack_comment(vc,&opb));
  114190. case 0x05: /* least significant *bit* is read first */
  114191. if(vi->rate==0 || vc->vendor==NULL){
  114192. /* um... we didn;t get the initial header or comments yet */
  114193. return(OV_EBADHEADER);
  114194. }
  114195. return(_vorbis_unpack_books(vi,&opb));
  114196. default:
  114197. /* Not a valid vorbis header type */
  114198. return(OV_EBADHEADER);
  114199. break;
  114200. }
  114201. }
  114202. }
  114203. return(OV_EBADHEADER);
  114204. }
  114205. /* pack side **********************************************************/
  114206. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114207. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114208. if(!ci)return(OV_EFAULT);
  114209. /* preamble */
  114210. oggpack_write(opb,0x01,8);
  114211. _v_writestring(opb,"vorbis", 6);
  114212. /* basic information about the stream */
  114213. oggpack_write(opb,0x00,32);
  114214. oggpack_write(opb,vi->channels,8);
  114215. oggpack_write(opb,vi->rate,32);
  114216. oggpack_write(opb,vi->bitrate_upper,32);
  114217. oggpack_write(opb,vi->bitrate_nominal,32);
  114218. oggpack_write(opb,vi->bitrate_lower,32);
  114219. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114220. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114221. oggpack_write(opb,1,1);
  114222. return(0);
  114223. }
  114224. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114225. char temp[]="Xiph.Org libVorbis I 20050304";
  114226. int bytes = strlen(temp);
  114227. /* preamble */
  114228. oggpack_write(opb,0x03,8);
  114229. _v_writestring(opb,"vorbis", 6);
  114230. /* vendor */
  114231. oggpack_write(opb,bytes,32);
  114232. _v_writestring(opb,temp, bytes);
  114233. /* comments */
  114234. oggpack_write(opb,vc->comments,32);
  114235. if(vc->comments){
  114236. int i;
  114237. for(i=0;i<vc->comments;i++){
  114238. if(vc->user_comments[i]){
  114239. oggpack_write(opb,vc->comment_lengths[i],32);
  114240. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114241. }else{
  114242. oggpack_write(opb,0,32);
  114243. }
  114244. }
  114245. }
  114246. oggpack_write(opb,1,1);
  114247. return(0);
  114248. }
  114249. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114250. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114251. int i;
  114252. if(!ci)return(OV_EFAULT);
  114253. oggpack_write(opb,0x05,8);
  114254. _v_writestring(opb,"vorbis", 6);
  114255. /* books */
  114256. oggpack_write(opb,ci->books-1,8);
  114257. for(i=0;i<ci->books;i++)
  114258. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114259. /* times; hook placeholders */
  114260. oggpack_write(opb,0,6);
  114261. oggpack_write(opb,0,16);
  114262. /* floors */
  114263. oggpack_write(opb,ci->floors-1,6);
  114264. for(i=0;i<ci->floors;i++){
  114265. oggpack_write(opb,ci->floor_type[i],16);
  114266. if(_floor_P[ci->floor_type[i]]->pack)
  114267. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114268. else
  114269. goto err_out;
  114270. }
  114271. /* residues */
  114272. oggpack_write(opb,ci->residues-1,6);
  114273. for(i=0;i<ci->residues;i++){
  114274. oggpack_write(opb,ci->residue_type[i],16);
  114275. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114276. }
  114277. /* maps */
  114278. oggpack_write(opb,ci->maps-1,6);
  114279. for(i=0;i<ci->maps;i++){
  114280. oggpack_write(opb,ci->map_type[i],16);
  114281. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114282. }
  114283. /* modes */
  114284. oggpack_write(opb,ci->modes-1,6);
  114285. for(i=0;i<ci->modes;i++){
  114286. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114287. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114288. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114289. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114290. }
  114291. oggpack_write(opb,1,1);
  114292. return(0);
  114293. err_out:
  114294. return(-1);
  114295. }
  114296. int vorbis_commentheader_out(vorbis_comment *vc,
  114297. ogg_packet *op){
  114298. oggpack_buffer opb;
  114299. oggpack_writeinit(&opb);
  114300. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114301. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114302. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114303. op->bytes=oggpack_bytes(&opb);
  114304. op->b_o_s=0;
  114305. op->e_o_s=0;
  114306. op->granulepos=0;
  114307. op->packetno=1;
  114308. return 0;
  114309. }
  114310. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114311. vorbis_comment *vc,
  114312. ogg_packet *op,
  114313. ogg_packet *op_comm,
  114314. ogg_packet *op_code){
  114315. int ret=OV_EIMPL;
  114316. vorbis_info *vi=v->vi;
  114317. oggpack_buffer opb;
  114318. private_state *b=(private_state*)v->backend_state;
  114319. if(!b){
  114320. ret=OV_EFAULT;
  114321. goto err_out;
  114322. }
  114323. /* first header packet **********************************************/
  114324. oggpack_writeinit(&opb);
  114325. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114326. /* build the packet */
  114327. if(b->header)_ogg_free(b->header);
  114328. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114329. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114330. op->packet=b->header;
  114331. op->bytes=oggpack_bytes(&opb);
  114332. op->b_o_s=1;
  114333. op->e_o_s=0;
  114334. op->granulepos=0;
  114335. op->packetno=0;
  114336. /* second header packet (comments) **********************************/
  114337. oggpack_reset(&opb);
  114338. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114339. if(b->header1)_ogg_free(b->header1);
  114340. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114341. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114342. op_comm->packet=b->header1;
  114343. op_comm->bytes=oggpack_bytes(&opb);
  114344. op_comm->b_o_s=0;
  114345. op_comm->e_o_s=0;
  114346. op_comm->granulepos=0;
  114347. op_comm->packetno=1;
  114348. /* third header packet (modes/codebooks) ****************************/
  114349. oggpack_reset(&opb);
  114350. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114351. if(b->header2)_ogg_free(b->header2);
  114352. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114353. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114354. op_code->packet=b->header2;
  114355. op_code->bytes=oggpack_bytes(&opb);
  114356. op_code->b_o_s=0;
  114357. op_code->e_o_s=0;
  114358. op_code->granulepos=0;
  114359. op_code->packetno=2;
  114360. oggpack_writeclear(&opb);
  114361. return(0);
  114362. err_out:
  114363. oggpack_writeclear(&opb);
  114364. memset(op,0,sizeof(*op));
  114365. memset(op_comm,0,sizeof(*op_comm));
  114366. memset(op_code,0,sizeof(*op_code));
  114367. if(b->header)_ogg_free(b->header);
  114368. if(b->header1)_ogg_free(b->header1);
  114369. if(b->header2)_ogg_free(b->header2);
  114370. b->header=NULL;
  114371. b->header1=NULL;
  114372. b->header2=NULL;
  114373. return(ret);
  114374. }
  114375. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114376. if(granulepos>=0)
  114377. return((double)granulepos/v->vi->rate);
  114378. return(-1);
  114379. }
  114380. #endif
  114381. /*** End of inlined file: info.c ***/
  114382. /*** Start of inlined file: lpc.c ***/
  114383. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114384. are derived from code written by Jutta Degener and Carsten Bormann;
  114385. thus we include their copyright below. The entirety of this file
  114386. is freely redistributable on the condition that both of these
  114387. copyright notices are preserved without modification. */
  114388. /* Preserved Copyright: *********************************************/
  114389. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114390. Technische Universita"t Berlin
  114391. Any use of this software is permitted provided that this notice is not
  114392. removed and that neither the authors nor the Technische Universita"t
  114393. Berlin are deemed to have made any representations as to the
  114394. suitability of this software for any purpose nor are held responsible
  114395. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114396. THIS SOFTWARE.
  114397. As a matter of courtesy, the authors request to be informed about uses
  114398. this software has found, about bugs in this software, and about any
  114399. improvements that may be of general interest.
  114400. Berlin, 28.11.1994
  114401. Jutta Degener
  114402. Carsten Bormann
  114403. *********************************************************************/
  114404. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114405. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114406. // tasks..
  114407. #if JUCE_MSVC
  114408. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114409. #endif
  114410. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114411. #if JUCE_USE_OGGVORBIS
  114412. #include <stdlib.h>
  114413. #include <string.h>
  114414. #include <math.h>
  114415. /* Autocorrelation LPC coeff generation algorithm invented by
  114416. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114417. /* Input : n elements of time doamin data
  114418. Output: m lpc coefficients, excitation energy */
  114419. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114420. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114421. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114422. double error;
  114423. int i,j;
  114424. /* autocorrelation, p+1 lag coefficients */
  114425. j=m+1;
  114426. while(j--){
  114427. double d=0; /* double needed for accumulator depth */
  114428. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114429. aut[j]=d;
  114430. }
  114431. /* Generate lpc coefficients from autocorr values */
  114432. error=aut[0];
  114433. for(i=0;i<m;i++){
  114434. double r= -aut[i+1];
  114435. if(error==0){
  114436. memset(lpci,0,m*sizeof(*lpci));
  114437. return 0;
  114438. }
  114439. /* Sum up this iteration's reflection coefficient; note that in
  114440. Vorbis we don't save it. If anyone wants to recycle this code
  114441. and needs reflection coefficients, save the results of 'r' from
  114442. each iteration. */
  114443. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114444. r/=error;
  114445. /* Update LPC coefficients and total error */
  114446. lpc[i]=r;
  114447. for(j=0;j<i/2;j++){
  114448. double tmp=lpc[j];
  114449. lpc[j]+=r*lpc[i-1-j];
  114450. lpc[i-1-j]+=r*tmp;
  114451. }
  114452. if(i%2)lpc[j]+=lpc[j]*r;
  114453. error*=1.f-r*r;
  114454. }
  114455. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114456. /* we need the error value to know how big an impulse to hit the
  114457. filter with later */
  114458. return error;
  114459. }
  114460. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114461. float *data,long n){
  114462. /* in: coeff[0...m-1] LPC coefficients
  114463. prime[0...m-1] initial values (allocated size of n+m-1)
  114464. out: data[0...n-1] data samples */
  114465. long i,j,o,p;
  114466. float y;
  114467. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114468. if(!prime)
  114469. for(i=0;i<m;i++)
  114470. work[i]=0.f;
  114471. else
  114472. for(i=0;i<m;i++)
  114473. work[i]=prime[i];
  114474. for(i=0;i<n;i++){
  114475. y=0;
  114476. o=i;
  114477. p=m;
  114478. for(j=0;j<m;j++)
  114479. y-=work[o++]*coeff[--p];
  114480. data[i]=work[o]=y;
  114481. }
  114482. }
  114483. #endif
  114484. /*** End of inlined file: lpc.c ***/
  114485. /*** Start of inlined file: lsp.c ***/
  114486. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114487. an iterative root polisher (CACM algorithm 283). It *is* possible
  114488. to confuse this algorithm into not converging; that should only
  114489. happen with absurdly closely spaced roots (very sharp peaks in the
  114490. LPC f response) which in turn should be impossible in our use of
  114491. the code. If this *does* happen anyway, it's a bug in the floor
  114492. finder; find the cause of the confusion (probably a single bin
  114493. spike or accidental near-float-limit resolution problems) and
  114494. correct it. */
  114495. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114496. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114497. // tasks..
  114498. #if JUCE_MSVC
  114499. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114500. #endif
  114501. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114502. #if JUCE_USE_OGGVORBIS
  114503. #include <math.h>
  114504. #include <string.h>
  114505. #include <stdlib.h>
  114506. /*** Start of inlined file: lookup.h ***/
  114507. #ifndef _V_LOOKUP_H_
  114508. #ifdef FLOAT_LOOKUP
  114509. extern float vorbis_coslook(float a);
  114510. extern float vorbis_invsqlook(float a);
  114511. extern float vorbis_invsq2explook(int a);
  114512. extern float vorbis_fromdBlook(float a);
  114513. #endif
  114514. #ifdef INT_LOOKUP
  114515. extern long vorbis_invsqlook_i(long a,long e);
  114516. extern long vorbis_coslook_i(long a);
  114517. extern float vorbis_fromdBlook_i(long a);
  114518. #endif
  114519. #endif
  114520. /*** End of inlined file: lookup.h ***/
  114521. /* three possible LSP to f curve functions; the exact computation
  114522. (float), a lookup based float implementation, and an integer
  114523. implementation. The float lookup is likely the optimal choice on
  114524. any machine with an FPU. The integer implementation is *not* fixed
  114525. point (due to the need for a large dynamic range and thus a
  114526. seperately tracked exponent) and thus much more complex than the
  114527. relatively simple float implementations. It's mostly for future
  114528. work on a fully fixed point implementation for processors like the
  114529. ARM family. */
  114530. /* undefine both for the 'old' but more precise implementation */
  114531. #define FLOAT_LOOKUP
  114532. #undef INT_LOOKUP
  114533. #ifdef FLOAT_LOOKUP
  114534. /*** Start of inlined file: lookup.c ***/
  114535. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114536. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114537. // tasks..
  114538. #if JUCE_MSVC
  114539. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114540. #endif
  114541. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114542. #if JUCE_USE_OGGVORBIS
  114543. #include <math.h>
  114544. /*** Start of inlined file: lookup.h ***/
  114545. #ifndef _V_LOOKUP_H_
  114546. #ifdef FLOAT_LOOKUP
  114547. extern float vorbis_coslook(float a);
  114548. extern float vorbis_invsqlook(float a);
  114549. extern float vorbis_invsq2explook(int a);
  114550. extern float vorbis_fromdBlook(float a);
  114551. #endif
  114552. #ifdef INT_LOOKUP
  114553. extern long vorbis_invsqlook_i(long a,long e);
  114554. extern long vorbis_coslook_i(long a);
  114555. extern float vorbis_fromdBlook_i(long a);
  114556. #endif
  114557. #endif
  114558. /*** End of inlined file: lookup.h ***/
  114559. /*** Start of inlined file: lookup_data.h ***/
  114560. #ifndef _V_LOOKUP_DATA_H_
  114561. #ifdef FLOAT_LOOKUP
  114562. #define COS_LOOKUP_SZ 128
  114563. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114564. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114565. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114566. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114567. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114568. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114569. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114570. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114571. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114572. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114573. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114574. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114575. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114576. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114577. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114578. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114579. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114580. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114581. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114582. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114583. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114584. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114585. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114586. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114587. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114588. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114589. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114590. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114591. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114592. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114593. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114594. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114595. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114596. -1.0000000000000f,
  114597. };
  114598. #define INVSQ_LOOKUP_SZ 32
  114599. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114600. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114601. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114602. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114603. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114604. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114605. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114606. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114607. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114608. 1.000000000000f,
  114609. };
  114610. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114611. #define INVSQ2EXP_LOOKUP_MAX 32
  114612. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114613. INVSQ2EXP_LOOKUP_MIN+1]={
  114614. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114615. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114616. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114617. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114618. 256.f, 181.019336f, 128.f, 90.50966799f,
  114619. 64.f, 45.254834f, 32.f, 22.627417f,
  114620. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114621. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114622. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114623. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114624. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114625. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114626. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114627. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114628. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114629. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114630. 1.525878906e-05f,
  114631. };
  114632. #endif
  114633. #define FROMdB_LOOKUP_SZ 35
  114634. #define FROMdB2_LOOKUP_SZ 32
  114635. #define FROMdB_SHIFT 5
  114636. #define FROMdB2_SHIFT 3
  114637. #define FROMdB2_MASK 31
  114638. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114639. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114640. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114641. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114642. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114643. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114644. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114645. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114646. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114647. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114648. };
  114649. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114650. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114651. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114652. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114653. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114654. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114655. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114656. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114657. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114658. };
  114659. #ifdef INT_LOOKUP
  114660. #define INVSQ_LOOKUP_I_SHIFT 10
  114661. #define INVSQ_LOOKUP_I_MASK 1023
  114662. static long INVSQ_LOOKUP_I[64+1]={
  114663. 92682l, 91966l, 91267l, 90583l,
  114664. 89915l, 89261l, 88621l, 87995l,
  114665. 87381l, 86781l, 86192l, 85616l,
  114666. 85051l, 84497l, 83953l, 83420l,
  114667. 82897l, 82384l, 81880l, 81385l,
  114668. 80899l, 80422l, 79953l, 79492l,
  114669. 79039l, 78594l, 78156l, 77726l,
  114670. 77302l, 76885l, 76475l, 76072l,
  114671. 75674l, 75283l, 74898l, 74519l,
  114672. 74146l, 73778l, 73415l, 73058l,
  114673. 72706l, 72359l, 72016l, 71679l,
  114674. 71347l, 71019l, 70695l, 70376l,
  114675. 70061l, 69750l, 69444l, 69141l,
  114676. 68842l, 68548l, 68256l, 67969l,
  114677. 67685l, 67405l, 67128l, 66855l,
  114678. 66585l, 66318l, 66054l, 65794l,
  114679. 65536l,
  114680. };
  114681. #define COS_LOOKUP_I_SHIFT 9
  114682. #define COS_LOOKUP_I_MASK 511
  114683. #define COS_LOOKUP_I_SZ 128
  114684. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114685. 16384l, 16379l, 16364l, 16340l,
  114686. 16305l, 16261l, 16207l, 16143l,
  114687. 16069l, 15986l, 15893l, 15791l,
  114688. 15679l, 15557l, 15426l, 15286l,
  114689. 15137l, 14978l, 14811l, 14635l,
  114690. 14449l, 14256l, 14053l, 13842l,
  114691. 13623l, 13395l, 13160l, 12916l,
  114692. 12665l, 12406l, 12140l, 11866l,
  114693. 11585l, 11297l, 11003l, 10702l,
  114694. 10394l, 10080l, 9760l, 9434l,
  114695. 9102l, 8765l, 8423l, 8076l,
  114696. 7723l, 7366l, 7005l, 6639l,
  114697. 6270l, 5897l, 5520l, 5139l,
  114698. 4756l, 4370l, 3981l, 3590l,
  114699. 3196l, 2801l, 2404l, 2006l,
  114700. 1606l, 1205l, 804l, 402l,
  114701. 0l, -401l, -803l, -1204l,
  114702. -1605l, -2005l, -2403l, -2800l,
  114703. -3195l, -3589l, -3980l, -4369l,
  114704. -4755l, -5138l, -5519l, -5896l,
  114705. -6269l, -6638l, -7004l, -7365l,
  114706. -7722l, -8075l, -8422l, -8764l,
  114707. -9101l, -9433l, -9759l, -10079l,
  114708. -10393l, -10701l, -11002l, -11296l,
  114709. -11584l, -11865l, -12139l, -12405l,
  114710. -12664l, -12915l, -13159l, -13394l,
  114711. -13622l, -13841l, -14052l, -14255l,
  114712. -14448l, -14634l, -14810l, -14977l,
  114713. -15136l, -15285l, -15425l, -15556l,
  114714. -15678l, -15790l, -15892l, -15985l,
  114715. -16068l, -16142l, -16206l, -16260l,
  114716. -16304l, -16339l, -16363l, -16378l,
  114717. -16383l,
  114718. };
  114719. #endif
  114720. #endif
  114721. /*** End of inlined file: lookup_data.h ***/
  114722. #ifdef FLOAT_LOOKUP
  114723. /* interpolated lookup based cos function, domain 0 to PI only */
  114724. float vorbis_coslook(float a){
  114725. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114726. int i=vorbis_ftoi(d-.5);
  114727. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114728. }
  114729. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114730. float vorbis_invsqlook(float a){
  114731. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114732. int i=vorbis_ftoi(d-.5f);
  114733. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114734. }
  114735. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114736. float vorbis_invsq2explook(int a){
  114737. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114738. }
  114739. #include <stdio.h>
  114740. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114741. float vorbis_fromdBlook(float a){
  114742. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114743. return (i<0)?1.f:
  114744. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114745. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114746. }
  114747. #endif
  114748. #ifdef INT_LOOKUP
  114749. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114750. 16.16 format
  114751. returns in m.8 format */
  114752. long vorbis_invsqlook_i(long a,long e){
  114753. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114754. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114755. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114756. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114757. d)>>16); /* result 1.16 */
  114758. e+=32;
  114759. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114760. e=(e>>1)-8;
  114761. return(val>>e);
  114762. }
  114763. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114764. /* a is in n.12 format */
  114765. float vorbis_fromdBlook_i(long a){
  114766. int i=(-a)>>(12-FROMdB2_SHIFT);
  114767. return (i<0)?1.f:
  114768. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114769. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114770. }
  114771. /* interpolated lookup based cos function, domain 0 to PI only */
  114772. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114773. long vorbis_coslook_i(long a){
  114774. int i=a>>COS_LOOKUP_I_SHIFT;
  114775. int d=a&COS_LOOKUP_I_MASK;
  114776. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114777. COS_LOOKUP_I_SHIFT);
  114778. }
  114779. #endif
  114780. #endif
  114781. /*** End of inlined file: lookup.c ***/
  114782. /* catch this in the build system; we #include for
  114783. compilers (like gcc) that can't inline across
  114784. modules */
  114785. /* side effect: changes *lsp to cosines of lsp */
  114786. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114787. float amp,float ampoffset){
  114788. int i;
  114789. float wdel=M_PI/ln;
  114790. vorbis_fpu_control fpu;
  114791. (void) fpu; // to avoid an unused variable warning
  114792. vorbis_fpu_setround(&fpu);
  114793. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114794. i=0;
  114795. while(i<n){
  114796. int k=map[i];
  114797. int qexp;
  114798. float p=.7071067812f;
  114799. float q=.7071067812f;
  114800. float w=vorbis_coslook(wdel*k);
  114801. float *ftmp=lsp;
  114802. int c=m>>1;
  114803. do{
  114804. q*=ftmp[0]-w;
  114805. p*=ftmp[1]-w;
  114806. ftmp+=2;
  114807. }while(--c);
  114808. if(m&1){
  114809. /* odd order filter; slightly assymetric */
  114810. /* the last coefficient */
  114811. q*=ftmp[0]-w;
  114812. q*=q;
  114813. p*=p*(1.f-w*w);
  114814. }else{
  114815. /* even order filter; still symmetric */
  114816. q*=q*(1.f+w);
  114817. p*=p*(1.f-w);
  114818. }
  114819. q=frexp(p+q,&qexp);
  114820. q=vorbis_fromdBlook(amp*
  114821. vorbis_invsqlook(q)*
  114822. vorbis_invsq2explook(qexp+m)-
  114823. ampoffset);
  114824. do{
  114825. curve[i++]*=q;
  114826. }while(map[i]==k);
  114827. }
  114828. vorbis_fpu_restore(fpu);
  114829. }
  114830. #else
  114831. #ifdef INT_LOOKUP
  114832. /*** Start of inlined file: lookup.c ***/
  114833. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114834. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114835. // tasks..
  114836. #if JUCE_MSVC
  114837. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114838. #endif
  114839. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114840. #if JUCE_USE_OGGVORBIS
  114841. #include <math.h>
  114842. /*** Start of inlined file: lookup.h ***/
  114843. #ifndef _V_LOOKUP_H_
  114844. #ifdef FLOAT_LOOKUP
  114845. extern float vorbis_coslook(float a);
  114846. extern float vorbis_invsqlook(float a);
  114847. extern float vorbis_invsq2explook(int a);
  114848. extern float vorbis_fromdBlook(float a);
  114849. #endif
  114850. #ifdef INT_LOOKUP
  114851. extern long vorbis_invsqlook_i(long a,long e);
  114852. extern long vorbis_coslook_i(long a);
  114853. extern float vorbis_fromdBlook_i(long a);
  114854. #endif
  114855. #endif
  114856. /*** End of inlined file: lookup.h ***/
  114857. /*** Start of inlined file: lookup_data.h ***/
  114858. #ifndef _V_LOOKUP_DATA_H_
  114859. #ifdef FLOAT_LOOKUP
  114860. #define COS_LOOKUP_SZ 128
  114861. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114862. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114863. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114864. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114865. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114866. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114867. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114868. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114869. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114870. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114871. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114872. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114873. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114874. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114875. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114876. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114877. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114878. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114879. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114880. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114881. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114882. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114883. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114884. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114885. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114886. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114887. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114888. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114889. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114890. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114891. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114892. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114893. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114894. -1.0000000000000f,
  114895. };
  114896. #define INVSQ_LOOKUP_SZ 32
  114897. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114898. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114899. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114900. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114901. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114902. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114903. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114904. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114905. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114906. 1.000000000000f,
  114907. };
  114908. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114909. #define INVSQ2EXP_LOOKUP_MAX 32
  114910. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114911. INVSQ2EXP_LOOKUP_MIN+1]={
  114912. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114913. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114914. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114915. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114916. 256.f, 181.019336f, 128.f, 90.50966799f,
  114917. 64.f, 45.254834f, 32.f, 22.627417f,
  114918. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114919. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114920. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114921. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114922. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114923. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114924. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114925. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114926. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114927. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114928. 1.525878906e-05f,
  114929. };
  114930. #endif
  114931. #define FROMdB_LOOKUP_SZ 35
  114932. #define FROMdB2_LOOKUP_SZ 32
  114933. #define FROMdB_SHIFT 5
  114934. #define FROMdB2_SHIFT 3
  114935. #define FROMdB2_MASK 31
  114936. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114937. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114938. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114939. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114940. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114941. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114942. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114943. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114944. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114945. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114946. };
  114947. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114948. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114949. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114950. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114951. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114952. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114953. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114954. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114955. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114956. };
  114957. #ifdef INT_LOOKUP
  114958. #define INVSQ_LOOKUP_I_SHIFT 10
  114959. #define INVSQ_LOOKUP_I_MASK 1023
  114960. static long INVSQ_LOOKUP_I[64+1]={
  114961. 92682l, 91966l, 91267l, 90583l,
  114962. 89915l, 89261l, 88621l, 87995l,
  114963. 87381l, 86781l, 86192l, 85616l,
  114964. 85051l, 84497l, 83953l, 83420l,
  114965. 82897l, 82384l, 81880l, 81385l,
  114966. 80899l, 80422l, 79953l, 79492l,
  114967. 79039l, 78594l, 78156l, 77726l,
  114968. 77302l, 76885l, 76475l, 76072l,
  114969. 75674l, 75283l, 74898l, 74519l,
  114970. 74146l, 73778l, 73415l, 73058l,
  114971. 72706l, 72359l, 72016l, 71679l,
  114972. 71347l, 71019l, 70695l, 70376l,
  114973. 70061l, 69750l, 69444l, 69141l,
  114974. 68842l, 68548l, 68256l, 67969l,
  114975. 67685l, 67405l, 67128l, 66855l,
  114976. 66585l, 66318l, 66054l, 65794l,
  114977. 65536l,
  114978. };
  114979. #define COS_LOOKUP_I_SHIFT 9
  114980. #define COS_LOOKUP_I_MASK 511
  114981. #define COS_LOOKUP_I_SZ 128
  114982. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114983. 16384l, 16379l, 16364l, 16340l,
  114984. 16305l, 16261l, 16207l, 16143l,
  114985. 16069l, 15986l, 15893l, 15791l,
  114986. 15679l, 15557l, 15426l, 15286l,
  114987. 15137l, 14978l, 14811l, 14635l,
  114988. 14449l, 14256l, 14053l, 13842l,
  114989. 13623l, 13395l, 13160l, 12916l,
  114990. 12665l, 12406l, 12140l, 11866l,
  114991. 11585l, 11297l, 11003l, 10702l,
  114992. 10394l, 10080l, 9760l, 9434l,
  114993. 9102l, 8765l, 8423l, 8076l,
  114994. 7723l, 7366l, 7005l, 6639l,
  114995. 6270l, 5897l, 5520l, 5139l,
  114996. 4756l, 4370l, 3981l, 3590l,
  114997. 3196l, 2801l, 2404l, 2006l,
  114998. 1606l, 1205l, 804l, 402l,
  114999. 0l, -401l, -803l, -1204l,
  115000. -1605l, -2005l, -2403l, -2800l,
  115001. -3195l, -3589l, -3980l, -4369l,
  115002. -4755l, -5138l, -5519l, -5896l,
  115003. -6269l, -6638l, -7004l, -7365l,
  115004. -7722l, -8075l, -8422l, -8764l,
  115005. -9101l, -9433l, -9759l, -10079l,
  115006. -10393l, -10701l, -11002l, -11296l,
  115007. -11584l, -11865l, -12139l, -12405l,
  115008. -12664l, -12915l, -13159l, -13394l,
  115009. -13622l, -13841l, -14052l, -14255l,
  115010. -14448l, -14634l, -14810l, -14977l,
  115011. -15136l, -15285l, -15425l, -15556l,
  115012. -15678l, -15790l, -15892l, -15985l,
  115013. -16068l, -16142l, -16206l, -16260l,
  115014. -16304l, -16339l, -16363l, -16378l,
  115015. -16383l,
  115016. };
  115017. #endif
  115018. #endif
  115019. /*** End of inlined file: lookup_data.h ***/
  115020. #ifdef FLOAT_LOOKUP
  115021. /* interpolated lookup based cos function, domain 0 to PI only */
  115022. float vorbis_coslook(float a){
  115023. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  115024. int i=vorbis_ftoi(d-.5);
  115025. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  115026. }
  115027. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115028. float vorbis_invsqlook(float a){
  115029. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  115030. int i=vorbis_ftoi(d-.5f);
  115031. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  115032. }
  115033. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115034. float vorbis_invsq2explook(int a){
  115035. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  115036. }
  115037. #include <stdio.h>
  115038. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115039. float vorbis_fromdBlook(float a){
  115040. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  115041. return (i<0)?1.f:
  115042. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115043. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115044. }
  115045. #endif
  115046. #ifdef INT_LOOKUP
  115047. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  115048. 16.16 format
  115049. returns in m.8 format */
  115050. long vorbis_invsqlook_i(long a,long e){
  115051. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  115052. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  115053. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  115054. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  115055. d)>>16); /* result 1.16 */
  115056. e+=32;
  115057. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  115058. e=(e>>1)-8;
  115059. return(val>>e);
  115060. }
  115061. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115062. /* a is in n.12 format */
  115063. float vorbis_fromdBlook_i(long a){
  115064. int i=(-a)>>(12-FROMdB2_SHIFT);
  115065. return (i<0)?1.f:
  115066. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115067. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115068. }
  115069. /* interpolated lookup based cos function, domain 0 to PI only */
  115070. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  115071. long vorbis_coslook_i(long a){
  115072. int i=a>>COS_LOOKUP_I_SHIFT;
  115073. int d=a&COS_LOOKUP_I_MASK;
  115074. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  115075. COS_LOOKUP_I_SHIFT);
  115076. }
  115077. #endif
  115078. #endif
  115079. /*** End of inlined file: lookup.c ***/
  115080. /* catch this in the build system; we #include for
  115081. compilers (like gcc) that can't inline across
  115082. modules */
  115083. static int MLOOP_1[64]={
  115084. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  115085. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  115086. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115087. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115088. };
  115089. static int MLOOP_2[64]={
  115090. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  115091. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  115092. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115093. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115094. };
  115095. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  115096. /* side effect: changes *lsp to cosines of lsp */
  115097. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115098. float amp,float ampoffset){
  115099. /* 0 <= m < 256 */
  115100. /* set up for using all int later */
  115101. int i;
  115102. int ampoffseti=rint(ampoffset*4096.f);
  115103. int ampi=rint(amp*16.f);
  115104. long *ilsp=alloca(m*sizeof(*ilsp));
  115105. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  115106. i=0;
  115107. while(i<n){
  115108. int j,k=map[i];
  115109. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  115110. unsigned long qi=46341;
  115111. int qexp=0,shift;
  115112. long wi=vorbis_coslook_i(k*65536/ln);
  115113. qi*=labs(ilsp[0]-wi);
  115114. pi*=labs(ilsp[1]-wi);
  115115. for(j=3;j<m;j+=2){
  115116. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115117. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115118. shift=MLOOP_3[(pi|qi)>>16];
  115119. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115120. pi=(pi>>shift)*labs(ilsp[j]-wi);
  115121. qexp+=shift;
  115122. }
  115123. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115124. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115125. shift=MLOOP_3[(pi|qi)>>16];
  115126. /* pi,qi normalized collectively, both tracked using qexp */
  115127. if(m&1){
  115128. /* odd order filter; slightly assymetric */
  115129. /* the last coefficient */
  115130. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115131. pi=(pi>>shift)<<14;
  115132. qexp+=shift;
  115133. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115134. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115135. shift=MLOOP_3[(pi|qi)>>16];
  115136. pi>>=shift;
  115137. qi>>=shift;
  115138. qexp+=shift-14*((m+1)>>1);
  115139. pi=((pi*pi)>>16);
  115140. qi=((qi*qi)>>16);
  115141. qexp=qexp*2+m;
  115142. pi*=(1<<14)-((wi*wi)>>14);
  115143. qi+=pi>>14;
  115144. }else{
  115145. /* even order filter; still symmetric */
  115146. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  115147. worth tracking step by step */
  115148. pi>>=shift;
  115149. qi>>=shift;
  115150. qexp+=shift-7*m;
  115151. pi=((pi*pi)>>16);
  115152. qi=((qi*qi)>>16);
  115153. qexp=qexp*2+m;
  115154. pi*=(1<<14)-wi;
  115155. qi*=(1<<14)+wi;
  115156. qi=(qi+pi)>>14;
  115157. }
  115158. /* we've let the normalization drift because it wasn't important;
  115159. however, for the lookup, things must be normalized again. We
  115160. need at most one right shift or a number of left shifts */
  115161. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  115162. qi>>=1; qexp++;
  115163. }else
  115164. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  115165. qi<<=1; qexp--;
  115166. }
  115167. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  115168. vorbis_invsqlook_i(qi,qexp)-
  115169. /* m.8, m+n<=8 */
  115170. ampoffseti); /* 8.12[0] */
  115171. curve[i]*=amp;
  115172. while(map[++i]==k)curve[i]*=amp;
  115173. }
  115174. }
  115175. #else
  115176. /* old, nonoptimized but simple version for any poor sap who needs to
  115177. figure out what the hell this code does, or wants the other
  115178. fraction of a dB precision */
  115179. /* side effect: changes *lsp to cosines of lsp */
  115180. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115181. float amp,float ampoffset){
  115182. int i;
  115183. float wdel=M_PI/ln;
  115184. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  115185. i=0;
  115186. while(i<n){
  115187. int j,k=map[i];
  115188. float p=.5f;
  115189. float q=.5f;
  115190. float w=2.f*cos(wdel*k);
  115191. for(j=1;j<m;j+=2){
  115192. q *= w-lsp[j-1];
  115193. p *= w-lsp[j];
  115194. }
  115195. if(j==m){
  115196. /* odd order filter; slightly assymetric */
  115197. /* the last coefficient */
  115198. q*=w-lsp[j-1];
  115199. p*=p*(4.f-w*w);
  115200. q*=q;
  115201. }else{
  115202. /* even order filter; still symmetric */
  115203. p*=p*(2.f-w);
  115204. q*=q*(2.f+w);
  115205. }
  115206. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115207. curve[i]*=q;
  115208. while(map[++i]==k)curve[i]*=q;
  115209. }
  115210. }
  115211. #endif
  115212. #endif
  115213. static void cheby(float *g, int ord) {
  115214. int i, j;
  115215. g[0] *= .5f;
  115216. for(i=2; i<= ord; i++) {
  115217. for(j=ord; j >= i; j--) {
  115218. g[j-2] -= g[j];
  115219. g[j] += g[j];
  115220. }
  115221. }
  115222. }
  115223. static int JUCE_CDECL comp(const void *a,const void *b){
  115224. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115225. }
  115226. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115227. but there are root sets for which it gets into limit cycles
  115228. (exacerbated by zero suppression) and fails. We can't afford to
  115229. fail, even if the failure is 1 in 100,000,000, so we now use
  115230. Laguerre and later polish with Newton-Raphson (which can then
  115231. afford to fail) */
  115232. #define EPSILON 10e-7
  115233. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115234. int i,m;
  115235. double lastdelta=0.f;
  115236. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115237. for(i=0;i<=ord;i++)defl[i]=a[i];
  115238. for(m=ord;m>0;m--){
  115239. double newx=0.f,delta;
  115240. /* iterate a root */
  115241. while(1){
  115242. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115243. /* eval the polynomial and its first two derivatives */
  115244. for(i=m;i>0;i--){
  115245. ppp = newx*ppp + pp;
  115246. pp = newx*pp + p;
  115247. p = newx*p + defl[i-1];
  115248. }
  115249. /* Laguerre's method */
  115250. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115251. if(denom<0)
  115252. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115253. if(pp>0){
  115254. denom = pp + sqrt(denom);
  115255. if(denom<EPSILON)denom=EPSILON;
  115256. }else{
  115257. denom = pp - sqrt(denom);
  115258. if(denom>-(EPSILON))denom=-(EPSILON);
  115259. }
  115260. delta = m*p/denom;
  115261. newx -= delta;
  115262. if(delta<0.f)delta*=-1;
  115263. if(fabs(delta/newx)<10e-12)break;
  115264. lastdelta=delta;
  115265. }
  115266. r[m-1]=newx;
  115267. /* forward deflation */
  115268. for(i=m;i>0;i--)
  115269. defl[i-1]+=newx*defl[i];
  115270. defl++;
  115271. }
  115272. return(0);
  115273. }
  115274. /* for spit-and-polish only */
  115275. static int Newton_Raphson(float *a,int ord,float *r){
  115276. int i, k, count=0;
  115277. double error=1.f;
  115278. double *root=(double*)alloca(ord*sizeof(*root));
  115279. for(i=0; i<ord;i++) root[i] = r[i];
  115280. while(error>1e-20){
  115281. error=0;
  115282. for(i=0; i<ord; i++) { /* Update each point. */
  115283. double pp=0.,delta;
  115284. double rooti=root[i];
  115285. double p=a[ord];
  115286. for(k=ord-1; k>= 0; k--) {
  115287. pp= pp* rooti + p;
  115288. p = p * rooti + a[k];
  115289. }
  115290. delta = p/pp;
  115291. root[i] -= delta;
  115292. error+= delta*delta;
  115293. }
  115294. if(count>40)return(-1);
  115295. count++;
  115296. }
  115297. /* Replaced the original bubble sort with a real sort. With your
  115298. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115299. for(i=0; i<ord;i++) r[i] = root[i];
  115300. return(0);
  115301. }
  115302. /* Convert lpc coefficients to lsp coefficients */
  115303. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115304. int order2=(m+1)>>1;
  115305. int g1_order,g2_order;
  115306. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115307. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115308. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115309. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115310. int i;
  115311. /* even and odd are slightly different base cases */
  115312. g1_order=(m+1)>>1;
  115313. g2_order=(m) >>1;
  115314. /* Compute the lengths of the x polynomials. */
  115315. /* Compute the first half of K & R F1 & F2 polynomials. */
  115316. /* Compute half of the symmetric and antisymmetric polynomials. */
  115317. /* Remove the roots at +1 and -1. */
  115318. g1[g1_order] = 1.f;
  115319. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115320. g2[g2_order] = 1.f;
  115321. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115322. if(g1_order>g2_order){
  115323. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115324. }else{
  115325. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115326. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115327. }
  115328. /* Convert into polynomials in cos(alpha) */
  115329. cheby(g1,g1_order);
  115330. cheby(g2,g2_order);
  115331. /* Find the roots of the 2 even polynomials.*/
  115332. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115333. Laguerre_With_Deflation(g2,g2_order,g2r))
  115334. return(-1);
  115335. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115336. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115337. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115338. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115339. for(i=0;i<g1_order;i++)
  115340. lsp[i*2] = acos(g1r[i]);
  115341. for(i=0;i<g2_order;i++)
  115342. lsp[i*2+1] = acos(g2r[i]);
  115343. return(0);
  115344. }
  115345. #endif
  115346. /*** End of inlined file: lsp.c ***/
  115347. /*** Start of inlined file: mapping0.c ***/
  115348. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115349. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115350. // tasks..
  115351. #if JUCE_MSVC
  115352. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115353. #endif
  115354. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115355. #if JUCE_USE_OGGVORBIS
  115356. #include <stdlib.h>
  115357. #include <stdio.h>
  115358. #include <string.h>
  115359. #include <math.h>
  115360. /* simplistic, wasteful way of doing this (unique lookup for each
  115361. mode/submapping); there should be a central repository for
  115362. identical lookups. That will require minor work, so I'm putting it
  115363. off as low priority.
  115364. Why a lookup for each backend in a given mode? Because the
  115365. blocksize is set by the mode, and low backend lookups may require
  115366. parameters from other areas of the mode/mapping */
  115367. static void mapping0_free_info(vorbis_info_mapping *i){
  115368. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115369. if(info){
  115370. memset(info,0,sizeof(*info));
  115371. _ogg_free(info);
  115372. }
  115373. }
  115374. static int ilog3(unsigned int v){
  115375. int ret=0;
  115376. if(v)--v;
  115377. while(v){
  115378. ret++;
  115379. v>>=1;
  115380. }
  115381. return(ret);
  115382. }
  115383. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115384. oggpack_buffer *opb){
  115385. int i;
  115386. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115387. /* another 'we meant to do it this way' hack... up to beta 4, we
  115388. packed 4 binary zeros here to signify one submapping in use. We
  115389. now redefine that to mean four bitflags that indicate use of
  115390. deeper features; bit0:submappings, bit1:coupling,
  115391. bit2,3:reserved. This is backward compatable with all actual uses
  115392. of the beta code. */
  115393. if(info->submaps>1){
  115394. oggpack_write(opb,1,1);
  115395. oggpack_write(opb,info->submaps-1,4);
  115396. }else
  115397. oggpack_write(opb,0,1);
  115398. if(info->coupling_steps>0){
  115399. oggpack_write(opb,1,1);
  115400. oggpack_write(opb,info->coupling_steps-1,8);
  115401. for(i=0;i<info->coupling_steps;i++){
  115402. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115403. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115404. }
  115405. }else
  115406. oggpack_write(opb,0,1);
  115407. oggpack_write(opb,0,2); /* 2,3:reserved */
  115408. /* we don't write the channel submappings if we only have one... */
  115409. if(info->submaps>1){
  115410. for(i=0;i<vi->channels;i++)
  115411. oggpack_write(opb,info->chmuxlist[i],4);
  115412. }
  115413. for(i=0;i<info->submaps;i++){
  115414. oggpack_write(opb,0,8); /* time submap unused */
  115415. oggpack_write(opb,info->floorsubmap[i],8);
  115416. oggpack_write(opb,info->residuesubmap[i],8);
  115417. }
  115418. }
  115419. /* also responsible for range checking */
  115420. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115421. int i;
  115422. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115423. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115424. memset(info,0,sizeof(*info));
  115425. if(oggpack_read(opb,1))
  115426. info->submaps=oggpack_read(opb,4)+1;
  115427. else
  115428. info->submaps=1;
  115429. if(oggpack_read(opb,1)){
  115430. info->coupling_steps=oggpack_read(opb,8)+1;
  115431. for(i=0;i<info->coupling_steps;i++){
  115432. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115433. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115434. if(testM<0 ||
  115435. testA<0 ||
  115436. testM==testA ||
  115437. testM>=vi->channels ||
  115438. testA>=vi->channels) goto err_out;
  115439. }
  115440. }
  115441. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115442. if(info->submaps>1){
  115443. for(i=0;i<vi->channels;i++){
  115444. info->chmuxlist[i]=oggpack_read(opb,4);
  115445. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115446. }
  115447. }
  115448. for(i=0;i<info->submaps;i++){
  115449. oggpack_read(opb,8); /* time submap unused */
  115450. info->floorsubmap[i]=oggpack_read(opb,8);
  115451. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115452. info->residuesubmap[i]=oggpack_read(opb,8);
  115453. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115454. }
  115455. return info;
  115456. err_out:
  115457. mapping0_free_info(info);
  115458. return(NULL);
  115459. }
  115460. #if 0
  115461. static long seq=0;
  115462. static ogg_int64_t total=0;
  115463. static float FLOOR1_fromdB_LOOKUP[256]={
  115464. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115465. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115466. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115467. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115468. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115469. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115470. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115471. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115472. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115473. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115474. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115475. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115476. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115477. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115478. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115479. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115480. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115481. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115482. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115483. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115484. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115485. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115486. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115487. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115488. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115489. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115490. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115491. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115492. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115493. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115494. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115495. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115496. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115497. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115498. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115499. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115500. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115501. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115502. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115503. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115504. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115505. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115506. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115507. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115508. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115509. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115510. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115511. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115512. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115513. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115514. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115515. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115516. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115517. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115518. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115519. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115520. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115521. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115522. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115523. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115524. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115525. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115526. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115527. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115528. };
  115529. #endif
  115530. extern int *floor1_fit(vorbis_block *vb,void *look,
  115531. const float *logmdct, /* in */
  115532. const float *logmask);
  115533. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115534. int *A,int *B,
  115535. int del);
  115536. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115537. void*look,
  115538. int *post,int *ilogmask);
  115539. static int mapping0_forward(vorbis_block *vb){
  115540. vorbis_dsp_state *vd=vb->vd;
  115541. vorbis_info *vi=vd->vi;
  115542. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115543. private_state *b=(private_state*)vb->vd->backend_state;
  115544. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115545. int n=vb->pcmend;
  115546. int i,j,k;
  115547. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115548. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115549. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115550. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115551. float global_ampmax=vbi->ampmax;
  115552. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115553. int blocktype=vbi->blocktype;
  115554. int modenumber=vb->W;
  115555. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115556. vorbis_look_psy *psy_look=
  115557. b->psy+blocktype+(vb->W?2:0);
  115558. vb->mode=modenumber;
  115559. for(i=0;i<vi->channels;i++){
  115560. float scale=4.f/n;
  115561. float scale_dB;
  115562. float *pcm =vb->pcm[i];
  115563. float *logfft =pcm;
  115564. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115565. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115566. todB estimation used on IEEE 754
  115567. compliant machines had a bug that
  115568. returned dB values about a third
  115569. of a decibel too high. The bug
  115570. was harmless because tunings
  115571. implicitly took that into
  115572. account. However, fixing the bug
  115573. in the estimator requires
  115574. changing all the tunings as well.
  115575. For now, it's easier to sync
  115576. things back up here, and
  115577. recalibrate the tunings in the
  115578. next major model upgrade. */
  115579. #if 0
  115580. if(vi->channels==2)
  115581. if(i==0)
  115582. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115583. else
  115584. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115585. #endif
  115586. /* window the PCM data */
  115587. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115588. #if 0
  115589. if(vi->channels==2)
  115590. if(i==0)
  115591. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115592. else
  115593. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115594. #endif
  115595. /* transform the PCM data */
  115596. /* only MDCT right now.... */
  115597. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115598. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115599. drft_forward(&b->fft_look[vb->W],pcm);
  115600. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115601. original todB estimation used on
  115602. IEEE 754 compliant machines had a
  115603. bug that returned dB values about
  115604. a third of a decibel too high.
  115605. The bug was harmless because
  115606. tunings implicitly took that into
  115607. account. However, fixing the bug
  115608. in the estimator requires
  115609. changing all the tunings as well.
  115610. For now, it's easier to sync
  115611. things back up here, and
  115612. recalibrate the tunings in the
  115613. next major model upgrade. */
  115614. local_ampmax[i]=logfft[0];
  115615. for(j=1;j<n-1;j+=2){
  115616. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115617. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115618. .345 is a hack; the original todB
  115619. estimation used on IEEE 754
  115620. compliant machines had a bug that
  115621. returned dB values about a third
  115622. of a decibel too high. The bug
  115623. was harmless because tunings
  115624. implicitly took that into
  115625. account. However, fixing the bug
  115626. in the estimator requires
  115627. changing all the tunings as well.
  115628. For now, it's easier to sync
  115629. things back up here, and
  115630. recalibrate the tunings in the
  115631. next major model upgrade. */
  115632. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115633. }
  115634. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115635. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115636. #if 0
  115637. if(vi->channels==2){
  115638. if(i==0){
  115639. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115640. }else{
  115641. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115642. }
  115643. }
  115644. #endif
  115645. }
  115646. {
  115647. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115648. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115649. for(i=0;i<vi->channels;i++){
  115650. /* the encoder setup assumes that all the modes used by any
  115651. specific bitrate tweaking use the same floor */
  115652. int submap=info->chmuxlist[i];
  115653. /* the following makes things clearer to *me* anyway */
  115654. float *mdct =gmdct[i];
  115655. float *logfft =vb->pcm[i];
  115656. float *logmdct =logfft+n/2;
  115657. float *logmask =logfft;
  115658. vb->mode=modenumber;
  115659. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115660. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115661. for(j=0;j<n/2;j++)
  115662. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115663. todB estimation used on IEEE 754
  115664. compliant machines had a bug that
  115665. returned dB values about a third
  115666. of a decibel too high. The bug
  115667. was harmless because tunings
  115668. implicitly took that into
  115669. account. However, fixing the bug
  115670. in the estimator requires
  115671. changing all the tunings as well.
  115672. For now, it's easier to sync
  115673. things back up here, and
  115674. recalibrate the tunings in the
  115675. next major model upgrade. */
  115676. #if 0
  115677. if(vi->channels==2){
  115678. if(i==0)
  115679. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115680. else
  115681. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115682. }else{
  115683. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115684. }
  115685. #endif
  115686. /* first step; noise masking. Not only does 'noise masking'
  115687. give us curves from which we can decide how much resolution
  115688. to give noise parts of the spectrum, it also implicitly hands
  115689. us a tonality estimate (the larger the value in the
  115690. 'noise_depth' vector, the more tonal that area is) */
  115691. _vp_noisemask(psy_look,
  115692. logmdct,
  115693. noise); /* noise does not have by-frequency offset
  115694. bias applied yet */
  115695. #if 0
  115696. if(vi->channels==2){
  115697. if(i==0)
  115698. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115699. else
  115700. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115701. }
  115702. #endif
  115703. /* second step: 'all the other crap'; all the stuff that isn't
  115704. computed/fit for bitrate management goes in the second psy
  115705. vector. This includes tone masking, peak limiting and ATH */
  115706. _vp_tonemask(psy_look,
  115707. logfft,
  115708. tone,
  115709. global_ampmax,
  115710. local_ampmax[i]);
  115711. #if 0
  115712. if(vi->channels==2){
  115713. if(i==0)
  115714. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115715. else
  115716. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115717. }
  115718. #endif
  115719. /* third step; we offset the noise vectors, overlay tone
  115720. masking. We then do a floor1-specific line fit. If we're
  115721. performing bitrate management, the line fit is performed
  115722. multiple times for up/down tweakage on demand. */
  115723. #if 0
  115724. {
  115725. float aotuv[psy_look->n];
  115726. #endif
  115727. _vp_offset_and_mix(psy_look,
  115728. noise,
  115729. tone,
  115730. 1,
  115731. logmask,
  115732. mdct,
  115733. logmdct);
  115734. #if 0
  115735. if(vi->channels==2){
  115736. if(i==0)
  115737. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115738. else
  115739. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115740. }
  115741. }
  115742. #endif
  115743. #if 0
  115744. if(vi->channels==2){
  115745. if(i==0)
  115746. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115747. else
  115748. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115749. }
  115750. #endif
  115751. /* this algorithm is hardwired to floor 1 for now; abort out if
  115752. we're *not* floor1. This won't happen unless someone has
  115753. broken the encode setup lib. Guard it anyway. */
  115754. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115755. floor_posts[i][PACKETBLOBS/2]=
  115756. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115757. logmdct,
  115758. logmask);
  115759. /* are we managing bitrate? If so, perform two more fits for
  115760. later rate tweaking (fits represent hi/lo) */
  115761. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115762. /* higher rate by way of lower noise curve */
  115763. _vp_offset_and_mix(psy_look,
  115764. noise,
  115765. tone,
  115766. 2,
  115767. logmask,
  115768. mdct,
  115769. logmdct);
  115770. #if 0
  115771. if(vi->channels==2){
  115772. if(i==0)
  115773. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115774. else
  115775. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115776. }
  115777. #endif
  115778. floor_posts[i][PACKETBLOBS-1]=
  115779. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115780. logmdct,
  115781. logmask);
  115782. /* lower rate by way of higher noise curve */
  115783. _vp_offset_and_mix(psy_look,
  115784. noise,
  115785. tone,
  115786. 0,
  115787. logmask,
  115788. mdct,
  115789. logmdct);
  115790. #if 0
  115791. if(vi->channels==2)
  115792. if(i==0)
  115793. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115794. else
  115795. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115796. #endif
  115797. floor_posts[i][0]=
  115798. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115799. logmdct,
  115800. logmask);
  115801. /* we also interpolate a range of intermediate curves for
  115802. intermediate rates */
  115803. for(k=1;k<PACKETBLOBS/2;k++)
  115804. floor_posts[i][k]=
  115805. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115806. floor_posts[i][0],
  115807. floor_posts[i][PACKETBLOBS/2],
  115808. k*65536/(PACKETBLOBS/2));
  115809. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115810. floor_posts[i][k]=
  115811. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115812. floor_posts[i][PACKETBLOBS/2],
  115813. floor_posts[i][PACKETBLOBS-1],
  115814. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115815. }
  115816. }
  115817. }
  115818. vbi->ampmax=global_ampmax;
  115819. /*
  115820. the next phases are performed once for vbr-only and PACKETBLOB
  115821. times for bitrate managed modes.
  115822. 1) encode actual mode being used
  115823. 2) encode the floor for each channel, compute coded mask curve/res
  115824. 3) normalize and couple.
  115825. 4) encode residue
  115826. 5) save packet bytes to the packetblob vector
  115827. */
  115828. /* iterate over the many masking curve fits we've created */
  115829. {
  115830. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115831. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115832. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115833. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115834. float **mag_memo;
  115835. int **mag_sort;
  115836. if(info->coupling_steps){
  115837. mag_memo=_vp_quantize_couple_memo(vb,
  115838. &ci->psy_g_param,
  115839. psy_look,
  115840. info,
  115841. gmdct);
  115842. mag_sort=_vp_quantize_couple_sort(vb,
  115843. psy_look,
  115844. info,
  115845. mag_memo);
  115846. hf_reduction(&ci->psy_g_param,
  115847. psy_look,
  115848. info,
  115849. mag_memo);
  115850. }
  115851. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115852. if(psy_look->vi->normal_channel_p){
  115853. for(i=0;i<vi->channels;i++){
  115854. float *mdct =gmdct[i];
  115855. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115856. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115857. }
  115858. }
  115859. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115860. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115861. k++){
  115862. oggpack_buffer *opb=vbi->packetblob[k];
  115863. /* start out our new packet blob with packet type and mode */
  115864. /* Encode the packet type */
  115865. oggpack_write(opb,0,1);
  115866. /* Encode the modenumber */
  115867. /* Encode frame mode, pre,post windowsize, then dispatch */
  115868. oggpack_write(opb,modenumber,b->modebits);
  115869. if(vb->W){
  115870. oggpack_write(opb,vb->lW,1);
  115871. oggpack_write(opb,vb->nW,1);
  115872. }
  115873. /* encode floor, compute masking curve, sep out residue */
  115874. for(i=0;i<vi->channels;i++){
  115875. int submap=info->chmuxlist[i];
  115876. float *mdct =gmdct[i];
  115877. float *res =vb->pcm[i];
  115878. int *ilogmask=ilogmaskch[i]=
  115879. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115880. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115881. floor_posts[i][k],
  115882. ilogmask);
  115883. #if 0
  115884. {
  115885. char buf[80];
  115886. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115887. float work[n/2];
  115888. for(j=0;j<n/2;j++)
  115889. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115890. _analysis_output(buf,seq,work,n/2,1,1,0);
  115891. }
  115892. #endif
  115893. _vp_remove_floor(psy_look,
  115894. mdct,
  115895. ilogmask,
  115896. res,
  115897. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115898. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115899. #if 0
  115900. {
  115901. char buf[80];
  115902. float work[n/2];
  115903. for(j=0;j<n/2;j++)
  115904. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115905. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115906. _analysis_output(buf,seq,work,n/2,1,1,0);
  115907. }
  115908. #endif
  115909. }
  115910. /* our iteration is now based on masking curve, not prequant and
  115911. coupling. Only one prequant/coupling step */
  115912. /* quantize/couple */
  115913. /* incomplete implementation that assumes the tree is all depth
  115914. one, or no tree at all */
  115915. if(info->coupling_steps){
  115916. _vp_couple(k,
  115917. &ci->psy_g_param,
  115918. psy_look,
  115919. info,
  115920. vb->pcm,
  115921. mag_memo,
  115922. mag_sort,
  115923. ilogmaskch,
  115924. nonzero,
  115925. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115926. }
  115927. /* classify and encode by submap */
  115928. for(i=0;i<info->submaps;i++){
  115929. int ch_in_bundle=0;
  115930. long **classifications;
  115931. int resnum=info->residuesubmap[i];
  115932. for(j=0;j<vi->channels;j++){
  115933. if(info->chmuxlist[j]==i){
  115934. zerobundle[ch_in_bundle]=0;
  115935. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115936. res_bundle[ch_in_bundle]=vb->pcm[j];
  115937. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115938. }
  115939. }
  115940. classifications=_residue_P[ci->residue_type[resnum]]->
  115941. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115942. _residue_P[ci->residue_type[resnum]]->
  115943. forward(opb,vb,b->residue[resnum],
  115944. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115945. }
  115946. /* ok, done encoding. Next protopacket. */
  115947. }
  115948. }
  115949. #if 0
  115950. seq++;
  115951. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115952. #endif
  115953. return(0);
  115954. }
  115955. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115956. vorbis_dsp_state *vd=vb->vd;
  115957. vorbis_info *vi=vd->vi;
  115958. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115959. private_state *b=(private_state*)vd->backend_state;
  115960. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115961. int i,j;
  115962. long n=vb->pcmend=ci->blocksizes[vb->W];
  115963. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115964. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115965. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115966. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115967. /* recover the spectral envelope; store it in the PCM vector for now */
  115968. for(i=0;i<vi->channels;i++){
  115969. int submap=info->chmuxlist[i];
  115970. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115971. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115972. if(floormemo[i])
  115973. nonzero[i]=1;
  115974. else
  115975. nonzero[i]=0;
  115976. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115977. }
  115978. /* channel coupling can 'dirty' the nonzero listing */
  115979. for(i=0;i<info->coupling_steps;i++){
  115980. if(nonzero[info->coupling_mag[i]] ||
  115981. nonzero[info->coupling_ang[i]]){
  115982. nonzero[info->coupling_mag[i]]=1;
  115983. nonzero[info->coupling_ang[i]]=1;
  115984. }
  115985. }
  115986. /* recover the residue into our working vectors */
  115987. for(i=0;i<info->submaps;i++){
  115988. int ch_in_bundle=0;
  115989. for(j=0;j<vi->channels;j++){
  115990. if(info->chmuxlist[j]==i){
  115991. if(nonzero[j])
  115992. zerobundle[ch_in_bundle]=1;
  115993. else
  115994. zerobundle[ch_in_bundle]=0;
  115995. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115996. }
  115997. }
  115998. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115999. inverse(vb,b->residue[info->residuesubmap[i]],
  116000. pcmbundle,zerobundle,ch_in_bundle);
  116001. }
  116002. /* channel coupling */
  116003. for(i=info->coupling_steps-1;i>=0;i--){
  116004. float *pcmM=vb->pcm[info->coupling_mag[i]];
  116005. float *pcmA=vb->pcm[info->coupling_ang[i]];
  116006. for(j=0;j<n/2;j++){
  116007. float mag=pcmM[j];
  116008. float ang=pcmA[j];
  116009. if(mag>0)
  116010. if(ang>0){
  116011. pcmM[j]=mag;
  116012. pcmA[j]=mag-ang;
  116013. }else{
  116014. pcmA[j]=mag;
  116015. pcmM[j]=mag+ang;
  116016. }
  116017. else
  116018. if(ang>0){
  116019. pcmM[j]=mag;
  116020. pcmA[j]=mag+ang;
  116021. }else{
  116022. pcmA[j]=mag;
  116023. pcmM[j]=mag-ang;
  116024. }
  116025. }
  116026. }
  116027. /* compute and apply spectral envelope */
  116028. for(i=0;i<vi->channels;i++){
  116029. float *pcm=vb->pcm[i];
  116030. int submap=info->chmuxlist[i];
  116031. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  116032. inverse2(vb,b->flr[info->floorsubmap[submap]],
  116033. floormemo[i],pcm);
  116034. }
  116035. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  116036. /* only MDCT right now.... */
  116037. for(i=0;i<vi->channels;i++){
  116038. float *pcm=vb->pcm[i];
  116039. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  116040. }
  116041. /* all done! */
  116042. return(0);
  116043. }
  116044. /* export hooks */
  116045. vorbis_func_mapping mapping0_exportbundle={
  116046. &mapping0_pack,
  116047. &mapping0_unpack,
  116048. &mapping0_free_info,
  116049. &mapping0_forward,
  116050. &mapping0_inverse
  116051. };
  116052. #endif
  116053. /*** End of inlined file: mapping0.c ***/
  116054. /*** Start of inlined file: mdct.c ***/
  116055. /* this can also be run as an integer transform by uncommenting a
  116056. define in mdct.h; the integerization is a first pass and although
  116057. it's likely stable for Vorbis, the dynamic range is constrained and
  116058. roundoff isn't done (so it's noisy). Consider it functional, but
  116059. only a starting point. There's no point on a machine with an FPU */
  116060. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116061. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116062. // tasks..
  116063. #if JUCE_MSVC
  116064. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116065. #endif
  116066. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116067. #if JUCE_USE_OGGVORBIS
  116068. #include <stdio.h>
  116069. #include <stdlib.h>
  116070. #include <string.h>
  116071. #include <math.h>
  116072. /* build lookups for trig functions; also pre-figure scaling and
  116073. some window function algebra. */
  116074. void mdct_init(mdct_lookup *lookup,int n){
  116075. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  116076. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  116077. int i;
  116078. int n2=n>>1;
  116079. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  116080. lookup->n=n;
  116081. lookup->trig=T;
  116082. lookup->bitrev=bitrev;
  116083. /* trig lookups... */
  116084. for(i=0;i<n/4;i++){
  116085. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  116086. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  116087. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  116088. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  116089. }
  116090. for(i=0;i<n/8;i++){
  116091. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  116092. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  116093. }
  116094. /* bitreverse lookup... */
  116095. {
  116096. int mask=(1<<(log2n-1))-1,i,j;
  116097. int msb=1<<(log2n-2);
  116098. for(i=0;i<n/8;i++){
  116099. int acc=0;
  116100. for(j=0;msb>>j;j++)
  116101. if((msb>>j)&i)acc|=1<<j;
  116102. bitrev[i*2]=((~acc)&mask)-1;
  116103. bitrev[i*2+1]=acc;
  116104. }
  116105. }
  116106. lookup->scale=FLOAT_CONV(4.f/n);
  116107. }
  116108. /* 8 point butterfly (in place, 4 register) */
  116109. STIN void mdct_butterfly_8(DATA_TYPE *x){
  116110. REG_TYPE r0 = x[6] + x[2];
  116111. REG_TYPE r1 = x[6] - x[2];
  116112. REG_TYPE r2 = x[4] + x[0];
  116113. REG_TYPE r3 = x[4] - x[0];
  116114. x[6] = r0 + r2;
  116115. x[4] = r0 - r2;
  116116. r0 = x[5] - x[1];
  116117. r2 = x[7] - x[3];
  116118. x[0] = r1 + r0;
  116119. x[2] = r1 - r0;
  116120. r0 = x[5] + x[1];
  116121. r1 = x[7] + x[3];
  116122. x[3] = r2 + r3;
  116123. x[1] = r2 - r3;
  116124. x[7] = r1 + r0;
  116125. x[5] = r1 - r0;
  116126. }
  116127. /* 16 point butterfly (in place, 4 register) */
  116128. STIN void mdct_butterfly_16(DATA_TYPE *x){
  116129. REG_TYPE r0 = x[1] - x[9];
  116130. REG_TYPE r1 = x[0] - x[8];
  116131. x[8] += x[0];
  116132. x[9] += x[1];
  116133. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  116134. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  116135. r0 = x[3] - x[11];
  116136. r1 = x[10] - x[2];
  116137. x[10] += x[2];
  116138. x[11] += x[3];
  116139. x[2] = r0;
  116140. x[3] = r1;
  116141. r0 = x[12] - x[4];
  116142. r1 = x[13] - x[5];
  116143. x[12] += x[4];
  116144. x[13] += x[5];
  116145. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  116146. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  116147. r0 = x[14] - x[6];
  116148. r1 = x[15] - x[7];
  116149. x[14] += x[6];
  116150. x[15] += x[7];
  116151. x[6] = r0;
  116152. x[7] = r1;
  116153. mdct_butterfly_8(x);
  116154. mdct_butterfly_8(x+8);
  116155. }
  116156. /* 32 point butterfly (in place, 4 register) */
  116157. STIN void mdct_butterfly_32(DATA_TYPE *x){
  116158. REG_TYPE r0 = x[30] - x[14];
  116159. REG_TYPE r1 = x[31] - x[15];
  116160. x[30] += x[14];
  116161. x[31] += x[15];
  116162. x[14] = r0;
  116163. x[15] = r1;
  116164. r0 = x[28] - x[12];
  116165. r1 = x[29] - x[13];
  116166. x[28] += x[12];
  116167. x[29] += x[13];
  116168. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  116169. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  116170. r0 = x[26] - x[10];
  116171. r1 = x[27] - x[11];
  116172. x[26] += x[10];
  116173. x[27] += x[11];
  116174. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  116175. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  116176. r0 = x[24] - x[8];
  116177. r1 = x[25] - x[9];
  116178. x[24] += x[8];
  116179. x[25] += x[9];
  116180. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  116181. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116182. r0 = x[22] - x[6];
  116183. r1 = x[7] - x[23];
  116184. x[22] += x[6];
  116185. x[23] += x[7];
  116186. x[6] = r1;
  116187. x[7] = r0;
  116188. r0 = x[4] - x[20];
  116189. r1 = x[5] - x[21];
  116190. x[20] += x[4];
  116191. x[21] += x[5];
  116192. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  116193. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  116194. r0 = x[2] - x[18];
  116195. r1 = x[3] - x[19];
  116196. x[18] += x[2];
  116197. x[19] += x[3];
  116198. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116199. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116200. r0 = x[0] - x[16];
  116201. r1 = x[1] - x[17];
  116202. x[16] += x[0];
  116203. x[17] += x[1];
  116204. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116205. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116206. mdct_butterfly_16(x);
  116207. mdct_butterfly_16(x+16);
  116208. }
  116209. /* N point first stage butterfly (in place, 2 register) */
  116210. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116211. DATA_TYPE *x,
  116212. int points){
  116213. DATA_TYPE *x1 = x + points - 8;
  116214. DATA_TYPE *x2 = x + (points>>1) - 8;
  116215. REG_TYPE r0;
  116216. REG_TYPE r1;
  116217. do{
  116218. r0 = x1[6] - x2[6];
  116219. r1 = x1[7] - x2[7];
  116220. x1[6] += x2[6];
  116221. x1[7] += x2[7];
  116222. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116223. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116224. r0 = x1[4] - x2[4];
  116225. r1 = x1[5] - x2[5];
  116226. x1[4] += x2[4];
  116227. x1[5] += x2[5];
  116228. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116229. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116230. r0 = x1[2] - x2[2];
  116231. r1 = x1[3] - x2[3];
  116232. x1[2] += x2[2];
  116233. x1[3] += x2[3];
  116234. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116235. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116236. r0 = x1[0] - x2[0];
  116237. r1 = x1[1] - x2[1];
  116238. x1[0] += x2[0];
  116239. x1[1] += x2[1];
  116240. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116241. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116242. x1-=8;
  116243. x2-=8;
  116244. T+=16;
  116245. }while(x2>=x);
  116246. }
  116247. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116248. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116249. DATA_TYPE *x,
  116250. int points,
  116251. int trigint){
  116252. DATA_TYPE *x1 = x + points - 8;
  116253. DATA_TYPE *x2 = x + (points>>1) - 8;
  116254. REG_TYPE r0;
  116255. REG_TYPE r1;
  116256. do{
  116257. r0 = x1[6] - x2[6];
  116258. r1 = x1[7] - x2[7];
  116259. x1[6] += x2[6];
  116260. x1[7] += x2[7];
  116261. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116262. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116263. T+=trigint;
  116264. r0 = x1[4] - x2[4];
  116265. r1 = x1[5] - x2[5];
  116266. x1[4] += x2[4];
  116267. x1[5] += x2[5];
  116268. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116269. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116270. T+=trigint;
  116271. r0 = x1[2] - x2[2];
  116272. r1 = x1[3] - x2[3];
  116273. x1[2] += x2[2];
  116274. x1[3] += x2[3];
  116275. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116276. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116277. T+=trigint;
  116278. r0 = x1[0] - x2[0];
  116279. r1 = x1[1] - x2[1];
  116280. x1[0] += x2[0];
  116281. x1[1] += x2[1];
  116282. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116283. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116284. T+=trigint;
  116285. x1-=8;
  116286. x2-=8;
  116287. }while(x2>=x);
  116288. }
  116289. STIN void mdct_butterflies(mdct_lookup *init,
  116290. DATA_TYPE *x,
  116291. int points){
  116292. DATA_TYPE *T=init->trig;
  116293. int stages=init->log2n-5;
  116294. int i,j;
  116295. if(--stages>0){
  116296. mdct_butterfly_first(T,x,points);
  116297. }
  116298. for(i=1;--stages>0;i++){
  116299. for(j=0;j<(1<<i);j++)
  116300. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116301. }
  116302. for(j=0;j<points;j+=32)
  116303. mdct_butterfly_32(x+j);
  116304. }
  116305. void mdct_clear(mdct_lookup *l){
  116306. if(l){
  116307. if(l->trig)_ogg_free(l->trig);
  116308. if(l->bitrev)_ogg_free(l->bitrev);
  116309. memset(l,0,sizeof(*l));
  116310. }
  116311. }
  116312. STIN void mdct_bitreverse(mdct_lookup *init,
  116313. DATA_TYPE *x){
  116314. int n = init->n;
  116315. int *bit = init->bitrev;
  116316. DATA_TYPE *w0 = x;
  116317. DATA_TYPE *w1 = x = w0+(n>>1);
  116318. DATA_TYPE *T = init->trig+n;
  116319. do{
  116320. DATA_TYPE *x0 = x+bit[0];
  116321. DATA_TYPE *x1 = x+bit[1];
  116322. REG_TYPE r0 = x0[1] - x1[1];
  116323. REG_TYPE r1 = x0[0] + x1[0];
  116324. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116325. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116326. w1 -= 4;
  116327. r0 = HALVE(x0[1] + x1[1]);
  116328. r1 = HALVE(x0[0] - x1[0]);
  116329. w0[0] = r0 + r2;
  116330. w1[2] = r0 - r2;
  116331. w0[1] = r1 + r3;
  116332. w1[3] = r3 - r1;
  116333. x0 = x+bit[2];
  116334. x1 = x+bit[3];
  116335. r0 = x0[1] - x1[1];
  116336. r1 = x0[0] + x1[0];
  116337. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116338. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116339. r0 = HALVE(x0[1] + x1[1]);
  116340. r1 = HALVE(x0[0] - x1[0]);
  116341. w0[2] = r0 + r2;
  116342. w1[0] = r0 - r2;
  116343. w0[3] = r1 + r3;
  116344. w1[1] = r3 - r1;
  116345. T += 4;
  116346. bit += 4;
  116347. w0 += 4;
  116348. }while(w0<w1);
  116349. }
  116350. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116351. int n=init->n;
  116352. int n2=n>>1;
  116353. int n4=n>>2;
  116354. /* rotate */
  116355. DATA_TYPE *iX = in+n2-7;
  116356. DATA_TYPE *oX = out+n2+n4;
  116357. DATA_TYPE *T = init->trig+n4;
  116358. do{
  116359. oX -= 4;
  116360. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116361. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116362. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116363. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116364. iX -= 8;
  116365. T += 4;
  116366. }while(iX>=in);
  116367. iX = in+n2-8;
  116368. oX = out+n2+n4;
  116369. T = init->trig+n4;
  116370. do{
  116371. T -= 4;
  116372. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116373. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116374. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116375. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116376. iX -= 8;
  116377. oX += 4;
  116378. }while(iX>=in);
  116379. mdct_butterflies(init,out+n2,n2);
  116380. mdct_bitreverse(init,out);
  116381. /* roatate + window */
  116382. {
  116383. DATA_TYPE *oX1=out+n2+n4;
  116384. DATA_TYPE *oX2=out+n2+n4;
  116385. DATA_TYPE *iX =out;
  116386. T =init->trig+n2;
  116387. do{
  116388. oX1-=4;
  116389. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116390. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116391. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116392. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116393. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116394. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116395. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116396. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116397. oX2+=4;
  116398. iX += 8;
  116399. T += 8;
  116400. }while(iX<oX1);
  116401. iX=out+n2+n4;
  116402. oX1=out+n4;
  116403. oX2=oX1;
  116404. do{
  116405. oX1-=4;
  116406. iX-=4;
  116407. oX2[0] = -(oX1[3] = iX[3]);
  116408. oX2[1] = -(oX1[2] = iX[2]);
  116409. oX2[2] = -(oX1[1] = iX[1]);
  116410. oX2[3] = -(oX1[0] = iX[0]);
  116411. oX2+=4;
  116412. }while(oX2<iX);
  116413. iX=out+n2+n4;
  116414. oX1=out+n2+n4;
  116415. oX2=out+n2;
  116416. do{
  116417. oX1-=4;
  116418. oX1[0]= iX[3];
  116419. oX1[1]= iX[2];
  116420. oX1[2]= iX[1];
  116421. oX1[3]= iX[0];
  116422. iX+=4;
  116423. }while(oX1>oX2);
  116424. }
  116425. }
  116426. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116427. int n=init->n;
  116428. int n2=n>>1;
  116429. int n4=n>>2;
  116430. int n8=n>>3;
  116431. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116432. DATA_TYPE *w2=w+n2;
  116433. /* rotate */
  116434. /* window + rotate + step 1 */
  116435. REG_TYPE r0;
  116436. REG_TYPE r1;
  116437. DATA_TYPE *x0=in+n2+n4;
  116438. DATA_TYPE *x1=x0+1;
  116439. DATA_TYPE *T=init->trig+n2;
  116440. int i=0;
  116441. for(i=0;i<n8;i+=2){
  116442. x0 -=4;
  116443. T-=2;
  116444. r0= x0[2] + x1[0];
  116445. r1= x0[0] + x1[2];
  116446. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116447. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116448. x1 +=4;
  116449. }
  116450. x1=in+1;
  116451. for(;i<n2-n8;i+=2){
  116452. T-=2;
  116453. x0 -=4;
  116454. r0= x0[2] - x1[0];
  116455. r1= x0[0] - x1[2];
  116456. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116457. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116458. x1 +=4;
  116459. }
  116460. x0=in+n;
  116461. for(;i<n2;i+=2){
  116462. T-=2;
  116463. x0 -=4;
  116464. r0= -x0[2] - x1[0];
  116465. r1= -x0[0] - x1[2];
  116466. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116467. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116468. x1 +=4;
  116469. }
  116470. mdct_butterflies(init,w+n2,n2);
  116471. mdct_bitreverse(init,w);
  116472. /* roatate + window */
  116473. T=init->trig+n2;
  116474. x0=out+n2;
  116475. for(i=0;i<n4;i++){
  116476. x0--;
  116477. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116478. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116479. w+=2;
  116480. T+=2;
  116481. }
  116482. }
  116483. #endif
  116484. /*** End of inlined file: mdct.c ***/
  116485. /*** Start of inlined file: psy.c ***/
  116486. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116487. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116488. // tasks..
  116489. #if JUCE_MSVC
  116490. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116491. #endif
  116492. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116493. #if JUCE_USE_OGGVORBIS
  116494. #include <stdlib.h>
  116495. #include <math.h>
  116496. #include <string.h>
  116497. /*** Start of inlined file: masking.h ***/
  116498. #ifndef _V_MASKING_H_
  116499. #define _V_MASKING_H_
  116500. /* more detailed ATH; the bass if flat to save stressing the floor
  116501. overly for only a bin or two of savings. */
  116502. #define MAX_ATH 88
  116503. static float ATH[]={
  116504. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116505. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116506. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116507. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116508. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116509. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116510. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116511. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116512. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116513. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116514. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116515. };
  116516. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116517. replaced by an empirically collected data set. The previously
  116518. published values were, far too often, simply on crack. */
  116519. #define EHMER_OFFSET 16
  116520. #define EHMER_MAX 56
  116521. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116522. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116523. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116524. for collection of these curves) */
  116525. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116526. /* 62.5 Hz */
  116527. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116528. -60, -60, -60, -60, -62, -62, -65, -73,
  116529. -69, -68, -68, -67, -70, -70, -72, -74,
  116530. -75, -79, -79, -80, -83, -88, -93, -100,
  116531. -110, -999, -999, -999, -999, -999, -999, -999,
  116532. -999, -999, -999, -999, -999, -999, -999, -999,
  116533. -999, -999, -999, -999, -999, -999, -999, -999},
  116534. { -48, -48, -48, -48, -48, -48, -48, -48,
  116535. -48, -48, -48, -48, -48, -53, -61, -66,
  116536. -66, -68, -67, -70, -76, -76, -72, -73,
  116537. -75, -76, -78, -79, -83, -88, -93, -100,
  116538. -110, -999, -999, -999, -999, -999, -999, -999,
  116539. -999, -999, -999, -999, -999, -999, -999, -999,
  116540. -999, -999, -999, -999, -999, -999, -999, -999},
  116541. { -37, -37, -37, -37, -37, -37, -37, -37,
  116542. -38, -40, -42, -46, -48, -53, -55, -62,
  116543. -65, -58, -56, -56, -61, -60, -65, -67,
  116544. -69, -71, -77, -77, -78, -80, -82, -84,
  116545. -88, -93, -98, -106, -112, -999, -999, -999,
  116546. -999, -999, -999, -999, -999, -999, -999, -999,
  116547. -999, -999, -999, -999, -999, -999, -999, -999},
  116548. { -25, -25, -25, -25, -25, -25, -25, -25,
  116549. -25, -26, -27, -29, -32, -38, -48, -52,
  116550. -52, -50, -48, -48, -51, -52, -54, -60,
  116551. -67, -67, -66, -68, -69, -73, -73, -76,
  116552. -80, -81, -81, -85, -85, -86, -88, -93,
  116553. -100, -110, -999, -999, -999, -999, -999, -999,
  116554. -999, -999, -999, -999, -999, -999, -999, -999},
  116555. { -16, -16, -16, -16, -16, -16, -16, -16,
  116556. -17, -19, -20, -22, -26, -28, -31, -40,
  116557. -47, -39, -39, -40, -42, -43, -47, -51,
  116558. -57, -52, -55, -55, -60, -58, -62, -63,
  116559. -70, -67, -69, -72, -73, -77, -80, -82,
  116560. -83, -87, -90, -94, -98, -104, -115, -999,
  116561. -999, -999, -999, -999, -999, -999, -999, -999},
  116562. { -8, -8, -8, -8, -8, -8, -8, -8,
  116563. -8, -8, -10, -11, -15, -19, -25, -30,
  116564. -34, -31, -30, -31, -29, -32, -35, -42,
  116565. -48, -42, -44, -46, -50, -50, -51, -52,
  116566. -59, -54, -55, -55, -58, -62, -63, -66,
  116567. -72, -73, -76, -75, -78, -80, -80, -81,
  116568. -84, -88, -90, -94, -98, -101, -106, -110}},
  116569. /* 88Hz */
  116570. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116571. -66, -66, -66, -66, -66, -67, -67, -67,
  116572. -76, -72, -71, -74, -76, -76, -75, -78,
  116573. -79, -79, -81, -83, -86, -89, -93, -97,
  116574. -100, -105, -110, -999, -999, -999, -999, -999,
  116575. -999, -999, -999, -999, -999, -999, -999, -999,
  116576. -999, -999, -999, -999, -999, -999, -999, -999},
  116577. { -47, -47, -47, -47, -47, -47, -47, -47,
  116578. -47, -47, -47, -48, -51, -55, -59, -66,
  116579. -66, -66, -67, -66, -68, -69, -70, -74,
  116580. -79, -77, -77, -78, -80, -81, -82, -84,
  116581. -86, -88, -91, -95, -100, -108, -116, -999,
  116582. -999, -999, -999, -999, -999, -999, -999, -999,
  116583. -999, -999, -999, -999, -999, -999, -999, -999},
  116584. { -36, -36, -36, -36, -36, -36, -36, -36,
  116585. -36, -37, -37, -41, -44, -48, -51, -58,
  116586. -62, -60, -57, -59, -59, -60, -63, -65,
  116587. -72, -71, -70, -72, -74, -77, -76, -78,
  116588. -81, -81, -80, -83, -86, -91, -96, -100,
  116589. -105, -110, -999, -999, -999, -999, -999, -999,
  116590. -999, -999, -999, -999, -999, -999, -999, -999},
  116591. { -28, -28, -28, -28, -28, -28, -28, -28,
  116592. -28, -30, -32, -32, -33, -35, -41, -49,
  116593. -50, -49, -47, -48, -48, -52, -51, -57,
  116594. -65, -61, -59, -61, -64, -69, -70, -74,
  116595. -77, -77, -78, -81, -84, -85, -87, -90,
  116596. -92, -96, -100, -107, -112, -999, -999, -999,
  116597. -999, -999, -999, -999, -999, -999, -999, -999},
  116598. { -19, -19, -19, -19, -19, -19, -19, -19,
  116599. -20, -21, -23, -27, -30, -35, -36, -41,
  116600. -46, -44, -42, -40, -41, -41, -43, -48,
  116601. -55, -53, -52, -53, -56, -59, -58, -60,
  116602. -67, -66, -69, -71, -72, -75, -79, -81,
  116603. -84, -87, -90, -93, -97, -101, -107, -114,
  116604. -999, -999, -999, -999, -999, -999, -999, -999},
  116605. { -9, -9, -9, -9, -9, -9, -9, -9,
  116606. -11, -12, -12, -15, -16, -20, -23, -30,
  116607. -37, -34, -33, -34, -31, -32, -32, -38,
  116608. -47, -44, -41, -40, -47, -49, -46, -46,
  116609. -58, -50, -50, -54, -58, -62, -64, -67,
  116610. -67, -70, -72, -76, -79, -83, -87, -91,
  116611. -96, -100, -104, -110, -999, -999, -999, -999}},
  116612. /* 125 Hz */
  116613. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116614. -62, -62, -63, -64, -66, -67, -66, -68,
  116615. -75, -72, -76, -75, -76, -78, -79, -82,
  116616. -84, -85, -90, -94, -101, -110, -999, -999,
  116617. -999, -999, -999, -999, -999, -999, -999, -999,
  116618. -999, -999, -999, -999, -999, -999, -999, -999,
  116619. -999, -999, -999, -999, -999, -999, -999, -999},
  116620. { -59, -59, -59, -59, -59, -59, -59, -59,
  116621. -59, -59, -59, -60, -60, -61, -63, -66,
  116622. -71, -68, -70, -70, -71, -72, -72, -75,
  116623. -81, -78, -79, -82, -83, -86, -90, -97,
  116624. -103, -113, -999, -999, -999, -999, -999, -999,
  116625. -999, -999, -999, -999, -999, -999, -999, -999,
  116626. -999, -999, -999, -999, -999, -999, -999, -999},
  116627. { -53, -53, -53, -53, -53, -53, -53, -53,
  116628. -53, -54, -55, -57, -56, -57, -55, -61,
  116629. -65, -60, -60, -62, -63, -63, -66, -68,
  116630. -74, -73, -75, -75, -78, -80, -80, -82,
  116631. -85, -90, -96, -101, -108, -999, -999, -999,
  116632. -999, -999, -999, -999, -999, -999, -999, -999,
  116633. -999, -999, -999, -999, -999, -999, -999, -999},
  116634. { -46, -46, -46, -46, -46, -46, -46, -46,
  116635. -46, -46, -47, -47, -47, -47, -48, -51,
  116636. -57, -51, -49, -50, -51, -53, -54, -59,
  116637. -66, -60, -62, -67, -67, -70, -72, -75,
  116638. -76, -78, -81, -85, -88, -94, -97, -104,
  116639. -112, -999, -999, -999, -999, -999, -999, -999,
  116640. -999, -999, -999, -999, -999, -999, -999, -999},
  116641. { -36, -36, -36, -36, -36, -36, -36, -36,
  116642. -39, -41, -42, -42, -39, -38, -41, -43,
  116643. -52, -44, -40, -39, -37, -37, -40, -47,
  116644. -54, -50, -48, -50, -55, -61, -59, -62,
  116645. -66, -66, -66, -69, -69, -73, -74, -74,
  116646. -75, -77, -79, -82, -87, -91, -95, -100,
  116647. -108, -115, -999, -999, -999, -999, -999, -999},
  116648. { -28, -26, -24, -22, -20, -20, -23, -29,
  116649. -30, -31, -28, -27, -28, -28, -28, -35,
  116650. -40, -33, -32, -29, -30, -30, -30, -37,
  116651. -45, -41, -37, -38, -45, -47, -47, -48,
  116652. -53, -49, -48, -50, -49, -49, -51, -52,
  116653. -58, -56, -57, -56, -60, -61, -62, -70,
  116654. -72, -74, -78, -83, -88, -93, -100, -106}},
  116655. /* 177 Hz */
  116656. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116657. -999, -110, -105, -100, -95, -91, -87, -83,
  116658. -80, -78, -76, -78, -78, -81, -83, -85,
  116659. -86, -85, -86, -87, -90, -97, -107, -999,
  116660. -999, -999, -999, -999, -999, -999, -999, -999,
  116661. -999, -999, -999, -999, -999, -999, -999, -999,
  116662. -999, -999, -999, -999, -999, -999, -999, -999},
  116663. {-999, -999, -999, -110, -105, -100, -95, -90,
  116664. -85, -81, -77, -73, -70, -67, -67, -68,
  116665. -75, -73, -70, -69, -70, -72, -75, -79,
  116666. -84, -83, -84, -86, -88, -89, -89, -93,
  116667. -98, -105, -112, -999, -999, -999, -999, -999,
  116668. -999, -999, -999, -999, -999, -999, -999, -999,
  116669. -999, -999, -999, -999, -999, -999, -999, -999},
  116670. {-105, -100, -95, -90, -85, -80, -76, -71,
  116671. -68, -68, -65, -63, -63, -62, -62, -64,
  116672. -65, -64, -61, -62, -63, -64, -66, -68,
  116673. -73, -73, -74, -75, -76, -81, -83, -85,
  116674. -88, -89, -92, -95, -100, -108, -999, -999,
  116675. -999, -999, -999, -999, -999, -999, -999, -999,
  116676. -999, -999, -999, -999, -999, -999, -999, -999},
  116677. { -80, -75, -71, -68, -65, -63, -62, -61,
  116678. -61, -61, -61, -59, -56, -57, -53, -50,
  116679. -58, -52, -50, -50, -52, -53, -54, -58,
  116680. -67, -63, -67, -68, -72, -75, -78, -80,
  116681. -81, -81, -82, -85, -89, -90, -93, -97,
  116682. -101, -107, -114, -999, -999, -999, -999, -999,
  116683. -999, -999, -999, -999, -999, -999, -999, -999},
  116684. { -65, -61, -59, -57, -56, -55, -55, -56,
  116685. -56, -57, -55, -53, -52, -47, -44, -44,
  116686. -50, -44, -41, -39, -39, -42, -40, -46,
  116687. -51, -49, -50, -53, -54, -63, -60, -61,
  116688. -62, -66, -66, -66, -70, -73, -74, -75,
  116689. -76, -75, -79, -85, -89, -91, -96, -102,
  116690. -110, -999, -999, -999, -999, -999, -999, -999},
  116691. { -52, -50, -49, -49, -48, -48, -48, -49,
  116692. -50, -50, -49, -46, -43, -39, -35, -33,
  116693. -38, -36, -32, -29, -32, -32, -32, -35,
  116694. -44, -39, -38, -38, -46, -50, -45, -46,
  116695. -53, -50, -50, -50, -54, -54, -53, -53,
  116696. -56, -57, -59, -66, -70, -72, -74, -79,
  116697. -83, -85, -90, -97, -114, -999, -999, -999}},
  116698. /* 250 Hz */
  116699. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116700. -100, -95, -90, -86, -80, -75, -75, -79,
  116701. -80, -79, -80, -81, -82, -88, -95, -103,
  116702. -110, -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, -999, -999, -999, -999, -999, -999, -999},
  116706. {-999, -999, -999, -999, -108, -103, -98, -93,
  116707. -88, -83, -79, -78, -75, -71, -67, -68,
  116708. -73, -73, -72, -73, -75, -77, -80, -82,
  116709. -88, -93, -100, -107, -114, -999, -999, -999,
  116710. -999, -999, -999, -999, -999, -999, -999, -999,
  116711. -999, -999, -999, -999, -999, -999, -999, -999,
  116712. -999, -999, -999, -999, -999, -999, -999, -999},
  116713. {-999, -999, -999, -110, -105, -101, -96, -90,
  116714. -86, -81, -77, -73, -69, -66, -61, -62,
  116715. -66, -64, -62, -65, -66, -70, -72, -76,
  116716. -81, -80, -84, -90, -95, -102, -110, -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, -107, -103, -97, -92, -88,
  116721. -83, -79, -74, -70, -66, -59, -53, -58,
  116722. -62, -55, -54, -54, -54, -58, -61, -62,
  116723. -72, -70, -72, -75, -78, -80, -81, -80,
  116724. -83, -83, -88, -93, -100, -107, -115, -999,
  116725. -999, -999, -999, -999, -999, -999, -999, -999,
  116726. -999, -999, -999, -999, -999, -999, -999, -999},
  116727. {-999, -999, -999, -105, -100, -95, -90, -85,
  116728. -80, -75, -70, -66, -62, -56, -48, -44,
  116729. -48, -46, -46, -43, -46, -48, -48, -51,
  116730. -58, -58, -59, -60, -62, -62, -61, -61,
  116731. -65, -64, -65, -68, -70, -74, -75, -78,
  116732. -81, -86, -95, -110, -999, -999, -999, -999,
  116733. -999, -999, -999, -999, -999, -999, -999, -999},
  116734. {-999, -999, -105, -100, -95, -90, -85, -80,
  116735. -75, -70, -65, -61, -55, -49, -39, -33,
  116736. -40, -35, -32, -38, -40, -33, -35, -37,
  116737. -46, -41, -45, -44, -46, -42, -45, -46,
  116738. -52, -50, -50, -50, -54, -54, -55, -57,
  116739. -62, -64, -66, -68, -70, -76, -81, -90,
  116740. -100, -110, -999, -999, -999, -999, -999, -999}},
  116741. /* 354 hz */
  116742. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116743. -105, -98, -90, -85, -82, -83, -80, -78,
  116744. -84, -79, -80, -83, -87, -89, -91, -93,
  116745. -99, -106, -117, -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, -999, -999, -999, -999, -999, -999},
  116749. {-999, -999, -999, -999, -999, -999, -999, -999,
  116750. -105, -98, -90, -85, -80, -75, -70, -68,
  116751. -74, -72, -74, -77, -80, -82, -85, -87,
  116752. -92, -89, -91, -95, -100, -106, -112, -999,
  116753. -999, -999, -999, -999, -999, -999, -999, -999,
  116754. -999, -999, -999, -999, -999, -999, -999, -999,
  116755. -999, -999, -999, -999, -999, -999, -999, -999},
  116756. {-999, -999, -999, -999, -999, -999, -999, -999,
  116757. -105, -98, -90, -83, -75, -71, -63, -64,
  116758. -67, -62, -64, -67, -70, -73, -77, -81,
  116759. -84, -83, -85, -89, -90, -93, -98, -104,
  116760. -109, -114, -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, -999, -999, -999,
  116764. -103, -96, -88, -81, -75, -68, -58, -54,
  116765. -56, -54, -56, -56, -58, -60, -63, -66,
  116766. -74, -69, -72, -72, -75, -74, -77, -81,
  116767. -81, -82, -84, -87, -93, -96, -99, -104,
  116768. -110, -999, -999, -999, -999, -999, -999, -999,
  116769. -999, -999, -999, -999, -999, -999, -999, -999},
  116770. {-999, -999, -999, -999, -999, -108, -102, -96,
  116771. -91, -85, -80, -74, -68, -60, -51, -46,
  116772. -48, -46, -43, -45, -47, -47, -49, -48,
  116773. -56, -53, -55, -58, -57, -63, -58, -60,
  116774. -66, -64, -67, -70, -70, -74, -77, -84,
  116775. -86, -89, -91, -93, -94, -101, -109, -118,
  116776. -999, -999, -999, -999, -999, -999, -999, -999},
  116777. {-999, -999, -999, -108, -103, -98, -93, -88,
  116778. -83, -78, -73, -68, -60, -53, -44, -35,
  116779. -38, -38, -34, -34, -36, -40, -41, -44,
  116780. -51, -45, -46, -47, -46, -54, -50, -49,
  116781. -50, -50, -50, -51, -54, -57, -58, -60,
  116782. -66, -66, -66, -64, -65, -68, -77, -82,
  116783. -87, -95, -110, -999, -999, -999, -999, -999}},
  116784. /* 500 Hz */
  116785. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116786. -107, -102, -97, -92, -87, -83, -78, -75,
  116787. -82, -79, -83, -85, -89, -92, -95, -98,
  116788. -101, -105, -109, -113, -999, -999, -999, -999,
  116789. -999, -999, -999, -999, -999, -999, -999, -999,
  116790. -999, -999, -999, -999, -999, -999, -999, -999,
  116791. -999, -999, -999, -999, -999, -999, -999, -999},
  116792. {-999, -999, -999, -999, -999, -999, -999, -106,
  116793. -100, -95, -90, -86, -81, -78, -74, -69,
  116794. -74, -74, -76, -79, -83, -84, -86, -89,
  116795. -92, -97, -93, -100, -103, -107, -110, -999,
  116796. -999, -999, -999, -999, -999, -999, -999, -999,
  116797. -999, -999, -999, -999, -999, -999, -999, -999,
  116798. -999, -999, -999, -999, -999, -999, -999, -999},
  116799. {-999, -999, -999, -999, -999, -999, -106, -100,
  116800. -95, -90, -87, -83, -80, -75, -69, -60,
  116801. -66, -66, -68, -70, -74, -78, -79, -81,
  116802. -81, -83, -84, -87, -93, -96, -99, -103,
  116803. -107, -110, -999, -999, -999, -999, -999, -999,
  116804. -999, -999, -999, -999, -999, -999, -999, -999,
  116805. -999, -999, -999, -999, -999, -999, -999, -999},
  116806. {-999, -999, -999, -999, -999, -108, -103, -98,
  116807. -93, -89, -85, -82, -78, -71, -62, -55,
  116808. -58, -58, -54, -54, -55, -59, -61, -62,
  116809. -70, -66, -66, -67, -70, -72, -75, -78,
  116810. -84, -84, -84, -88, -91, -90, -95, -98,
  116811. -102, -103, -106, -110, -999, -999, -999, -999,
  116812. -999, -999, -999, -999, -999, -999, -999, -999},
  116813. {-999, -999, -999, -999, -108, -103, -98, -94,
  116814. -90, -87, -82, -79, -73, -67, -58, -47,
  116815. -50, -45, -41, -45, -48, -44, -44, -49,
  116816. -54, -51, -48, -47, -49, -50, -51, -57,
  116817. -58, -60, -63, -69, -70, -69, -71, -74,
  116818. -78, -82, -90, -95, -101, -105, -110, -999,
  116819. -999, -999, -999, -999, -999, -999, -999, -999},
  116820. {-999, -999, -999, -105, -101, -97, -93, -90,
  116821. -85, -80, -77, -72, -65, -56, -48, -37,
  116822. -40, -36, -34, -40, -50, -47, -38, -41,
  116823. -47, -38, -35, -39, -38, -43, -40, -45,
  116824. -50, -45, -44, -47, -50, -55, -48, -48,
  116825. -52, -66, -70, -76, -82, -90, -97, -105,
  116826. -110, -999, -999, -999, -999, -999, -999, -999}},
  116827. /* 707 Hz */
  116828. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116829. -999, -108, -103, -98, -93, -86, -79, -76,
  116830. -83, -81, -85, -87, -89, -93, -98, -102,
  116831. -107, -112, -999, -999, -999, -999, -999, -999,
  116832. -999, -999, -999, -999, -999, -999, -999, -999,
  116833. -999, -999, -999, -999, -999, -999, -999, -999,
  116834. -999, -999, -999, -999, -999, -999, -999, -999},
  116835. {-999, -999, -999, -999, -999, -999, -999, -999,
  116836. -999, -108, -103, -98, -93, -86, -79, -71,
  116837. -77, -74, -77, -79, -81, -84, -85, -90,
  116838. -92, -93, -92, -98, -101, -108, -112, -999,
  116839. -999, -999, -999, -999, -999, -999, -999, -999,
  116840. -999, -999, -999, -999, -999, -999, -999, -999,
  116841. -999, -999, -999, -999, -999, -999, -999, -999},
  116842. {-999, -999, -999, -999, -999, -999, -999, -999,
  116843. -108, -103, -98, -93, -87, -78, -68, -65,
  116844. -66, -62, -65, -67, -70, -73, -75, -78,
  116845. -82, -82, -83, -84, -91, -93, -98, -102,
  116846. -106, -110, -999, -999, -999, -999, -999, -999,
  116847. -999, -999, -999, -999, -999, -999, -999, -999,
  116848. -999, -999, -999, -999, -999, -999, -999, -999},
  116849. {-999, -999, -999, -999, -999, -999, -999, -999,
  116850. -105, -100, -95, -90, -82, -74, -62, -57,
  116851. -58, -56, -51, -52, -52, -54, -54, -58,
  116852. -66, -59, -60, -63, -66, -69, -73, -79,
  116853. -83, -84, -80, -81, -81, -82, -88, -92,
  116854. -98, -105, -113, -999, -999, -999, -999, -999,
  116855. -999, -999, -999, -999, -999, -999, -999, -999},
  116856. {-999, -999, -999, -999, -999, -999, -999, -107,
  116857. -102, -97, -92, -84, -79, -69, -57, -47,
  116858. -52, -47, -44, -45, -50, -52, -42, -42,
  116859. -53, -43, -43, -48, -51, -56, -55, -52,
  116860. -57, -59, -61, -62, -67, -71, -78, -83,
  116861. -86, -94, -98, -103, -110, -999, -999, -999,
  116862. -999, -999, -999, -999, -999, -999, -999, -999},
  116863. {-999, -999, -999, -999, -999, -999, -105, -100,
  116864. -95, -90, -84, -78, -70, -61, -51, -41,
  116865. -40, -38, -40, -46, -52, -51, -41, -40,
  116866. -46, -40, -38, -38, -41, -46, -41, -46,
  116867. -47, -43, -43, -45, -41, -45, -56, -67,
  116868. -68, -83, -87, -90, -95, -102, -107, -113,
  116869. -999, -999, -999, -999, -999, -999, -999, -999}},
  116870. /* 1000 Hz */
  116871. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116872. -999, -109, -105, -101, -96, -91, -84, -77,
  116873. -82, -82, -85, -89, -94, -100, -106, -110,
  116874. -999, -999, -999, -999, -999, -999, -999, -999,
  116875. -999, -999, -999, -999, -999, -999, -999, -999,
  116876. -999, -999, -999, -999, -999, -999, -999, -999,
  116877. -999, -999, -999, -999, -999, -999, -999, -999},
  116878. {-999, -999, -999, -999, -999, -999, -999, -999,
  116879. -999, -106, -103, -98, -92, -85, -80, -71,
  116880. -75, -72, -76, -80, -84, -86, -89, -93,
  116881. -100, -107, -113, -999, -999, -999, -999, -999,
  116882. -999, -999, -999, -999, -999, -999, -999, -999,
  116883. -999, -999, -999, -999, -999, -999, -999, -999,
  116884. -999, -999, -999, -999, -999, -999, -999, -999},
  116885. {-999, -999, -999, -999, -999, -999, -999, -107,
  116886. -104, -101, -97, -92, -88, -84, -80, -64,
  116887. -66, -63, -64, -66, -69, -73, -77, -83,
  116888. -83, -86, -91, -98, -104, -111, -999, -999,
  116889. -999, -999, -999, -999, -999, -999, -999, -999,
  116890. -999, -999, -999, -999, -999, -999, -999, -999,
  116891. -999, -999, -999, -999, -999, -999, -999, -999},
  116892. {-999, -999, -999, -999, -999, -999, -999, -107,
  116893. -104, -101, -97, -92, -90, -84, -74, -57,
  116894. -58, -52, -55, -54, -50, -52, -50, -52,
  116895. -63, -62, -69, -76, -77, -78, -78, -79,
  116896. -82, -88, -94, -100, -106, -111, -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, -999, -106, -102,
  116900. -98, -95, -90, -85, -83, -78, -70, -50,
  116901. -50, -41, -44, -49, -47, -50, -50, -44,
  116902. -55, -46, -47, -48, -48, -54, -49, -49,
  116903. -58, -62, -71, -81, -87, -92, -97, -102,
  116904. -108, -114, -999, -999, -999, -999, -999, -999,
  116905. -999, -999, -999, -999, -999, -999, -999, -999},
  116906. {-999, -999, -999, -999, -999, -999, -106, -102,
  116907. -98, -95, -90, -85, -83, -78, -70, -45,
  116908. -43, -41, -47, -50, -51, -50, -49, -45,
  116909. -47, -41, -44, -41, -39, -43, -38, -37,
  116910. -40, -41, -44, -50, -58, -65, -73, -79,
  116911. -85, -92, -97, -101, -105, -109, -113, -999,
  116912. -999, -999, -999, -999, -999, -999, -999, -999}},
  116913. /* 1414 Hz */
  116914. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116915. -999, -999, -999, -107, -100, -95, -87, -81,
  116916. -85, -83, -88, -93, -100, -107, -114, -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, -999, -999, -999, -999},
  116921. {-999, -999, -999, -999, -999, -999, -999, -999,
  116922. -999, -999, -107, -101, -95, -88, -83, -76,
  116923. -73, -72, -79, -84, -90, -95, -100, -105,
  116924. -110, -115, -999, -999, -999, -999, -999, -999,
  116925. -999, -999, -999, -999, -999, -999, -999, -999,
  116926. -999, -999, -999, -999, -999, -999, -999, -999,
  116927. -999, -999, -999, -999, -999, -999, -999, -999},
  116928. {-999, -999, -999, -999, -999, -999, -999, -999,
  116929. -999, -999, -104, -98, -92, -87, -81, -70,
  116930. -65, -62, -67, -71, -74, -80, -85, -91,
  116931. -95, -99, -103, -108, -111, -114, -999, -999,
  116932. -999, -999, -999, -999, -999, -999, -999, -999,
  116933. -999, -999, -999, -999, -999, -999, -999, -999,
  116934. -999, -999, -999, -999, -999, -999, -999, -999},
  116935. {-999, -999, -999, -999, -999, -999, -999, -999,
  116936. -999, -999, -103, -97, -90, -85, -76, -60,
  116937. -56, -54, -60, -62, -61, -56, -63, -65,
  116938. -73, -74, -77, -75, -78, -81, -86, -87,
  116939. -88, -91, -94, -98, -103, -110, -999, -999,
  116940. -999, -999, -999, -999, -999, -999, -999, -999,
  116941. -999, -999, -999, -999, -999, -999, -999, -999},
  116942. {-999, -999, -999, -999, -999, -999, -999, -105,
  116943. -100, -97, -92, -86, -81, -79, -70, -57,
  116944. -51, -47, -51, -58, -60, -56, -53, -50,
  116945. -58, -52, -50, -50, -53, -55, -64, -69,
  116946. -71, -85, -82, -78, -81, -85, -95, -102,
  116947. -112, -999, -999, -999, -999, -999, -999, -999,
  116948. -999, -999, -999, -999, -999, -999, -999, -999},
  116949. {-999, -999, -999, -999, -999, -999, -999, -105,
  116950. -100, -97, -92, -85, -83, -79, -72, -49,
  116951. -40, -43, -43, -54, -56, -51, -50, -40,
  116952. -43, -38, -36, -35, -37, -38, -37, -44,
  116953. -54, -60, -57, -60, -70, -75, -84, -92,
  116954. -103, -112, -999, -999, -999, -999, -999, -999,
  116955. -999, -999, -999, -999, -999, -999, -999, -999}},
  116956. /* 2000 Hz */
  116957. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116958. -999, -999, -999, -110, -102, -95, -89, -82,
  116959. -83, -84, -90, -92, -99, -107, -113, -999,
  116960. -999, -999, -999, -999, -999, -999, -999, -999,
  116961. -999, -999, -999, -999, -999, -999, -999, -999,
  116962. -999, -999, -999, -999, -999, -999, -999, -999,
  116963. -999, -999, -999, -999, -999, -999, -999, -999},
  116964. {-999, -999, -999, -999, -999, -999, -999, -999,
  116965. -999, -999, -107, -101, -95, -89, -83, -72,
  116966. -74, -78, -85, -88, -88, -90, -92, -98,
  116967. -105, -111, -999, -999, -999, -999, -999, -999,
  116968. -999, -999, -999, -999, -999, -999, -999, -999,
  116969. -999, -999, -999, -999, -999, -999, -999, -999,
  116970. -999, -999, -999, -999, -999, -999, -999, -999},
  116971. {-999, -999, -999, -999, -999, -999, -999, -999,
  116972. -999, -109, -103, -97, -93, -87, -81, -70,
  116973. -70, -67, -75, -73, -76, -79, -81, -83,
  116974. -88, -89, -97, -103, -110, -999, -999, -999,
  116975. -999, -999, -999, -999, -999, -999, -999, -999,
  116976. -999, -999, -999, -999, -999, -999, -999, -999,
  116977. -999, -999, -999, -999, -999, -999, -999, -999},
  116978. {-999, -999, -999, -999, -999, -999, -999, -999,
  116979. -999, -107, -100, -94, -88, -83, -75, -63,
  116980. -59, -59, -63, -66, -60, -62, -67, -67,
  116981. -77, -76, -81, -88, -86, -92, -96, -102,
  116982. -109, -116, -999, -999, -999, -999, -999, -999,
  116983. -999, -999, -999, -999, -999, -999, -999, -999,
  116984. -999, -999, -999, -999, -999, -999, -999, -999},
  116985. {-999, -999, -999, -999, -999, -999, -999, -999,
  116986. -999, -105, -98, -92, -86, -81, -73, -56,
  116987. -52, -47, -55, -60, -58, -52, -51, -45,
  116988. -49, -50, -53, -54, -61, -71, -70, -69,
  116989. -78, -79, -87, -90, -96, -104, -112, -999,
  116990. -999, -999, -999, -999, -999, -999, -999, -999,
  116991. -999, -999, -999, -999, -999, -999, -999, -999},
  116992. {-999, -999, -999, -999, -999, -999, -999, -999,
  116993. -999, -103, -96, -90, -86, -78, -70, -51,
  116994. -42, -47, -48, -55, -54, -54, -53, -42,
  116995. -35, -28, -33, -38, -37, -44, -47, -49,
  116996. -54, -63, -68, -78, -82, -89, -94, -99,
  116997. -104, -109, -114, -999, -999, -999, -999, -999,
  116998. -999, -999, -999, -999, -999, -999, -999, -999}},
  116999. /* 2828 Hz */
  117000. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117001. -999, -999, -999, -999, -110, -100, -90, -79,
  117002. -85, -81, -82, -82, -89, -94, -99, -103,
  117003. -109, -115, -999, -999, -999, -999, -999, -999,
  117004. -999, -999, -999, -999, -999, -999, -999, -999,
  117005. -999, -999, -999, -999, -999, -999, -999, -999,
  117006. -999, -999, -999, -999, -999, -999, -999, -999},
  117007. {-999, -999, -999, -999, -999, -999, -999, -999,
  117008. -999, -999, -999, -999, -105, -97, -85, -72,
  117009. -74, -70, -70, -70, -76, -85, -91, -93,
  117010. -97, -103, -109, -115, -999, -999, -999, -999,
  117011. -999, -999, -999, -999, -999, -999, -999, -999,
  117012. -999, -999, -999, -999, -999, -999, -999, -999,
  117013. -999, -999, -999, -999, -999, -999, -999, -999},
  117014. {-999, -999, -999, -999, -999, -999, -999, -999,
  117015. -999, -999, -999, -999, -112, -93, -81, -68,
  117016. -62, -60, -60, -57, -63, -70, -77, -82,
  117017. -90, -93, -98, -104, -109, -113, -999, -999,
  117018. -999, -999, -999, -999, -999, -999, -999, -999,
  117019. -999, -999, -999, -999, -999, -999, -999, -999,
  117020. -999, -999, -999, -999, -999, -999, -999, -999},
  117021. {-999, -999, -999, -999, -999, -999, -999, -999,
  117022. -999, -999, -999, -113, -100, -93, -84, -63,
  117023. -58, -48, -53, -54, -52, -52, -57, -64,
  117024. -66, -76, -83, -81, -85, -85, -90, -95,
  117025. -98, -101, -103, -106, -108, -111, -999, -999,
  117026. -999, -999, -999, -999, -999, -999, -999, -999,
  117027. -999, -999, -999, -999, -999, -999, -999, -999},
  117028. {-999, -999, -999, -999, -999, -999, -999, -999,
  117029. -999, -999, -999, -105, -95, -86, -74, -53,
  117030. -50, -38, -43, -49, -43, -42, -39, -39,
  117031. -46, -52, -57, -56, -72, -69, -74, -81,
  117032. -87, -92, -94, -97, -99, -102, -105, -108,
  117033. -999, -999, -999, -999, -999, -999, -999, -999,
  117034. -999, -999, -999, -999, -999, -999, -999, -999},
  117035. {-999, -999, -999, -999, -999, -999, -999, -999,
  117036. -999, -999, -108, -99, -90, -76, -66, -45,
  117037. -43, -41, -44, -47, -43, -47, -40, -30,
  117038. -31, -31, -39, -33, -40, -41, -43, -53,
  117039. -59, -70, -73, -77, -79, -82, -84, -87,
  117040. -999, -999, -999, -999, -999, -999, -999, -999,
  117041. -999, -999, -999, -999, -999, -999, -999, -999}},
  117042. /* 4000 Hz */
  117043. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117044. -999, -999, -999, -999, -999, -110, -91, -76,
  117045. -75, -85, -93, -98, -104, -110, -999, -999,
  117046. -999, -999, -999, -999, -999, -999, -999, -999,
  117047. -999, -999, -999, -999, -999, -999, -999, -999,
  117048. -999, -999, -999, -999, -999, -999, -999, -999,
  117049. -999, -999, -999, -999, -999, -999, -999, -999},
  117050. {-999, -999, -999, -999, -999, -999, -999, -999,
  117051. -999, -999, -999, -999, -999, -110, -91, -70,
  117052. -70, -75, -86, -89, -94, -98, -101, -106,
  117053. -110, -999, -999, -999, -999, -999, -999, -999,
  117054. -999, -999, -999, -999, -999, -999, -999, -999,
  117055. -999, -999, -999, -999, -999, -999, -999, -999,
  117056. -999, -999, -999, -999, -999, -999, -999, -999},
  117057. {-999, -999, -999, -999, -999, -999, -999, -999,
  117058. -999, -999, -999, -999, -110, -95, -80, -60,
  117059. -65, -64, -74, -83, -88, -91, -95, -99,
  117060. -103, -107, -110, -999, -999, -999, -999, -999,
  117061. -999, -999, -999, -999, -999, -999, -999, -999,
  117062. -999, -999, -999, -999, -999, -999, -999, -999,
  117063. -999, -999, -999, -999, -999, -999, -999, -999},
  117064. {-999, -999, -999, -999, -999, -999, -999, -999,
  117065. -999, -999, -999, -999, -110, -95, -80, -58,
  117066. -55, -49, -66, -68, -71, -78, -78, -80,
  117067. -88, -85, -89, -97, -100, -105, -110, -999,
  117068. -999, -999, -999, -999, -999, -999, -999, -999,
  117069. -999, -999, -999, -999, -999, -999, -999, -999,
  117070. -999, -999, -999, -999, -999, -999, -999, -999},
  117071. {-999, -999, -999, -999, -999, -999, -999, -999,
  117072. -999, -999, -999, -999, -110, -95, -80, -53,
  117073. -52, -41, -59, -59, -49, -58, -56, -63,
  117074. -86, -79, -90, -93, -98, -103, -107, -112,
  117075. -999, -999, -999, -999, -999, -999, -999, -999,
  117076. -999, -999, -999, -999, -999, -999, -999, -999,
  117077. -999, -999, -999, -999, -999, -999, -999, -999},
  117078. {-999, -999, -999, -999, -999, -999, -999, -999,
  117079. -999, -999, -999, -110, -97, -91, -73, -45,
  117080. -40, -33, -53, -61, -49, -54, -50, -50,
  117081. -60, -52, -67, -74, -81, -92, -96, -100,
  117082. -105, -110, -999, -999, -999, -999, -999, -999,
  117083. -999, -999, -999, -999, -999, -999, -999, -999,
  117084. -999, -999, -999, -999, -999, -999, -999, -999}},
  117085. /* 5657 Hz */
  117086. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117087. -999, -999, -999, -113, -106, -99, -92, -77,
  117088. -80, -88, -97, -106, -115, -999, -999, -999,
  117089. -999, -999, -999, -999, -999, -999, -999, -999,
  117090. -999, -999, -999, -999, -999, -999, -999, -999,
  117091. -999, -999, -999, -999, -999, -999, -999, -999,
  117092. -999, -999, -999, -999, -999, -999, -999, -999},
  117093. {-999, -999, -999, -999, -999, -999, -999, -999,
  117094. -999, -999, -116, -109, -102, -95, -89, -74,
  117095. -72, -88, -87, -95, -102, -109, -116, -999,
  117096. -999, -999, -999, -999, -999, -999, -999, -999,
  117097. -999, -999, -999, -999, -999, -999, -999, -999,
  117098. -999, -999, -999, -999, -999, -999, -999, -999,
  117099. -999, -999, -999, -999, -999, -999, -999, -999},
  117100. {-999, -999, -999, -999, -999, -999, -999, -999,
  117101. -999, -999, -116, -109, -102, -95, -89, -75,
  117102. -66, -74, -77, -78, -86, -87, -90, -96,
  117103. -105, -115, -999, -999, -999, -999, -999, -999,
  117104. -999, -999, -999, -999, -999, -999, -999, -999,
  117105. -999, -999, -999, -999, -999, -999, -999, -999,
  117106. -999, -999, -999, -999, -999, -999, -999, -999},
  117107. {-999, -999, -999, -999, -999, -999, -999, -999,
  117108. -999, -999, -115, -108, -101, -94, -88, -66,
  117109. -56, -61, -70, -65, -78, -72, -83, -84,
  117110. -93, -98, -105, -110, -999, -999, -999, -999,
  117111. -999, -999, -999, -999, -999, -999, -999, -999,
  117112. -999, -999, -999, -999, -999, -999, -999, -999,
  117113. -999, -999, -999, -999, -999, -999, -999, -999},
  117114. {-999, -999, -999, -999, -999, -999, -999, -999,
  117115. -999, -999, -110, -105, -95, -89, -82, -57,
  117116. -52, -52, -59, -56, -59, -58, -69, -67,
  117117. -88, -82, -82, -89, -94, -100, -108, -999,
  117118. -999, -999, -999, -999, -999, -999, -999, -999,
  117119. -999, -999, -999, -999, -999, -999, -999, -999,
  117120. -999, -999, -999, -999, -999, -999, -999, -999},
  117121. {-999, -999, -999, -999, -999, -999, -999, -999,
  117122. -999, -110, -101, -96, -90, -83, -77, -54,
  117123. -43, -38, -50, -48, -52, -48, -42, -42,
  117124. -51, -52, -53, -59, -65, -71, -78, -85,
  117125. -95, -999, -999, -999, -999, -999, -999, -999,
  117126. -999, -999, -999, -999, -999, -999, -999, -999,
  117127. -999, -999, -999, -999, -999, -999, -999, -999}},
  117128. /* 8000 Hz */
  117129. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117130. -999, -999, -999, -999, -120, -105, -86, -68,
  117131. -78, -79, -90, -100, -110, -999, -999, -999,
  117132. -999, -999, -999, -999, -999, -999, -999, -999,
  117133. -999, -999, -999, -999, -999, -999, -999, -999,
  117134. -999, -999, -999, -999, -999, -999, -999, -999,
  117135. -999, -999, -999, -999, -999, -999, -999, -999},
  117136. {-999, -999, -999, -999, -999, -999, -999, -999,
  117137. -999, -999, -999, -999, -120, -105, -86, -66,
  117138. -73, -77, -88, -96, -105, -115, -999, -999,
  117139. -999, -999, -999, -999, -999, -999, -999, -999,
  117140. -999, -999, -999, -999, -999, -999, -999, -999,
  117141. -999, -999, -999, -999, -999, -999, -999, -999,
  117142. -999, -999, -999, -999, -999, -999, -999, -999},
  117143. {-999, -999, -999, -999, -999, -999, -999, -999,
  117144. -999, -999, -999, -120, -105, -92, -80, -61,
  117145. -64, -68, -80, -87, -92, -100, -110, -999,
  117146. -999, -999, -999, -999, -999, -999, -999, -999,
  117147. -999, -999, -999, -999, -999, -999, -999, -999,
  117148. -999, -999, -999, -999, -999, -999, -999, -999,
  117149. -999, -999, -999, -999, -999, -999, -999, -999},
  117150. {-999, -999, -999, -999, -999, -999, -999, -999,
  117151. -999, -999, -999, -120, -104, -91, -79, -52,
  117152. -60, -54, -64, -69, -77, -80, -82, -84,
  117153. -85, -87, -88, -90, -999, -999, -999, -999,
  117154. -999, -999, -999, -999, -999, -999, -999, -999,
  117155. -999, -999, -999, -999, -999, -999, -999, -999,
  117156. -999, -999, -999, -999, -999, -999, -999, -999},
  117157. {-999, -999, -999, -999, -999, -999, -999, -999,
  117158. -999, -999, -999, -118, -100, -87, -77, -49,
  117159. -50, -44, -58, -61, -61, -67, -65, -62,
  117160. -62, -62, -65, -68, -999, -999, -999, -999,
  117161. -999, -999, -999, -999, -999, -999, -999, -999,
  117162. -999, -999, -999, -999, -999, -999, -999, -999,
  117163. -999, -999, -999, -999, -999, -999, -999, -999},
  117164. {-999, -999, -999, -999, -999, -999, -999, -999,
  117165. -999, -999, -999, -115, -98, -84, -62, -49,
  117166. -44, -38, -46, -49, -49, -46, -39, -37,
  117167. -39, -40, -42, -43, -999, -999, -999, -999,
  117168. -999, -999, -999, -999, -999, -999, -999, -999,
  117169. -999, -999, -999, -999, -999, -999, -999, -999,
  117170. -999, -999, -999, -999, -999, -999, -999, -999}},
  117171. /* 11314 Hz */
  117172. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117173. -999, -999, -999, -999, -999, -110, -88, -74,
  117174. -77, -82, -82, -85, -90, -94, -99, -104,
  117175. -999, -999, -999, -999, -999, -999, -999, -999,
  117176. -999, -999, -999, -999, -999, -999, -999, -999,
  117177. -999, -999, -999, -999, -999, -999, -999, -999,
  117178. -999, -999, -999, -999, -999, -999, -999, -999},
  117179. {-999, -999, -999, -999, -999, -999, -999, -999,
  117180. -999, -999, -999, -999, -999, -110, -88, -66,
  117181. -70, -81, -80, -81, -84, -88, -91, -93,
  117182. -999, -999, -999, -999, -999, -999, -999, -999,
  117183. -999, -999, -999, -999, -999, -999, -999, -999,
  117184. -999, -999, -999, -999, -999, -999, -999, -999,
  117185. -999, -999, -999, -999, -999, -999, -999, -999},
  117186. {-999, -999, -999, -999, -999, -999, -999, -999,
  117187. -999, -999, -999, -999, -999, -110, -88, -61,
  117188. -63, -70, -71, -74, -77, -80, -83, -85,
  117189. -999, -999, -999, -999, -999, -999, -999, -999,
  117190. -999, -999, -999, -999, -999, -999, -999, -999,
  117191. -999, -999, -999, -999, -999, -999, -999, -999,
  117192. -999, -999, -999, -999, -999, -999, -999, -999},
  117193. {-999, -999, -999, -999, -999, -999, -999, -999,
  117194. -999, -999, -999, -999, -999, -110, -86, -62,
  117195. -63, -62, -62, -58, -52, -50, -50, -52,
  117196. -54, -999, -999, -999, -999, -999, -999, -999,
  117197. -999, -999, -999, -999, -999, -999, -999, -999,
  117198. -999, -999, -999, -999, -999, -999, -999, -999,
  117199. -999, -999, -999, -999, -999, -999, -999, -999},
  117200. {-999, -999, -999, -999, -999, -999, -999, -999,
  117201. -999, -999, -999, -999, -118, -108, -84, -53,
  117202. -50, -50, -50, -55, -47, -45, -40, -40,
  117203. -40, -999, -999, -999, -999, -999, -999, -999,
  117204. -999, -999, -999, -999, -999, -999, -999, -999,
  117205. -999, -999, -999, -999, -999, -999, -999, -999,
  117206. -999, -999, -999, -999, -999, -999, -999, -999},
  117207. {-999, -999, -999, -999, -999, -999, -999, -999,
  117208. -999, -999, -999, -999, -118, -100, -73, -43,
  117209. -37, -42, -43, -53, -38, -37, -35, -35,
  117210. -38, -999, -999, -999, -999, -999, -999, -999,
  117211. -999, -999, -999, -999, -999, -999, -999, -999,
  117212. -999, -999, -999, -999, -999, -999, -999, -999,
  117213. -999, -999, -999, -999, -999, -999, -999, -999}},
  117214. /* 16000 Hz */
  117215. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117216. -999, -999, -999, -110, -100, -91, -84, -74,
  117217. -80, -80, -80, -80, -80, -999, -999, -999,
  117218. -999, -999, -999, -999, -999, -999, -999, -999,
  117219. -999, -999, -999, -999, -999, -999, -999, -999,
  117220. -999, -999, -999, -999, -999, -999, -999, -999,
  117221. -999, -999, -999, -999, -999, -999, -999, -999},
  117222. {-999, -999, -999, -999, -999, -999, -999, -999,
  117223. -999, -999, -999, -110, -100, -91, -84, -74,
  117224. -68, -68, -68, -68, -68, -999, -999, -999,
  117225. -999, -999, -999, -999, -999, -999, -999, -999,
  117226. -999, -999, -999, -999, -999, -999, -999, -999,
  117227. -999, -999, -999, -999, -999, -999, -999, -999,
  117228. -999, -999, -999, -999, -999, -999, -999, -999},
  117229. {-999, -999, -999, -999, -999, -999, -999, -999,
  117230. -999, -999, -999, -110, -100, -86, -78, -70,
  117231. -60, -45, -30, -21, -999, -999, -999, -999,
  117232. -999, -999, -999, -999, -999, -999, -999, -999,
  117233. -999, -999, -999, -999, -999, -999, -999, -999,
  117234. -999, -999, -999, -999, -999, -999, -999, -999,
  117235. -999, -999, -999, -999, -999, -999, -999, -999},
  117236. {-999, -999, -999, -999, -999, -999, -999, -999,
  117237. -999, -999, -999, -110, -100, -87, -78, -67,
  117238. -48, -38, -29, -21, -999, -999, -999, -999,
  117239. -999, -999, -999, -999, -999, -999, -999, -999,
  117240. -999, -999, -999, -999, -999, -999, -999, -999,
  117241. -999, -999, -999, -999, -999, -999, -999, -999,
  117242. -999, -999, -999, -999, -999, -999, -999, -999},
  117243. {-999, -999, -999, -999, -999, -999, -999, -999,
  117244. -999, -999, -999, -110, -100, -86, -69, -56,
  117245. -45, -35, -33, -29, -999, -999, -999, -999,
  117246. -999, -999, -999, -999, -999, -999, -999, -999,
  117247. -999, -999, -999, -999, -999, -999, -999, -999,
  117248. -999, -999, -999, -999, -999, -999, -999, -999,
  117249. -999, -999, -999, -999, -999, -999, -999, -999},
  117250. {-999, -999, -999, -999, -999, -999, -999, -999,
  117251. -999, -999, -999, -110, -100, -83, -71, -48,
  117252. -27, -38, -37, -34, -999, -999, -999, -999,
  117253. -999, -999, -999, -999, -999, -999, -999, -999,
  117254. -999, -999, -999, -999, -999, -999, -999, -999,
  117255. -999, -999, -999, -999, -999, -999, -999, -999,
  117256. -999, -999, -999, -999, -999, -999, -999, -999}}
  117257. };
  117258. #endif
  117259. /*** End of inlined file: masking.h ***/
  117260. #define NEGINF -9999.f
  117261. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117262. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117263. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117264. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117265. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117266. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117267. look->channels=vi->channels;
  117268. look->ampmax=-9999.;
  117269. look->gi=gi;
  117270. return(look);
  117271. }
  117272. void _vp_global_free(vorbis_look_psy_global *look){
  117273. if(look){
  117274. memset(look,0,sizeof(*look));
  117275. _ogg_free(look);
  117276. }
  117277. }
  117278. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117279. if(i){
  117280. memset(i,0,sizeof(*i));
  117281. _ogg_free(i);
  117282. }
  117283. }
  117284. void _vi_psy_free(vorbis_info_psy *i){
  117285. if(i){
  117286. memset(i,0,sizeof(*i));
  117287. _ogg_free(i);
  117288. }
  117289. }
  117290. static void min_curve(float *c,
  117291. float *c2){
  117292. int i;
  117293. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117294. }
  117295. static void max_curve(float *c,
  117296. float *c2){
  117297. int i;
  117298. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117299. }
  117300. static void attenuate_curve(float *c,float att){
  117301. int i;
  117302. for(i=0;i<EHMER_MAX;i++)
  117303. c[i]+=att;
  117304. }
  117305. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117306. float center_boost, float center_decay_rate){
  117307. int i,j,k,m;
  117308. float ath[EHMER_MAX];
  117309. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117310. float athc[P_LEVELS][EHMER_MAX];
  117311. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117312. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117313. memset(workc,0,sizeof(workc));
  117314. for(i=0;i<P_BANDS;i++){
  117315. /* we add back in the ATH to avoid low level curves falling off to
  117316. -infinity and unnecessarily cutting off high level curves in the
  117317. curve limiting (last step). */
  117318. /* A half-band's settings must be valid over the whole band, and
  117319. it's better to mask too little than too much */
  117320. int ath_offset=i*4;
  117321. for(j=0;j<EHMER_MAX;j++){
  117322. float min=999.;
  117323. for(k=0;k<4;k++)
  117324. if(j+k+ath_offset<MAX_ATH){
  117325. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117326. }else{
  117327. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117328. }
  117329. ath[j]=min;
  117330. }
  117331. /* copy curves into working space, replicate the 50dB curve to 30
  117332. and 40, replicate the 100dB curve to 110 */
  117333. for(j=0;j<6;j++)
  117334. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117335. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117336. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117337. /* apply centered curve boost/decay */
  117338. for(j=0;j<P_LEVELS;j++){
  117339. for(k=0;k<EHMER_MAX;k++){
  117340. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117341. if(adj<0. && center_boost>0)adj=0.;
  117342. if(adj>0. && center_boost<0)adj=0.;
  117343. workc[i][j][k]+=adj;
  117344. }
  117345. }
  117346. /* normalize curves so the driving amplitude is 0dB */
  117347. /* make temp curves with the ATH overlayed */
  117348. for(j=0;j<P_LEVELS;j++){
  117349. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117350. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117351. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117352. max_curve(athc[j],workc[i][j]);
  117353. }
  117354. /* Now limit the louder curves.
  117355. the idea is this: We don't know what the playback attenuation
  117356. will be; 0dB SL moves every time the user twiddles the volume
  117357. knob. So that means we have to use a single 'most pessimal' curve
  117358. for all masking amplitudes, right? Wrong. The *loudest* sound
  117359. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117360. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117361. etc... */
  117362. for(j=1;j<P_LEVELS;j++){
  117363. min_curve(athc[j],athc[j-1]);
  117364. min_curve(workc[i][j],athc[j]);
  117365. }
  117366. }
  117367. for(i=0;i<P_BANDS;i++){
  117368. int hi_curve,lo_curve,bin;
  117369. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117370. /* low frequency curves are measured with greater resolution than
  117371. the MDCT/FFT will actually give us; we want the curve applied
  117372. to the tone data to be pessimistic and thus apply the minimum
  117373. masking possible for a given bin. That means that a single bin
  117374. could span more than one octave and that the curve will be a
  117375. composite of multiple octaves. It also may mean that a single
  117376. bin may span > an eighth of an octave and that the eighth
  117377. octave values may also be composited. */
  117378. /* which octave curves will we be compositing? */
  117379. bin=floor(fromOC(i*.5)/binHz);
  117380. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117381. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117382. if(lo_curve>i)lo_curve=i;
  117383. if(lo_curve<0)lo_curve=0;
  117384. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117385. for(m=0;m<P_LEVELS;m++){
  117386. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117387. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117388. /* render the curve into bins, then pull values back into curve.
  117389. The point is that any inherent subsampling aliasing results in
  117390. a safe minimum */
  117391. for(k=lo_curve;k<=hi_curve;k++){
  117392. int l=0;
  117393. for(j=0;j<EHMER_MAX;j++){
  117394. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117395. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117396. if(lo_bin<0)lo_bin=0;
  117397. if(lo_bin>n)lo_bin=n;
  117398. if(lo_bin<l)l=lo_bin;
  117399. if(hi_bin<0)hi_bin=0;
  117400. if(hi_bin>n)hi_bin=n;
  117401. for(;l<hi_bin && l<n;l++)
  117402. if(brute_buffer[l]>workc[k][m][j])
  117403. brute_buffer[l]=workc[k][m][j];
  117404. }
  117405. for(;l<n;l++)
  117406. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117407. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117408. }
  117409. /* be equally paranoid about being valid up to next half ocatve */
  117410. if(i+1<P_BANDS){
  117411. int l=0;
  117412. k=i+1;
  117413. for(j=0;j<EHMER_MAX;j++){
  117414. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117415. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117416. if(lo_bin<0)lo_bin=0;
  117417. if(lo_bin>n)lo_bin=n;
  117418. if(lo_bin<l)l=lo_bin;
  117419. if(hi_bin<0)hi_bin=0;
  117420. if(hi_bin>n)hi_bin=n;
  117421. for(;l<hi_bin && l<n;l++)
  117422. if(brute_buffer[l]>workc[k][m][j])
  117423. brute_buffer[l]=workc[k][m][j];
  117424. }
  117425. for(;l<n;l++)
  117426. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117427. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117428. }
  117429. for(j=0;j<EHMER_MAX;j++){
  117430. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117431. if(bin<0){
  117432. ret[i][m][j+2]=-999.;
  117433. }else{
  117434. if(bin>=n){
  117435. ret[i][m][j+2]=-999.;
  117436. }else{
  117437. ret[i][m][j+2]=brute_buffer[bin];
  117438. }
  117439. }
  117440. }
  117441. /* add fenceposts */
  117442. for(j=0;j<EHMER_OFFSET;j++)
  117443. if(ret[i][m][j+2]>-200.f)break;
  117444. ret[i][m][0]=j;
  117445. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117446. if(ret[i][m][j+2]>-200.f)
  117447. break;
  117448. ret[i][m][1]=j;
  117449. }
  117450. }
  117451. return(ret);
  117452. }
  117453. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117454. vorbis_info_psy_global *gi,int n,long rate){
  117455. long i,j,lo=-99,hi=1;
  117456. long maxoc;
  117457. memset(p,0,sizeof(*p));
  117458. p->eighth_octave_lines=gi->eighth_octave_lines;
  117459. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117460. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117461. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117462. p->total_octave_lines=maxoc-p->firstoc+1;
  117463. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117464. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117465. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117466. p->vi=vi;
  117467. p->n=n;
  117468. p->rate=rate;
  117469. /* AoTuV HF weighting */
  117470. p->m_val = 1.;
  117471. if(rate < 26000) p->m_val = 0;
  117472. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117473. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117474. /* set up the lookups for a given blocksize and sample rate */
  117475. for(i=0,j=0;i<MAX_ATH-1;i++){
  117476. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117477. float base=ATH[i];
  117478. if(j<endpos){
  117479. float delta=(ATH[i+1]-base)/(endpos-j);
  117480. for(;j<endpos && j<n;j++){
  117481. p->ath[j]=base+100.;
  117482. base+=delta;
  117483. }
  117484. }
  117485. }
  117486. for(i=0;i<n;i++){
  117487. float bark=toBARK(rate/(2*n)*i);
  117488. for(;lo+vi->noisewindowlomin<i &&
  117489. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117490. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117491. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117492. p->bark[i]=((lo-1)<<16)+(hi-1);
  117493. }
  117494. for(i=0;i<n;i++)
  117495. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117496. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117497. vi->tone_centerboost,vi->tone_decay);
  117498. /* set up rolling noise median */
  117499. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117500. for(i=0;i<P_NOISECURVES;i++)
  117501. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117502. for(i=0;i<n;i++){
  117503. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117504. int inthalfoc;
  117505. float del;
  117506. if(halfoc<0)halfoc=0;
  117507. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117508. inthalfoc=(int)halfoc;
  117509. del=halfoc-inthalfoc;
  117510. for(j=0;j<P_NOISECURVES;j++)
  117511. p->noiseoffset[j][i]=
  117512. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117513. p->vi->noiseoff[j][inthalfoc+1]*del;
  117514. }
  117515. #if 0
  117516. {
  117517. static int ls=0;
  117518. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117519. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117520. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117521. }
  117522. #endif
  117523. }
  117524. void _vp_psy_clear(vorbis_look_psy *p){
  117525. int i,j;
  117526. if(p){
  117527. if(p->ath)_ogg_free(p->ath);
  117528. if(p->octave)_ogg_free(p->octave);
  117529. if(p->bark)_ogg_free(p->bark);
  117530. if(p->tonecurves){
  117531. for(i=0;i<P_BANDS;i++){
  117532. for(j=0;j<P_LEVELS;j++){
  117533. _ogg_free(p->tonecurves[i][j]);
  117534. }
  117535. _ogg_free(p->tonecurves[i]);
  117536. }
  117537. _ogg_free(p->tonecurves);
  117538. }
  117539. if(p->noiseoffset){
  117540. for(i=0;i<P_NOISECURVES;i++){
  117541. _ogg_free(p->noiseoffset[i]);
  117542. }
  117543. _ogg_free(p->noiseoffset);
  117544. }
  117545. memset(p,0,sizeof(*p));
  117546. }
  117547. }
  117548. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117549. static void seed_curve(float *seed,
  117550. const float **curves,
  117551. float amp,
  117552. int oc, int n,
  117553. int linesper,float dBoffset){
  117554. int i,post1;
  117555. int seedptr;
  117556. const float *posts,*curve;
  117557. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117558. choice=max(choice,0);
  117559. choice=min(choice,P_LEVELS-1);
  117560. posts=curves[choice];
  117561. curve=posts+2;
  117562. post1=(int)posts[1];
  117563. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117564. for(i=posts[0];i<post1;i++){
  117565. if(seedptr>0){
  117566. float lin=amp+curve[i];
  117567. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117568. }
  117569. seedptr+=linesper;
  117570. if(seedptr>=n)break;
  117571. }
  117572. }
  117573. static void seed_loop(vorbis_look_psy *p,
  117574. const float ***curves,
  117575. const float *f,
  117576. const float *flr,
  117577. float *seed,
  117578. float specmax){
  117579. vorbis_info_psy *vi=p->vi;
  117580. long n=p->n,i;
  117581. float dBoffset=vi->max_curve_dB-specmax;
  117582. /* prime the working vector with peak values */
  117583. for(i=0;i<n;i++){
  117584. float max=f[i];
  117585. long oc=p->octave[i];
  117586. while(i+1<n && p->octave[i+1]==oc){
  117587. i++;
  117588. if(f[i]>max)max=f[i];
  117589. }
  117590. if(max+6.f>flr[i]){
  117591. oc=oc>>p->shiftoc;
  117592. if(oc>=P_BANDS)oc=P_BANDS-1;
  117593. if(oc<0)oc=0;
  117594. seed_curve(seed,
  117595. curves[oc],
  117596. max,
  117597. p->octave[i]-p->firstoc,
  117598. p->total_octave_lines,
  117599. p->eighth_octave_lines,
  117600. dBoffset);
  117601. }
  117602. }
  117603. }
  117604. static void seed_chase(float *seeds, int linesper, long n){
  117605. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117606. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117607. long stack=0;
  117608. long pos=0;
  117609. long i;
  117610. for(i=0;i<n;i++){
  117611. if(stack<2){
  117612. posstack[stack]=i;
  117613. ampstack[stack++]=seeds[i];
  117614. }else{
  117615. while(1){
  117616. if(seeds[i]<ampstack[stack-1]){
  117617. posstack[stack]=i;
  117618. ampstack[stack++]=seeds[i];
  117619. break;
  117620. }else{
  117621. if(i<posstack[stack-1]+linesper){
  117622. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117623. i<posstack[stack-2]+linesper){
  117624. /* we completely overlap, making stack-1 irrelevant. pop it */
  117625. stack--;
  117626. continue;
  117627. }
  117628. }
  117629. posstack[stack]=i;
  117630. ampstack[stack++]=seeds[i];
  117631. break;
  117632. }
  117633. }
  117634. }
  117635. }
  117636. /* the stack now contains only the positions that are relevant. Scan
  117637. 'em straight through */
  117638. for(i=0;i<stack;i++){
  117639. long endpos;
  117640. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117641. endpos=posstack[i+1];
  117642. }else{
  117643. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117644. discarded in short frames */
  117645. }
  117646. if(endpos>n)endpos=n;
  117647. for(;pos<endpos;pos++)
  117648. seeds[pos]=ampstack[i];
  117649. }
  117650. /* there. Linear time. I now remember this was on a problem set I
  117651. had in Grad Skool... I didn't solve it at the time ;-) */
  117652. }
  117653. /* bleaugh, this is more complicated than it needs to be */
  117654. #include<stdio.h>
  117655. static void max_seeds(vorbis_look_psy *p,
  117656. float *seed,
  117657. float *flr){
  117658. long n=p->total_octave_lines;
  117659. int linesper=p->eighth_octave_lines;
  117660. long linpos=0;
  117661. long pos;
  117662. seed_chase(seed,linesper,n); /* for masking */
  117663. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117664. while(linpos+1<p->n){
  117665. float minV=seed[pos];
  117666. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117667. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117668. while(pos+1<=end){
  117669. pos++;
  117670. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117671. minV=seed[pos];
  117672. }
  117673. end=pos+p->firstoc;
  117674. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117675. if(flr[linpos]<minV)flr[linpos]=minV;
  117676. }
  117677. {
  117678. float minV=seed[p->total_octave_lines-1];
  117679. for(;linpos<p->n;linpos++)
  117680. if(flr[linpos]<minV)flr[linpos]=minV;
  117681. }
  117682. }
  117683. static void bark_noise_hybridmp(int n,const long *b,
  117684. const float *f,
  117685. float *noise,
  117686. const float offset,
  117687. const int fixed){
  117688. float *N=(float*) alloca(n*sizeof(*N));
  117689. float *X=(float*) alloca(n*sizeof(*N));
  117690. float *XX=(float*) alloca(n*sizeof(*N));
  117691. float *Y=(float*) alloca(n*sizeof(*N));
  117692. float *XY=(float*) alloca(n*sizeof(*N));
  117693. float tN, tX, tXX, tY, tXY;
  117694. int i;
  117695. int lo, hi;
  117696. float R, A, B, D;
  117697. float w, x, y;
  117698. tN = tX = tXX = tY = tXY = 0.f;
  117699. y = f[0] + offset;
  117700. if (y < 1.f) y = 1.f;
  117701. w = y * y * .5;
  117702. tN += w;
  117703. tX += w;
  117704. tY += w * y;
  117705. N[0] = tN;
  117706. X[0] = tX;
  117707. XX[0] = tXX;
  117708. Y[0] = tY;
  117709. XY[0] = tXY;
  117710. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117711. y = f[i] + offset;
  117712. if (y < 1.f) y = 1.f;
  117713. w = y * y;
  117714. tN += w;
  117715. tX += w * x;
  117716. tXX += w * x * x;
  117717. tY += w * y;
  117718. tXY += w * x * y;
  117719. N[i] = tN;
  117720. X[i] = tX;
  117721. XX[i] = tXX;
  117722. Y[i] = tY;
  117723. XY[i] = tXY;
  117724. }
  117725. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117726. lo = b[i] >> 16;
  117727. if( lo>=0 ) break;
  117728. hi = b[i] & 0xffff;
  117729. tN = N[hi] + N[-lo];
  117730. tX = X[hi] - X[-lo];
  117731. tXX = XX[hi] + XX[-lo];
  117732. tY = Y[hi] + Y[-lo];
  117733. tXY = XY[hi] - XY[-lo];
  117734. A = tY * tXX - tX * tXY;
  117735. B = tN * tXY - tX * tY;
  117736. D = tN * tXX - tX * tX;
  117737. R = (A + x * B) / D;
  117738. if (R < 0.f)
  117739. R = 0.f;
  117740. noise[i] = R - offset;
  117741. }
  117742. for ( ;; i++, x += 1.f) {
  117743. lo = b[i] >> 16;
  117744. hi = b[i] & 0xffff;
  117745. if(hi>=n)break;
  117746. tN = N[hi] - N[lo];
  117747. tX = X[hi] - X[lo];
  117748. tXX = XX[hi] - XX[lo];
  117749. tY = Y[hi] - Y[lo];
  117750. tXY = XY[hi] - XY[lo];
  117751. A = tY * tXX - tX * tXY;
  117752. B = tN * tXY - tX * tY;
  117753. D = tN * tXX - tX * tX;
  117754. R = (A + x * B) / D;
  117755. if (R < 0.f) R = 0.f;
  117756. noise[i] = R - offset;
  117757. }
  117758. for ( ; i < n; i++, x += 1.f) {
  117759. R = (A + x * B) / D;
  117760. if (R < 0.f) R = 0.f;
  117761. noise[i] = R - offset;
  117762. }
  117763. if (fixed <= 0) return;
  117764. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117765. hi = i + fixed / 2;
  117766. lo = hi - fixed;
  117767. if(lo>=0)break;
  117768. tN = N[hi] + N[-lo];
  117769. tX = X[hi] - X[-lo];
  117770. tXX = XX[hi] + XX[-lo];
  117771. tY = Y[hi] + Y[-lo];
  117772. tXY = XY[hi] - XY[-lo];
  117773. A = tY * tXX - tX * tXY;
  117774. B = tN * tXY - tX * tY;
  117775. D = tN * tXX - tX * tX;
  117776. R = (A + x * B) / D;
  117777. if (R - offset < noise[i]) noise[i] = R - offset;
  117778. }
  117779. for ( ;; i++, x += 1.f) {
  117780. hi = i + fixed / 2;
  117781. lo = hi - fixed;
  117782. if(hi>=n)break;
  117783. tN = N[hi] - N[lo];
  117784. tX = X[hi] - X[lo];
  117785. tXX = XX[hi] - XX[lo];
  117786. tY = Y[hi] - Y[lo];
  117787. tXY = XY[hi] - XY[lo];
  117788. A = tY * tXX - tX * tXY;
  117789. B = tN * tXY - tX * tY;
  117790. D = tN * tXX - tX * tX;
  117791. R = (A + x * B) / D;
  117792. if (R - offset < noise[i]) noise[i] = R - offset;
  117793. }
  117794. for ( ; i < n; i++, x += 1.f) {
  117795. R = (A + x * B) / D;
  117796. if (R - offset < noise[i]) noise[i] = R - offset;
  117797. }
  117798. }
  117799. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117800. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117801. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117802. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117803. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117804. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117805. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117806. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117807. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117808. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117809. 973377.F, 913981.F, 858210.F, 805842.F,
  117810. 756669.F, 710497.F, 667142.F, 626433.F,
  117811. 588208.F, 552316.F, 518613.F, 486967.F,
  117812. 457252.F, 429351.F, 403152.F, 378551.F,
  117813. 355452.F, 333762.F, 313396.F, 294273.F,
  117814. 276316.F, 259455.F, 243623.F, 228757.F,
  117815. 214798.F, 201691.F, 189384.F, 177828.F,
  117816. 166977.F, 156788.F, 147221.F, 138237.F,
  117817. 129802.F, 121881.F, 114444.F, 107461.F,
  117818. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117819. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117820. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117821. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117822. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117823. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117824. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117825. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117826. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117827. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117828. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117829. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117830. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117831. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117832. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117833. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117834. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117835. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117836. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117837. 842.910F, 791.475F, 743.179F, 697.830F,
  117838. 655.249F, 615.265F, 577.722F, 542.469F,
  117839. 509.367F, 478.286F, 449.101F, 421.696F,
  117840. 395.964F, 371.803F, 349.115F, 327.812F,
  117841. 307.809F, 289.026F, 271.390F, 254.830F,
  117842. 239.280F, 224.679F, 210.969F, 198.096F,
  117843. 186.008F, 174.658F, 164.000F, 153.993F,
  117844. 144.596F, 135.773F, 127.488F, 119.708F,
  117845. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117846. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117847. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117848. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117849. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117850. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117851. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117852. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117853. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117854. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117855. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117856. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117857. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117858. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117859. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117860. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117861. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117862. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117863. 1.20790F, 1.13419F, 1.06499F, 1.F
  117864. };
  117865. void _vp_remove_floor(vorbis_look_psy *p,
  117866. float *mdct,
  117867. int *codedflr,
  117868. float *residue,
  117869. int sliding_lowpass){
  117870. int i,n=p->n;
  117871. if(sliding_lowpass>n)sliding_lowpass=n;
  117872. for(i=0;i<sliding_lowpass;i++){
  117873. residue[i]=
  117874. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117875. }
  117876. for(;i<n;i++)
  117877. residue[i]=0.;
  117878. }
  117879. void _vp_noisemask(vorbis_look_psy *p,
  117880. float *logmdct,
  117881. float *logmask){
  117882. int i,n=p->n;
  117883. float *work=(float*) alloca(n*sizeof(*work));
  117884. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117885. 140.,-1);
  117886. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117887. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117888. p->vi->noisewindowfixed);
  117889. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117890. #if 0
  117891. {
  117892. static int seq=0;
  117893. float work2[n];
  117894. for(i=0;i<n;i++){
  117895. work2[i]=logmask[i]+work[i];
  117896. }
  117897. if(seq&1)
  117898. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117899. else
  117900. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117901. if(seq&1)
  117902. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117903. else
  117904. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117905. seq++;
  117906. }
  117907. #endif
  117908. for(i=0;i<n;i++){
  117909. int dB=logmask[i]+.5;
  117910. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117911. if(dB<0)dB=0;
  117912. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117913. }
  117914. }
  117915. void _vp_tonemask(vorbis_look_psy *p,
  117916. float *logfft,
  117917. float *logmask,
  117918. float global_specmax,
  117919. float local_specmax){
  117920. int i,n=p->n;
  117921. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117922. float att=local_specmax+p->vi->ath_adjatt;
  117923. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117924. /* set the ATH (floating below localmax, not global max by a
  117925. specified att) */
  117926. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117927. for(i=0;i<n;i++)
  117928. logmask[i]=p->ath[i]+att;
  117929. /* tone masking */
  117930. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117931. max_seeds(p,seed,logmask);
  117932. }
  117933. void _vp_offset_and_mix(vorbis_look_psy *p,
  117934. float *noise,
  117935. float *tone,
  117936. int offset_select,
  117937. float *logmask,
  117938. float *mdct,
  117939. float *logmdct){
  117940. int i,n=p->n;
  117941. float de, coeffi, cx;/* AoTuV */
  117942. float toneatt=p->vi->tone_masteratt[offset_select];
  117943. cx = p->m_val;
  117944. for(i=0;i<n;i++){
  117945. float val= noise[i]+p->noiseoffset[offset_select][i];
  117946. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117947. logmask[i]=max(val,tone[i]+toneatt);
  117948. /* AoTuV */
  117949. /** @ M1 **
  117950. The following codes improve a noise problem.
  117951. A fundamental idea uses the value of masking and carries out
  117952. the relative compensation of the MDCT.
  117953. However, this code is not perfect and all noise problems cannot be solved.
  117954. by Aoyumi @ 2004/04/18
  117955. */
  117956. if(offset_select == 1) {
  117957. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117958. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117959. if(val > coeffi){
  117960. /* mdct value is > -17.2 dB below floor */
  117961. de = 1.0-((val-coeffi)*0.005*cx);
  117962. /* pro-rated attenuation:
  117963. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117964. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117965. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117966. etc... */
  117967. if(de < 0) de = 0.0001;
  117968. }else
  117969. /* mdct value is <= -17.2 dB below floor */
  117970. de = 1.0-((val-coeffi)*0.0003*cx);
  117971. /* pro-rated attenuation:
  117972. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117973. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117974. etc... */
  117975. mdct[i] *= de;
  117976. }
  117977. }
  117978. }
  117979. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117980. vorbis_info *vi=vd->vi;
  117981. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117982. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117983. int n=ci->blocksizes[vd->W]/2;
  117984. float secs=(float)n/vi->rate;
  117985. amp+=secs*gi->ampmax_att_per_sec;
  117986. if(amp<-9999)amp=-9999;
  117987. return(amp);
  117988. }
  117989. static void couple_lossless(float A, float B,
  117990. float *qA, float *qB){
  117991. int test1=fabs(*qA)>fabs(*qB);
  117992. test1-= fabs(*qA)<fabs(*qB);
  117993. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117994. if(test1==1){
  117995. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117996. }else{
  117997. float temp=*qB;
  117998. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117999. *qA=temp;
  118000. }
  118001. if(*qB>fabs(*qA)*1.9999f){
  118002. *qB= -fabs(*qA)*2.f;
  118003. *qA= -*qA;
  118004. }
  118005. }
  118006. static float hypot_lookup[32]={
  118007. -0.009935, -0.011245, -0.012726, -0.014397,
  118008. -0.016282, -0.018407, -0.020800, -0.023494,
  118009. -0.026522, -0.029923, -0.033737, -0.038010,
  118010. -0.042787, -0.048121, -0.054064, -0.060671,
  118011. -0.068000, -0.076109, -0.085054, -0.094892,
  118012. -0.105675, -0.117451, -0.130260, -0.144134,
  118013. -0.159093, -0.175146, -0.192286, -0.210490,
  118014. -0.229718, -0.249913, -0.271001, -0.292893};
  118015. static void precomputed_couple_point(float premag,
  118016. int floorA,int floorB,
  118017. float *mag, float *ang){
  118018. int test=(floorA>floorB)-1;
  118019. int offset=31-abs(floorA-floorB);
  118020. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  118021. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  118022. *mag=premag*floormag;
  118023. *ang=0.f;
  118024. }
  118025. /* just like below, this is currently set up to only do
  118026. single-step-depth coupling. Otherwise, we'd have to do more
  118027. copying (which will be inevitable later) */
  118028. /* doing the real circular magnitude calculation is audibly superior
  118029. to (A+B)/sqrt(2) */
  118030. static float dipole_hypot(float a, float b){
  118031. if(a>0.){
  118032. if(b>0.)return sqrt(a*a+b*b);
  118033. if(a>-b)return sqrt(a*a-b*b);
  118034. return -sqrt(b*b-a*a);
  118035. }
  118036. if(b<0.)return -sqrt(a*a+b*b);
  118037. if(-a>b)return -sqrt(a*a-b*b);
  118038. return sqrt(b*b-a*a);
  118039. }
  118040. static float round_hypot(float a, float b){
  118041. if(a>0.){
  118042. if(b>0.)return sqrt(a*a+b*b);
  118043. if(a>-b)return sqrt(a*a+b*b);
  118044. return -sqrt(b*b+a*a);
  118045. }
  118046. if(b<0.)return -sqrt(a*a+b*b);
  118047. if(-a>b)return -sqrt(a*a+b*b);
  118048. return sqrt(b*b+a*a);
  118049. }
  118050. /* revert to round hypot for now */
  118051. float **_vp_quantize_couple_memo(vorbis_block *vb,
  118052. vorbis_info_psy_global *g,
  118053. vorbis_look_psy *p,
  118054. vorbis_info_mapping0 *vi,
  118055. float **mdct){
  118056. int i,j,n=p->n;
  118057. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118058. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118059. for(i=0;i<vi->coupling_steps;i++){
  118060. float *mdctM=mdct[vi->coupling_mag[i]];
  118061. float *mdctA=mdct[vi->coupling_ang[i]];
  118062. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118063. for(j=0;j<limit;j++)
  118064. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  118065. for(;j<n;j++)
  118066. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  118067. }
  118068. return(ret);
  118069. }
  118070. /* this is for per-channel noise normalization */
  118071. static int JUCE_CDECL apsort(const void *a, const void *b){
  118072. float f1=fabs(**(float**)a);
  118073. float f2=fabs(**(float**)b);
  118074. return (f1<f2)-(f1>f2);
  118075. }
  118076. int **_vp_quantize_couple_sort(vorbis_block *vb,
  118077. vorbis_look_psy *p,
  118078. vorbis_info_mapping0 *vi,
  118079. float **mags){
  118080. if(p->vi->normal_point_p){
  118081. int i,j,k,n=p->n;
  118082. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118083. int partition=p->vi->normal_partition;
  118084. float **work=(float**) alloca(sizeof(*work)*partition);
  118085. for(i=0;i<vi->coupling_steps;i++){
  118086. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118087. for(j=0;j<n;j+=partition){
  118088. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  118089. qsort(work,partition,sizeof(*work),apsort);
  118090. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  118091. }
  118092. }
  118093. return(ret);
  118094. }
  118095. return(NULL);
  118096. }
  118097. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  118098. float *magnitudes,int *sortedindex){
  118099. int i,j,n=p->n;
  118100. vorbis_info_psy *vi=p->vi;
  118101. int partition=vi->normal_partition;
  118102. float **work=(float**) alloca(sizeof(*work)*partition);
  118103. int start=vi->normal_start;
  118104. for(j=start;j<n;j+=partition){
  118105. if(j+partition>n)partition=n-j;
  118106. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  118107. qsort(work,partition,sizeof(*work),apsort);
  118108. for(i=0;i<partition;i++){
  118109. sortedindex[i+j-start]=work[i]-magnitudes;
  118110. }
  118111. }
  118112. }
  118113. void _vp_noise_normalize(vorbis_look_psy *p,
  118114. float *in,float *out,int *sortedindex){
  118115. int flag=0,i,j=0,n=p->n;
  118116. vorbis_info_psy *vi=p->vi;
  118117. int partition=vi->normal_partition;
  118118. int start=vi->normal_start;
  118119. if(start>n)start=n;
  118120. if(vi->normal_channel_p){
  118121. for(;j<start;j++)
  118122. out[j]=rint(in[j]);
  118123. for(;j+partition<=n;j+=partition){
  118124. float acc=0.;
  118125. int k;
  118126. for(i=j;i<j+partition;i++)
  118127. acc+=in[i]*in[i];
  118128. for(i=0;i<partition;i++){
  118129. k=sortedindex[i+j-start];
  118130. if(in[k]*in[k]>=.25f){
  118131. out[k]=rint(in[k]);
  118132. acc-=in[k]*in[k];
  118133. flag=1;
  118134. }else{
  118135. if(acc<vi->normal_thresh)break;
  118136. out[k]=unitnorm(in[k]);
  118137. acc-=1.;
  118138. }
  118139. }
  118140. for(;i<partition;i++){
  118141. k=sortedindex[i+j-start];
  118142. out[k]=0.;
  118143. }
  118144. }
  118145. }
  118146. for(;j<n;j++)
  118147. out[j]=rint(in[j]);
  118148. }
  118149. void _vp_couple(int blobno,
  118150. vorbis_info_psy_global *g,
  118151. vorbis_look_psy *p,
  118152. vorbis_info_mapping0 *vi,
  118153. float **res,
  118154. float **mag_memo,
  118155. int **mag_sort,
  118156. int **ifloor,
  118157. int *nonzero,
  118158. int sliding_lowpass){
  118159. int i,j,k,n=p->n;
  118160. /* perform any requested channel coupling */
  118161. /* point stereo can only be used in a first stage (in this encoder)
  118162. because of the dependency on floor lookups */
  118163. for(i=0;i<vi->coupling_steps;i++){
  118164. /* once we're doing multistage coupling in which a channel goes
  118165. through more than one coupling step, the floor vector
  118166. magnitudes will also have to be recalculated an propogated
  118167. along with PCM. Right now, we're not (that will wait until 5.1
  118168. most likely), so the code isn't here yet. The memory management
  118169. here is all assuming single depth couplings anyway. */
  118170. /* make sure coupling a zero and a nonzero channel results in two
  118171. nonzero channels. */
  118172. if(nonzero[vi->coupling_mag[i]] ||
  118173. nonzero[vi->coupling_ang[i]]){
  118174. float *rM=res[vi->coupling_mag[i]];
  118175. float *rA=res[vi->coupling_ang[i]];
  118176. float *qM=rM+n;
  118177. float *qA=rA+n;
  118178. int *floorM=ifloor[vi->coupling_mag[i]];
  118179. int *floorA=ifloor[vi->coupling_ang[i]];
  118180. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  118181. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  118182. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  118183. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  118184. int pointlimit=limit;
  118185. nonzero[vi->coupling_mag[i]]=1;
  118186. nonzero[vi->coupling_ang[i]]=1;
  118187. /* The threshold of a stereo is changed with the size of n */
  118188. if(n > 1000)
  118189. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  118190. for(j=0;j<p->n;j+=partition){
  118191. float acc=0.f;
  118192. for(k=0;k<partition;k++){
  118193. int l=k+j;
  118194. if(l<sliding_lowpass){
  118195. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  118196. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  118197. precomputed_couple_point(mag_memo[i][l],
  118198. floorM[l],floorA[l],
  118199. qM+l,qA+l);
  118200. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118201. }else{
  118202. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118203. }
  118204. }else{
  118205. qM[l]=0.;
  118206. qA[l]=0.;
  118207. }
  118208. }
  118209. if(p->vi->normal_point_p){
  118210. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118211. int l=mag_sort[i][j+k];
  118212. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118213. qM[l]=unitnorm(qM[l]);
  118214. acc-=1.f;
  118215. }
  118216. }
  118217. }
  118218. }
  118219. }
  118220. }
  118221. }
  118222. /* AoTuV */
  118223. /** @ M2 **
  118224. The boost problem by the combination of noise normalization and point stereo is eased.
  118225. However, this is a temporary patch.
  118226. by Aoyumi @ 2004/04/18
  118227. */
  118228. void hf_reduction(vorbis_info_psy_global *g,
  118229. vorbis_look_psy *p,
  118230. vorbis_info_mapping0 *vi,
  118231. float **mdct){
  118232. int i,j,n=p->n, de=0.3*p->m_val;
  118233. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118234. for(i=0; i<vi->coupling_steps; i++){
  118235. /* for(j=start; j<limit; j++){} // ???*/
  118236. for(j=limit; j<n; j++)
  118237. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118238. }
  118239. }
  118240. #endif
  118241. /*** End of inlined file: psy.c ***/
  118242. /*** Start of inlined file: registry.c ***/
  118243. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118244. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118245. // tasks..
  118246. #if JUCE_MSVC
  118247. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118248. #endif
  118249. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118250. #if JUCE_USE_OGGVORBIS
  118251. /* seems like major overkill now; the backend numbers will grow into
  118252. the infrastructure soon enough */
  118253. extern vorbis_func_floor floor0_exportbundle;
  118254. extern vorbis_func_floor floor1_exportbundle;
  118255. extern vorbis_func_residue residue0_exportbundle;
  118256. extern vorbis_func_residue residue1_exportbundle;
  118257. extern vorbis_func_residue residue2_exportbundle;
  118258. extern vorbis_func_mapping mapping0_exportbundle;
  118259. vorbis_func_floor *_floor_P[]={
  118260. &floor0_exportbundle,
  118261. &floor1_exportbundle,
  118262. };
  118263. vorbis_func_residue *_residue_P[]={
  118264. &residue0_exportbundle,
  118265. &residue1_exportbundle,
  118266. &residue2_exportbundle,
  118267. };
  118268. vorbis_func_mapping *_mapping_P[]={
  118269. &mapping0_exportbundle,
  118270. };
  118271. #endif
  118272. /*** End of inlined file: registry.c ***/
  118273. /*** Start of inlined file: res0.c ***/
  118274. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118275. encode/decode loops are coded for clarity and performance is not
  118276. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118277. it's slow. */
  118278. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118279. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118280. // tasks..
  118281. #if JUCE_MSVC
  118282. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118283. #endif
  118284. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118285. #if JUCE_USE_OGGVORBIS
  118286. #include <stdlib.h>
  118287. #include <string.h>
  118288. #include <math.h>
  118289. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118290. #include <stdio.h>
  118291. #endif
  118292. typedef struct {
  118293. vorbis_info_residue0 *info;
  118294. int parts;
  118295. int stages;
  118296. codebook *fullbooks;
  118297. codebook *phrasebook;
  118298. codebook ***partbooks;
  118299. int partvals;
  118300. int **decodemap;
  118301. long postbits;
  118302. long phrasebits;
  118303. long frames;
  118304. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118305. int train_seq;
  118306. long *training_data[8][64];
  118307. float training_max[8][64];
  118308. float training_min[8][64];
  118309. float tmin;
  118310. float tmax;
  118311. #endif
  118312. } vorbis_look_residue0;
  118313. void res0_free_info(vorbis_info_residue *i){
  118314. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118315. if(info){
  118316. memset(info,0,sizeof(*info));
  118317. _ogg_free(info);
  118318. }
  118319. }
  118320. void res0_free_look(vorbis_look_residue *i){
  118321. int j;
  118322. if(i){
  118323. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118324. #ifdef TRAIN_RES
  118325. {
  118326. int j,k,l;
  118327. for(j=0;j<look->parts;j++){
  118328. /*fprintf(stderr,"partition %d: ",j);*/
  118329. for(k=0;k<8;k++)
  118330. if(look->training_data[k][j]){
  118331. char buffer[80];
  118332. FILE *of;
  118333. codebook *statebook=look->partbooks[j][k];
  118334. /* long and short into the same bucket by current convention */
  118335. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118336. of=fopen(buffer,"a");
  118337. for(l=0;l<statebook->entries;l++)
  118338. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118339. fclose(of);
  118340. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118341. look->training_min[k][j],look->training_max[k][j]);*/
  118342. _ogg_free(look->training_data[k][j]);
  118343. look->training_data[k][j]=NULL;
  118344. }
  118345. /*fprintf(stderr,"\n");*/
  118346. }
  118347. }
  118348. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118349. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118350. (float)look->phrasebits/look->frames,
  118351. (float)look->postbits/look->frames,
  118352. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118353. #endif
  118354. /*vorbis_info_residue0 *info=look->info;
  118355. fprintf(stderr,
  118356. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118357. "(%g/frame) \n",look->frames,look->phrasebits,
  118358. look->resbitsflat,
  118359. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118360. for(j=0;j<look->parts;j++){
  118361. long acc=0;
  118362. fprintf(stderr,"\t[%d] == ",j);
  118363. for(k=0;k<look->stages;k++)
  118364. if((info->secondstages[j]>>k)&1){
  118365. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118366. acc+=look->resbits[j][k];
  118367. }
  118368. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118369. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118370. }
  118371. fprintf(stderr,"\n");*/
  118372. for(j=0;j<look->parts;j++)
  118373. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118374. _ogg_free(look->partbooks);
  118375. for(j=0;j<look->partvals;j++)
  118376. _ogg_free(look->decodemap[j]);
  118377. _ogg_free(look->decodemap);
  118378. memset(look,0,sizeof(*look));
  118379. _ogg_free(look);
  118380. }
  118381. }
  118382. static int icount(unsigned int v){
  118383. int ret=0;
  118384. while(v){
  118385. ret+=v&1;
  118386. v>>=1;
  118387. }
  118388. return(ret);
  118389. }
  118390. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118391. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118392. int j,acc=0;
  118393. oggpack_write(opb,info->begin,24);
  118394. oggpack_write(opb,info->end,24);
  118395. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118396. code with a partitioned book */
  118397. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118398. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118399. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118400. bitmask of one indicates this partition class has bits to write
  118401. this pass */
  118402. for(j=0;j<info->partitions;j++){
  118403. if(ilog(info->secondstages[j])>3){
  118404. /* yes, this is a minor hack due to not thinking ahead */
  118405. oggpack_write(opb,info->secondstages[j],3);
  118406. oggpack_write(opb,1,1);
  118407. oggpack_write(opb,info->secondstages[j]>>3,5);
  118408. }else
  118409. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118410. acc+=icount(info->secondstages[j]);
  118411. }
  118412. for(j=0;j<acc;j++)
  118413. oggpack_write(opb,info->booklist[j],8);
  118414. }
  118415. /* vorbis_info is for range checking */
  118416. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118417. int j,acc=0;
  118418. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118419. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118420. info->begin=oggpack_read(opb,24);
  118421. info->end=oggpack_read(opb,24);
  118422. info->grouping=oggpack_read(opb,24)+1;
  118423. info->partitions=oggpack_read(opb,6)+1;
  118424. info->groupbook=oggpack_read(opb,8);
  118425. for(j=0;j<info->partitions;j++){
  118426. int cascade=oggpack_read(opb,3);
  118427. if(oggpack_read(opb,1))
  118428. cascade|=(oggpack_read(opb,5)<<3);
  118429. info->secondstages[j]=cascade;
  118430. acc+=icount(cascade);
  118431. }
  118432. for(j=0;j<acc;j++)
  118433. info->booklist[j]=oggpack_read(opb,8);
  118434. if(info->groupbook>=ci->books)goto errout;
  118435. for(j=0;j<acc;j++)
  118436. if(info->booklist[j]>=ci->books)goto errout;
  118437. return(info);
  118438. errout:
  118439. res0_free_info(info);
  118440. return(NULL);
  118441. }
  118442. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118443. vorbis_info_residue *vr){
  118444. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118445. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118446. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118447. int j,k,acc=0;
  118448. int dim;
  118449. int maxstage=0;
  118450. look->info=info;
  118451. look->parts=info->partitions;
  118452. look->fullbooks=ci->fullbooks;
  118453. look->phrasebook=ci->fullbooks+info->groupbook;
  118454. dim=look->phrasebook->dim;
  118455. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118456. for(j=0;j<look->parts;j++){
  118457. int stages=ilog(info->secondstages[j]);
  118458. if(stages){
  118459. if(stages>maxstage)maxstage=stages;
  118460. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118461. for(k=0;k<stages;k++)
  118462. if(info->secondstages[j]&(1<<k)){
  118463. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118464. #ifdef TRAIN_RES
  118465. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118466. sizeof(***look->training_data));
  118467. #endif
  118468. }
  118469. }
  118470. }
  118471. look->partvals=rint(pow((float)look->parts,(float)dim));
  118472. look->stages=maxstage;
  118473. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118474. for(j=0;j<look->partvals;j++){
  118475. long val=j;
  118476. long mult=look->partvals/look->parts;
  118477. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118478. for(k=0;k<dim;k++){
  118479. long deco=val/mult;
  118480. val-=deco*mult;
  118481. mult/=look->parts;
  118482. look->decodemap[j][k]=deco;
  118483. }
  118484. }
  118485. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118486. {
  118487. static int train_seq=0;
  118488. look->train_seq=train_seq++;
  118489. }
  118490. #endif
  118491. return(look);
  118492. }
  118493. /* break an abstraction and copy some code for performance purposes */
  118494. static int local_book_besterror(codebook *book,float *a){
  118495. int dim=book->dim,i,k,o;
  118496. int best=0;
  118497. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118498. /* find the quant val of each scalar */
  118499. for(k=0,o=dim;k<dim;++k){
  118500. float val=a[--o];
  118501. i=tt->threshvals>>1;
  118502. if(val<tt->quantthresh[i]){
  118503. if(val<tt->quantthresh[i-1]){
  118504. for(--i;i>0;--i)
  118505. if(val>=tt->quantthresh[i-1])
  118506. break;
  118507. }
  118508. }else{
  118509. for(++i;i<tt->threshvals-1;++i)
  118510. if(val<tt->quantthresh[i])break;
  118511. }
  118512. best=(best*tt->quantvals)+tt->quantmap[i];
  118513. }
  118514. /* regular lattices are easy :-) */
  118515. if(book->c->lengthlist[best]<=0){
  118516. const static_codebook *c=book->c;
  118517. int i,j;
  118518. float bestf=0.f;
  118519. float *e=book->valuelist;
  118520. best=-1;
  118521. for(i=0;i<book->entries;i++){
  118522. if(c->lengthlist[i]>0){
  118523. float thisx=0.f;
  118524. for(j=0;j<dim;j++){
  118525. float val=(e[j]-a[j]);
  118526. thisx+=val*val;
  118527. }
  118528. if(best==-1 || thisx<bestf){
  118529. bestf=thisx;
  118530. best=i;
  118531. }
  118532. }
  118533. e+=dim;
  118534. }
  118535. }
  118536. {
  118537. float *ptr=book->valuelist+best*dim;
  118538. for(i=0;i<dim;i++)
  118539. *a++ -= *ptr++;
  118540. }
  118541. return(best);
  118542. }
  118543. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118544. codebook *book,long *acc){
  118545. int i,bits=0;
  118546. int dim=book->dim;
  118547. int step=n/dim;
  118548. for(i=0;i<step;i++){
  118549. int entry=local_book_besterror(book,vec+i*dim);
  118550. #ifdef TRAIN_RES
  118551. acc[entry]++;
  118552. #endif
  118553. bits+=vorbis_book_encode(book,entry,opb);
  118554. }
  118555. return(bits);
  118556. }
  118557. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118558. float **in,int ch){
  118559. long i,j,k;
  118560. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118561. vorbis_info_residue0 *info=look->info;
  118562. /* move all this setup out later */
  118563. int samples_per_partition=info->grouping;
  118564. int possible_partitions=info->partitions;
  118565. int n=info->end-info->begin;
  118566. int partvals=n/samples_per_partition;
  118567. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118568. float scale=100./samples_per_partition;
  118569. /* we find the partition type for each partition of each
  118570. channel. We'll go back and do the interleaved encoding in a
  118571. bit. For now, clarity */
  118572. for(i=0;i<ch;i++){
  118573. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118574. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118575. }
  118576. for(i=0;i<partvals;i++){
  118577. int offset=i*samples_per_partition+info->begin;
  118578. for(j=0;j<ch;j++){
  118579. float max=0.;
  118580. float ent=0.;
  118581. for(k=0;k<samples_per_partition;k++){
  118582. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118583. ent+=fabs(rint(in[j][offset+k]));
  118584. }
  118585. ent*=scale;
  118586. for(k=0;k<possible_partitions-1;k++)
  118587. if(max<=info->classmetric1[k] &&
  118588. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118589. break;
  118590. partword[j][i]=k;
  118591. }
  118592. }
  118593. #ifdef TRAIN_RESAUX
  118594. {
  118595. FILE *of;
  118596. char buffer[80];
  118597. for(i=0;i<ch;i++){
  118598. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118599. of=fopen(buffer,"a");
  118600. for(j=0;j<partvals;j++)
  118601. fprintf(of,"%ld, ",partword[i][j]);
  118602. fprintf(of,"\n");
  118603. fclose(of);
  118604. }
  118605. }
  118606. #endif
  118607. look->frames++;
  118608. return(partword);
  118609. }
  118610. /* designed for stereo or other modes where the partition size is an
  118611. integer multiple of the number of channels encoded in the current
  118612. submap */
  118613. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118614. int ch){
  118615. long i,j,k,l;
  118616. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118617. vorbis_info_residue0 *info=look->info;
  118618. /* move all this setup out later */
  118619. int samples_per_partition=info->grouping;
  118620. int possible_partitions=info->partitions;
  118621. int n=info->end-info->begin;
  118622. int partvals=n/samples_per_partition;
  118623. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118624. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118625. FILE *of;
  118626. char buffer[80];
  118627. #endif
  118628. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118629. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118630. for(i=0,l=info->begin/ch;i<partvals;i++){
  118631. float magmax=0.f;
  118632. float angmax=0.f;
  118633. for(j=0;j<samples_per_partition;j+=ch){
  118634. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118635. for(k=1;k<ch;k++)
  118636. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118637. l++;
  118638. }
  118639. for(j=0;j<possible_partitions-1;j++)
  118640. if(magmax<=info->classmetric1[j] &&
  118641. angmax<=info->classmetric2[j])
  118642. break;
  118643. partword[0][i]=j;
  118644. }
  118645. #ifdef TRAIN_RESAUX
  118646. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118647. of=fopen(buffer,"a");
  118648. for(i=0;i<partvals;i++)
  118649. fprintf(of,"%ld, ",partword[0][i]);
  118650. fprintf(of,"\n");
  118651. fclose(of);
  118652. #endif
  118653. look->frames++;
  118654. return(partword);
  118655. }
  118656. static int _01forward(oggpack_buffer *opb,
  118657. vorbis_block *vb,vorbis_look_residue *vl,
  118658. float **in,int ch,
  118659. long **partword,
  118660. int (*encode)(oggpack_buffer *,float *,int,
  118661. codebook *,long *)){
  118662. long i,j,k,s;
  118663. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118664. vorbis_info_residue0 *info=look->info;
  118665. /* move all this setup out later */
  118666. int samples_per_partition=info->grouping;
  118667. int possible_partitions=info->partitions;
  118668. int partitions_per_word=look->phrasebook->dim;
  118669. int n=info->end-info->begin;
  118670. int partvals=n/samples_per_partition;
  118671. long resbits[128];
  118672. long resvals[128];
  118673. #ifdef TRAIN_RES
  118674. for(i=0;i<ch;i++)
  118675. for(j=info->begin;j<info->end;j++){
  118676. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118677. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118678. }
  118679. #endif
  118680. memset(resbits,0,sizeof(resbits));
  118681. memset(resvals,0,sizeof(resvals));
  118682. /* we code the partition words for each channel, then the residual
  118683. words for a partition per channel until we've written all the
  118684. residual words for that partition word. Then write the next
  118685. partition channel words... */
  118686. for(s=0;s<look->stages;s++){
  118687. for(i=0;i<partvals;){
  118688. /* first we encode a partition codeword for each channel */
  118689. if(s==0){
  118690. for(j=0;j<ch;j++){
  118691. long val=partword[j][i];
  118692. for(k=1;k<partitions_per_word;k++){
  118693. val*=possible_partitions;
  118694. if(i+k<partvals)
  118695. val+=partword[j][i+k];
  118696. }
  118697. /* training hack */
  118698. if(val<look->phrasebook->entries)
  118699. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118700. #if 0 /*def TRAIN_RES*/
  118701. else
  118702. fprintf(stderr,"!");
  118703. #endif
  118704. }
  118705. }
  118706. /* now we encode interleaved residual values for the partitions */
  118707. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118708. long offset=i*samples_per_partition+info->begin;
  118709. for(j=0;j<ch;j++){
  118710. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118711. if(info->secondstages[partword[j][i]]&(1<<s)){
  118712. codebook *statebook=look->partbooks[partword[j][i]][s];
  118713. if(statebook){
  118714. int ret;
  118715. long *accumulator=NULL;
  118716. #ifdef TRAIN_RES
  118717. accumulator=look->training_data[s][partword[j][i]];
  118718. {
  118719. int l;
  118720. float *samples=in[j]+offset;
  118721. for(l=0;l<samples_per_partition;l++){
  118722. if(samples[l]<look->training_min[s][partword[j][i]])
  118723. look->training_min[s][partword[j][i]]=samples[l];
  118724. if(samples[l]>look->training_max[s][partword[j][i]])
  118725. look->training_max[s][partword[j][i]]=samples[l];
  118726. }
  118727. }
  118728. #endif
  118729. ret=encode(opb,in[j]+offset,samples_per_partition,
  118730. statebook,accumulator);
  118731. look->postbits+=ret;
  118732. resbits[partword[j][i]]+=ret;
  118733. }
  118734. }
  118735. }
  118736. }
  118737. }
  118738. }
  118739. /*{
  118740. long total=0;
  118741. long totalbits=0;
  118742. fprintf(stderr,"%d :: ",vb->mode);
  118743. for(k=0;k<possible_partitions;k++){
  118744. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118745. total+=resvals[k];
  118746. totalbits+=resbits[k];
  118747. }
  118748. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118749. }*/
  118750. return(0);
  118751. }
  118752. /* a truncated packet here just means 'stop working'; it's not an error */
  118753. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118754. float **in,int ch,
  118755. long (*decodepart)(codebook *, float *,
  118756. oggpack_buffer *,int)){
  118757. long i,j,k,l,s;
  118758. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118759. vorbis_info_residue0 *info=look->info;
  118760. /* move all this setup out later */
  118761. int samples_per_partition=info->grouping;
  118762. int partitions_per_word=look->phrasebook->dim;
  118763. int n=info->end-info->begin;
  118764. int partvals=n/samples_per_partition;
  118765. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118766. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118767. for(j=0;j<ch;j++)
  118768. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118769. for(s=0;s<look->stages;s++){
  118770. /* each loop decodes on partition codeword containing
  118771. partitions_pre_word partitions */
  118772. for(i=0,l=0;i<partvals;l++){
  118773. if(s==0){
  118774. /* fetch the partition word for each channel */
  118775. for(j=0;j<ch;j++){
  118776. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118777. if(temp==-1)goto eopbreak;
  118778. partword[j][l]=look->decodemap[temp];
  118779. if(partword[j][l]==NULL)goto errout;
  118780. }
  118781. }
  118782. /* now we decode residual values for the partitions */
  118783. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118784. for(j=0;j<ch;j++){
  118785. long offset=info->begin+i*samples_per_partition;
  118786. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118787. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118788. if(stagebook){
  118789. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118790. samples_per_partition)==-1)goto eopbreak;
  118791. }
  118792. }
  118793. }
  118794. }
  118795. }
  118796. errout:
  118797. eopbreak:
  118798. return(0);
  118799. }
  118800. #if 0
  118801. /* residue 0 and 1 are just slight variants of one another. 0 is
  118802. interleaved, 1 is not */
  118803. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118804. float **in,int *nonzero,int ch){
  118805. /* we encode only the nonzero parts of a bundle */
  118806. int i,used=0;
  118807. for(i=0;i<ch;i++)
  118808. if(nonzero[i])
  118809. in[used++]=in[i];
  118810. if(used)
  118811. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118812. return(_01class(vb,vl,in,used));
  118813. else
  118814. return(0);
  118815. }
  118816. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118817. float **in,float **out,int *nonzero,int ch,
  118818. long **partword){
  118819. /* we encode only the nonzero parts of a bundle */
  118820. int i,j,used=0,n=vb->pcmend/2;
  118821. for(i=0;i<ch;i++)
  118822. if(nonzero[i]){
  118823. if(out)
  118824. for(j=0;j<n;j++)
  118825. out[i][j]+=in[i][j];
  118826. in[used++]=in[i];
  118827. }
  118828. if(used){
  118829. int ret=_01forward(vb,vl,in,used,partword,
  118830. _interleaved_encodepart);
  118831. if(out){
  118832. used=0;
  118833. for(i=0;i<ch;i++)
  118834. if(nonzero[i]){
  118835. for(j=0;j<n;j++)
  118836. out[i][j]-=in[used][j];
  118837. used++;
  118838. }
  118839. }
  118840. return(ret);
  118841. }else{
  118842. return(0);
  118843. }
  118844. }
  118845. #endif
  118846. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118847. float **in,int *nonzero,int ch){
  118848. int i,used=0;
  118849. for(i=0;i<ch;i++)
  118850. if(nonzero[i])
  118851. in[used++]=in[i];
  118852. if(used)
  118853. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118854. else
  118855. return(0);
  118856. }
  118857. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118858. float **in,float **out,int *nonzero,int ch,
  118859. long **partword){
  118860. int i,j,used=0,n=vb->pcmend/2;
  118861. for(i=0;i<ch;i++)
  118862. if(nonzero[i]){
  118863. if(out)
  118864. for(j=0;j<n;j++)
  118865. out[i][j]+=in[i][j];
  118866. in[used++]=in[i];
  118867. }
  118868. if(used){
  118869. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118870. if(out){
  118871. used=0;
  118872. for(i=0;i<ch;i++)
  118873. if(nonzero[i]){
  118874. for(j=0;j<n;j++)
  118875. out[i][j]-=in[used][j];
  118876. used++;
  118877. }
  118878. }
  118879. return(ret);
  118880. }else{
  118881. return(0);
  118882. }
  118883. }
  118884. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118885. float **in,int *nonzero,int ch){
  118886. int i,used=0;
  118887. for(i=0;i<ch;i++)
  118888. if(nonzero[i])
  118889. in[used++]=in[i];
  118890. if(used)
  118891. return(_01class(vb,vl,in,used));
  118892. else
  118893. return(0);
  118894. }
  118895. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118896. float **in,int *nonzero,int ch){
  118897. int i,used=0;
  118898. for(i=0;i<ch;i++)
  118899. if(nonzero[i])
  118900. in[used++]=in[i];
  118901. if(used)
  118902. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118903. else
  118904. return(0);
  118905. }
  118906. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118907. float **in,int *nonzero,int ch){
  118908. int i,used=0;
  118909. for(i=0;i<ch;i++)
  118910. if(nonzero[i])used++;
  118911. if(used)
  118912. return(_2class(vb,vl,in,ch));
  118913. else
  118914. return(0);
  118915. }
  118916. /* res2 is slightly more different; all the channels are interleaved
  118917. into a single vector and encoded. */
  118918. int res2_forward(oggpack_buffer *opb,
  118919. vorbis_block *vb,vorbis_look_residue *vl,
  118920. float **in,float **out,int *nonzero,int ch,
  118921. long **partword){
  118922. long i,j,k,n=vb->pcmend/2,used=0;
  118923. /* don't duplicate the code; use a working vector hack for now and
  118924. reshape ourselves into a single channel res1 */
  118925. /* ugly; reallocs for each coupling pass :-( */
  118926. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118927. for(i=0;i<ch;i++){
  118928. float *pcm=in[i];
  118929. if(nonzero[i])used++;
  118930. for(j=0,k=i;j<n;j++,k+=ch)
  118931. work[k]=pcm[j];
  118932. }
  118933. if(used){
  118934. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118935. /* update the sofar vector */
  118936. if(out){
  118937. for(i=0;i<ch;i++){
  118938. float *pcm=in[i];
  118939. float *sofar=out[i];
  118940. for(j=0,k=i;j<n;j++,k+=ch)
  118941. sofar[j]+=pcm[j]-work[k];
  118942. }
  118943. }
  118944. return(ret);
  118945. }else{
  118946. return(0);
  118947. }
  118948. }
  118949. /* duplicate code here as speed is somewhat more important */
  118950. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118951. float **in,int *nonzero,int ch){
  118952. long i,k,l,s;
  118953. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118954. vorbis_info_residue0 *info=look->info;
  118955. /* move all this setup out later */
  118956. int samples_per_partition=info->grouping;
  118957. int partitions_per_word=look->phrasebook->dim;
  118958. int n=info->end-info->begin;
  118959. int partvals=n/samples_per_partition;
  118960. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118961. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118962. for(i=0;i<ch;i++)if(nonzero[i])break;
  118963. if(i==ch)return(0); /* no nonzero vectors */
  118964. for(s=0;s<look->stages;s++){
  118965. for(i=0,l=0;i<partvals;l++){
  118966. if(s==0){
  118967. /* fetch the partition word */
  118968. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118969. if(temp==-1)goto eopbreak;
  118970. partword[l]=look->decodemap[temp];
  118971. if(partword[l]==NULL)goto errout;
  118972. }
  118973. /* now we decode residual values for the partitions */
  118974. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118975. if(info->secondstages[partword[l][k]]&(1<<s)){
  118976. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118977. if(stagebook){
  118978. if(vorbis_book_decodevv_add(stagebook,in,
  118979. i*samples_per_partition+info->begin,ch,
  118980. &vb->opb,samples_per_partition)==-1)
  118981. goto eopbreak;
  118982. }
  118983. }
  118984. }
  118985. }
  118986. errout:
  118987. eopbreak:
  118988. return(0);
  118989. }
  118990. vorbis_func_residue residue0_exportbundle={
  118991. NULL,
  118992. &res0_unpack,
  118993. &res0_look,
  118994. &res0_free_info,
  118995. &res0_free_look,
  118996. NULL,
  118997. NULL,
  118998. &res0_inverse
  118999. };
  119000. vorbis_func_residue residue1_exportbundle={
  119001. &res0_pack,
  119002. &res0_unpack,
  119003. &res0_look,
  119004. &res0_free_info,
  119005. &res0_free_look,
  119006. &res1_class,
  119007. &res1_forward,
  119008. &res1_inverse
  119009. };
  119010. vorbis_func_residue residue2_exportbundle={
  119011. &res0_pack,
  119012. &res0_unpack,
  119013. &res0_look,
  119014. &res0_free_info,
  119015. &res0_free_look,
  119016. &res2_class,
  119017. &res2_forward,
  119018. &res2_inverse
  119019. };
  119020. #endif
  119021. /*** End of inlined file: res0.c ***/
  119022. /*** Start of inlined file: sharedbook.c ***/
  119023. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119024. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119025. // tasks..
  119026. #if JUCE_MSVC
  119027. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119028. #endif
  119029. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119030. #if JUCE_USE_OGGVORBIS
  119031. #include <stdlib.h>
  119032. #include <math.h>
  119033. #include <string.h>
  119034. /**** pack/unpack helpers ******************************************/
  119035. int _ilog(unsigned int v){
  119036. int ret=0;
  119037. while(v){
  119038. ret++;
  119039. v>>=1;
  119040. }
  119041. return(ret);
  119042. }
  119043. /* 32 bit float (not IEEE; nonnormalized mantissa +
  119044. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  119045. Why not IEEE? It's just not that important here. */
  119046. #define VQ_FEXP 10
  119047. #define VQ_FMAN 21
  119048. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  119049. /* doesn't currently guard under/overflow */
  119050. long _float32_pack(float val){
  119051. int sign=0;
  119052. long exp;
  119053. long mant;
  119054. if(val<0){
  119055. sign=0x80000000;
  119056. val= -val;
  119057. }
  119058. exp= floor(log(val)/log(2.f));
  119059. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  119060. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  119061. return(sign|exp|mant);
  119062. }
  119063. float _float32_unpack(long val){
  119064. double mant=val&0x1fffff;
  119065. int sign=val&0x80000000;
  119066. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  119067. if(sign)mant= -mant;
  119068. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  119069. }
  119070. /* given a list of word lengths, generate a list of codewords. Works
  119071. for length ordered or unordered, always assigns the lowest valued
  119072. codewords first. Extended to handle unused entries (length 0) */
  119073. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  119074. long i,j,count=0;
  119075. ogg_uint32_t marker[33];
  119076. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  119077. memset(marker,0,sizeof(marker));
  119078. for(i=0;i<n;i++){
  119079. long length=l[i];
  119080. if(length>0){
  119081. ogg_uint32_t entry=marker[length];
  119082. /* when we claim a node for an entry, we also claim the nodes
  119083. below it (pruning off the imagined tree that may have dangled
  119084. from it) as well as blocking the use of any nodes directly
  119085. above for leaves */
  119086. /* update ourself */
  119087. if(length<32 && (entry>>length)){
  119088. /* error condition; the lengths must specify an overpopulated tree */
  119089. _ogg_free(r);
  119090. return(NULL);
  119091. }
  119092. r[count++]=entry;
  119093. /* Look to see if the next shorter marker points to the node
  119094. above. if so, update it and repeat. */
  119095. {
  119096. for(j=length;j>0;j--){
  119097. if(marker[j]&1){
  119098. /* have to jump branches */
  119099. if(j==1)
  119100. marker[1]++;
  119101. else
  119102. marker[j]=marker[j-1]<<1;
  119103. break; /* invariant says next upper marker would already
  119104. have been moved if it was on the same path */
  119105. }
  119106. marker[j]++;
  119107. }
  119108. }
  119109. /* prune the tree; the implicit invariant says all the longer
  119110. markers were dangling from our just-taken node. Dangle them
  119111. from our *new* node. */
  119112. for(j=length+1;j<33;j++)
  119113. if((marker[j]>>1) == entry){
  119114. entry=marker[j];
  119115. marker[j]=marker[j-1]<<1;
  119116. }else
  119117. break;
  119118. }else
  119119. if(sparsecount==0)count++;
  119120. }
  119121. /* bitreverse the words because our bitwise packer/unpacker is LSb
  119122. endian */
  119123. for(i=0,count=0;i<n;i++){
  119124. ogg_uint32_t temp=0;
  119125. for(j=0;j<l[i];j++){
  119126. temp<<=1;
  119127. temp|=(r[count]>>j)&1;
  119128. }
  119129. if(sparsecount){
  119130. if(l[i])
  119131. r[count++]=temp;
  119132. }else
  119133. r[count++]=temp;
  119134. }
  119135. return(r);
  119136. }
  119137. /* there might be a straightforward one-line way to do the below
  119138. that's portable and totally safe against roundoff, but I haven't
  119139. thought of it. Therefore, we opt on the side of caution */
  119140. long _book_maptype1_quantvals(const static_codebook *b){
  119141. long vals=floor(pow((float)b->entries,1.f/b->dim));
  119142. /* the above *should* be reliable, but we'll not assume that FP is
  119143. ever reliable when bitstream sync is at stake; verify via integer
  119144. means that vals really is the greatest value of dim for which
  119145. vals^b->bim <= b->entries */
  119146. /* treat the above as an initial guess */
  119147. while(1){
  119148. long acc=1;
  119149. long acc1=1;
  119150. int i;
  119151. for(i=0;i<b->dim;i++){
  119152. acc*=vals;
  119153. acc1*=vals+1;
  119154. }
  119155. if(acc<=b->entries && acc1>b->entries){
  119156. return(vals);
  119157. }else{
  119158. if(acc>b->entries){
  119159. vals--;
  119160. }else{
  119161. vals++;
  119162. }
  119163. }
  119164. }
  119165. }
  119166. /* unpack the quantized list of values for encode/decode ***********/
  119167. /* we need to deal with two map types: in map type 1, the values are
  119168. generated algorithmically (each column of the vector counts through
  119169. the values in the quant vector). in map type 2, all the values came
  119170. in in an explicit list. Both value lists must be unpacked */
  119171. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  119172. long j,k,count=0;
  119173. if(b->maptype==1 || b->maptype==2){
  119174. int quantvals;
  119175. float mindel=_float32_unpack(b->q_min);
  119176. float delta=_float32_unpack(b->q_delta);
  119177. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  119178. /* maptype 1 and 2 both use a quantized value vector, but
  119179. different sizes */
  119180. switch(b->maptype){
  119181. case 1:
  119182. /* most of the time, entries%dimensions == 0, but we need to be
  119183. well defined. We define that the possible vales at each
  119184. scalar is values == entries/dim. If entries%dim != 0, we'll
  119185. have 'too few' values (values*dim<entries), which means that
  119186. we'll have 'left over' entries; left over entries use zeroed
  119187. values (and are wasted). So don't generate codebooks like
  119188. that */
  119189. quantvals=_book_maptype1_quantvals(b);
  119190. for(j=0;j<b->entries;j++){
  119191. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119192. float last=0.f;
  119193. int indexdiv=1;
  119194. for(k=0;k<b->dim;k++){
  119195. int index= (j/indexdiv)%quantvals;
  119196. float val=b->quantlist[index];
  119197. val=fabs(val)*delta+mindel+last;
  119198. if(b->q_sequencep)last=val;
  119199. if(sparsemap)
  119200. r[sparsemap[count]*b->dim+k]=val;
  119201. else
  119202. r[count*b->dim+k]=val;
  119203. indexdiv*=quantvals;
  119204. }
  119205. count++;
  119206. }
  119207. }
  119208. break;
  119209. case 2:
  119210. for(j=0;j<b->entries;j++){
  119211. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119212. float last=0.f;
  119213. for(k=0;k<b->dim;k++){
  119214. float val=b->quantlist[j*b->dim+k];
  119215. val=fabs(val)*delta+mindel+last;
  119216. if(b->q_sequencep)last=val;
  119217. if(sparsemap)
  119218. r[sparsemap[count]*b->dim+k]=val;
  119219. else
  119220. r[count*b->dim+k]=val;
  119221. }
  119222. count++;
  119223. }
  119224. }
  119225. break;
  119226. }
  119227. return(r);
  119228. }
  119229. return(NULL);
  119230. }
  119231. void vorbis_staticbook_clear(static_codebook *b){
  119232. if(b->allocedp){
  119233. if(b->quantlist)_ogg_free(b->quantlist);
  119234. if(b->lengthlist)_ogg_free(b->lengthlist);
  119235. if(b->nearest_tree){
  119236. _ogg_free(b->nearest_tree->ptr0);
  119237. _ogg_free(b->nearest_tree->ptr1);
  119238. _ogg_free(b->nearest_tree->p);
  119239. _ogg_free(b->nearest_tree->q);
  119240. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119241. _ogg_free(b->nearest_tree);
  119242. }
  119243. if(b->thresh_tree){
  119244. _ogg_free(b->thresh_tree->quantthresh);
  119245. _ogg_free(b->thresh_tree->quantmap);
  119246. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119247. _ogg_free(b->thresh_tree);
  119248. }
  119249. memset(b,0,sizeof(*b));
  119250. }
  119251. }
  119252. void vorbis_staticbook_destroy(static_codebook *b){
  119253. if(b->allocedp){
  119254. vorbis_staticbook_clear(b);
  119255. _ogg_free(b);
  119256. }
  119257. }
  119258. void vorbis_book_clear(codebook *b){
  119259. /* static book is not cleared; we're likely called on the lookup and
  119260. the static codebook belongs to the info struct */
  119261. if(b->valuelist)_ogg_free(b->valuelist);
  119262. if(b->codelist)_ogg_free(b->codelist);
  119263. if(b->dec_index)_ogg_free(b->dec_index);
  119264. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119265. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119266. memset(b,0,sizeof(*b));
  119267. }
  119268. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119269. memset(c,0,sizeof(*c));
  119270. c->c=s;
  119271. c->entries=s->entries;
  119272. c->used_entries=s->entries;
  119273. c->dim=s->dim;
  119274. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119275. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119276. return(0);
  119277. }
  119278. static int JUCE_CDECL sort32a(const void *a,const void *b){
  119279. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119280. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119281. }
  119282. /* decode codebook arrangement is more heavily optimized than encode */
  119283. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119284. int i,j,n=0,tabn;
  119285. int *sortindex;
  119286. memset(c,0,sizeof(*c));
  119287. /* count actually used entries */
  119288. for(i=0;i<s->entries;i++)
  119289. if(s->lengthlist[i]>0)
  119290. n++;
  119291. c->entries=s->entries;
  119292. c->used_entries=n;
  119293. c->dim=s->dim;
  119294. /* two different remappings go on here.
  119295. First, we collapse the likely sparse codebook down only to
  119296. actually represented values/words. This collapsing needs to be
  119297. indexed as map-valueless books are used to encode original entry
  119298. positions as integers.
  119299. Second, we reorder all vectors, including the entry index above,
  119300. by sorted bitreversed codeword to allow treeless decode. */
  119301. {
  119302. /* perform sort */
  119303. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119304. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119305. if(codes==NULL)goto err_out;
  119306. for(i=0;i<n;i++){
  119307. codes[i]=ogg_bitreverse(codes[i]);
  119308. codep[i]=codes+i;
  119309. }
  119310. qsort(codep,n,sizeof(*codep),sort32a);
  119311. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119312. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119313. /* the index is a reverse index */
  119314. for(i=0;i<n;i++){
  119315. int position=codep[i]-codes;
  119316. sortindex[position]=i;
  119317. }
  119318. for(i=0;i<n;i++)
  119319. c->codelist[sortindex[i]]=codes[i];
  119320. _ogg_free(codes);
  119321. }
  119322. c->valuelist=_book_unquantize(s,n,sortindex);
  119323. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119324. for(n=0,i=0;i<s->entries;i++)
  119325. if(s->lengthlist[i]>0)
  119326. c->dec_index[sortindex[n++]]=i;
  119327. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119328. for(n=0,i=0;i<s->entries;i++)
  119329. if(s->lengthlist[i]>0)
  119330. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119331. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119332. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119333. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119334. tabn=1<<c->dec_firsttablen;
  119335. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119336. c->dec_maxlength=0;
  119337. for(i=0;i<n;i++){
  119338. if(c->dec_maxlength<c->dec_codelengths[i])
  119339. c->dec_maxlength=c->dec_codelengths[i];
  119340. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119341. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119342. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119343. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119344. }
  119345. }
  119346. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119347. hints for the non-direct-hits */
  119348. {
  119349. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119350. long lo=0,hi=0;
  119351. for(i=0;i<tabn;i++){
  119352. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119353. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119354. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119355. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119356. /* we only actually have 15 bits per hint to play with here.
  119357. In order to overflow gracefully (nothing breaks, efficiency
  119358. just drops), encode as the difference from the extremes. */
  119359. {
  119360. unsigned long loval=lo;
  119361. unsigned long hival=n-hi;
  119362. if(loval>0x7fff)loval=0x7fff;
  119363. if(hival>0x7fff)hival=0x7fff;
  119364. c->dec_firsttable[ogg_bitreverse(word)]=
  119365. 0x80000000UL | (loval<<15) | hival;
  119366. }
  119367. }
  119368. }
  119369. }
  119370. return(0);
  119371. err_out:
  119372. vorbis_book_clear(c);
  119373. return(-1);
  119374. }
  119375. static float _dist(int el,float *ref, float *b,int step){
  119376. int i;
  119377. float acc=0.f;
  119378. for(i=0;i<el;i++){
  119379. float val=(ref[i]-b[i*step]);
  119380. acc+=val*val;
  119381. }
  119382. return(acc);
  119383. }
  119384. int _best(codebook *book, float *a, int step){
  119385. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119386. #if 0
  119387. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119388. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119389. #endif
  119390. int dim=book->dim;
  119391. int k,o;
  119392. /*int savebest=-1;
  119393. float saverr;*/
  119394. /* do we have a threshhold encode hint? */
  119395. if(tt){
  119396. int index=0,i;
  119397. /* find the quant val of each scalar */
  119398. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119399. i=tt->threshvals>>1;
  119400. if(a[o]<tt->quantthresh[i]){
  119401. for(;i>0;i--)
  119402. if(a[o]>=tt->quantthresh[i-1])
  119403. break;
  119404. }else{
  119405. for(i++;i<tt->threshvals-1;i++)
  119406. if(a[o]<tt->quantthresh[i])break;
  119407. }
  119408. index=(index*tt->quantvals)+tt->quantmap[i];
  119409. }
  119410. /* regular lattices are easy :-) */
  119411. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119412. use a decision tree after all
  119413. and fall through*/
  119414. return(index);
  119415. }
  119416. #if 0
  119417. /* do we have a pigeonhole encode hint? */
  119418. if(pt){
  119419. const static_codebook *c=book->c;
  119420. int i,besti=-1;
  119421. float best=0.f;
  119422. int entry=0;
  119423. /* dealing with sequentialness is a pain in the ass */
  119424. if(c->q_sequencep){
  119425. int pv;
  119426. long mul=1;
  119427. float qlast=0;
  119428. for(k=0,o=0;k<dim;k++,o+=step){
  119429. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119430. if(pv<0 || pv>=pt->mapentries)break;
  119431. entry+=pt->pigeonmap[pv]*mul;
  119432. mul*=pt->quantvals;
  119433. qlast+=pv*pt->del+pt->min;
  119434. }
  119435. }else{
  119436. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119437. int pv=(int)((a[o]-pt->min)/pt->del);
  119438. if(pv<0 || pv>=pt->mapentries)break;
  119439. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119440. }
  119441. }
  119442. /* must be within the pigeonholable range; if we quant outside (or
  119443. in an entry that we define no list for), brute force it */
  119444. if(k==dim && pt->fitlength[entry]){
  119445. /* search the abbreviated list */
  119446. long *list=pt->fitlist+pt->fitmap[entry];
  119447. for(i=0;i<pt->fitlength[entry];i++){
  119448. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119449. if(besti==-1 || this<best){
  119450. best=this;
  119451. besti=list[i];
  119452. }
  119453. }
  119454. return(besti);
  119455. }
  119456. }
  119457. if(nt){
  119458. /* optimized using the decision tree */
  119459. while(1){
  119460. float c=0.f;
  119461. float *p=book->valuelist+nt->p[ptr];
  119462. float *q=book->valuelist+nt->q[ptr];
  119463. for(k=0,o=0;k<dim;k++,o+=step)
  119464. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119465. if(c>0.f) /* in A */
  119466. ptr= -nt->ptr0[ptr];
  119467. else /* in B */
  119468. ptr= -nt->ptr1[ptr];
  119469. if(ptr<=0)break;
  119470. }
  119471. return(-ptr);
  119472. }
  119473. #endif
  119474. /* brute force it! */
  119475. {
  119476. const static_codebook *c=book->c;
  119477. int i,besti=-1;
  119478. float best=0.f;
  119479. float *e=book->valuelist;
  119480. for(i=0;i<book->entries;i++){
  119481. if(c->lengthlist[i]>0){
  119482. float thisx=_dist(dim,e,a,step);
  119483. if(besti==-1 || thisx<best){
  119484. best=thisx;
  119485. besti=i;
  119486. }
  119487. }
  119488. e+=dim;
  119489. }
  119490. /*if(savebest!=-1 && savebest!=besti){
  119491. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119492. "original:");
  119493. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119494. fprintf(stderr,"\n"
  119495. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119496. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119497. (book->valuelist+savebest*dim)[i]);
  119498. fprintf(stderr,"\n"
  119499. "bruteforce (entry %d, err %g):",besti,best);
  119500. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119501. (book->valuelist+besti*dim)[i]);
  119502. fprintf(stderr,"\n");
  119503. }*/
  119504. return(besti);
  119505. }
  119506. }
  119507. long vorbis_book_codeword(codebook *book,int entry){
  119508. if(book->c) /* only use with encode; decode optimizations are
  119509. allowed to break this */
  119510. return book->codelist[entry];
  119511. return -1;
  119512. }
  119513. long vorbis_book_codelen(codebook *book,int entry){
  119514. if(book->c) /* only use with encode; decode optimizations are
  119515. allowed to break this */
  119516. return book->c->lengthlist[entry];
  119517. return -1;
  119518. }
  119519. #ifdef _V_SELFTEST
  119520. /* Unit tests of the dequantizer; this stuff will be OK
  119521. cross-platform, I simply want to be sure that special mapping cases
  119522. actually work properly; a bug could go unnoticed for a while */
  119523. #include <stdio.h>
  119524. /* cases:
  119525. no mapping
  119526. full, explicit mapping
  119527. algorithmic mapping
  119528. nonsequential
  119529. sequential
  119530. */
  119531. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119532. static long partial_quantlist1[]={0,7,2};
  119533. /* no mapping */
  119534. static_codebook test1={
  119535. 4,16,
  119536. NULL,
  119537. 0,
  119538. 0,0,0,0,
  119539. NULL,
  119540. NULL,NULL
  119541. };
  119542. static float *test1_result=NULL;
  119543. /* linear, full mapping, nonsequential */
  119544. static_codebook test2={
  119545. 4,3,
  119546. NULL,
  119547. 2,
  119548. -533200896,1611661312,4,0,
  119549. full_quantlist1,
  119550. NULL,NULL
  119551. };
  119552. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119553. /* linear, full mapping, sequential */
  119554. static_codebook test3={
  119555. 4,3,
  119556. NULL,
  119557. 2,
  119558. -533200896,1611661312,4,1,
  119559. full_quantlist1,
  119560. NULL,NULL
  119561. };
  119562. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119563. /* linear, algorithmic mapping, nonsequential */
  119564. static_codebook test4={
  119565. 3,27,
  119566. NULL,
  119567. 1,
  119568. -533200896,1611661312,4,0,
  119569. partial_quantlist1,
  119570. NULL,NULL
  119571. };
  119572. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119573. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119574. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119575. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119576. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119577. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119578. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119579. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119580. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119581. /* linear, algorithmic mapping, sequential */
  119582. static_codebook test5={
  119583. 3,27,
  119584. NULL,
  119585. 1,
  119586. -533200896,1611661312,4,1,
  119587. partial_quantlist1,
  119588. NULL,NULL
  119589. };
  119590. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119591. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119592. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119593. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119594. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119595. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119596. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119597. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119598. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119599. void run_test(static_codebook *b,float *comp){
  119600. float *out=_book_unquantize(b,b->entries,NULL);
  119601. int i;
  119602. if(comp){
  119603. if(!out){
  119604. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119605. exit(1);
  119606. }
  119607. for(i=0;i<b->entries*b->dim;i++)
  119608. if(fabs(out[i]-comp[i])>.0001){
  119609. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119610. "position %d, %g != %g\n",i,out[i],comp[i]);
  119611. exit(1);
  119612. }
  119613. }else{
  119614. if(out){
  119615. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119616. " correct result should have been NULL\n");
  119617. exit(1);
  119618. }
  119619. }
  119620. }
  119621. int main(){
  119622. /* run the nine dequant tests, and compare to the hand-rolled results */
  119623. fprintf(stderr,"Dequant test 1... ");
  119624. run_test(&test1,test1_result);
  119625. fprintf(stderr,"OK\nDequant test 2... ");
  119626. run_test(&test2,test2_result);
  119627. fprintf(stderr,"OK\nDequant test 3... ");
  119628. run_test(&test3,test3_result);
  119629. fprintf(stderr,"OK\nDequant test 4... ");
  119630. run_test(&test4,test4_result);
  119631. fprintf(stderr,"OK\nDequant test 5... ");
  119632. run_test(&test5,test5_result);
  119633. fprintf(stderr,"OK\n\n");
  119634. return(0);
  119635. }
  119636. #endif
  119637. #endif
  119638. /*** End of inlined file: sharedbook.c ***/
  119639. /*** Start of inlined file: smallft.c ***/
  119640. /* FFT implementation from OggSquish, minus cosine transforms,
  119641. * minus all but radix 2/4 case. In Vorbis we only need this
  119642. * cut-down version.
  119643. *
  119644. * To do more than just power-of-two sized vectors, see the full
  119645. * version I wrote for NetLib.
  119646. *
  119647. * Note that the packing is a little strange; rather than the FFT r/i
  119648. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119649. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119650. * FORTRAN version
  119651. */
  119652. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119653. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119654. // tasks..
  119655. #if JUCE_MSVC
  119656. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119657. #endif
  119658. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119659. #if JUCE_USE_OGGVORBIS
  119660. #include <stdlib.h>
  119661. #include <string.h>
  119662. #include <math.h>
  119663. static void drfti1(int n, float *wa, int *ifac){
  119664. static int ntryh[4] = { 4,2,3,5 };
  119665. static float tpi = 6.28318530717958648f;
  119666. float arg,argh,argld,fi;
  119667. int ntry=0,i,j=-1;
  119668. int k1, l1, l2, ib;
  119669. int ld, ii, ip, is, nq, nr;
  119670. int ido, ipm, nfm1;
  119671. int nl=n;
  119672. int nf=0;
  119673. L101:
  119674. j++;
  119675. if (j < 4)
  119676. ntry=ntryh[j];
  119677. else
  119678. ntry+=2;
  119679. L104:
  119680. nq=nl/ntry;
  119681. nr=nl-ntry*nq;
  119682. if (nr!=0) goto L101;
  119683. nf++;
  119684. ifac[nf+1]=ntry;
  119685. nl=nq;
  119686. if(ntry!=2)goto L107;
  119687. if(nf==1)goto L107;
  119688. for (i=1;i<nf;i++){
  119689. ib=nf-i+1;
  119690. ifac[ib+1]=ifac[ib];
  119691. }
  119692. ifac[2] = 2;
  119693. L107:
  119694. if(nl!=1)goto L104;
  119695. ifac[0]=n;
  119696. ifac[1]=nf;
  119697. argh=tpi/n;
  119698. is=0;
  119699. nfm1=nf-1;
  119700. l1=1;
  119701. if(nfm1==0)return;
  119702. for (k1=0;k1<nfm1;k1++){
  119703. ip=ifac[k1+2];
  119704. ld=0;
  119705. l2=l1*ip;
  119706. ido=n/l2;
  119707. ipm=ip-1;
  119708. for (j=0;j<ipm;j++){
  119709. ld+=l1;
  119710. i=is;
  119711. argld=(float)ld*argh;
  119712. fi=0.f;
  119713. for (ii=2;ii<ido;ii+=2){
  119714. fi+=1.f;
  119715. arg=fi*argld;
  119716. wa[i++]=cos(arg);
  119717. wa[i++]=sin(arg);
  119718. }
  119719. is+=ido;
  119720. }
  119721. l1=l2;
  119722. }
  119723. }
  119724. static void fdrffti(int n, float *wsave, int *ifac){
  119725. if (n == 1) return;
  119726. drfti1(n, wsave+n, ifac);
  119727. }
  119728. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119729. int i,k;
  119730. float ti2,tr2;
  119731. int t0,t1,t2,t3,t4,t5,t6;
  119732. t1=0;
  119733. t0=(t2=l1*ido);
  119734. t3=ido<<1;
  119735. for(k=0;k<l1;k++){
  119736. ch[t1<<1]=cc[t1]+cc[t2];
  119737. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119738. t1+=ido;
  119739. t2+=ido;
  119740. }
  119741. if(ido<2)return;
  119742. if(ido==2)goto L105;
  119743. t1=0;
  119744. t2=t0;
  119745. for(k=0;k<l1;k++){
  119746. t3=t2;
  119747. t4=(t1<<1)+(ido<<1);
  119748. t5=t1;
  119749. t6=t1+t1;
  119750. for(i=2;i<ido;i+=2){
  119751. t3+=2;
  119752. t4-=2;
  119753. t5+=2;
  119754. t6+=2;
  119755. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119756. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119757. ch[t6]=cc[t5]+ti2;
  119758. ch[t4]=ti2-cc[t5];
  119759. ch[t6-1]=cc[t5-1]+tr2;
  119760. ch[t4-1]=cc[t5-1]-tr2;
  119761. }
  119762. t1+=ido;
  119763. t2+=ido;
  119764. }
  119765. if(ido%2==1)return;
  119766. L105:
  119767. t3=(t2=(t1=ido)-1);
  119768. t2+=t0;
  119769. for(k=0;k<l1;k++){
  119770. ch[t1]=-cc[t2];
  119771. ch[t1-1]=cc[t3];
  119772. t1+=ido<<1;
  119773. t2+=ido;
  119774. t3+=ido;
  119775. }
  119776. }
  119777. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119778. float *wa2,float *wa3){
  119779. static float hsqt2 = .70710678118654752f;
  119780. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119781. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119782. t0=l1*ido;
  119783. t1=t0;
  119784. t4=t1<<1;
  119785. t2=t1+(t1<<1);
  119786. t3=0;
  119787. for(k=0;k<l1;k++){
  119788. tr1=cc[t1]+cc[t2];
  119789. tr2=cc[t3]+cc[t4];
  119790. ch[t5=t3<<2]=tr1+tr2;
  119791. ch[(ido<<2)+t5-1]=tr2-tr1;
  119792. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119793. ch[t5]=cc[t2]-cc[t1];
  119794. t1+=ido;
  119795. t2+=ido;
  119796. t3+=ido;
  119797. t4+=ido;
  119798. }
  119799. if(ido<2)return;
  119800. if(ido==2)goto L105;
  119801. t1=0;
  119802. for(k=0;k<l1;k++){
  119803. t2=t1;
  119804. t4=t1<<2;
  119805. t5=(t6=ido<<1)+t4;
  119806. for(i=2;i<ido;i+=2){
  119807. t3=(t2+=2);
  119808. t4+=2;
  119809. t5-=2;
  119810. t3+=t0;
  119811. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119812. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119813. t3+=t0;
  119814. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119815. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119816. t3+=t0;
  119817. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119818. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119819. tr1=cr2+cr4;
  119820. tr4=cr4-cr2;
  119821. ti1=ci2+ci4;
  119822. ti4=ci2-ci4;
  119823. ti2=cc[t2]+ci3;
  119824. ti3=cc[t2]-ci3;
  119825. tr2=cc[t2-1]+cr3;
  119826. tr3=cc[t2-1]-cr3;
  119827. ch[t4-1]=tr1+tr2;
  119828. ch[t4]=ti1+ti2;
  119829. ch[t5-1]=tr3-ti4;
  119830. ch[t5]=tr4-ti3;
  119831. ch[t4+t6-1]=ti4+tr3;
  119832. ch[t4+t6]=tr4+ti3;
  119833. ch[t5+t6-1]=tr2-tr1;
  119834. ch[t5+t6]=ti1-ti2;
  119835. }
  119836. t1+=ido;
  119837. }
  119838. if(ido&1)return;
  119839. L105:
  119840. t2=(t1=t0+ido-1)+(t0<<1);
  119841. t3=ido<<2;
  119842. t4=ido;
  119843. t5=ido<<1;
  119844. t6=ido;
  119845. for(k=0;k<l1;k++){
  119846. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119847. tr1=hsqt2*(cc[t1]-cc[t2]);
  119848. ch[t4-1]=tr1+cc[t6-1];
  119849. ch[t4+t5-1]=cc[t6-1]-tr1;
  119850. ch[t4]=ti1-cc[t1+t0];
  119851. ch[t4+t5]=ti1+cc[t1+t0];
  119852. t1+=ido;
  119853. t2+=ido;
  119854. t4+=t3;
  119855. t6+=ido;
  119856. }
  119857. }
  119858. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119859. float *c2,float *ch,float *ch2,float *wa){
  119860. static float tpi=6.283185307179586f;
  119861. int idij,ipph,i,j,k,l,ic,ik,is;
  119862. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119863. float dc2,ai1,ai2,ar1,ar2,ds2;
  119864. int nbd;
  119865. float dcp,arg,dsp,ar1h,ar2h;
  119866. int idp2,ipp2;
  119867. arg=tpi/(float)ip;
  119868. dcp=cos(arg);
  119869. dsp=sin(arg);
  119870. ipph=(ip+1)>>1;
  119871. ipp2=ip;
  119872. idp2=ido;
  119873. nbd=(ido-1)>>1;
  119874. t0=l1*ido;
  119875. t10=ip*ido;
  119876. if(ido==1)goto L119;
  119877. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119878. t1=0;
  119879. for(j=1;j<ip;j++){
  119880. t1+=t0;
  119881. t2=t1;
  119882. for(k=0;k<l1;k++){
  119883. ch[t2]=c1[t2];
  119884. t2+=ido;
  119885. }
  119886. }
  119887. is=-ido;
  119888. t1=0;
  119889. if(nbd>l1){
  119890. for(j=1;j<ip;j++){
  119891. t1+=t0;
  119892. is+=ido;
  119893. t2= -ido+t1;
  119894. for(k=0;k<l1;k++){
  119895. idij=is-1;
  119896. t2+=ido;
  119897. t3=t2;
  119898. for(i=2;i<ido;i+=2){
  119899. idij+=2;
  119900. t3+=2;
  119901. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119902. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119903. }
  119904. }
  119905. }
  119906. }else{
  119907. for(j=1;j<ip;j++){
  119908. is+=ido;
  119909. idij=is-1;
  119910. t1+=t0;
  119911. t2=t1;
  119912. for(i=2;i<ido;i+=2){
  119913. idij+=2;
  119914. t2+=2;
  119915. t3=t2;
  119916. for(k=0;k<l1;k++){
  119917. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119918. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119919. t3+=ido;
  119920. }
  119921. }
  119922. }
  119923. }
  119924. t1=0;
  119925. t2=ipp2*t0;
  119926. if(nbd<l1){
  119927. for(j=1;j<ipph;j++){
  119928. t1+=t0;
  119929. t2-=t0;
  119930. t3=t1;
  119931. t4=t2;
  119932. for(i=2;i<ido;i+=2){
  119933. t3+=2;
  119934. t4+=2;
  119935. t5=t3-ido;
  119936. t6=t4-ido;
  119937. for(k=0;k<l1;k++){
  119938. t5+=ido;
  119939. t6+=ido;
  119940. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119941. c1[t6-1]=ch[t5]-ch[t6];
  119942. c1[t5]=ch[t5]+ch[t6];
  119943. c1[t6]=ch[t6-1]-ch[t5-1];
  119944. }
  119945. }
  119946. }
  119947. }else{
  119948. for(j=1;j<ipph;j++){
  119949. t1+=t0;
  119950. t2-=t0;
  119951. t3=t1;
  119952. t4=t2;
  119953. for(k=0;k<l1;k++){
  119954. t5=t3;
  119955. t6=t4;
  119956. for(i=2;i<ido;i+=2){
  119957. t5+=2;
  119958. t6+=2;
  119959. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119960. c1[t6-1]=ch[t5]-ch[t6];
  119961. c1[t5]=ch[t5]+ch[t6];
  119962. c1[t6]=ch[t6-1]-ch[t5-1];
  119963. }
  119964. t3+=ido;
  119965. t4+=ido;
  119966. }
  119967. }
  119968. }
  119969. L119:
  119970. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119971. t1=0;
  119972. t2=ipp2*idl1;
  119973. for(j=1;j<ipph;j++){
  119974. t1+=t0;
  119975. t2-=t0;
  119976. t3=t1-ido;
  119977. t4=t2-ido;
  119978. for(k=0;k<l1;k++){
  119979. t3+=ido;
  119980. t4+=ido;
  119981. c1[t3]=ch[t3]+ch[t4];
  119982. c1[t4]=ch[t4]-ch[t3];
  119983. }
  119984. }
  119985. ar1=1.f;
  119986. ai1=0.f;
  119987. t1=0;
  119988. t2=ipp2*idl1;
  119989. t3=(ip-1)*idl1;
  119990. for(l=1;l<ipph;l++){
  119991. t1+=idl1;
  119992. t2-=idl1;
  119993. ar1h=dcp*ar1-dsp*ai1;
  119994. ai1=dcp*ai1+dsp*ar1;
  119995. ar1=ar1h;
  119996. t4=t1;
  119997. t5=t2;
  119998. t6=t3;
  119999. t7=idl1;
  120000. for(ik=0;ik<idl1;ik++){
  120001. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  120002. ch2[t5++]=ai1*c2[t6++];
  120003. }
  120004. dc2=ar1;
  120005. ds2=ai1;
  120006. ar2=ar1;
  120007. ai2=ai1;
  120008. t4=idl1;
  120009. t5=(ipp2-1)*idl1;
  120010. for(j=2;j<ipph;j++){
  120011. t4+=idl1;
  120012. t5-=idl1;
  120013. ar2h=dc2*ar2-ds2*ai2;
  120014. ai2=dc2*ai2+ds2*ar2;
  120015. ar2=ar2h;
  120016. t6=t1;
  120017. t7=t2;
  120018. t8=t4;
  120019. t9=t5;
  120020. for(ik=0;ik<idl1;ik++){
  120021. ch2[t6++]+=ar2*c2[t8++];
  120022. ch2[t7++]+=ai2*c2[t9++];
  120023. }
  120024. }
  120025. }
  120026. t1=0;
  120027. for(j=1;j<ipph;j++){
  120028. t1+=idl1;
  120029. t2=t1;
  120030. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  120031. }
  120032. if(ido<l1)goto L132;
  120033. t1=0;
  120034. t2=0;
  120035. for(k=0;k<l1;k++){
  120036. t3=t1;
  120037. t4=t2;
  120038. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  120039. t1+=ido;
  120040. t2+=t10;
  120041. }
  120042. goto L135;
  120043. L132:
  120044. for(i=0;i<ido;i++){
  120045. t1=i;
  120046. t2=i;
  120047. for(k=0;k<l1;k++){
  120048. cc[t2]=ch[t1];
  120049. t1+=ido;
  120050. t2+=t10;
  120051. }
  120052. }
  120053. L135:
  120054. t1=0;
  120055. t2=ido<<1;
  120056. t3=0;
  120057. t4=ipp2*t0;
  120058. for(j=1;j<ipph;j++){
  120059. t1+=t2;
  120060. t3+=t0;
  120061. t4-=t0;
  120062. t5=t1;
  120063. t6=t3;
  120064. t7=t4;
  120065. for(k=0;k<l1;k++){
  120066. cc[t5-1]=ch[t6];
  120067. cc[t5]=ch[t7];
  120068. t5+=t10;
  120069. t6+=ido;
  120070. t7+=ido;
  120071. }
  120072. }
  120073. if(ido==1)return;
  120074. if(nbd<l1)goto L141;
  120075. t1=-ido;
  120076. t3=0;
  120077. t4=0;
  120078. t5=ipp2*t0;
  120079. for(j=1;j<ipph;j++){
  120080. t1+=t2;
  120081. t3+=t2;
  120082. t4+=t0;
  120083. t5-=t0;
  120084. t6=t1;
  120085. t7=t3;
  120086. t8=t4;
  120087. t9=t5;
  120088. for(k=0;k<l1;k++){
  120089. for(i=2;i<ido;i+=2){
  120090. ic=idp2-i;
  120091. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  120092. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  120093. cc[i+t7]=ch[i+t8]+ch[i+t9];
  120094. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  120095. }
  120096. t6+=t10;
  120097. t7+=t10;
  120098. t8+=ido;
  120099. t9+=ido;
  120100. }
  120101. }
  120102. return;
  120103. L141:
  120104. t1=-ido;
  120105. t3=0;
  120106. t4=0;
  120107. t5=ipp2*t0;
  120108. for(j=1;j<ipph;j++){
  120109. t1+=t2;
  120110. t3+=t2;
  120111. t4+=t0;
  120112. t5-=t0;
  120113. for(i=2;i<ido;i+=2){
  120114. t6=idp2+t1-i;
  120115. t7=i+t3;
  120116. t8=i+t4;
  120117. t9=i+t5;
  120118. for(k=0;k<l1;k++){
  120119. cc[t7-1]=ch[t8-1]+ch[t9-1];
  120120. cc[t6-1]=ch[t8-1]-ch[t9-1];
  120121. cc[t7]=ch[t8]+ch[t9];
  120122. cc[t6]=ch[t9]-ch[t8];
  120123. t6+=t10;
  120124. t7+=t10;
  120125. t8+=ido;
  120126. t9+=ido;
  120127. }
  120128. }
  120129. }
  120130. }
  120131. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  120132. int i,k1,l1,l2;
  120133. int na,kh,nf;
  120134. int ip,iw,ido,idl1,ix2,ix3;
  120135. nf=ifac[1];
  120136. na=1;
  120137. l2=n;
  120138. iw=n;
  120139. for(k1=0;k1<nf;k1++){
  120140. kh=nf-k1;
  120141. ip=ifac[kh+1];
  120142. l1=l2/ip;
  120143. ido=n/l2;
  120144. idl1=ido*l1;
  120145. iw-=(ip-1)*ido;
  120146. na=1-na;
  120147. if(ip!=4)goto L102;
  120148. ix2=iw+ido;
  120149. ix3=ix2+ido;
  120150. if(na!=0)
  120151. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120152. else
  120153. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120154. goto L110;
  120155. L102:
  120156. if(ip!=2)goto L104;
  120157. if(na!=0)goto L103;
  120158. dradf2(ido,l1,c,ch,wa+iw-1);
  120159. goto L110;
  120160. L103:
  120161. dradf2(ido,l1,ch,c,wa+iw-1);
  120162. goto L110;
  120163. L104:
  120164. if(ido==1)na=1-na;
  120165. if(na!=0)goto L109;
  120166. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120167. na=1;
  120168. goto L110;
  120169. L109:
  120170. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120171. na=0;
  120172. L110:
  120173. l2=l1;
  120174. }
  120175. if(na==1)return;
  120176. for(i=0;i<n;i++)c[i]=ch[i];
  120177. }
  120178. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  120179. int i,k,t0,t1,t2,t3,t4,t5,t6;
  120180. float ti2,tr2;
  120181. t0=l1*ido;
  120182. t1=0;
  120183. t2=0;
  120184. t3=(ido<<1)-1;
  120185. for(k=0;k<l1;k++){
  120186. ch[t1]=cc[t2]+cc[t3+t2];
  120187. ch[t1+t0]=cc[t2]-cc[t3+t2];
  120188. t2=(t1+=ido)<<1;
  120189. }
  120190. if(ido<2)return;
  120191. if(ido==2)goto L105;
  120192. t1=0;
  120193. t2=0;
  120194. for(k=0;k<l1;k++){
  120195. t3=t1;
  120196. t5=(t4=t2)+(ido<<1);
  120197. t6=t0+t1;
  120198. for(i=2;i<ido;i+=2){
  120199. t3+=2;
  120200. t4+=2;
  120201. t5-=2;
  120202. t6+=2;
  120203. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120204. tr2=cc[t4-1]-cc[t5-1];
  120205. ch[t3]=cc[t4]-cc[t5];
  120206. ti2=cc[t4]+cc[t5];
  120207. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120208. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120209. }
  120210. t2=(t1+=ido)<<1;
  120211. }
  120212. if(ido%2==1)return;
  120213. L105:
  120214. t1=ido-1;
  120215. t2=ido-1;
  120216. for(k=0;k<l1;k++){
  120217. ch[t1]=cc[t2]+cc[t2];
  120218. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120219. t1+=ido;
  120220. t2+=ido<<1;
  120221. }
  120222. }
  120223. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120224. float *wa2){
  120225. static float taur = -.5f;
  120226. static float taui = .8660254037844386f;
  120227. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120228. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120229. t0=l1*ido;
  120230. t1=0;
  120231. t2=t0<<1;
  120232. t3=ido<<1;
  120233. t4=ido+(ido<<1);
  120234. t5=0;
  120235. for(k=0;k<l1;k++){
  120236. tr2=cc[t3-1]+cc[t3-1];
  120237. cr2=cc[t5]+(taur*tr2);
  120238. ch[t1]=cc[t5]+tr2;
  120239. ci3=taui*(cc[t3]+cc[t3]);
  120240. ch[t1+t0]=cr2-ci3;
  120241. ch[t1+t2]=cr2+ci3;
  120242. t1+=ido;
  120243. t3+=t4;
  120244. t5+=t4;
  120245. }
  120246. if(ido==1)return;
  120247. t1=0;
  120248. t3=ido<<1;
  120249. for(k=0;k<l1;k++){
  120250. t7=t1+(t1<<1);
  120251. t6=(t5=t7+t3);
  120252. t8=t1;
  120253. t10=(t9=t1+t0)+t0;
  120254. for(i=2;i<ido;i+=2){
  120255. t5+=2;
  120256. t6-=2;
  120257. t7+=2;
  120258. t8+=2;
  120259. t9+=2;
  120260. t10+=2;
  120261. tr2=cc[t5-1]+cc[t6-1];
  120262. cr2=cc[t7-1]+(taur*tr2);
  120263. ch[t8-1]=cc[t7-1]+tr2;
  120264. ti2=cc[t5]-cc[t6];
  120265. ci2=cc[t7]+(taur*ti2);
  120266. ch[t8]=cc[t7]+ti2;
  120267. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120268. ci3=taui*(cc[t5]+cc[t6]);
  120269. dr2=cr2-ci3;
  120270. dr3=cr2+ci3;
  120271. di2=ci2+cr3;
  120272. di3=ci2-cr3;
  120273. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120274. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120275. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120276. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120277. }
  120278. t1+=ido;
  120279. }
  120280. }
  120281. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120282. float *wa2,float *wa3){
  120283. static float sqrt2=1.414213562373095f;
  120284. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120285. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120286. t0=l1*ido;
  120287. t1=0;
  120288. t2=ido<<2;
  120289. t3=0;
  120290. t6=ido<<1;
  120291. for(k=0;k<l1;k++){
  120292. t4=t3+t6;
  120293. t5=t1;
  120294. tr3=cc[t4-1]+cc[t4-1];
  120295. tr4=cc[t4]+cc[t4];
  120296. tr1=cc[t3]-cc[(t4+=t6)-1];
  120297. tr2=cc[t3]+cc[t4-1];
  120298. ch[t5]=tr2+tr3;
  120299. ch[t5+=t0]=tr1-tr4;
  120300. ch[t5+=t0]=tr2-tr3;
  120301. ch[t5+=t0]=tr1+tr4;
  120302. t1+=ido;
  120303. t3+=t2;
  120304. }
  120305. if(ido<2)return;
  120306. if(ido==2)goto L105;
  120307. t1=0;
  120308. for(k=0;k<l1;k++){
  120309. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120310. t7=t1;
  120311. for(i=2;i<ido;i+=2){
  120312. t2+=2;
  120313. t3+=2;
  120314. t4-=2;
  120315. t5-=2;
  120316. t7+=2;
  120317. ti1=cc[t2]+cc[t5];
  120318. ti2=cc[t2]-cc[t5];
  120319. ti3=cc[t3]-cc[t4];
  120320. tr4=cc[t3]+cc[t4];
  120321. tr1=cc[t2-1]-cc[t5-1];
  120322. tr2=cc[t2-1]+cc[t5-1];
  120323. ti4=cc[t3-1]-cc[t4-1];
  120324. tr3=cc[t3-1]+cc[t4-1];
  120325. ch[t7-1]=tr2+tr3;
  120326. cr3=tr2-tr3;
  120327. ch[t7]=ti2+ti3;
  120328. ci3=ti2-ti3;
  120329. cr2=tr1-tr4;
  120330. cr4=tr1+tr4;
  120331. ci2=ti1+ti4;
  120332. ci4=ti1-ti4;
  120333. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120334. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120335. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120336. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120337. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120338. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120339. }
  120340. t1+=ido;
  120341. }
  120342. if(ido%2 == 1)return;
  120343. L105:
  120344. t1=ido;
  120345. t2=ido<<2;
  120346. t3=ido-1;
  120347. t4=ido+(ido<<1);
  120348. for(k=0;k<l1;k++){
  120349. t5=t3;
  120350. ti1=cc[t1]+cc[t4];
  120351. ti2=cc[t4]-cc[t1];
  120352. tr1=cc[t1-1]-cc[t4-1];
  120353. tr2=cc[t1-1]+cc[t4-1];
  120354. ch[t5]=tr2+tr2;
  120355. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120356. ch[t5+=t0]=ti2+ti2;
  120357. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120358. t3+=ido;
  120359. t1+=t2;
  120360. t4+=t2;
  120361. }
  120362. }
  120363. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120364. float *c2,float *ch,float *ch2,float *wa){
  120365. static float tpi=6.283185307179586f;
  120366. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120367. t11,t12;
  120368. float dc2,ai1,ai2,ar1,ar2,ds2;
  120369. int nbd;
  120370. float dcp,arg,dsp,ar1h,ar2h;
  120371. int ipp2;
  120372. t10=ip*ido;
  120373. t0=l1*ido;
  120374. arg=tpi/(float)ip;
  120375. dcp=cos(arg);
  120376. dsp=sin(arg);
  120377. nbd=(ido-1)>>1;
  120378. ipp2=ip;
  120379. ipph=(ip+1)>>1;
  120380. if(ido<l1)goto L103;
  120381. t1=0;
  120382. t2=0;
  120383. for(k=0;k<l1;k++){
  120384. t3=t1;
  120385. t4=t2;
  120386. for(i=0;i<ido;i++){
  120387. ch[t3]=cc[t4];
  120388. t3++;
  120389. t4++;
  120390. }
  120391. t1+=ido;
  120392. t2+=t10;
  120393. }
  120394. goto L106;
  120395. L103:
  120396. t1=0;
  120397. for(i=0;i<ido;i++){
  120398. t2=t1;
  120399. t3=t1;
  120400. for(k=0;k<l1;k++){
  120401. ch[t2]=cc[t3];
  120402. t2+=ido;
  120403. t3+=t10;
  120404. }
  120405. t1++;
  120406. }
  120407. L106:
  120408. t1=0;
  120409. t2=ipp2*t0;
  120410. t7=(t5=ido<<1);
  120411. for(j=1;j<ipph;j++){
  120412. t1+=t0;
  120413. t2-=t0;
  120414. t3=t1;
  120415. t4=t2;
  120416. t6=t5;
  120417. for(k=0;k<l1;k++){
  120418. ch[t3]=cc[t6-1]+cc[t6-1];
  120419. ch[t4]=cc[t6]+cc[t6];
  120420. t3+=ido;
  120421. t4+=ido;
  120422. t6+=t10;
  120423. }
  120424. t5+=t7;
  120425. }
  120426. if (ido == 1)goto L116;
  120427. if(nbd<l1)goto L112;
  120428. t1=0;
  120429. t2=ipp2*t0;
  120430. t7=0;
  120431. for(j=1;j<ipph;j++){
  120432. t1+=t0;
  120433. t2-=t0;
  120434. t3=t1;
  120435. t4=t2;
  120436. t7+=(ido<<1);
  120437. t8=t7;
  120438. for(k=0;k<l1;k++){
  120439. t5=t3;
  120440. t6=t4;
  120441. t9=t8;
  120442. t11=t8;
  120443. for(i=2;i<ido;i+=2){
  120444. t5+=2;
  120445. t6+=2;
  120446. t9+=2;
  120447. t11-=2;
  120448. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120449. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120450. ch[t5]=cc[t9]-cc[t11];
  120451. ch[t6]=cc[t9]+cc[t11];
  120452. }
  120453. t3+=ido;
  120454. t4+=ido;
  120455. t8+=t10;
  120456. }
  120457. }
  120458. goto L116;
  120459. L112:
  120460. t1=0;
  120461. t2=ipp2*t0;
  120462. t7=0;
  120463. for(j=1;j<ipph;j++){
  120464. t1+=t0;
  120465. t2-=t0;
  120466. t3=t1;
  120467. t4=t2;
  120468. t7+=(ido<<1);
  120469. t8=t7;
  120470. t9=t7;
  120471. for(i=2;i<ido;i+=2){
  120472. t3+=2;
  120473. t4+=2;
  120474. t8+=2;
  120475. t9-=2;
  120476. t5=t3;
  120477. t6=t4;
  120478. t11=t8;
  120479. t12=t9;
  120480. for(k=0;k<l1;k++){
  120481. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120482. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120483. ch[t5]=cc[t11]-cc[t12];
  120484. ch[t6]=cc[t11]+cc[t12];
  120485. t5+=ido;
  120486. t6+=ido;
  120487. t11+=t10;
  120488. t12+=t10;
  120489. }
  120490. }
  120491. }
  120492. L116:
  120493. ar1=1.f;
  120494. ai1=0.f;
  120495. t1=0;
  120496. t9=(t2=ipp2*idl1);
  120497. t3=(ip-1)*idl1;
  120498. for(l=1;l<ipph;l++){
  120499. t1+=idl1;
  120500. t2-=idl1;
  120501. ar1h=dcp*ar1-dsp*ai1;
  120502. ai1=dcp*ai1+dsp*ar1;
  120503. ar1=ar1h;
  120504. t4=t1;
  120505. t5=t2;
  120506. t6=0;
  120507. t7=idl1;
  120508. t8=t3;
  120509. for(ik=0;ik<idl1;ik++){
  120510. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120511. c2[t5++]=ai1*ch2[t8++];
  120512. }
  120513. dc2=ar1;
  120514. ds2=ai1;
  120515. ar2=ar1;
  120516. ai2=ai1;
  120517. t6=idl1;
  120518. t7=t9-idl1;
  120519. for(j=2;j<ipph;j++){
  120520. t6+=idl1;
  120521. t7-=idl1;
  120522. ar2h=dc2*ar2-ds2*ai2;
  120523. ai2=dc2*ai2+ds2*ar2;
  120524. ar2=ar2h;
  120525. t4=t1;
  120526. t5=t2;
  120527. t11=t6;
  120528. t12=t7;
  120529. for(ik=0;ik<idl1;ik++){
  120530. c2[t4++]+=ar2*ch2[t11++];
  120531. c2[t5++]+=ai2*ch2[t12++];
  120532. }
  120533. }
  120534. }
  120535. t1=0;
  120536. for(j=1;j<ipph;j++){
  120537. t1+=idl1;
  120538. t2=t1;
  120539. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120540. }
  120541. t1=0;
  120542. t2=ipp2*t0;
  120543. for(j=1;j<ipph;j++){
  120544. t1+=t0;
  120545. t2-=t0;
  120546. t3=t1;
  120547. t4=t2;
  120548. for(k=0;k<l1;k++){
  120549. ch[t3]=c1[t3]-c1[t4];
  120550. ch[t4]=c1[t3]+c1[t4];
  120551. t3+=ido;
  120552. t4+=ido;
  120553. }
  120554. }
  120555. if(ido==1)goto L132;
  120556. if(nbd<l1)goto L128;
  120557. t1=0;
  120558. t2=ipp2*t0;
  120559. for(j=1;j<ipph;j++){
  120560. t1+=t0;
  120561. t2-=t0;
  120562. t3=t1;
  120563. t4=t2;
  120564. for(k=0;k<l1;k++){
  120565. t5=t3;
  120566. t6=t4;
  120567. for(i=2;i<ido;i+=2){
  120568. t5+=2;
  120569. t6+=2;
  120570. ch[t5-1]=c1[t5-1]-c1[t6];
  120571. ch[t6-1]=c1[t5-1]+c1[t6];
  120572. ch[t5]=c1[t5]+c1[t6-1];
  120573. ch[t6]=c1[t5]-c1[t6-1];
  120574. }
  120575. t3+=ido;
  120576. t4+=ido;
  120577. }
  120578. }
  120579. goto L132;
  120580. L128:
  120581. t1=0;
  120582. t2=ipp2*t0;
  120583. for(j=1;j<ipph;j++){
  120584. t1+=t0;
  120585. t2-=t0;
  120586. t3=t1;
  120587. t4=t2;
  120588. for(i=2;i<ido;i+=2){
  120589. t3+=2;
  120590. t4+=2;
  120591. t5=t3;
  120592. t6=t4;
  120593. for(k=0;k<l1;k++){
  120594. ch[t5-1]=c1[t5-1]-c1[t6];
  120595. ch[t6-1]=c1[t5-1]+c1[t6];
  120596. ch[t5]=c1[t5]+c1[t6-1];
  120597. ch[t6]=c1[t5]-c1[t6-1];
  120598. t5+=ido;
  120599. t6+=ido;
  120600. }
  120601. }
  120602. }
  120603. L132:
  120604. if(ido==1)return;
  120605. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120606. t1=0;
  120607. for(j=1;j<ip;j++){
  120608. t2=(t1+=t0);
  120609. for(k=0;k<l1;k++){
  120610. c1[t2]=ch[t2];
  120611. t2+=ido;
  120612. }
  120613. }
  120614. if(nbd>l1)goto L139;
  120615. is= -ido-1;
  120616. t1=0;
  120617. for(j=1;j<ip;j++){
  120618. is+=ido;
  120619. t1+=t0;
  120620. idij=is;
  120621. t2=t1;
  120622. for(i=2;i<ido;i+=2){
  120623. t2+=2;
  120624. idij+=2;
  120625. t3=t2;
  120626. for(k=0;k<l1;k++){
  120627. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120628. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120629. t3+=ido;
  120630. }
  120631. }
  120632. }
  120633. return;
  120634. L139:
  120635. is= -ido-1;
  120636. t1=0;
  120637. for(j=1;j<ip;j++){
  120638. is+=ido;
  120639. t1+=t0;
  120640. t2=t1;
  120641. for(k=0;k<l1;k++){
  120642. idij=is;
  120643. t3=t2;
  120644. for(i=2;i<ido;i+=2){
  120645. idij+=2;
  120646. t3+=2;
  120647. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120648. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120649. }
  120650. t2+=ido;
  120651. }
  120652. }
  120653. }
  120654. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120655. int i,k1,l1,l2;
  120656. int na;
  120657. int nf,ip,iw,ix2,ix3,ido,idl1;
  120658. nf=ifac[1];
  120659. na=0;
  120660. l1=1;
  120661. iw=1;
  120662. for(k1=0;k1<nf;k1++){
  120663. ip=ifac[k1 + 2];
  120664. l2=ip*l1;
  120665. ido=n/l2;
  120666. idl1=ido*l1;
  120667. if(ip!=4)goto L103;
  120668. ix2=iw+ido;
  120669. ix3=ix2+ido;
  120670. if(na!=0)
  120671. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120672. else
  120673. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120674. na=1-na;
  120675. goto L115;
  120676. L103:
  120677. if(ip!=2)goto L106;
  120678. if(na!=0)
  120679. dradb2(ido,l1,ch,c,wa+iw-1);
  120680. else
  120681. dradb2(ido,l1,c,ch,wa+iw-1);
  120682. na=1-na;
  120683. goto L115;
  120684. L106:
  120685. if(ip!=3)goto L109;
  120686. ix2=iw+ido;
  120687. if(na!=0)
  120688. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120689. else
  120690. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120691. na=1-na;
  120692. goto L115;
  120693. L109:
  120694. /* The radix five case can be translated later..... */
  120695. /* if(ip!=5)goto L112;
  120696. ix2=iw+ido;
  120697. ix3=ix2+ido;
  120698. ix4=ix3+ido;
  120699. if(na!=0)
  120700. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120701. else
  120702. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120703. na=1-na;
  120704. goto L115;
  120705. L112:*/
  120706. if(na!=0)
  120707. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120708. else
  120709. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120710. if(ido==1)na=1-na;
  120711. L115:
  120712. l1=l2;
  120713. iw+=(ip-1)*ido;
  120714. }
  120715. if(na==0)return;
  120716. for(i=0;i<n;i++)c[i]=ch[i];
  120717. }
  120718. void drft_forward(drft_lookup *l,float *data){
  120719. if(l->n==1)return;
  120720. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120721. }
  120722. void drft_backward(drft_lookup *l,float *data){
  120723. if (l->n==1)return;
  120724. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120725. }
  120726. void drft_init(drft_lookup *l,int n){
  120727. l->n=n;
  120728. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120729. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120730. fdrffti(n, l->trigcache, l->splitcache);
  120731. }
  120732. void drft_clear(drft_lookup *l){
  120733. if(l){
  120734. if(l->trigcache)_ogg_free(l->trigcache);
  120735. if(l->splitcache)_ogg_free(l->splitcache);
  120736. memset(l,0,sizeof(*l));
  120737. }
  120738. }
  120739. #endif
  120740. /*** End of inlined file: smallft.c ***/
  120741. /*** Start of inlined file: synthesis.c ***/
  120742. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120743. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120744. // tasks..
  120745. #if JUCE_MSVC
  120746. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120747. #endif
  120748. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120749. #if JUCE_USE_OGGVORBIS
  120750. #include <stdio.h>
  120751. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120752. vorbis_dsp_state *vd=vb->vd;
  120753. private_state *b=(private_state*)vd->backend_state;
  120754. vorbis_info *vi=vd->vi;
  120755. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120756. oggpack_buffer *opb=&vb->opb;
  120757. int type,mode,i;
  120758. /* first things first. Make sure decode is ready */
  120759. _vorbis_block_ripcord(vb);
  120760. oggpack_readinit(opb,op->packet,op->bytes);
  120761. /* Check the packet type */
  120762. if(oggpack_read(opb,1)!=0){
  120763. /* Oops. This is not an audio data packet */
  120764. return(OV_ENOTAUDIO);
  120765. }
  120766. /* read our mode and pre/post windowsize */
  120767. mode=oggpack_read(opb,b->modebits);
  120768. if(mode==-1)return(OV_EBADPACKET);
  120769. vb->mode=mode;
  120770. vb->W=ci->mode_param[mode]->blockflag;
  120771. if(vb->W){
  120772. /* this doesn;t get mapped through mode selection as it's used
  120773. only for window selection */
  120774. vb->lW=oggpack_read(opb,1);
  120775. vb->nW=oggpack_read(opb,1);
  120776. if(vb->nW==-1) return(OV_EBADPACKET);
  120777. }else{
  120778. vb->lW=0;
  120779. vb->nW=0;
  120780. }
  120781. /* more setup */
  120782. vb->granulepos=op->granulepos;
  120783. vb->sequence=op->packetno;
  120784. vb->eofflag=op->e_o_s;
  120785. /* alloc pcm passback storage */
  120786. vb->pcmend=ci->blocksizes[vb->W];
  120787. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120788. for(i=0;i<vi->channels;i++)
  120789. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120790. /* unpack_header enforces range checking */
  120791. type=ci->map_type[ci->mode_param[mode]->mapping];
  120792. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120793. mapping]));
  120794. }
  120795. /* used to track pcm position without actually performing decode.
  120796. Useful for sequential 'fast forward' */
  120797. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120798. vorbis_dsp_state *vd=vb->vd;
  120799. private_state *b=(private_state*)vd->backend_state;
  120800. vorbis_info *vi=vd->vi;
  120801. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120802. oggpack_buffer *opb=&vb->opb;
  120803. int mode;
  120804. /* first things first. Make sure decode is ready */
  120805. _vorbis_block_ripcord(vb);
  120806. oggpack_readinit(opb,op->packet,op->bytes);
  120807. /* Check the packet type */
  120808. if(oggpack_read(opb,1)!=0){
  120809. /* Oops. This is not an audio data packet */
  120810. return(OV_ENOTAUDIO);
  120811. }
  120812. /* read our mode and pre/post windowsize */
  120813. mode=oggpack_read(opb,b->modebits);
  120814. if(mode==-1)return(OV_EBADPACKET);
  120815. vb->mode=mode;
  120816. vb->W=ci->mode_param[mode]->blockflag;
  120817. if(vb->W){
  120818. vb->lW=oggpack_read(opb,1);
  120819. vb->nW=oggpack_read(opb,1);
  120820. if(vb->nW==-1) return(OV_EBADPACKET);
  120821. }else{
  120822. vb->lW=0;
  120823. vb->nW=0;
  120824. }
  120825. /* more setup */
  120826. vb->granulepos=op->granulepos;
  120827. vb->sequence=op->packetno;
  120828. vb->eofflag=op->e_o_s;
  120829. /* no pcm */
  120830. vb->pcmend=0;
  120831. vb->pcm=NULL;
  120832. return(0);
  120833. }
  120834. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120835. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120836. oggpack_buffer opb;
  120837. int mode;
  120838. oggpack_readinit(&opb,op->packet,op->bytes);
  120839. /* Check the packet type */
  120840. if(oggpack_read(&opb,1)!=0){
  120841. /* Oops. This is not an audio data packet */
  120842. return(OV_ENOTAUDIO);
  120843. }
  120844. {
  120845. int modebits=0;
  120846. int v=ci->modes;
  120847. while(v>1){
  120848. modebits++;
  120849. v>>=1;
  120850. }
  120851. /* read our mode and pre/post windowsize */
  120852. mode=oggpack_read(&opb,modebits);
  120853. }
  120854. if(mode==-1)return(OV_EBADPACKET);
  120855. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120856. }
  120857. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120858. /* set / clear half-sample-rate mode */
  120859. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120860. /* right now, our MDCT can't handle < 64 sample windows. */
  120861. if(ci->blocksizes[0]<=64 && flag)return -1;
  120862. ci->halfrate_flag=(flag?1:0);
  120863. return 0;
  120864. }
  120865. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120866. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120867. return ci->halfrate_flag;
  120868. }
  120869. #endif
  120870. /*** End of inlined file: synthesis.c ***/
  120871. /*** Start of inlined file: vorbisenc.c ***/
  120872. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120873. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120874. // tasks..
  120875. #if JUCE_MSVC
  120876. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120877. #endif
  120878. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120879. #if JUCE_USE_OGGVORBIS
  120880. #include <stdlib.h>
  120881. #include <string.h>
  120882. #include <math.h>
  120883. /* careful with this; it's using static array sizing to make managing
  120884. all the modes a little less annoying. If we use a residue backend
  120885. with > 12 partition types, or a different division of iteration,
  120886. this needs to be updated. */
  120887. typedef struct {
  120888. static_codebook *books[12][3];
  120889. } static_bookblock;
  120890. typedef struct {
  120891. int res_type;
  120892. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120893. vorbis_info_residue0 *res;
  120894. static_codebook *book_aux;
  120895. static_codebook *book_aux_managed;
  120896. static_bookblock *books_base;
  120897. static_bookblock *books_base_managed;
  120898. } vorbis_residue_template;
  120899. typedef struct {
  120900. vorbis_info_mapping0 *map;
  120901. vorbis_residue_template *res;
  120902. } vorbis_mapping_template;
  120903. typedef struct vp_adjblock{
  120904. int block[P_BANDS];
  120905. } vp_adjblock;
  120906. typedef struct {
  120907. int data[NOISE_COMPAND_LEVELS];
  120908. } compandblock;
  120909. /* high level configuration information for setting things up
  120910. step-by-step with the detailed vorbis_encode_ctl interface.
  120911. There's a fair amount of redundancy such that interactive setup
  120912. does not directly deal with any vorbis_info or codec_setup_info
  120913. initialization; it's all stored (until full init) in this highlevel
  120914. setup, then flushed out to the real codec setup structs later. */
  120915. typedef struct {
  120916. int att[P_NOISECURVES];
  120917. float boost;
  120918. float decay;
  120919. } att3;
  120920. typedef struct { int data[P_NOISECURVES]; } adj3;
  120921. typedef struct {
  120922. int pre[PACKETBLOBS];
  120923. int post[PACKETBLOBS];
  120924. float kHz[PACKETBLOBS];
  120925. float lowpasskHz[PACKETBLOBS];
  120926. } adj_stereo;
  120927. typedef struct {
  120928. int lo;
  120929. int hi;
  120930. int fixed;
  120931. } noiseguard;
  120932. typedef struct {
  120933. int data[P_NOISECURVES][17];
  120934. } noise3;
  120935. typedef struct {
  120936. int mappings;
  120937. double *rate_mapping;
  120938. double *quality_mapping;
  120939. int coupling_restriction;
  120940. long samplerate_min_restriction;
  120941. long samplerate_max_restriction;
  120942. int *blocksize_short;
  120943. int *blocksize_long;
  120944. att3 *psy_tone_masteratt;
  120945. int *psy_tone_0dB;
  120946. int *psy_tone_dBsuppress;
  120947. vp_adjblock *psy_tone_adj_impulse;
  120948. vp_adjblock *psy_tone_adj_long;
  120949. vp_adjblock *psy_tone_adj_other;
  120950. noiseguard *psy_noiseguards;
  120951. noise3 *psy_noise_bias_impulse;
  120952. noise3 *psy_noise_bias_padding;
  120953. noise3 *psy_noise_bias_trans;
  120954. noise3 *psy_noise_bias_long;
  120955. int *psy_noise_dBsuppress;
  120956. compandblock *psy_noise_compand;
  120957. double *psy_noise_compand_short_mapping;
  120958. double *psy_noise_compand_long_mapping;
  120959. int *psy_noise_normal_start[2];
  120960. int *psy_noise_normal_partition[2];
  120961. double *psy_noise_normal_thresh;
  120962. int *psy_ath_float;
  120963. int *psy_ath_abs;
  120964. double *psy_lowpass;
  120965. vorbis_info_psy_global *global_params;
  120966. double *global_mapping;
  120967. adj_stereo *stereo_modes;
  120968. static_codebook ***floor_books;
  120969. vorbis_info_floor1 *floor_params;
  120970. int *floor_short_mapping;
  120971. int *floor_long_mapping;
  120972. vorbis_mapping_template *maps;
  120973. } ve_setup_data_template;
  120974. /* a few static coder conventions */
  120975. static vorbis_info_mode _mode_template[2]={
  120976. {0,0,0,0},
  120977. {1,0,0,1}
  120978. };
  120979. static vorbis_info_mapping0 _map_nominal[2]={
  120980. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120981. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120982. };
  120983. /*** Start of inlined file: setup_44.h ***/
  120984. /*** Start of inlined file: floor_all.h ***/
  120985. /*** Start of inlined file: floor_books.h ***/
  120986. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120987. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120988. };
  120989. static static_codebook _huff_book_line_256x7_0sub1 = {
  120990. 1, 9,
  120991. _huff_lengthlist_line_256x7_0sub1,
  120992. 0, 0, 0, 0, 0,
  120993. NULL,
  120994. NULL,
  120995. NULL,
  120996. NULL,
  120997. 0
  120998. };
  120999. static long _huff_lengthlist_line_256x7_0sub2[] = {
  121000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  121001. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  121002. };
  121003. static static_codebook _huff_book_line_256x7_0sub2 = {
  121004. 1, 25,
  121005. _huff_lengthlist_line_256x7_0sub2,
  121006. 0, 0, 0, 0, 0,
  121007. NULL,
  121008. NULL,
  121009. NULL,
  121010. NULL,
  121011. 0
  121012. };
  121013. static long _huff_lengthlist_line_256x7_0sub3[] = {
  121014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  121016. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  121017. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  121018. };
  121019. static static_codebook _huff_book_line_256x7_0sub3 = {
  121020. 1, 64,
  121021. _huff_lengthlist_line_256x7_0sub3,
  121022. 0, 0, 0, 0, 0,
  121023. NULL,
  121024. NULL,
  121025. NULL,
  121026. NULL,
  121027. 0
  121028. };
  121029. static long _huff_lengthlist_line_256x7_1sub1[] = {
  121030. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  121031. };
  121032. static static_codebook _huff_book_line_256x7_1sub1 = {
  121033. 1, 9,
  121034. _huff_lengthlist_line_256x7_1sub1,
  121035. 0, 0, 0, 0, 0,
  121036. NULL,
  121037. NULL,
  121038. NULL,
  121039. NULL,
  121040. 0
  121041. };
  121042. static long _huff_lengthlist_line_256x7_1sub2[] = {
  121043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  121044. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  121045. };
  121046. static static_codebook _huff_book_line_256x7_1sub2 = {
  121047. 1, 25,
  121048. _huff_lengthlist_line_256x7_1sub2,
  121049. 0, 0, 0, 0, 0,
  121050. NULL,
  121051. NULL,
  121052. NULL,
  121053. NULL,
  121054. 0
  121055. };
  121056. static long _huff_lengthlist_line_256x7_1sub3[] = {
  121057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  121059. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121060. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  121061. };
  121062. static static_codebook _huff_book_line_256x7_1sub3 = {
  121063. 1, 64,
  121064. _huff_lengthlist_line_256x7_1sub3,
  121065. 0, 0, 0, 0, 0,
  121066. NULL,
  121067. NULL,
  121068. NULL,
  121069. NULL,
  121070. 0
  121071. };
  121072. static long _huff_lengthlist_line_256x7_class0[] = {
  121073. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  121074. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  121075. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  121076. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  121077. };
  121078. static static_codebook _huff_book_line_256x7_class0 = {
  121079. 1, 64,
  121080. _huff_lengthlist_line_256x7_class0,
  121081. 0, 0, 0, 0, 0,
  121082. NULL,
  121083. NULL,
  121084. NULL,
  121085. NULL,
  121086. 0
  121087. };
  121088. static long _huff_lengthlist_line_256x7_class1[] = {
  121089. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  121090. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  121091. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  121092. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  121093. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  121094. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  121095. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  121096. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  121097. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  121098. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  121099. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  121100. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  121101. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121102. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121103. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  121104. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  121105. };
  121106. static static_codebook _huff_book_line_256x7_class1 = {
  121107. 1, 256,
  121108. _huff_lengthlist_line_256x7_class1,
  121109. 0, 0, 0, 0, 0,
  121110. NULL,
  121111. NULL,
  121112. NULL,
  121113. NULL,
  121114. 0
  121115. };
  121116. static long _huff_lengthlist_line_512x17_0sub0[] = {
  121117. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  121118. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  121119. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  121120. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  121121. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  121122. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  121123. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  121124. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121125. };
  121126. static static_codebook _huff_book_line_512x17_0sub0 = {
  121127. 1, 128,
  121128. _huff_lengthlist_line_512x17_0sub0,
  121129. 0, 0, 0, 0, 0,
  121130. NULL,
  121131. NULL,
  121132. NULL,
  121133. NULL,
  121134. 0
  121135. };
  121136. static long _huff_lengthlist_line_512x17_1sub0[] = {
  121137. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121138. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  121139. };
  121140. static static_codebook _huff_book_line_512x17_1sub0 = {
  121141. 1, 32,
  121142. _huff_lengthlist_line_512x17_1sub0,
  121143. 0, 0, 0, 0, 0,
  121144. NULL,
  121145. NULL,
  121146. NULL,
  121147. NULL,
  121148. 0
  121149. };
  121150. static long _huff_lengthlist_line_512x17_1sub1[] = {
  121151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121153. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  121154. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  121155. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  121156. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  121157. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  121158. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121159. };
  121160. static static_codebook _huff_book_line_512x17_1sub1 = {
  121161. 1, 128,
  121162. _huff_lengthlist_line_512x17_1sub1,
  121163. 0, 0, 0, 0, 0,
  121164. NULL,
  121165. NULL,
  121166. NULL,
  121167. NULL,
  121168. 0
  121169. };
  121170. static long _huff_lengthlist_line_512x17_2sub1[] = {
  121171. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  121172. 5, 3,
  121173. };
  121174. static static_codebook _huff_book_line_512x17_2sub1 = {
  121175. 1, 18,
  121176. _huff_lengthlist_line_512x17_2sub1,
  121177. 0, 0, 0, 0, 0,
  121178. NULL,
  121179. NULL,
  121180. NULL,
  121181. NULL,
  121182. 0
  121183. };
  121184. static long _huff_lengthlist_line_512x17_2sub2[] = {
  121185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121186. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  121187. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  121188. 9, 8,
  121189. };
  121190. static static_codebook _huff_book_line_512x17_2sub2 = {
  121191. 1, 50,
  121192. _huff_lengthlist_line_512x17_2sub2,
  121193. 0, 0, 0, 0, 0,
  121194. NULL,
  121195. NULL,
  121196. NULL,
  121197. NULL,
  121198. 0
  121199. };
  121200. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121204. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121205. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121206. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121207. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121208. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121209. };
  121210. static static_codebook _huff_book_line_512x17_2sub3 = {
  121211. 1, 128,
  121212. _huff_lengthlist_line_512x17_2sub3,
  121213. 0, 0, 0, 0, 0,
  121214. NULL,
  121215. NULL,
  121216. NULL,
  121217. NULL,
  121218. 0
  121219. };
  121220. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121221. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121222. 5, 5,
  121223. };
  121224. static static_codebook _huff_book_line_512x17_3sub1 = {
  121225. 1, 18,
  121226. _huff_lengthlist_line_512x17_3sub1,
  121227. 0, 0, 0, 0, 0,
  121228. NULL,
  121229. NULL,
  121230. NULL,
  121231. NULL,
  121232. 0
  121233. };
  121234. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121236. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121237. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121238. 11,14,
  121239. };
  121240. static static_codebook _huff_book_line_512x17_3sub2 = {
  121241. 1, 50,
  121242. _huff_lengthlist_line_512x17_3sub2,
  121243. 0, 0, 0, 0, 0,
  121244. NULL,
  121245. NULL,
  121246. NULL,
  121247. NULL,
  121248. 0
  121249. };
  121250. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121254. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121255. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121256. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121257. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121258. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121259. };
  121260. static static_codebook _huff_book_line_512x17_3sub3 = {
  121261. 1, 128,
  121262. _huff_lengthlist_line_512x17_3sub3,
  121263. 0, 0, 0, 0, 0,
  121264. NULL,
  121265. NULL,
  121266. NULL,
  121267. NULL,
  121268. 0
  121269. };
  121270. static long _huff_lengthlist_line_512x17_class1[] = {
  121271. 1, 2, 3, 6, 5, 4, 7, 7,
  121272. };
  121273. static static_codebook _huff_book_line_512x17_class1 = {
  121274. 1, 8,
  121275. _huff_lengthlist_line_512x17_class1,
  121276. 0, 0, 0, 0, 0,
  121277. NULL,
  121278. NULL,
  121279. NULL,
  121280. NULL,
  121281. 0
  121282. };
  121283. static long _huff_lengthlist_line_512x17_class2[] = {
  121284. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121285. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121286. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121287. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121288. };
  121289. static static_codebook _huff_book_line_512x17_class2 = {
  121290. 1, 64,
  121291. _huff_lengthlist_line_512x17_class2,
  121292. 0, 0, 0, 0, 0,
  121293. NULL,
  121294. NULL,
  121295. NULL,
  121296. NULL,
  121297. 0
  121298. };
  121299. static long _huff_lengthlist_line_512x17_class3[] = {
  121300. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121301. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121302. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121303. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121304. };
  121305. static static_codebook _huff_book_line_512x17_class3 = {
  121306. 1, 64,
  121307. _huff_lengthlist_line_512x17_class3,
  121308. 0, 0, 0, 0, 0,
  121309. NULL,
  121310. NULL,
  121311. NULL,
  121312. NULL,
  121313. 0
  121314. };
  121315. static long _huff_lengthlist_line_128x4_class0[] = {
  121316. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121317. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121318. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121319. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121320. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121321. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121322. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121323. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121324. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121325. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121326. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121327. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121328. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121329. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121330. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121331. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121332. };
  121333. static static_codebook _huff_book_line_128x4_class0 = {
  121334. 1, 256,
  121335. _huff_lengthlist_line_128x4_class0,
  121336. 0, 0, 0, 0, 0,
  121337. NULL,
  121338. NULL,
  121339. NULL,
  121340. NULL,
  121341. 0
  121342. };
  121343. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121344. 2, 2, 2, 2,
  121345. };
  121346. static static_codebook _huff_book_line_128x4_0sub0 = {
  121347. 1, 4,
  121348. _huff_lengthlist_line_128x4_0sub0,
  121349. 0, 0, 0, 0, 0,
  121350. NULL,
  121351. NULL,
  121352. NULL,
  121353. NULL,
  121354. 0
  121355. };
  121356. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121357. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121358. };
  121359. static static_codebook _huff_book_line_128x4_0sub1 = {
  121360. 1, 10,
  121361. _huff_lengthlist_line_128x4_0sub1,
  121362. 0, 0, 0, 0, 0,
  121363. NULL,
  121364. NULL,
  121365. NULL,
  121366. NULL,
  121367. 0
  121368. };
  121369. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121371. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121372. };
  121373. static static_codebook _huff_book_line_128x4_0sub2 = {
  121374. 1, 25,
  121375. _huff_lengthlist_line_128x4_0sub2,
  121376. 0, 0, 0, 0, 0,
  121377. NULL,
  121378. NULL,
  121379. NULL,
  121380. NULL,
  121381. 0
  121382. };
  121383. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121386. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121387. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121388. };
  121389. static static_codebook _huff_book_line_128x4_0sub3 = {
  121390. 1, 64,
  121391. _huff_lengthlist_line_128x4_0sub3,
  121392. 0, 0, 0, 0, 0,
  121393. NULL,
  121394. NULL,
  121395. NULL,
  121396. NULL,
  121397. 0
  121398. };
  121399. static long _huff_lengthlist_line_256x4_class0[] = {
  121400. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121401. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121402. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121403. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121404. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121405. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121406. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121407. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121408. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121409. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121410. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121411. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121412. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121413. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121414. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121415. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121416. };
  121417. static static_codebook _huff_book_line_256x4_class0 = {
  121418. 1, 256,
  121419. _huff_lengthlist_line_256x4_class0,
  121420. 0, 0, 0, 0, 0,
  121421. NULL,
  121422. NULL,
  121423. NULL,
  121424. NULL,
  121425. 0
  121426. };
  121427. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121428. 2, 2, 2, 2,
  121429. };
  121430. static static_codebook _huff_book_line_256x4_0sub0 = {
  121431. 1, 4,
  121432. _huff_lengthlist_line_256x4_0sub0,
  121433. 0, 0, 0, 0, 0,
  121434. NULL,
  121435. NULL,
  121436. NULL,
  121437. NULL,
  121438. 0
  121439. };
  121440. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121441. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121442. };
  121443. static static_codebook _huff_book_line_256x4_0sub1 = {
  121444. 1, 10,
  121445. _huff_lengthlist_line_256x4_0sub1,
  121446. 0, 0, 0, 0, 0,
  121447. NULL,
  121448. NULL,
  121449. NULL,
  121450. NULL,
  121451. 0
  121452. };
  121453. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121455. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121456. };
  121457. static static_codebook _huff_book_line_256x4_0sub2 = {
  121458. 1, 25,
  121459. _huff_lengthlist_line_256x4_0sub2,
  121460. 0, 0, 0, 0, 0,
  121461. NULL,
  121462. NULL,
  121463. NULL,
  121464. NULL,
  121465. 0
  121466. };
  121467. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121470. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121471. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121472. };
  121473. static static_codebook _huff_book_line_256x4_0sub3 = {
  121474. 1, 64,
  121475. _huff_lengthlist_line_256x4_0sub3,
  121476. 0, 0, 0, 0, 0,
  121477. NULL,
  121478. NULL,
  121479. NULL,
  121480. NULL,
  121481. 0
  121482. };
  121483. static long _huff_lengthlist_line_128x7_class0[] = {
  121484. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121485. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121486. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121487. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121488. };
  121489. static static_codebook _huff_book_line_128x7_class0 = {
  121490. 1, 64,
  121491. _huff_lengthlist_line_128x7_class0,
  121492. 0, 0, 0, 0, 0,
  121493. NULL,
  121494. NULL,
  121495. NULL,
  121496. NULL,
  121497. 0
  121498. };
  121499. static long _huff_lengthlist_line_128x7_class1[] = {
  121500. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121501. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121502. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121503. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121504. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121505. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121506. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121507. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121508. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121509. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121510. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121511. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121512. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121513. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121514. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121515. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121516. };
  121517. static static_codebook _huff_book_line_128x7_class1 = {
  121518. 1, 256,
  121519. _huff_lengthlist_line_128x7_class1,
  121520. 0, 0, 0, 0, 0,
  121521. NULL,
  121522. NULL,
  121523. NULL,
  121524. NULL,
  121525. 0
  121526. };
  121527. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121528. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121529. };
  121530. static static_codebook _huff_book_line_128x7_0sub1 = {
  121531. 1, 9,
  121532. _huff_lengthlist_line_128x7_0sub1,
  121533. 0, 0, 0, 0, 0,
  121534. NULL,
  121535. NULL,
  121536. NULL,
  121537. NULL,
  121538. 0
  121539. };
  121540. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121542. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121543. };
  121544. static static_codebook _huff_book_line_128x7_0sub2 = {
  121545. 1, 25,
  121546. _huff_lengthlist_line_128x7_0sub2,
  121547. 0, 0, 0, 0, 0,
  121548. NULL,
  121549. NULL,
  121550. NULL,
  121551. NULL,
  121552. 0
  121553. };
  121554. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121557. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121558. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121559. };
  121560. static static_codebook _huff_book_line_128x7_0sub3 = {
  121561. 1, 64,
  121562. _huff_lengthlist_line_128x7_0sub3,
  121563. 0, 0, 0, 0, 0,
  121564. NULL,
  121565. NULL,
  121566. NULL,
  121567. NULL,
  121568. 0
  121569. };
  121570. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121571. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121572. };
  121573. static static_codebook _huff_book_line_128x7_1sub1 = {
  121574. 1, 9,
  121575. _huff_lengthlist_line_128x7_1sub1,
  121576. 0, 0, 0, 0, 0,
  121577. NULL,
  121578. NULL,
  121579. NULL,
  121580. NULL,
  121581. 0
  121582. };
  121583. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121585. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121586. };
  121587. static static_codebook _huff_book_line_128x7_1sub2 = {
  121588. 1, 25,
  121589. _huff_lengthlist_line_128x7_1sub2,
  121590. 0, 0, 0, 0, 0,
  121591. NULL,
  121592. NULL,
  121593. NULL,
  121594. NULL,
  121595. 0
  121596. };
  121597. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121600. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121601. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121602. };
  121603. static static_codebook _huff_book_line_128x7_1sub3 = {
  121604. 1, 64,
  121605. _huff_lengthlist_line_128x7_1sub3,
  121606. 0, 0, 0, 0, 0,
  121607. NULL,
  121608. NULL,
  121609. NULL,
  121610. NULL,
  121611. 0
  121612. };
  121613. static long _huff_lengthlist_line_128x11_class1[] = {
  121614. 1, 6, 3, 7, 2, 4, 5, 7,
  121615. };
  121616. static static_codebook _huff_book_line_128x11_class1 = {
  121617. 1, 8,
  121618. _huff_lengthlist_line_128x11_class1,
  121619. 0, 0, 0, 0, 0,
  121620. NULL,
  121621. NULL,
  121622. NULL,
  121623. NULL,
  121624. 0
  121625. };
  121626. static long _huff_lengthlist_line_128x11_class2[] = {
  121627. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121628. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121629. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121630. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121631. };
  121632. static static_codebook _huff_book_line_128x11_class2 = {
  121633. 1, 64,
  121634. _huff_lengthlist_line_128x11_class2,
  121635. 0, 0, 0, 0, 0,
  121636. NULL,
  121637. NULL,
  121638. NULL,
  121639. NULL,
  121640. 0
  121641. };
  121642. static long _huff_lengthlist_line_128x11_class3[] = {
  121643. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121644. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121645. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121646. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121647. };
  121648. static static_codebook _huff_book_line_128x11_class3 = {
  121649. 1, 64,
  121650. _huff_lengthlist_line_128x11_class3,
  121651. 0, 0, 0, 0, 0,
  121652. NULL,
  121653. NULL,
  121654. NULL,
  121655. NULL,
  121656. 0
  121657. };
  121658. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121659. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121660. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121661. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121662. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121663. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121664. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121665. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121666. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121667. };
  121668. static static_codebook _huff_book_line_128x11_0sub0 = {
  121669. 1, 128,
  121670. _huff_lengthlist_line_128x11_0sub0,
  121671. 0, 0, 0, 0, 0,
  121672. NULL,
  121673. NULL,
  121674. NULL,
  121675. NULL,
  121676. 0
  121677. };
  121678. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121679. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121680. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121681. };
  121682. static static_codebook _huff_book_line_128x11_1sub0 = {
  121683. 1, 32,
  121684. _huff_lengthlist_line_128x11_1sub0,
  121685. 0, 0, 0, 0, 0,
  121686. NULL,
  121687. NULL,
  121688. NULL,
  121689. NULL,
  121690. 0
  121691. };
  121692. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121695. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121696. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121697. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121698. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121699. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121700. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121701. };
  121702. static static_codebook _huff_book_line_128x11_1sub1 = {
  121703. 1, 128,
  121704. _huff_lengthlist_line_128x11_1sub1,
  121705. 0, 0, 0, 0, 0,
  121706. NULL,
  121707. NULL,
  121708. NULL,
  121709. NULL,
  121710. 0
  121711. };
  121712. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121713. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121714. 5, 5,
  121715. };
  121716. static static_codebook _huff_book_line_128x11_2sub1 = {
  121717. 1, 18,
  121718. _huff_lengthlist_line_128x11_2sub1,
  121719. 0, 0, 0, 0, 0,
  121720. NULL,
  121721. NULL,
  121722. NULL,
  121723. NULL,
  121724. 0
  121725. };
  121726. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121728. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121729. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121730. 8,11,
  121731. };
  121732. static static_codebook _huff_book_line_128x11_2sub2 = {
  121733. 1, 50,
  121734. _huff_lengthlist_line_128x11_2sub2,
  121735. 0, 0, 0, 0, 0,
  121736. NULL,
  121737. NULL,
  121738. NULL,
  121739. NULL,
  121740. 0
  121741. };
  121742. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121746. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121747. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121748. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121749. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121750. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121751. };
  121752. static static_codebook _huff_book_line_128x11_2sub3 = {
  121753. 1, 128,
  121754. _huff_lengthlist_line_128x11_2sub3,
  121755. 0, 0, 0, 0, 0,
  121756. NULL,
  121757. NULL,
  121758. NULL,
  121759. NULL,
  121760. 0
  121761. };
  121762. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121763. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121764. 5, 4,
  121765. };
  121766. static static_codebook _huff_book_line_128x11_3sub1 = {
  121767. 1, 18,
  121768. _huff_lengthlist_line_128x11_3sub1,
  121769. 0, 0, 0, 0, 0,
  121770. NULL,
  121771. NULL,
  121772. NULL,
  121773. NULL,
  121774. 0
  121775. };
  121776. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121779. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121780. 12, 6,
  121781. };
  121782. static static_codebook _huff_book_line_128x11_3sub2 = {
  121783. 1, 50,
  121784. _huff_lengthlist_line_128x11_3sub2,
  121785. 0, 0, 0, 0, 0,
  121786. NULL,
  121787. NULL,
  121788. NULL,
  121789. NULL,
  121790. 0
  121791. };
  121792. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121796. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121797. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121798. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121799. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121800. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121801. };
  121802. static static_codebook _huff_book_line_128x11_3sub3 = {
  121803. 1, 128,
  121804. _huff_lengthlist_line_128x11_3sub3,
  121805. 0, 0, 0, 0, 0,
  121806. NULL,
  121807. NULL,
  121808. NULL,
  121809. NULL,
  121810. 0
  121811. };
  121812. static long _huff_lengthlist_line_128x17_class1[] = {
  121813. 1, 3, 4, 7, 2, 5, 6, 7,
  121814. };
  121815. static static_codebook _huff_book_line_128x17_class1 = {
  121816. 1, 8,
  121817. _huff_lengthlist_line_128x17_class1,
  121818. 0, 0, 0, 0, 0,
  121819. NULL,
  121820. NULL,
  121821. NULL,
  121822. NULL,
  121823. 0
  121824. };
  121825. static long _huff_lengthlist_line_128x17_class2[] = {
  121826. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121827. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121828. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121829. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121830. };
  121831. static static_codebook _huff_book_line_128x17_class2 = {
  121832. 1, 64,
  121833. _huff_lengthlist_line_128x17_class2,
  121834. 0, 0, 0, 0, 0,
  121835. NULL,
  121836. NULL,
  121837. NULL,
  121838. NULL,
  121839. 0
  121840. };
  121841. static long _huff_lengthlist_line_128x17_class3[] = {
  121842. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121843. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121844. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121845. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121846. };
  121847. static static_codebook _huff_book_line_128x17_class3 = {
  121848. 1, 64,
  121849. _huff_lengthlist_line_128x17_class3,
  121850. 0, 0, 0, 0, 0,
  121851. NULL,
  121852. NULL,
  121853. NULL,
  121854. NULL,
  121855. 0
  121856. };
  121857. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121858. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121859. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121860. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121861. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121862. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121863. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121864. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121865. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121866. };
  121867. static static_codebook _huff_book_line_128x17_0sub0 = {
  121868. 1, 128,
  121869. _huff_lengthlist_line_128x17_0sub0,
  121870. 0, 0, 0, 0, 0,
  121871. NULL,
  121872. NULL,
  121873. NULL,
  121874. NULL,
  121875. 0
  121876. };
  121877. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121878. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121879. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121880. };
  121881. static static_codebook _huff_book_line_128x17_1sub0 = {
  121882. 1, 32,
  121883. _huff_lengthlist_line_128x17_1sub0,
  121884. 0, 0, 0, 0, 0,
  121885. NULL,
  121886. NULL,
  121887. NULL,
  121888. NULL,
  121889. 0
  121890. };
  121891. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121894. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121895. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121896. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121897. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121898. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121899. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121900. };
  121901. static static_codebook _huff_book_line_128x17_1sub1 = {
  121902. 1, 128,
  121903. _huff_lengthlist_line_128x17_1sub1,
  121904. 0, 0, 0, 0, 0,
  121905. NULL,
  121906. NULL,
  121907. NULL,
  121908. NULL,
  121909. 0
  121910. };
  121911. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121912. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121913. 9, 4,
  121914. };
  121915. static static_codebook _huff_book_line_128x17_2sub1 = {
  121916. 1, 18,
  121917. _huff_lengthlist_line_128x17_2sub1,
  121918. 0, 0, 0, 0, 0,
  121919. NULL,
  121920. NULL,
  121921. NULL,
  121922. NULL,
  121923. 0
  121924. };
  121925. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121927. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121928. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121929. 13,13,
  121930. };
  121931. static static_codebook _huff_book_line_128x17_2sub2 = {
  121932. 1, 50,
  121933. _huff_lengthlist_line_128x17_2sub2,
  121934. 0, 0, 0, 0, 0,
  121935. NULL,
  121936. NULL,
  121937. NULL,
  121938. NULL,
  121939. 0
  121940. };
  121941. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121945. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121946. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121947. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121948. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121949. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121950. };
  121951. static static_codebook _huff_book_line_128x17_2sub3 = {
  121952. 1, 128,
  121953. _huff_lengthlist_line_128x17_2sub3,
  121954. 0, 0, 0, 0, 0,
  121955. NULL,
  121956. NULL,
  121957. NULL,
  121958. NULL,
  121959. 0
  121960. };
  121961. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121962. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121963. 6, 4,
  121964. };
  121965. static static_codebook _huff_book_line_128x17_3sub1 = {
  121966. 1, 18,
  121967. _huff_lengthlist_line_128x17_3sub1,
  121968. 0, 0, 0, 0, 0,
  121969. NULL,
  121970. NULL,
  121971. NULL,
  121972. NULL,
  121973. 0
  121974. };
  121975. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121977. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121978. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121979. 10, 8,
  121980. };
  121981. static static_codebook _huff_book_line_128x17_3sub2 = {
  121982. 1, 50,
  121983. _huff_lengthlist_line_128x17_3sub2,
  121984. 0, 0, 0, 0, 0,
  121985. NULL,
  121986. NULL,
  121987. NULL,
  121988. NULL,
  121989. 0
  121990. };
  121991. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121995. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121996. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121997. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121998. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121999. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122000. };
  122001. static static_codebook _huff_book_line_128x17_3sub3 = {
  122002. 1, 128,
  122003. _huff_lengthlist_line_128x17_3sub3,
  122004. 0, 0, 0, 0, 0,
  122005. NULL,
  122006. NULL,
  122007. NULL,
  122008. NULL,
  122009. 0
  122010. };
  122011. static long _huff_lengthlist_line_1024x27_class1[] = {
  122012. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  122013. };
  122014. static static_codebook _huff_book_line_1024x27_class1 = {
  122015. 1, 16,
  122016. _huff_lengthlist_line_1024x27_class1,
  122017. 0, 0, 0, 0, 0,
  122018. NULL,
  122019. NULL,
  122020. NULL,
  122021. NULL,
  122022. 0
  122023. };
  122024. static long _huff_lengthlist_line_1024x27_class2[] = {
  122025. 1, 4, 2, 6, 3, 7, 5, 7,
  122026. };
  122027. static static_codebook _huff_book_line_1024x27_class2 = {
  122028. 1, 8,
  122029. _huff_lengthlist_line_1024x27_class2,
  122030. 0, 0, 0, 0, 0,
  122031. NULL,
  122032. NULL,
  122033. NULL,
  122034. NULL,
  122035. 0
  122036. };
  122037. static long _huff_lengthlist_line_1024x27_class3[] = {
  122038. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  122039. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  122040. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  122041. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  122042. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  122043. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  122044. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  122045. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  122046. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  122047. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  122048. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  122049. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122050. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  122051. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  122052. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  122053. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122054. };
  122055. static static_codebook _huff_book_line_1024x27_class3 = {
  122056. 1, 256,
  122057. _huff_lengthlist_line_1024x27_class3,
  122058. 0, 0, 0, 0, 0,
  122059. NULL,
  122060. NULL,
  122061. NULL,
  122062. NULL,
  122063. 0
  122064. };
  122065. static long _huff_lengthlist_line_1024x27_class4[] = {
  122066. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  122067. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  122068. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  122069. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  122070. };
  122071. static static_codebook _huff_book_line_1024x27_class4 = {
  122072. 1, 64,
  122073. _huff_lengthlist_line_1024x27_class4,
  122074. 0, 0, 0, 0, 0,
  122075. NULL,
  122076. NULL,
  122077. NULL,
  122078. NULL,
  122079. 0
  122080. };
  122081. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  122082. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122083. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  122084. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  122085. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  122086. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  122087. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  122088. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  122089. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  122090. };
  122091. static static_codebook _huff_book_line_1024x27_0sub0 = {
  122092. 1, 128,
  122093. _huff_lengthlist_line_1024x27_0sub0,
  122094. 0, 0, 0, 0, 0,
  122095. NULL,
  122096. NULL,
  122097. NULL,
  122098. NULL,
  122099. 0
  122100. };
  122101. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  122102. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  122103. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  122104. };
  122105. static static_codebook _huff_book_line_1024x27_1sub0 = {
  122106. 1, 32,
  122107. _huff_lengthlist_line_1024x27_1sub0,
  122108. 0, 0, 0, 0, 0,
  122109. NULL,
  122110. NULL,
  122111. NULL,
  122112. NULL,
  122113. 0
  122114. };
  122115. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  122116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122118. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  122119. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  122120. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  122121. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  122122. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  122123. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  122124. };
  122125. static static_codebook _huff_book_line_1024x27_1sub1 = {
  122126. 1, 128,
  122127. _huff_lengthlist_line_1024x27_1sub1,
  122128. 0, 0, 0, 0, 0,
  122129. NULL,
  122130. NULL,
  122131. NULL,
  122132. NULL,
  122133. 0
  122134. };
  122135. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  122136. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122137. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  122138. };
  122139. static static_codebook _huff_book_line_1024x27_2sub0 = {
  122140. 1, 32,
  122141. _huff_lengthlist_line_1024x27_2sub0,
  122142. 0, 0, 0, 0, 0,
  122143. NULL,
  122144. NULL,
  122145. NULL,
  122146. NULL,
  122147. 0
  122148. };
  122149. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  122150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122152. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  122153. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  122154. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  122155. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  122156. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  122157. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  122158. };
  122159. static static_codebook _huff_book_line_1024x27_2sub1 = {
  122160. 1, 128,
  122161. _huff_lengthlist_line_1024x27_2sub1,
  122162. 0, 0, 0, 0, 0,
  122163. NULL,
  122164. NULL,
  122165. NULL,
  122166. NULL,
  122167. 0
  122168. };
  122169. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  122170. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  122171. 5, 5,
  122172. };
  122173. static static_codebook _huff_book_line_1024x27_3sub1 = {
  122174. 1, 18,
  122175. _huff_lengthlist_line_1024x27_3sub1,
  122176. 0, 0, 0, 0, 0,
  122177. NULL,
  122178. NULL,
  122179. NULL,
  122180. NULL,
  122181. 0
  122182. };
  122183. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  122184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122185. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  122186. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  122187. 9,11,
  122188. };
  122189. static static_codebook _huff_book_line_1024x27_3sub2 = {
  122190. 1, 50,
  122191. _huff_lengthlist_line_1024x27_3sub2,
  122192. 0, 0, 0, 0, 0,
  122193. NULL,
  122194. NULL,
  122195. NULL,
  122196. NULL,
  122197. 0
  122198. };
  122199. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122203. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122204. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122205. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122206. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122207. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122208. };
  122209. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122210. 1, 128,
  122211. _huff_lengthlist_line_1024x27_3sub3,
  122212. 0, 0, 0, 0, 0,
  122213. NULL,
  122214. NULL,
  122215. NULL,
  122216. NULL,
  122217. 0
  122218. };
  122219. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122220. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122221. 5, 4,
  122222. };
  122223. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122224. 1, 18,
  122225. _huff_lengthlist_line_1024x27_4sub1,
  122226. 0, 0, 0, 0, 0,
  122227. NULL,
  122228. NULL,
  122229. NULL,
  122230. NULL,
  122231. 0
  122232. };
  122233. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122235. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122236. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122237. 9,12,
  122238. };
  122239. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122240. 1, 50,
  122241. _huff_lengthlist_line_1024x27_4sub2,
  122242. 0, 0, 0, 0, 0,
  122243. NULL,
  122244. NULL,
  122245. NULL,
  122246. NULL,
  122247. 0
  122248. };
  122249. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122253. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122254. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122255. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122256. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122257. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122258. };
  122259. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122260. 1, 128,
  122261. _huff_lengthlist_line_1024x27_4sub3,
  122262. 0, 0, 0, 0, 0,
  122263. NULL,
  122264. NULL,
  122265. NULL,
  122266. NULL,
  122267. 0
  122268. };
  122269. static long _huff_lengthlist_line_2048x27_class1[] = {
  122270. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122271. };
  122272. static static_codebook _huff_book_line_2048x27_class1 = {
  122273. 1, 16,
  122274. _huff_lengthlist_line_2048x27_class1,
  122275. 0, 0, 0, 0, 0,
  122276. NULL,
  122277. NULL,
  122278. NULL,
  122279. NULL,
  122280. 0
  122281. };
  122282. static long _huff_lengthlist_line_2048x27_class2[] = {
  122283. 1, 2, 3, 6, 4, 7, 5, 7,
  122284. };
  122285. static static_codebook _huff_book_line_2048x27_class2 = {
  122286. 1, 8,
  122287. _huff_lengthlist_line_2048x27_class2,
  122288. 0, 0, 0, 0, 0,
  122289. NULL,
  122290. NULL,
  122291. NULL,
  122292. NULL,
  122293. 0
  122294. };
  122295. static long _huff_lengthlist_line_2048x27_class3[] = {
  122296. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122297. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122298. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122299. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122300. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122301. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122302. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122303. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122304. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122305. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122306. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122307. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122308. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122309. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122310. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122311. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122312. };
  122313. static static_codebook _huff_book_line_2048x27_class3 = {
  122314. 1, 256,
  122315. _huff_lengthlist_line_2048x27_class3,
  122316. 0, 0, 0, 0, 0,
  122317. NULL,
  122318. NULL,
  122319. NULL,
  122320. NULL,
  122321. 0
  122322. };
  122323. static long _huff_lengthlist_line_2048x27_class4[] = {
  122324. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122325. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122326. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122327. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122328. };
  122329. static static_codebook _huff_book_line_2048x27_class4 = {
  122330. 1, 64,
  122331. _huff_lengthlist_line_2048x27_class4,
  122332. 0, 0, 0, 0, 0,
  122333. NULL,
  122334. NULL,
  122335. NULL,
  122336. NULL,
  122337. 0
  122338. };
  122339. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122340. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122341. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122342. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122343. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122344. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122345. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122346. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122347. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122348. };
  122349. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122350. 1, 128,
  122351. _huff_lengthlist_line_2048x27_0sub0,
  122352. 0, 0, 0, 0, 0,
  122353. NULL,
  122354. NULL,
  122355. NULL,
  122356. NULL,
  122357. 0
  122358. };
  122359. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122360. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122361. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122362. };
  122363. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122364. 1, 32,
  122365. _huff_lengthlist_line_2048x27_1sub0,
  122366. 0, 0, 0, 0, 0,
  122367. NULL,
  122368. NULL,
  122369. NULL,
  122370. NULL,
  122371. 0
  122372. };
  122373. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122376. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122377. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122378. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122379. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122380. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122381. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122382. };
  122383. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122384. 1, 128,
  122385. _huff_lengthlist_line_2048x27_1sub1,
  122386. 0, 0, 0, 0, 0,
  122387. NULL,
  122388. NULL,
  122389. NULL,
  122390. NULL,
  122391. 0
  122392. };
  122393. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122394. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122395. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122396. };
  122397. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122398. 1, 32,
  122399. _huff_lengthlist_line_2048x27_2sub0,
  122400. 0, 0, 0, 0, 0,
  122401. NULL,
  122402. NULL,
  122403. NULL,
  122404. NULL,
  122405. 0
  122406. };
  122407. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122410. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122411. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122412. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122413. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122414. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122415. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122416. };
  122417. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122418. 1, 128,
  122419. _huff_lengthlist_line_2048x27_2sub1,
  122420. 0, 0, 0, 0, 0,
  122421. NULL,
  122422. NULL,
  122423. NULL,
  122424. NULL,
  122425. 0
  122426. };
  122427. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122428. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122429. 5, 5,
  122430. };
  122431. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122432. 1, 18,
  122433. _huff_lengthlist_line_2048x27_3sub1,
  122434. 0, 0, 0, 0, 0,
  122435. NULL,
  122436. NULL,
  122437. NULL,
  122438. NULL,
  122439. 0
  122440. };
  122441. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122444. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122445. 10,12,
  122446. };
  122447. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122448. 1, 50,
  122449. _huff_lengthlist_line_2048x27_3sub2,
  122450. 0, 0, 0, 0, 0,
  122451. NULL,
  122452. NULL,
  122453. NULL,
  122454. NULL,
  122455. 0
  122456. };
  122457. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122461. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122462. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122463. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122464. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122465. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122466. };
  122467. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122468. 1, 128,
  122469. _huff_lengthlist_line_2048x27_3sub3,
  122470. 0, 0, 0, 0, 0,
  122471. NULL,
  122472. NULL,
  122473. NULL,
  122474. NULL,
  122475. 0
  122476. };
  122477. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122478. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122479. 4, 5,
  122480. };
  122481. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122482. 1, 18,
  122483. _huff_lengthlist_line_2048x27_4sub1,
  122484. 0, 0, 0, 0, 0,
  122485. NULL,
  122486. NULL,
  122487. NULL,
  122488. NULL,
  122489. 0
  122490. };
  122491. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122493. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122494. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122495. 10,10,
  122496. };
  122497. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122498. 1, 50,
  122499. _huff_lengthlist_line_2048x27_4sub2,
  122500. 0, 0, 0, 0, 0,
  122501. NULL,
  122502. NULL,
  122503. NULL,
  122504. NULL,
  122505. 0
  122506. };
  122507. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122511. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122512. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122513. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122514. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122515. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122516. };
  122517. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122518. 1, 128,
  122519. _huff_lengthlist_line_2048x27_4sub3,
  122520. 0, 0, 0, 0, 0,
  122521. NULL,
  122522. NULL,
  122523. NULL,
  122524. NULL,
  122525. 0
  122526. };
  122527. static long _huff_lengthlist_line_256x4low_class0[] = {
  122528. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122529. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122530. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122531. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122532. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122533. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122534. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122535. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122536. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122537. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122538. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122539. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122540. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122541. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122542. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122543. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122544. };
  122545. static static_codebook _huff_book_line_256x4low_class0 = {
  122546. 1, 256,
  122547. _huff_lengthlist_line_256x4low_class0,
  122548. 0, 0, 0, 0, 0,
  122549. NULL,
  122550. NULL,
  122551. NULL,
  122552. NULL,
  122553. 0
  122554. };
  122555. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122556. 1, 3, 2, 3,
  122557. };
  122558. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122559. 1, 4,
  122560. _huff_lengthlist_line_256x4low_0sub0,
  122561. 0, 0, 0, 0, 0,
  122562. NULL,
  122563. NULL,
  122564. NULL,
  122565. NULL,
  122566. 0
  122567. };
  122568. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122569. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122570. };
  122571. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122572. 1, 10,
  122573. _huff_lengthlist_line_256x4low_0sub1,
  122574. 0, 0, 0, 0, 0,
  122575. NULL,
  122576. NULL,
  122577. NULL,
  122578. NULL,
  122579. 0
  122580. };
  122581. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122583. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122584. };
  122585. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122586. 1, 25,
  122587. _huff_lengthlist_line_256x4low_0sub2,
  122588. 0, 0, 0, 0, 0,
  122589. NULL,
  122590. NULL,
  122591. NULL,
  122592. NULL,
  122593. 0
  122594. };
  122595. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  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, 3, 4, 2, 4, 3, 5, 4,
  122598. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122599. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122600. };
  122601. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122602. 1, 64,
  122603. _huff_lengthlist_line_256x4low_0sub3,
  122604. 0, 0, 0, 0, 0,
  122605. NULL,
  122606. NULL,
  122607. NULL,
  122608. NULL,
  122609. 0
  122610. };
  122611. /*** End of inlined file: floor_books.h ***/
  122612. static static_codebook *_floor_128x4_books[]={
  122613. &_huff_book_line_128x4_class0,
  122614. &_huff_book_line_128x4_0sub0,
  122615. &_huff_book_line_128x4_0sub1,
  122616. &_huff_book_line_128x4_0sub2,
  122617. &_huff_book_line_128x4_0sub3,
  122618. };
  122619. static static_codebook *_floor_256x4_books[]={
  122620. &_huff_book_line_256x4_class0,
  122621. &_huff_book_line_256x4_0sub0,
  122622. &_huff_book_line_256x4_0sub1,
  122623. &_huff_book_line_256x4_0sub2,
  122624. &_huff_book_line_256x4_0sub3,
  122625. };
  122626. static static_codebook *_floor_128x7_books[]={
  122627. &_huff_book_line_128x7_class0,
  122628. &_huff_book_line_128x7_class1,
  122629. &_huff_book_line_128x7_0sub1,
  122630. &_huff_book_line_128x7_0sub2,
  122631. &_huff_book_line_128x7_0sub3,
  122632. &_huff_book_line_128x7_1sub1,
  122633. &_huff_book_line_128x7_1sub2,
  122634. &_huff_book_line_128x7_1sub3,
  122635. };
  122636. static static_codebook *_floor_256x7_books[]={
  122637. &_huff_book_line_256x7_class0,
  122638. &_huff_book_line_256x7_class1,
  122639. &_huff_book_line_256x7_0sub1,
  122640. &_huff_book_line_256x7_0sub2,
  122641. &_huff_book_line_256x7_0sub3,
  122642. &_huff_book_line_256x7_1sub1,
  122643. &_huff_book_line_256x7_1sub2,
  122644. &_huff_book_line_256x7_1sub3,
  122645. };
  122646. static static_codebook *_floor_128x11_books[]={
  122647. &_huff_book_line_128x11_class1,
  122648. &_huff_book_line_128x11_class2,
  122649. &_huff_book_line_128x11_class3,
  122650. &_huff_book_line_128x11_0sub0,
  122651. &_huff_book_line_128x11_1sub0,
  122652. &_huff_book_line_128x11_1sub1,
  122653. &_huff_book_line_128x11_2sub1,
  122654. &_huff_book_line_128x11_2sub2,
  122655. &_huff_book_line_128x11_2sub3,
  122656. &_huff_book_line_128x11_3sub1,
  122657. &_huff_book_line_128x11_3sub2,
  122658. &_huff_book_line_128x11_3sub3,
  122659. };
  122660. static static_codebook *_floor_128x17_books[]={
  122661. &_huff_book_line_128x17_class1,
  122662. &_huff_book_line_128x17_class2,
  122663. &_huff_book_line_128x17_class3,
  122664. &_huff_book_line_128x17_0sub0,
  122665. &_huff_book_line_128x17_1sub0,
  122666. &_huff_book_line_128x17_1sub1,
  122667. &_huff_book_line_128x17_2sub1,
  122668. &_huff_book_line_128x17_2sub2,
  122669. &_huff_book_line_128x17_2sub3,
  122670. &_huff_book_line_128x17_3sub1,
  122671. &_huff_book_line_128x17_3sub2,
  122672. &_huff_book_line_128x17_3sub3,
  122673. };
  122674. static static_codebook *_floor_256x4low_books[]={
  122675. &_huff_book_line_256x4low_class0,
  122676. &_huff_book_line_256x4low_0sub0,
  122677. &_huff_book_line_256x4low_0sub1,
  122678. &_huff_book_line_256x4low_0sub2,
  122679. &_huff_book_line_256x4low_0sub3,
  122680. };
  122681. static static_codebook *_floor_1024x27_books[]={
  122682. &_huff_book_line_1024x27_class1,
  122683. &_huff_book_line_1024x27_class2,
  122684. &_huff_book_line_1024x27_class3,
  122685. &_huff_book_line_1024x27_class4,
  122686. &_huff_book_line_1024x27_0sub0,
  122687. &_huff_book_line_1024x27_1sub0,
  122688. &_huff_book_line_1024x27_1sub1,
  122689. &_huff_book_line_1024x27_2sub0,
  122690. &_huff_book_line_1024x27_2sub1,
  122691. &_huff_book_line_1024x27_3sub1,
  122692. &_huff_book_line_1024x27_3sub2,
  122693. &_huff_book_line_1024x27_3sub3,
  122694. &_huff_book_line_1024x27_4sub1,
  122695. &_huff_book_line_1024x27_4sub2,
  122696. &_huff_book_line_1024x27_4sub3,
  122697. };
  122698. static static_codebook *_floor_2048x27_books[]={
  122699. &_huff_book_line_2048x27_class1,
  122700. &_huff_book_line_2048x27_class2,
  122701. &_huff_book_line_2048x27_class3,
  122702. &_huff_book_line_2048x27_class4,
  122703. &_huff_book_line_2048x27_0sub0,
  122704. &_huff_book_line_2048x27_1sub0,
  122705. &_huff_book_line_2048x27_1sub1,
  122706. &_huff_book_line_2048x27_2sub0,
  122707. &_huff_book_line_2048x27_2sub1,
  122708. &_huff_book_line_2048x27_3sub1,
  122709. &_huff_book_line_2048x27_3sub2,
  122710. &_huff_book_line_2048x27_3sub3,
  122711. &_huff_book_line_2048x27_4sub1,
  122712. &_huff_book_line_2048x27_4sub2,
  122713. &_huff_book_line_2048x27_4sub3,
  122714. };
  122715. static static_codebook *_floor_512x17_books[]={
  122716. &_huff_book_line_512x17_class1,
  122717. &_huff_book_line_512x17_class2,
  122718. &_huff_book_line_512x17_class3,
  122719. &_huff_book_line_512x17_0sub0,
  122720. &_huff_book_line_512x17_1sub0,
  122721. &_huff_book_line_512x17_1sub1,
  122722. &_huff_book_line_512x17_2sub1,
  122723. &_huff_book_line_512x17_2sub2,
  122724. &_huff_book_line_512x17_2sub3,
  122725. &_huff_book_line_512x17_3sub1,
  122726. &_huff_book_line_512x17_3sub2,
  122727. &_huff_book_line_512x17_3sub3,
  122728. };
  122729. static static_codebook **_floor_books[10]={
  122730. _floor_128x4_books,
  122731. _floor_256x4_books,
  122732. _floor_128x7_books,
  122733. _floor_256x7_books,
  122734. _floor_128x11_books,
  122735. _floor_128x17_books,
  122736. _floor_256x4low_books,
  122737. _floor_1024x27_books,
  122738. _floor_2048x27_books,
  122739. _floor_512x17_books,
  122740. };
  122741. static vorbis_info_floor1 _floor[10]={
  122742. /* 128 x 4 */
  122743. {
  122744. 1,{0},{4},{2},{0},
  122745. {{1,2,3,4}},
  122746. 4,{0,128, 33,8,16,70},
  122747. 60,30,500, 1.,18., -1
  122748. },
  122749. /* 256 x 4 */
  122750. {
  122751. 1,{0},{4},{2},{0},
  122752. {{1,2,3,4}},
  122753. 4,{0,256, 66,16,32,140},
  122754. 60,30,500, 1.,18., -1
  122755. },
  122756. /* 128 x 7 */
  122757. {
  122758. 2,{0,1},{3,4},{2,2},{0,1},
  122759. {{-1,2,3,4},{-1,5,6,7}},
  122760. 4,{0,128, 14,4,58, 2,8,28,90},
  122761. 60,30,500, 1.,18., -1
  122762. },
  122763. /* 256 x 7 */
  122764. {
  122765. 2,{0,1},{3,4},{2,2},{0,1},
  122766. {{-1,2,3,4},{-1,5,6,7}},
  122767. 4,{0,256, 28,8,116, 4,16,56,180},
  122768. 60,30,500, 1.,18., -1
  122769. },
  122770. /* 128 x 11 */
  122771. {
  122772. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122773. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122774. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122775. 60,30,500, 1,18., -1
  122776. },
  122777. /* 128 x 17 */
  122778. {
  122779. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122780. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122781. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122782. 60,30,500, 1,18., -1
  122783. },
  122784. /* 256 x 4 (low bitrate version) */
  122785. {
  122786. 1,{0},{4},{2},{0},
  122787. {{1,2,3,4}},
  122788. 4,{0,256, 66,16,32,140},
  122789. 60,30,500, 1.,18., -1
  122790. },
  122791. /* 1024 x 27 */
  122792. {
  122793. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122794. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122795. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122796. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122797. 60,30,500, 3,18., -1 /* lowpass */
  122798. },
  122799. /* 2048 x 27 */
  122800. {
  122801. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122802. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122803. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122804. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122805. 60,30,500, 3,18., -1 /* lowpass */
  122806. },
  122807. /* 512 x 17 */
  122808. {
  122809. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122810. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122811. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122812. 7,23,39, 55,79,110, 156,232,360},
  122813. 60,30,500, 1,18., -1 /* lowpass! */
  122814. },
  122815. };
  122816. /*** End of inlined file: floor_all.h ***/
  122817. /*** Start of inlined file: residue_44.h ***/
  122818. /*** Start of inlined file: res_books_stereo.h ***/
  122819. static long _vq_quantlist__16c0_s_p1_0[] = {
  122820. 1,
  122821. 0,
  122822. 2,
  122823. };
  122824. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122825. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122826. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122831. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122836. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  122871. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  122876. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  122881. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122917. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122922. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122927. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123235. 0,
  123236. };
  123237. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123238. -0.5, 0.5,
  123239. };
  123240. static long _vq_quantmap__16c0_s_p1_0[] = {
  123241. 1, 0, 2,
  123242. };
  123243. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123244. _vq_quantthresh__16c0_s_p1_0,
  123245. _vq_quantmap__16c0_s_p1_0,
  123246. 3,
  123247. 3
  123248. };
  123249. static static_codebook _16c0_s_p1_0 = {
  123250. 8, 6561,
  123251. _vq_lengthlist__16c0_s_p1_0,
  123252. 1, -535822336, 1611661312, 2, 0,
  123253. _vq_quantlist__16c0_s_p1_0,
  123254. NULL,
  123255. &_vq_auxt__16c0_s_p1_0,
  123256. NULL,
  123257. 0
  123258. };
  123259. static long _vq_quantlist__16c0_s_p2_0[] = {
  123260. 2,
  123261. 1,
  123262. 3,
  123263. 0,
  123264. 4,
  123265. };
  123266. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123306. 0,
  123307. };
  123308. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123309. -1.5, -0.5, 0.5, 1.5,
  123310. };
  123311. static long _vq_quantmap__16c0_s_p2_0[] = {
  123312. 3, 1, 0, 2, 4,
  123313. };
  123314. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123315. _vq_quantthresh__16c0_s_p2_0,
  123316. _vq_quantmap__16c0_s_p2_0,
  123317. 5,
  123318. 5
  123319. };
  123320. static static_codebook _16c0_s_p2_0 = {
  123321. 4, 625,
  123322. _vq_lengthlist__16c0_s_p2_0,
  123323. 1, -533725184, 1611661312, 3, 0,
  123324. _vq_quantlist__16c0_s_p2_0,
  123325. NULL,
  123326. &_vq_auxt__16c0_s_p2_0,
  123327. NULL,
  123328. 0
  123329. };
  123330. static long _vq_quantlist__16c0_s_p3_0[] = {
  123331. 2,
  123332. 1,
  123333. 3,
  123334. 0,
  123335. 4,
  123336. };
  123337. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123338. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123341. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123344. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123377. 0,
  123378. };
  123379. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123380. -1.5, -0.5, 0.5, 1.5,
  123381. };
  123382. static long _vq_quantmap__16c0_s_p3_0[] = {
  123383. 3, 1, 0, 2, 4,
  123384. };
  123385. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123386. _vq_quantthresh__16c0_s_p3_0,
  123387. _vq_quantmap__16c0_s_p3_0,
  123388. 5,
  123389. 5
  123390. };
  123391. static static_codebook _16c0_s_p3_0 = {
  123392. 4, 625,
  123393. _vq_lengthlist__16c0_s_p3_0,
  123394. 1, -533725184, 1611661312, 3, 0,
  123395. _vq_quantlist__16c0_s_p3_0,
  123396. NULL,
  123397. &_vq_auxt__16c0_s_p3_0,
  123398. NULL,
  123399. 0
  123400. };
  123401. static long _vq_quantlist__16c0_s_p4_0[] = {
  123402. 4,
  123403. 3,
  123404. 5,
  123405. 2,
  123406. 6,
  123407. 1,
  123408. 7,
  123409. 0,
  123410. 8,
  123411. };
  123412. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123413. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123414. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123415. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123416. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123417. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123418. 0,
  123419. };
  123420. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123421. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123422. };
  123423. static long _vq_quantmap__16c0_s_p4_0[] = {
  123424. 7, 5, 3, 1, 0, 2, 4, 6,
  123425. 8,
  123426. };
  123427. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123428. _vq_quantthresh__16c0_s_p4_0,
  123429. _vq_quantmap__16c0_s_p4_0,
  123430. 9,
  123431. 9
  123432. };
  123433. static static_codebook _16c0_s_p4_0 = {
  123434. 2, 81,
  123435. _vq_lengthlist__16c0_s_p4_0,
  123436. 1, -531628032, 1611661312, 4, 0,
  123437. _vq_quantlist__16c0_s_p4_0,
  123438. NULL,
  123439. &_vq_auxt__16c0_s_p4_0,
  123440. NULL,
  123441. 0
  123442. };
  123443. static long _vq_quantlist__16c0_s_p5_0[] = {
  123444. 4,
  123445. 3,
  123446. 5,
  123447. 2,
  123448. 6,
  123449. 1,
  123450. 7,
  123451. 0,
  123452. 8,
  123453. };
  123454. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123455. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123456. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123457. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123458. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123459. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123460. 10,
  123461. };
  123462. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123463. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123464. };
  123465. static long _vq_quantmap__16c0_s_p5_0[] = {
  123466. 7, 5, 3, 1, 0, 2, 4, 6,
  123467. 8,
  123468. };
  123469. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123470. _vq_quantthresh__16c0_s_p5_0,
  123471. _vq_quantmap__16c0_s_p5_0,
  123472. 9,
  123473. 9
  123474. };
  123475. static static_codebook _16c0_s_p5_0 = {
  123476. 2, 81,
  123477. _vq_lengthlist__16c0_s_p5_0,
  123478. 1, -531628032, 1611661312, 4, 0,
  123479. _vq_quantlist__16c0_s_p5_0,
  123480. NULL,
  123481. &_vq_auxt__16c0_s_p5_0,
  123482. NULL,
  123483. 0
  123484. };
  123485. static long _vq_quantlist__16c0_s_p6_0[] = {
  123486. 8,
  123487. 7,
  123488. 9,
  123489. 6,
  123490. 10,
  123491. 5,
  123492. 11,
  123493. 4,
  123494. 12,
  123495. 3,
  123496. 13,
  123497. 2,
  123498. 14,
  123499. 1,
  123500. 15,
  123501. 0,
  123502. 16,
  123503. };
  123504. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123505. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123506. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123507. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123508. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123509. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123510. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123511. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123512. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123513. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123514. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123515. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123516. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123517. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123518. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123519. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123520. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123521. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123522. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123523. 14,
  123524. };
  123525. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123526. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123527. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123528. };
  123529. static long _vq_quantmap__16c0_s_p6_0[] = {
  123530. 15, 13, 11, 9, 7, 5, 3, 1,
  123531. 0, 2, 4, 6, 8, 10, 12, 14,
  123532. 16,
  123533. };
  123534. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123535. _vq_quantthresh__16c0_s_p6_0,
  123536. _vq_quantmap__16c0_s_p6_0,
  123537. 17,
  123538. 17
  123539. };
  123540. static static_codebook _16c0_s_p6_0 = {
  123541. 2, 289,
  123542. _vq_lengthlist__16c0_s_p6_0,
  123543. 1, -529530880, 1611661312, 5, 0,
  123544. _vq_quantlist__16c0_s_p6_0,
  123545. NULL,
  123546. &_vq_auxt__16c0_s_p6_0,
  123547. NULL,
  123548. 0
  123549. };
  123550. static long _vq_quantlist__16c0_s_p7_0[] = {
  123551. 1,
  123552. 0,
  123553. 2,
  123554. };
  123555. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123556. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123557. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123558. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123559. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123560. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123561. 13,
  123562. };
  123563. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123564. -5.5, 5.5,
  123565. };
  123566. static long _vq_quantmap__16c0_s_p7_0[] = {
  123567. 1, 0, 2,
  123568. };
  123569. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123570. _vq_quantthresh__16c0_s_p7_0,
  123571. _vq_quantmap__16c0_s_p7_0,
  123572. 3,
  123573. 3
  123574. };
  123575. static static_codebook _16c0_s_p7_0 = {
  123576. 4, 81,
  123577. _vq_lengthlist__16c0_s_p7_0,
  123578. 1, -529137664, 1618345984, 2, 0,
  123579. _vq_quantlist__16c0_s_p7_0,
  123580. NULL,
  123581. &_vq_auxt__16c0_s_p7_0,
  123582. NULL,
  123583. 0
  123584. };
  123585. static long _vq_quantlist__16c0_s_p7_1[] = {
  123586. 5,
  123587. 4,
  123588. 6,
  123589. 3,
  123590. 7,
  123591. 2,
  123592. 8,
  123593. 1,
  123594. 9,
  123595. 0,
  123596. 10,
  123597. };
  123598. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123599. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123600. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123601. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123602. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123603. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123604. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123605. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123606. 11,11,11, 9, 9, 9, 9,10,10,
  123607. };
  123608. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123609. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123610. 3.5, 4.5,
  123611. };
  123612. static long _vq_quantmap__16c0_s_p7_1[] = {
  123613. 9, 7, 5, 3, 1, 0, 2, 4,
  123614. 6, 8, 10,
  123615. };
  123616. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123617. _vq_quantthresh__16c0_s_p7_1,
  123618. _vq_quantmap__16c0_s_p7_1,
  123619. 11,
  123620. 11
  123621. };
  123622. static static_codebook _16c0_s_p7_1 = {
  123623. 2, 121,
  123624. _vq_lengthlist__16c0_s_p7_1,
  123625. 1, -531365888, 1611661312, 4, 0,
  123626. _vq_quantlist__16c0_s_p7_1,
  123627. NULL,
  123628. &_vq_auxt__16c0_s_p7_1,
  123629. NULL,
  123630. 0
  123631. };
  123632. static long _vq_quantlist__16c0_s_p8_0[] = {
  123633. 6,
  123634. 5,
  123635. 7,
  123636. 4,
  123637. 8,
  123638. 3,
  123639. 9,
  123640. 2,
  123641. 10,
  123642. 1,
  123643. 11,
  123644. 0,
  123645. 12,
  123646. };
  123647. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123648. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123649. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123650. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123651. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123652. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123653. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123654. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123655. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123656. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123657. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123658. 0,12,13,13,12,13,14,14,14,
  123659. };
  123660. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123661. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123662. 12.5, 17.5, 22.5, 27.5,
  123663. };
  123664. static long _vq_quantmap__16c0_s_p8_0[] = {
  123665. 11, 9, 7, 5, 3, 1, 0, 2,
  123666. 4, 6, 8, 10, 12,
  123667. };
  123668. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123669. _vq_quantthresh__16c0_s_p8_0,
  123670. _vq_quantmap__16c0_s_p8_0,
  123671. 13,
  123672. 13
  123673. };
  123674. static static_codebook _16c0_s_p8_0 = {
  123675. 2, 169,
  123676. _vq_lengthlist__16c0_s_p8_0,
  123677. 1, -526516224, 1616117760, 4, 0,
  123678. _vq_quantlist__16c0_s_p8_0,
  123679. NULL,
  123680. &_vq_auxt__16c0_s_p8_0,
  123681. NULL,
  123682. 0
  123683. };
  123684. static long _vq_quantlist__16c0_s_p8_1[] = {
  123685. 2,
  123686. 1,
  123687. 3,
  123688. 0,
  123689. 4,
  123690. };
  123691. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123692. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123693. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123694. };
  123695. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123696. -1.5, -0.5, 0.5, 1.5,
  123697. };
  123698. static long _vq_quantmap__16c0_s_p8_1[] = {
  123699. 3, 1, 0, 2, 4,
  123700. };
  123701. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123702. _vq_quantthresh__16c0_s_p8_1,
  123703. _vq_quantmap__16c0_s_p8_1,
  123704. 5,
  123705. 5
  123706. };
  123707. static static_codebook _16c0_s_p8_1 = {
  123708. 2, 25,
  123709. _vq_lengthlist__16c0_s_p8_1,
  123710. 1, -533725184, 1611661312, 3, 0,
  123711. _vq_quantlist__16c0_s_p8_1,
  123712. NULL,
  123713. &_vq_auxt__16c0_s_p8_1,
  123714. NULL,
  123715. 0
  123716. };
  123717. static long _vq_quantlist__16c0_s_p9_0[] = {
  123718. 1,
  123719. 0,
  123720. 2,
  123721. };
  123722. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123723. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123724. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123725. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123726. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123727. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123728. 7,
  123729. };
  123730. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123731. -157.5, 157.5,
  123732. };
  123733. static long _vq_quantmap__16c0_s_p9_0[] = {
  123734. 1, 0, 2,
  123735. };
  123736. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123737. _vq_quantthresh__16c0_s_p9_0,
  123738. _vq_quantmap__16c0_s_p9_0,
  123739. 3,
  123740. 3
  123741. };
  123742. static static_codebook _16c0_s_p9_0 = {
  123743. 4, 81,
  123744. _vq_lengthlist__16c0_s_p9_0,
  123745. 1, -518803456, 1628680192, 2, 0,
  123746. _vq_quantlist__16c0_s_p9_0,
  123747. NULL,
  123748. &_vq_auxt__16c0_s_p9_0,
  123749. NULL,
  123750. 0
  123751. };
  123752. static long _vq_quantlist__16c0_s_p9_1[] = {
  123753. 7,
  123754. 6,
  123755. 8,
  123756. 5,
  123757. 9,
  123758. 4,
  123759. 10,
  123760. 3,
  123761. 11,
  123762. 2,
  123763. 12,
  123764. 1,
  123765. 13,
  123766. 0,
  123767. 14,
  123768. };
  123769. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123770. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123771. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123772. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123773. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123774. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123775. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123776. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123777. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123778. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123779. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123780. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123781. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123782. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123783. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123784. 10,
  123785. };
  123786. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123787. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123788. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123789. };
  123790. static long _vq_quantmap__16c0_s_p9_1[] = {
  123791. 13, 11, 9, 7, 5, 3, 1, 0,
  123792. 2, 4, 6, 8, 10, 12, 14,
  123793. };
  123794. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123795. _vq_quantthresh__16c0_s_p9_1,
  123796. _vq_quantmap__16c0_s_p9_1,
  123797. 15,
  123798. 15
  123799. };
  123800. static static_codebook _16c0_s_p9_1 = {
  123801. 2, 225,
  123802. _vq_lengthlist__16c0_s_p9_1,
  123803. 1, -520986624, 1620377600, 4, 0,
  123804. _vq_quantlist__16c0_s_p9_1,
  123805. NULL,
  123806. &_vq_auxt__16c0_s_p9_1,
  123807. NULL,
  123808. 0
  123809. };
  123810. static long _vq_quantlist__16c0_s_p9_2[] = {
  123811. 10,
  123812. 9,
  123813. 11,
  123814. 8,
  123815. 12,
  123816. 7,
  123817. 13,
  123818. 6,
  123819. 14,
  123820. 5,
  123821. 15,
  123822. 4,
  123823. 16,
  123824. 3,
  123825. 17,
  123826. 2,
  123827. 18,
  123828. 1,
  123829. 19,
  123830. 0,
  123831. 20,
  123832. };
  123833. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123834. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123835. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123836. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123837. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123838. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123839. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123840. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123841. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123842. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123843. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123844. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123845. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123846. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123847. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123848. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123849. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123850. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123851. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123852. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123853. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123854. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123855. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123856. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123857. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123858. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123859. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123860. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123861. 10,11,10,10,11, 9,10,10,10,
  123862. };
  123863. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123864. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123865. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123866. 6.5, 7.5, 8.5, 9.5,
  123867. };
  123868. static long _vq_quantmap__16c0_s_p9_2[] = {
  123869. 19, 17, 15, 13, 11, 9, 7, 5,
  123870. 3, 1, 0, 2, 4, 6, 8, 10,
  123871. 12, 14, 16, 18, 20,
  123872. };
  123873. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123874. _vq_quantthresh__16c0_s_p9_2,
  123875. _vq_quantmap__16c0_s_p9_2,
  123876. 21,
  123877. 21
  123878. };
  123879. static static_codebook _16c0_s_p9_2 = {
  123880. 2, 441,
  123881. _vq_lengthlist__16c0_s_p9_2,
  123882. 1, -529268736, 1611661312, 5, 0,
  123883. _vq_quantlist__16c0_s_p9_2,
  123884. NULL,
  123885. &_vq_auxt__16c0_s_p9_2,
  123886. NULL,
  123887. 0
  123888. };
  123889. static long _huff_lengthlist__16c0_s_single[] = {
  123890. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123891. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123892. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123893. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123894. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123895. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123896. 16,16,18,18,
  123897. };
  123898. static static_codebook _huff_book__16c0_s_single = {
  123899. 2, 100,
  123900. _huff_lengthlist__16c0_s_single,
  123901. 0, 0, 0, 0, 0,
  123902. NULL,
  123903. NULL,
  123904. NULL,
  123905. NULL,
  123906. 0
  123907. };
  123908. static long _huff_lengthlist__16c1_s_long[] = {
  123909. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123910. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123911. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123912. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123913. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123914. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123915. 12,11,11,13,
  123916. };
  123917. static static_codebook _huff_book__16c1_s_long = {
  123918. 2, 100,
  123919. _huff_lengthlist__16c1_s_long,
  123920. 0, 0, 0, 0, 0,
  123921. NULL,
  123922. NULL,
  123923. NULL,
  123924. NULL,
  123925. 0
  123926. };
  123927. static long _vq_quantlist__16c1_s_p1_0[] = {
  123928. 1,
  123929. 0,
  123930. 2,
  123931. };
  123932. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123933. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123934. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123939. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123944. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  123979. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  123984. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  123989. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124025. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  124030. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  124035. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124343. 0,
  124344. };
  124345. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124346. -0.5, 0.5,
  124347. };
  124348. static long _vq_quantmap__16c1_s_p1_0[] = {
  124349. 1, 0, 2,
  124350. };
  124351. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124352. _vq_quantthresh__16c1_s_p1_0,
  124353. _vq_quantmap__16c1_s_p1_0,
  124354. 3,
  124355. 3
  124356. };
  124357. static static_codebook _16c1_s_p1_0 = {
  124358. 8, 6561,
  124359. _vq_lengthlist__16c1_s_p1_0,
  124360. 1, -535822336, 1611661312, 2, 0,
  124361. _vq_quantlist__16c1_s_p1_0,
  124362. NULL,
  124363. &_vq_auxt__16c1_s_p1_0,
  124364. NULL,
  124365. 0
  124366. };
  124367. static long _vq_quantlist__16c1_s_p2_0[] = {
  124368. 2,
  124369. 1,
  124370. 3,
  124371. 0,
  124372. 4,
  124373. };
  124374. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124414. 0,
  124415. };
  124416. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124417. -1.5, -0.5, 0.5, 1.5,
  124418. };
  124419. static long _vq_quantmap__16c1_s_p2_0[] = {
  124420. 3, 1, 0, 2, 4,
  124421. };
  124422. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124423. _vq_quantthresh__16c1_s_p2_0,
  124424. _vq_quantmap__16c1_s_p2_0,
  124425. 5,
  124426. 5
  124427. };
  124428. static static_codebook _16c1_s_p2_0 = {
  124429. 4, 625,
  124430. _vq_lengthlist__16c1_s_p2_0,
  124431. 1, -533725184, 1611661312, 3, 0,
  124432. _vq_quantlist__16c1_s_p2_0,
  124433. NULL,
  124434. &_vq_auxt__16c1_s_p2_0,
  124435. NULL,
  124436. 0
  124437. };
  124438. static long _vq_quantlist__16c1_s_p3_0[] = {
  124439. 2,
  124440. 1,
  124441. 3,
  124442. 0,
  124443. 4,
  124444. };
  124445. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124446. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124449. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124452. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124485. 0,
  124486. };
  124487. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124488. -1.5, -0.5, 0.5, 1.5,
  124489. };
  124490. static long _vq_quantmap__16c1_s_p3_0[] = {
  124491. 3, 1, 0, 2, 4,
  124492. };
  124493. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124494. _vq_quantthresh__16c1_s_p3_0,
  124495. _vq_quantmap__16c1_s_p3_0,
  124496. 5,
  124497. 5
  124498. };
  124499. static static_codebook _16c1_s_p3_0 = {
  124500. 4, 625,
  124501. _vq_lengthlist__16c1_s_p3_0,
  124502. 1, -533725184, 1611661312, 3, 0,
  124503. _vq_quantlist__16c1_s_p3_0,
  124504. NULL,
  124505. &_vq_auxt__16c1_s_p3_0,
  124506. NULL,
  124507. 0
  124508. };
  124509. static long _vq_quantlist__16c1_s_p4_0[] = {
  124510. 4,
  124511. 3,
  124512. 5,
  124513. 2,
  124514. 6,
  124515. 1,
  124516. 7,
  124517. 0,
  124518. 8,
  124519. };
  124520. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124521. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124522. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124523. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124524. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124525. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124526. 0,
  124527. };
  124528. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124529. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124530. };
  124531. static long _vq_quantmap__16c1_s_p4_0[] = {
  124532. 7, 5, 3, 1, 0, 2, 4, 6,
  124533. 8,
  124534. };
  124535. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124536. _vq_quantthresh__16c1_s_p4_0,
  124537. _vq_quantmap__16c1_s_p4_0,
  124538. 9,
  124539. 9
  124540. };
  124541. static static_codebook _16c1_s_p4_0 = {
  124542. 2, 81,
  124543. _vq_lengthlist__16c1_s_p4_0,
  124544. 1, -531628032, 1611661312, 4, 0,
  124545. _vq_quantlist__16c1_s_p4_0,
  124546. NULL,
  124547. &_vq_auxt__16c1_s_p4_0,
  124548. NULL,
  124549. 0
  124550. };
  124551. static long _vq_quantlist__16c1_s_p5_0[] = {
  124552. 4,
  124553. 3,
  124554. 5,
  124555. 2,
  124556. 6,
  124557. 1,
  124558. 7,
  124559. 0,
  124560. 8,
  124561. };
  124562. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124563. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124564. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124565. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124566. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124567. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124568. 10,
  124569. };
  124570. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124571. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124572. };
  124573. static long _vq_quantmap__16c1_s_p5_0[] = {
  124574. 7, 5, 3, 1, 0, 2, 4, 6,
  124575. 8,
  124576. };
  124577. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124578. _vq_quantthresh__16c1_s_p5_0,
  124579. _vq_quantmap__16c1_s_p5_0,
  124580. 9,
  124581. 9
  124582. };
  124583. static static_codebook _16c1_s_p5_0 = {
  124584. 2, 81,
  124585. _vq_lengthlist__16c1_s_p5_0,
  124586. 1, -531628032, 1611661312, 4, 0,
  124587. _vq_quantlist__16c1_s_p5_0,
  124588. NULL,
  124589. &_vq_auxt__16c1_s_p5_0,
  124590. NULL,
  124591. 0
  124592. };
  124593. static long _vq_quantlist__16c1_s_p6_0[] = {
  124594. 8,
  124595. 7,
  124596. 9,
  124597. 6,
  124598. 10,
  124599. 5,
  124600. 11,
  124601. 4,
  124602. 12,
  124603. 3,
  124604. 13,
  124605. 2,
  124606. 14,
  124607. 1,
  124608. 15,
  124609. 0,
  124610. 16,
  124611. };
  124612. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124613. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124614. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124615. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124616. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124617. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124618. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124619. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124620. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124621. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124622. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124623. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124624. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124625. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124626. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124627. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124628. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124629. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124630. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124631. 14,
  124632. };
  124633. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124634. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124635. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124636. };
  124637. static long _vq_quantmap__16c1_s_p6_0[] = {
  124638. 15, 13, 11, 9, 7, 5, 3, 1,
  124639. 0, 2, 4, 6, 8, 10, 12, 14,
  124640. 16,
  124641. };
  124642. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124643. _vq_quantthresh__16c1_s_p6_0,
  124644. _vq_quantmap__16c1_s_p6_0,
  124645. 17,
  124646. 17
  124647. };
  124648. static static_codebook _16c1_s_p6_0 = {
  124649. 2, 289,
  124650. _vq_lengthlist__16c1_s_p6_0,
  124651. 1, -529530880, 1611661312, 5, 0,
  124652. _vq_quantlist__16c1_s_p6_0,
  124653. NULL,
  124654. &_vq_auxt__16c1_s_p6_0,
  124655. NULL,
  124656. 0
  124657. };
  124658. static long _vq_quantlist__16c1_s_p7_0[] = {
  124659. 1,
  124660. 0,
  124661. 2,
  124662. };
  124663. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124664. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124665. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124666. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124667. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124668. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124669. 11,
  124670. };
  124671. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124672. -5.5, 5.5,
  124673. };
  124674. static long _vq_quantmap__16c1_s_p7_0[] = {
  124675. 1, 0, 2,
  124676. };
  124677. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124678. _vq_quantthresh__16c1_s_p7_0,
  124679. _vq_quantmap__16c1_s_p7_0,
  124680. 3,
  124681. 3
  124682. };
  124683. static static_codebook _16c1_s_p7_0 = {
  124684. 4, 81,
  124685. _vq_lengthlist__16c1_s_p7_0,
  124686. 1, -529137664, 1618345984, 2, 0,
  124687. _vq_quantlist__16c1_s_p7_0,
  124688. NULL,
  124689. &_vq_auxt__16c1_s_p7_0,
  124690. NULL,
  124691. 0
  124692. };
  124693. static long _vq_quantlist__16c1_s_p7_1[] = {
  124694. 5,
  124695. 4,
  124696. 6,
  124697. 3,
  124698. 7,
  124699. 2,
  124700. 8,
  124701. 1,
  124702. 9,
  124703. 0,
  124704. 10,
  124705. };
  124706. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124707. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124708. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124709. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124710. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124711. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124712. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124713. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124714. 10,10,10, 8, 8, 8, 8, 9, 9,
  124715. };
  124716. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124717. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124718. 3.5, 4.5,
  124719. };
  124720. static long _vq_quantmap__16c1_s_p7_1[] = {
  124721. 9, 7, 5, 3, 1, 0, 2, 4,
  124722. 6, 8, 10,
  124723. };
  124724. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124725. _vq_quantthresh__16c1_s_p7_1,
  124726. _vq_quantmap__16c1_s_p7_1,
  124727. 11,
  124728. 11
  124729. };
  124730. static static_codebook _16c1_s_p7_1 = {
  124731. 2, 121,
  124732. _vq_lengthlist__16c1_s_p7_1,
  124733. 1, -531365888, 1611661312, 4, 0,
  124734. _vq_quantlist__16c1_s_p7_1,
  124735. NULL,
  124736. &_vq_auxt__16c1_s_p7_1,
  124737. NULL,
  124738. 0
  124739. };
  124740. static long _vq_quantlist__16c1_s_p8_0[] = {
  124741. 6,
  124742. 5,
  124743. 7,
  124744. 4,
  124745. 8,
  124746. 3,
  124747. 9,
  124748. 2,
  124749. 10,
  124750. 1,
  124751. 11,
  124752. 0,
  124753. 12,
  124754. };
  124755. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124756. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124757. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124758. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124759. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124760. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124761. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124762. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124763. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124764. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124765. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124766. 0,12,12,12,12,13,13,14,15,
  124767. };
  124768. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124769. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124770. 12.5, 17.5, 22.5, 27.5,
  124771. };
  124772. static long _vq_quantmap__16c1_s_p8_0[] = {
  124773. 11, 9, 7, 5, 3, 1, 0, 2,
  124774. 4, 6, 8, 10, 12,
  124775. };
  124776. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124777. _vq_quantthresh__16c1_s_p8_0,
  124778. _vq_quantmap__16c1_s_p8_0,
  124779. 13,
  124780. 13
  124781. };
  124782. static static_codebook _16c1_s_p8_0 = {
  124783. 2, 169,
  124784. _vq_lengthlist__16c1_s_p8_0,
  124785. 1, -526516224, 1616117760, 4, 0,
  124786. _vq_quantlist__16c1_s_p8_0,
  124787. NULL,
  124788. &_vq_auxt__16c1_s_p8_0,
  124789. NULL,
  124790. 0
  124791. };
  124792. static long _vq_quantlist__16c1_s_p8_1[] = {
  124793. 2,
  124794. 1,
  124795. 3,
  124796. 0,
  124797. 4,
  124798. };
  124799. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124800. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124801. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124802. };
  124803. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124804. -1.5, -0.5, 0.5, 1.5,
  124805. };
  124806. static long _vq_quantmap__16c1_s_p8_1[] = {
  124807. 3, 1, 0, 2, 4,
  124808. };
  124809. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124810. _vq_quantthresh__16c1_s_p8_1,
  124811. _vq_quantmap__16c1_s_p8_1,
  124812. 5,
  124813. 5
  124814. };
  124815. static static_codebook _16c1_s_p8_1 = {
  124816. 2, 25,
  124817. _vq_lengthlist__16c1_s_p8_1,
  124818. 1, -533725184, 1611661312, 3, 0,
  124819. _vq_quantlist__16c1_s_p8_1,
  124820. NULL,
  124821. &_vq_auxt__16c1_s_p8_1,
  124822. NULL,
  124823. 0
  124824. };
  124825. static long _vq_quantlist__16c1_s_p9_0[] = {
  124826. 6,
  124827. 5,
  124828. 7,
  124829. 4,
  124830. 8,
  124831. 3,
  124832. 9,
  124833. 2,
  124834. 10,
  124835. 1,
  124836. 11,
  124837. 0,
  124838. 12,
  124839. };
  124840. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124841. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124842. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124843. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124844. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124845. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124846. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124847. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124848. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124849. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124850. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124851. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124852. };
  124853. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124854. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124855. 787.5, 1102.5, 1417.5, 1732.5,
  124856. };
  124857. static long _vq_quantmap__16c1_s_p9_0[] = {
  124858. 11, 9, 7, 5, 3, 1, 0, 2,
  124859. 4, 6, 8, 10, 12,
  124860. };
  124861. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124862. _vq_quantthresh__16c1_s_p9_0,
  124863. _vq_quantmap__16c1_s_p9_0,
  124864. 13,
  124865. 13
  124866. };
  124867. static static_codebook _16c1_s_p9_0 = {
  124868. 2, 169,
  124869. _vq_lengthlist__16c1_s_p9_0,
  124870. 1, -513964032, 1628680192, 4, 0,
  124871. _vq_quantlist__16c1_s_p9_0,
  124872. NULL,
  124873. &_vq_auxt__16c1_s_p9_0,
  124874. NULL,
  124875. 0
  124876. };
  124877. static long _vq_quantlist__16c1_s_p9_1[] = {
  124878. 7,
  124879. 6,
  124880. 8,
  124881. 5,
  124882. 9,
  124883. 4,
  124884. 10,
  124885. 3,
  124886. 11,
  124887. 2,
  124888. 12,
  124889. 1,
  124890. 13,
  124891. 0,
  124892. 14,
  124893. };
  124894. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124895. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124896. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124897. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124898. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124899. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124900. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124901. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124902. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124903. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124904. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124905. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124906. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124907. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124908. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124909. 13,
  124910. };
  124911. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124912. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124913. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124914. };
  124915. static long _vq_quantmap__16c1_s_p9_1[] = {
  124916. 13, 11, 9, 7, 5, 3, 1, 0,
  124917. 2, 4, 6, 8, 10, 12, 14,
  124918. };
  124919. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124920. _vq_quantthresh__16c1_s_p9_1,
  124921. _vq_quantmap__16c1_s_p9_1,
  124922. 15,
  124923. 15
  124924. };
  124925. static static_codebook _16c1_s_p9_1 = {
  124926. 2, 225,
  124927. _vq_lengthlist__16c1_s_p9_1,
  124928. 1, -520986624, 1620377600, 4, 0,
  124929. _vq_quantlist__16c1_s_p9_1,
  124930. NULL,
  124931. &_vq_auxt__16c1_s_p9_1,
  124932. NULL,
  124933. 0
  124934. };
  124935. static long _vq_quantlist__16c1_s_p9_2[] = {
  124936. 10,
  124937. 9,
  124938. 11,
  124939. 8,
  124940. 12,
  124941. 7,
  124942. 13,
  124943. 6,
  124944. 14,
  124945. 5,
  124946. 15,
  124947. 4,
  124948. 16,
  124949. 3,
  124950. 17,
  124951. 2,
  124952. 18,
  124953. 1,
  124954. 19,
  124955. 0,
  124956. 20,
  124957. };
  124958. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124959. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124960. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124961. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124962. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124963. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124964. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124965. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124966. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124967. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124968. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124969. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124970. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124971. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124972. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124973. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124974. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124975. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124976. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124977. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124978. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124979. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124980. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124981. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124982. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124983. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124984. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124985. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124986. 11,11,11,11,12,11,11,12,11,
  124987. };
  124988. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124989. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124990. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124991. 6.5, 7.5, 8.5, 9.5,
  124992. };
  124993. static long _vq_quantmap__16c1_s_p9_2[] = {
  124994. 19, 17, 15, 13, 11, 9, 7, 5,
  124995. 3, 1, 0, 2, 4, 6, 8, 10,
  124996. 12, 14, 16, 18, 20,
  124997. };
  124998. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124999. _vq_quantthresh__16c1_s_p9_2,
  125000. _vq_quantmap__16c1_s_p9_2,
  125001. 21,
  125002. 21
  125003. };
  125004. static static_codebook _16c1_s_p9_2 = {
  125005. 2, 441,
  125006. _vq_lengthlist__16c1_s_p9_2,
  125007. 1, -529268736, 1611661312, 5, 0,
  125008. _vq_quantlist__16c1_s_p9_2,
  125009. NULL,
  125010. &_vq_auxt__16c1_s_p9_2,
  125011. NULL,
  125012. 0
  125013. };
  125014. static long _huff_lengthlist__16c1_s_short[] = {
  125015. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  125016. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  125017. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  125018. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  125019. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  125020. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  125021. 9, 9,10,13,
  125022. };
  125023. static static_codebook _huff_book__16c1_s_short = {
  125024. 2, 100,
  125025. _huff_lengthlist__16c1_s_short,
  125026. 0, 0, 0, 0, 0,
  125027. NULL,
  125028. NULL,
  125029. NULL,
  125030. NULL,
  125031. 0
  125032. };
  125033. static long _huff_lengthlist__16c2_s_long[] = {
  125034. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  125035. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  125036. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  125037. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  125038. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  125039. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  125040. 14,14,16,18,
  125041. };
  125042. static static_codebook _huff_book__16c2_s_long = {
  125043. 2, 100,
  125044. _huff_lengthlist__16c2_s_long,
  125045. 0, 0, 0, 0, 0,
  125046. NULL,
  125047. NULL,
  125048. NULL,
  125049. NULL,
  125050. 0
  125051. };
  125052. static long _vq_quantlist__16c2_s_p1_0[] = {
  125053. 1,
  125054. 0,
  125055. 2,
  125056. };
  125057. static long _vq_lengthlist__16c2_s_p1_0[] = {
  125058. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  125059. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125063. 0,
  125064. };
  125065. static float _vq_quantthresh__16c2_s_p1_0[] = {
  125066. -0.5, 0.5,
  125067. };
  125068. static long _vq_quantmap__16c2_s_p1_0[] = {
  125069. 1, 0, 2,
  125070. };
  125071. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  125072. _vq_quantthresh__16c2_s_p1_0,
  125073. _vq_quantmap__16c2_s_p1_0,
  125074. 3,
  125075. 3
  125076. };
  125077. static static_codebook _16c2_s_p1_0 = {
  125078. 4, 81,
  125079. _vq_lengthlist__16c2_s_p1_0,
  125080. 1, -535822336, 1611661312, 2, 0,
  125081. _vq_quantlist__16c2_s_p1_0,
  125082. NULL,
  125083. &_vq_auxt__16c2_s_p1_0,
  125084. NULL,
  125085. 0
  125086. };
  125087. static long _vq_quantlist__16c2_s_p2_0[] = {
  125088. 2,
  125089. 1,
  125090. 3,
  125091. 0,
  125092. 4,
  125093. };
  125094. static long _vq_lengthlist__16c2_s_p2_0[] = {
  125095. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  125096. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  125097. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  125098. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  125099. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  125100. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  125101. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  125102. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  125103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125107. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  125108. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  125109. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  125110. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  125111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125115. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  125116. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  125117. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  125118. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125123. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  125124. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  125125. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  125126. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  125131. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  125132. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  125133. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  125134. 13,
  125135. };
  125136. static float _vq_quantthresh__16c2_s_p2_0[] = {
  125137. -1.5, -0.5, 0.5, 1.5,
  125138. };
  125139. static long _vq_quantmap__16c2_s_p2_0[] = {
  125140. 3, 1, 0, 2, 4,
  125141. };
  125142. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  125143. _vq_quantthresh__16c2_s_p2_0,
  125144. _vq_quantmap__16c2_s_p2_0,
  125145. 5,
  125146. 5
  125147. };
  125148. static static_codebook _16c2_s_p2_0 = {
  125149. 4, 625,
  125150. _vq_lengthlist__16c2_s_p2_0,
  125151. 1, -533725184, 1611661312, 3, 0,
  125152. _vq_quantlist__16c2_s_p2_0,
  125153. NULL,
  125154. &_vq_auxt__16c2_s_p2_0,
  125155. NULL,
  125156. 0
  125157. };
  125158. static long _vq_quantlist__16c2_s_p3_0[] = {
  125159. 4,
  125160. 3,
  125161. 5,
  125162. 2,
  125163. 6,
  125164. 1,
  125165. 7,
  125166. 0,
  125167. 8,
  125168. };
  125169. static long _vq_lengthlist__16c2_s_p3_0[] = {
  125170. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  125171. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  125172. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125173. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  125174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125175. 0,
  125176. };
  125177. static float _vq_quantthresh__16c2_s_p3_0[] = {
  125178. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125179. };
  125180. static long _vq_quantmap__16c2_s_p3_0[] = {
  125181. 7, 5, 3, 1, 0, 2, 4, 6,
  125182. 8,
  125183. };
  125184. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  125185. _vq_quantthresh__16c2_s_p3_0,
  125186. _vq_quantmap__16c2_s_p3_0,
  125187. 9,
  125188. 9
  125189. };
  125190. static static_codebook _16c2_s_p3_0 = {
  125191. 2, 81,
  125192. _vq_lengthlist__16c2_s_p3_0,
  125193. 1, -531628032, 1611661312, 4, 0,
  125194. _vq_quantlist__16c2_s_p3_0,
  125195. NULL,
  125196. &_vq_auxt__16c2_s_p3_0,
  125197. NULL,
  125198. 0
  125199. };
  125200. static long _vq_quantlist__16c2_s_p4_0[] = {
  125201. 8,
  125202. 7,
  125203. 9,
  125204. 6,
  125205. 10,
  125206. 5,
  125207. 11,
  125208. 4,
  125209. 12,
  125210. 3,
  125211. 13,
  125212. 2,
  125213. 14,
  125214. 1,
  125215. 15,
  125216. 0,
  125217. 16,
  125218. };
  125219. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125220. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125221. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125222. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125223. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125224. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125225. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125226. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125227. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125228. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125229. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125238. 0,
  125239. };
  125240. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125241. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125242. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125243. };
  125244. static long _vq_quantmap__16c2_s_p4_0[] = {
  125245. 15, 13, 11, 9, 7, 5, 3, 1,
  125246. 0, 2, 4, 6, 8, 10, 12, 14,
  125247. 16,
  125248. };
  125249. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125250. _vq_quantthresh__16c2_s_p4_0,
  125251. _vq_quantmap__16c2_s_p4_0,
  125252. 17,
  125253. 17
  125254. };
  125255. static static_codebook _16c2_s_p4_0 = {
  125256. 2, 289,
  125257. _vq_lengthlist__16c2_s_p4_0,
  125258. 1, -529530880, 1611661312, 5, 0,
  125259. _vq_quantlist__16c2_s_p4_0,
  125260. NULL,
  125261. &_vq_auxt__16c2_s_p4_0,
  125262. NULL,
  125263. 0
  125264. };
  125265. static long _vq_quantlist__16c2_s_p5_0[] = {
  125266. 1,
  125267. 0,
  125268. 2,
  125269. };
  125270. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125271. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125272. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125273. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125274. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125275. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125276. 12,
  125277. };
  125278. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125279. -5.5, 5.5,
  125280. };
  125281. static long _vq_quantmap__16c2_s_p5_0[] = {
  125282. 1, 0, 2,
  125283. };
  125284. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125285. _vq_quantthresh__16c2_s_p5_0,
  125286. _vq_quantmap__16c2_s_p5_0,
  125287. 3,
  125288. 3
  125289. };
  125290. static static_codebook _16c2_s_p5_0 = {
  125291. 4, 81,
  125292. _vq_lengthlist__16c2_s_p5_0,
  125293. 1, -529137664, 1618345984, 2, 0,
  125294. _vq_quantlist__16c2_s_p5_0,
  125295. NULL,
  125296. &_vq_auxt__16c2_s_p5_0,
  125297. NULL,
  125298. 0
  125299. };
  125300. static long _vq_quantlist__16c2_s_p5_1[] = {
  125301. 5,
  125302. 4,
  125303. 6,
  125304. 3,
  125305. 7,
  125306. 2,
  125307. 8,
  125308. 1,
  125309. 9,
  125310. 0,
  125311. 10,
  125312. };
  125313. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125314. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125315. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125316. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125317. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125318. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125319. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125320. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125321. 11,11,11, 7, 7, 8, 8, 8, 8,
  125322. };
  125323. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125324. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125325. 3.5, 4.5,
  125326. };
  125327. static long _vq_quantmap__16c2_s_p5_1[] = {
  125328. 9, 7, 5, 3, 1, 0, 2, 4,
  125329. 6, 8, 10,
  125330. };
  125331. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125332. _vq_quantthresh__16c2_s_p5_1,
  125333. _vq_quantmap__16c2_s_p5_1,
  125334. 11,
  125335. 11
  125336. };
  125337. static static_codebook _16c2_s_p5_1 = {
  125338. 2, 121,
  125339. _vq_lengthlist__16c2_s_p5_1,
  125340. 1, -531365888, 1611661312, 4, 0,
  125341. _vq_quantlist__16c2_s_p5_1,
  125342. NULL,
  125343. &_vq_auxt__16c2_s_p5_1,
  125344. NULL,
  125345. 0
  125346. };
  125347. static long _vq_quantlist__16c2_s_p6_0[] = {
  125348. 6,
  125349. 5,
  125350. 7,
  125351. 4,
  125352. 8,
  125353. 3,
  125354. 9,
  125355. 2,
  125356. 10,
  125357. 1,
  125358. 11,
  125359. 0,
  125360. 12,
  125361. };
  125362. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125363. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125364. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125365. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125366. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125367. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125368. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. };
  125375. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125376. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125377. 12.5, 17.5, 22.5, 27.5,
  125378. };
  125379. static long _vq_quantmap__16c2_s_p6_0[] = {
  125380. 11, 9, 7, 5, 3, 1, 0, 2,
  125381. 4, 6, 8, 10, 12,
  125382. };
  125383. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125384. _vq_quantthresh__16c2_s_p6_0,
  125385. _vq_quantmap__16c2_s_p6_0,
  125386. 13,
  125387. 13
  125388. };
  125389. static static_codebook _16c2_s_p6_0 = {
  125390. 2, 169,
  125391. _vq_lengthlist__16c2_s_p6_0,
  125392. 1, -526516224, 1616117760, 4, 0,
  125393. _vq_quantlist__16c2_s_p6_0,
  125394. NULL,
  125395. &_vq_auxt__16c2_s_p6_0,
  125396. NULL,
  125397. 0
  125398. };
  125399. static long _vq_quantlist__16c2_s_p6_1[] = {
  125400. 2,
  125401. 1,
  125402. 3,
  125403. 0,
  125404. 4,
  125405. };
  125406. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125407. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125408. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125409. };
  125410. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125411. -1.5, -0.5, 0.5, 1.5,
  125412. };
  125413. static long _vq_quantmap__16c2_s_p6_1[] = {
  125414. 3, 1, 0, 2, 4,
  125415. };
  125416. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125417. _vq_quantthresh__16c2_s_p6_1,
  125418. _vq_quantmap__16c2_s_p6_1,
  125419. 5,
  125420. 5
  125421. };
  125422. static static_codebook _16c2_s_p6_1 = {
  125423. 2, 25,
  125424. _vq_lengthlist__16c2_s_p6_1,
  125425. 1, -533725184, 1611661312, 3, 0,
  125426. _vq_quantlist__16c2_s_p6_1,
  125427. NULL,
  125428. &_vq_auxt__16c2_s_p6_1,
  125429. NULL,
  125430. 0
  125431. };
  125432. static long _vq_quantlist__16c2_s_p7_0[] = {
  125433. 6,
  125434. 5,
  125435. 7,
  125436. 4,
  125437. 8,
  125438. 3,
  125439. 9,
  125440. 2,
  125441. 10,
  125442. 1,
  125443. 11,
  125444. 0,
  125445. 12,
  125446. };
  125447. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125448. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125449. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125450. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125451. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125452. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125453. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125454. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125455. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125456. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125457. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125458. 18,13,14,13,13,14,13,15,14,
  125459. };
  125460. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125461. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125462. 27.5, 38.5, 49.5, 60.5,
  125463. };
  125464. static long _vq_quantmap__16c2_s_p7_0[] = {
  125465. 11, 9, 7, 5, 3, 1, 0, 2,
  125466. 4, 6, 8, 10, 12,
  125467. };
  125468. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125469. _vq_quantthresh__16c2_s_p7_0,
  125470. _vq_quantmap__16c2_s_p7_0,
  125471. 13,
  125472. 13
  125473. };
  125474. static static_codebook _16c2_s_p7_0 = {
  125475. 2, 169,
  125476. _vq_lengthlist__16c2_s_p7_0,
  125477. 1, -523206656, 1618345984, 4, 0,
  125478. _vq_quantlist__16c2_s_p7_0,
  125479. NULL,
  125480. &_vq_auxt__16c2_s_p7_0,
  125481. NULL,
  125482. 0
  125483. };
  125484. static long _vq_quantlist__16c2_s_p7_1[] = {
  125485. 5,
  125486. 4,
  125487. 6,
  125488. 3,
  125489. 7,
  125490. 2,
  125491. 8,
  125492. 1,
  125493. 9,
  125494. 0,
  125495. 10,
  125496. };
  125497. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125498. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125499. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125500. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125501. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125502. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125503. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125504. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125505. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125506. };
  125507. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125508. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125509. 3.5, 4.5,
  125510. };
  125511. static long _vq_quantmap__16c2_s_p7_1[] = {
  125512. 9, 7, 5, 3, 1, 0, 2, 4,
  125513. 6, 8, 10,
  125514. };
  125515. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125516. _vq_quantthresh__16c2_s_p7_1,
  125517. _vq_quantmap__16c2_s_p7_1,
  125518. 11,
  125519. 11
  125520. };
  125521. static static_codebook _16c2_s_p7_1 = {
  125522. 2, 121,
  125523. _vq_lengthlist__16c2_s_p7_1,
  125524. 1, -531365888, 1611661312, 4, 0,
  125525. _vq_quantlist__16c2_s_p7_1,
  125526. NULL,
  125527. &_vq_auxt__16c2_s_p7_1,
  125528. NULL,
  125529. 0
  125530. };
  125531. static long _vq_quantlist__16c2_s_p8_0[] = {
  125532. 7,
  125533. 6,
  125534. 8,
  125535. 5,
  125536. 9,
  125537. 4,
  125538. 10,
  125539. 3,
  125540. 11,
  125541. 2,
  125542. 12,
  125543. 1,
  125544. 13,
  125545. 0,
  125546. 14,
  125547. };
  125548. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125549. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125550. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125551. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125552. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125553. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125554. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125555. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125556. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125557. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125558. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125559. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125560. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125561. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125562. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125563. 13,
  125564. };
  125565. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125566. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125567. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125568. };
  125569. static long _vq_quantmap__16c2_s_p8_0[] = {
  125570. 13, 11, 9, 7, 5, 3, 1, 0,
  125571. 2, 4, 6, 8, 10, 12, 14,
  125572. };
  125573. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125574. _vq_quantthresh__16c2_s_p8_0,
  125575. _vq_quantmap__16c2_s_p8_0,
  125576. 15,
  125577. 15
  125578. };
  125579. static static_codebook _16c2_s_p8_0 = {
  125580. 2, 225,
  125581. _vq_lengthlist__16c2_s_p8_0,
  125582. 1, -520986624, 1620377600, 4, 0,
  125583. _vq_quantlist__16c2_s_p8_0,
  125584. NULL,
  125585. &_vq_auxt__16c2_s_p8_0,
  125586. NULL,
  125587. 0
  125588. };
  125589. static long _vq_quantlist__16c2_s_p8_1[] = {
  125590. 10,
  125591. 9,
  125592. 11,
  125593. 8,
  125594. 12,
  125595. 7,
  125596. 13,
  125597. 6,
  125598. 14,
  125599. 5,
  125600. 15,
  125601. 4,
  125602. 16,
  125603. 3,
  125604. 17,
  125605. 2,
  125606. 18,
  125607. 1,
  125608. 19,
  125609. 0,
  125610. 20,
  125611. };
  125612. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125613. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125614. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125615. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125616. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125617. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125618. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125619. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125620. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125621. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125622. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125623. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125624. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125625. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125626. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125627. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125628. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125629. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125630. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125631. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125632. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125633. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125634. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125635. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125636. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125637. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125638. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125639. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125640. 10,11,10,10,10,10,10,10,10,
  125641. };
  125642. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125643. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125644. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125645. 6.5, 7.5, 8.5, 9.5,
  125646. };
  125647. static long _vq_quantmap__16c2_s_p8_1[] = {
  125648. 19, 17, 15, 13, 11, 9, 7, 5,
  125649. 3, 1, 0, 2, 4, 6, 8, 10,
  125650. 12, 14, 16, 18, 20,
  125651. };
  125652. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125653. _vq_quantthresh__16c2_s_p8_1,
  125654. _vq_quantmap__16c2_s_p8_1,
  125655. 21,
  125656. 21
  125657. };
  125658. static static_codebook _16c2_s_p8_1 = {
  125659. 2, 441,
  125660. _vq_lengthlist__16c2_s_p8_1,
  125661. 1, -529268736, 1611661312, 5, 0,
  125662. _vq_quantlist__16c2_s_p8_1,
  125663. NULL,
  125664. &_vq_auxt__16c2_s_p8_1,
  125665. NULL,
  125666. 0
  125667. };
  125668. static long _vq_quantlist__16c2_s_p9_0[] = {
  125669. 6,
  125670. 5,
  125671. 7,
  125672. 4,
  125673. 8,
  125674. 3,
  125675. 9,
  125676. 2,
  125677. 10,
  125678. 1,
  125679. 11,
  125680. 0,
  125681. 12,
  125682. };
  125683. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125684. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125685. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125686. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125687. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125688. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125689. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125690. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125691. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125692. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125693. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125694. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125695. };
  125696. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125697. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125698. 2327.5, 3258.5, 4189.5, 5120.5,
  125699. };
  125700. static long _vq_quantmap__16c2_s_p9_0[] = {
  125701. 11, 9, 7, 5, 3, 1, 0, 2,
  125702. 4, 6, 8, 10, 12,
  125703. };
  125704. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125705. _vq_quantthresh__16c2_s_p9_0,
  125706. _vq_quantmap__16c2_s_p9_0,
  125707. 13,
  125708. 13
  125709. };
  125710. static static_codebook _16c2_s_p9_0 = {
  125711. 2, 169,
  125712. _vq_lengthlist__16c2_s_p9_0,
  125713. 1, -510275072, 1631393792, 4, 0,
  125714. _vq_quantlist__16c2_s_p9_0,
  125715. NULL,
  125716. &_vq_auxt__16c2_s_p9_0,
  125717. NULL,
  125718. 0
  125719. };
  125720. static long _vq_quantlist__16c2_s_p9_1[] = {
  125721. 8,
  125722. 7,
  125723. 9,
  125724. 6,
  125725. 10,
  125726. 5,
  125727. 11,
  125728. 4,
  125729. 12,
  125730. 3,
  125731. 13,
  125732. 2,
  125733. 14,
  125734. 1,
  125735. 15,
  125736. 0,
  125737. 16,
  125738. };
  125739. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125740. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125741. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125742. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125743. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125744. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125745. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125746. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125747. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125748. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125749. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125750. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125751. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125752. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125753. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125754. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125755. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125756. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125757. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125758. 10,
  125759. };
  125760. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125761. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125762. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125763. };
  125764. static long _vq_quantmap__16c2_s_p9_1[] = {
  125765. 15, 13, 11, 9, 7, 5, 3, 1,
  125766. 0, 2, 4, 6, 8, 10, 12, 14,
  125767. 16,
  125768. };
  125769. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125770. _vq_quantthresh__16c2_s_p9_1,
  125771. _vq_quantmap__16c2_s_p9_1,
  125772. 17,
  125773. 17
  125774. };
  125775. static static_codebook _16c2_s_p9_1 = {
  125776. 2, 289,
  125777. _vq_lengthlist__16c2_s_p9_1,
  125778. 1, -518488064, 1622704128, 5, 0,
  125779. _vq_quantlist__16c2_s_p9_1,
  125780. NULL,
  125781. &_vq_auxt__16c2_s_p9_1,
  125782. NULL,
  125783. 0
  125784. };
  125785. static long _vq_quantlist__16c2_s_p9_2[] = {
  125786. 13,
  125787. 12,
  125788. 14,
  125789. 11,
  125790. 15,
  125791. 10,
  125792. 16,
  125793. 9,
  125794. 17,
  125795. 8,
  125796. 18,
  125797. 7,
  125798. 19,
  125799. 6,
  125800. 20,
  125801. 5,
  125802. 21,
  125803. 4,
  125804. 22,
  125805. 3,
  125806. 23,
  125807. 2,
  125808. 24,
  125809. 1,
  125810. 25,
  125811. 0,
  125812. 26,
  125813. };
  125814. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125815. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125816. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125817. };
  125818. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125819. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125820. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125821. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125822. 11.5, 12.5,
  125823. };
  125824. static long _vq_quantmap__16c2_s_p9_2[] = {
  125825. 25, 23, 21, 19, 17, 15, 13, 11,
  125826. 9, 7, 5, 3, 1, 0, 2, 4,
  125827. 6, 8, 10, 12, 14, 16, 18, 20,
  125828. 22, 24, 26,
  125829. };
  125830. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125831. _vq_quantthresh__16c2_s_p9_2,
  125832. _vq_quantmap__16c2_s_p9_2,
  125833. 27,
  125834. 27
  125835. };
  125836. static static_codebook _16c2_s_p9_2 = {
  125837. 1, 27,
  125838. _vq_lengthlist__16c2_s_p9_2,
  125839. 1, -528875520, 1611661312, 5, 0,
  125840. _vq_quantlist__16c2_s_p9_2,
  125841. NULL,
  125842. &_vq_auxt__16c2_s_p9_2,
  125843. NULL,
  125844. 0
  125845. };
  125846. static long _huff_lengthlist__16c2_s_short[] = {
  125847. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125848. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125849. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125850. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125851. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125852. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125853. 15,12,14,14,
  125854. };
  125855. static static_codebook _huff_book__16c2_s_short = {
  125856. 2, 100,
  125857. _huff_lengthlist__16c2_s_short,
  125858. 0, 0, 0, 0, 0,
  125859. NULL,
  125860. NULL,
  125861. NULL,
  125862. NULL,
  125863. 0
  125864. };
  125865. static long _vq_quantlist__8c0_s_p1_0[] = {
  125866. 1,
  125867. 0,
  125868. 2,
  125869. };
  125870. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125871. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125872. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125877. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125882. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  125917. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  125922. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  125927. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125963. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125968. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125973. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126281. 0,
  126282. };
  126283. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126284. -0.5, 0.5,
  126285. };
  126286. static long _vq_quantmap__8c0_s_p1_0[] = {
  126287. 1, 0, 2,
  126288. };
  126289. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126290. _vq_quantthresh__8c0_s_p1_0,
  126291. _vq_quantmap__8c0_s_p1_0,
  126292. 3,
  126293. 3
  126294. };
  126295. static static_codebook _8c0_s_p1_0 = {
  126296. 8, 6561,
  126297. _vq_lengthlist__8c0_s_p1_0,
  126298. 1, -535822336, 1611661312, 2, 0,
  126299. _vq_quantlist__8c0_s_p1_0,
  126300. NULL,
  126301. &_vq_auxt__8c0_s_p1_0,
  126302. NULL,
  126303. 0
  126304. };
  126305. static long _vq_quantlist__8c0_s_p2_0[] = {
  126306. 2,
  126307. 1,
  126308. 3,
  126309. 0,
  126310. 4,
  126311. };
  126312. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126352. 0,
  126353. };
  126354. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126355. -1.5, -0.5, 0.5, 1.5,
  126356. };
  126357. static long _vq_quantmap__8c0_s_p2_0[] = {
  126358. 3, 1, 0, 2, 4,
  126359. };
  126360. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126361. _vq_quantthresh__8c0_s_p2_0,
  126362. _vq_quantmap__8c0_s_p2_0,
  126363. 5,
  126364. 5
  126365. };
  126366. static static_codebook _8c0_s_p2_0 = {
  126367. 4, 625,
  126368. _vq_lengthlist__8c0_s_p2_0,
  126369. 1, -533725184, 1611661312, 3, 0,
  126370. _vq_quantlist__8c0_s_p2_0,
  126371. NULL,
  126372. &_vq_auxt__8c0_s_p2_0,
  126373. NULL,
  126374. 0
  126375. };
  126376. static long _vq_quantlist__8c0_s_p3_0[] = {
  126377. 2,
  126378. 1,
  126379. 3,
  126380. 0,
  126381. 4,
  126382. };
  126383. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126384. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126387. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126390. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126423. 0,
  126424. };
  126425. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126426. -1.5, -0.5, 0.5, 1.5,
  126427. };
  126428. static long _vq_quantmap__8c0_s_p3_0[] = {
  126429. 3, 1, 0, 2, 4,
  126430. };
  126431. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126432. _vq_quantthresh__8c0_s_p3_0,
  126433. _vq_quantmap__8c0_s_p3_0,
  126434. 5,
  126435. 5
  126436. };
  126437. static static_codebook _8c0_s_p3_0 = {
  126438. 4, 625,
  126439. _vq_lengthlist__8c0_s_p3_0,
  126440. 1, -533725184, 1611661312, 3, 0,
  126441. _vq_quantlist__8c0_s_p3_0,
  126442. NULL,
  126443. &_vq_auxt__8c0_s_p3_0,
  126444. NULL,
  126445. 0
  126446. };
  126447. static long _vq_quantlist__8c0_s_p4_0[] = {
  126448. 4,
  126449. 3,
  126450. 5,
  126451. 2,
  126452. 6,
  126453. 1,
  126454. 7,
  126455. 0,
  126456. 8,
  126457. };
  126458. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126459. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126460. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126461. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126462. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126463. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0,
  126465. };
  126466. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126467. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126468. };
  126469. static long _vq_quantmap__8c0_s_p4_0[] = {
  126470. 7, 5, 3, 1, 0, 2, 4, 6,
  126471. 8,
  126472. };
  126473. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126474. _vq_quantthresh__8c0_s_p4_0,
  126475. _vq_quantmap__8c0_s_p4_0,
  126476. 9,
  126477. 9
  126478. };
  126479. static static_codebook _8c0_s_p4_0 = {
  126480. 2, 81,
  126481. _vq_lengthlist__8c0_s_p4_0,
  126482. 1, -531628032, 1611661312, 4, 0,
  126483. _vq_quantlist__8c0_s_p4_0,
  126484. NULL,
  126485. &_vq_auxt__8c0_s_p4_0,
  126486. NULL,
  126487. 0
  126488. };
  126489. static long _vq_quantlist__8c0_s_p5_0[] = {
  126490. 4,
  126491. 3,
  126492. 5,
  126493. 2,
  126494. 6,
  126495. 1,
  126496. 7,
  126497. 0,
  126498. 8,
  126499. };
  126500. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126501. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126502. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126503. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126504. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126505. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126506. 10,
  126507. };
  126508. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126509. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126510. };
  126511. static long _vq_quantmap__8c0_s_p5_0[] = {
  126512. 7, 5, 3, 1, 0, 2, 4, 6,
  126513. 8,
  126514. };
  126515. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126516. _vq_quantthresh__8c0_s_p5_0,
  126517. _vq_quantmap__8c0_s_p5_0,
  126518. 9,
  126519. 9
  126520. };
  126521. static static_codebook _8c0_s_p5_0 = {
  126522. 2, 81,
  126523. _vq_lengthlist__8c0_s_p5_0,
  126524. 1, -531628032, 1611661312, 4, 0,
  126525. _vq_quantlist__8c0_s_p5_0,
  126526. NULL,
  126527. &_vq_auxt__8c0_s_p5_0,
  126528. NULL,
  126529. 0
  126530. };
  126531. static long _vq_quantlist__8c0_s_p6_0[] = {
  126532. 8,
  126533. 7,
  126534. 9,
  126535. 6,
  126536. 10,
  126537. 5,
  126538. 11,
  126539. 4,
  126540. 12,
  126541. 3,
  126542. 13,
  126543. 2,
  126544. 14,
  126545. 1,
  126546. 15,
  126547. 0,
  126548. 16,
  126549. };
  126550. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126551. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126552. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126553. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126554. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126555. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126556. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126557. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126558. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126559. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126560. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126561. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126562. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126563. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126564. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126565. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126566. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126567. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126569. 14,
  126570. };
  126571. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126572. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126573. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126574. };
  126575. static long _vq_quantmap__8c0_s_p6_0[] = {
  126576. 15, 13, 11, 9, 7, 5, 3, 1,
  126577. 0, 2, 4, 6, 8, 10, 12, 14,
  126578. 16,
  126579. };
  126580. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126581. _vq_quantthresh__8c0_s_p6_0,
  126582. _vq_quantmap__8c0_s_p6_0,
  126583. 17,
  126584. 17
  126585. };
  126586. static static_codebook _8c0_s_p6_0 = {
  126587. 2, 289,
  126588. _vq_lengthlist__8c0_s_p6_0,
  126589. 1, -529530880, 1611661312, 5, 0,
  126590. _vq_quantlist__8c0_s_p6_0,
  126591. NULL,
  126592. &_vq_auxt__8c0_s_p6_0,
  126593. NULL,
  126594. 0
  126595. };
  126596. static long _vq_quantlist__8c0_s_p7_0[] = {
  126597. 1,
  126598. 0,
  126599. 2,
  126600. };
  126601. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126602. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126603. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126604. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126605. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126606. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126607. 10,
  126608. };
  126609. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126610. -5.5, 5.5,
  126611. };
  126612. static long _vq_quantmap__8c0_s_p7_0[] = {
  126613. 1, 0, 2,
  126614. };
  126615. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126616. _vq_quantthresh__8c0_s_p7_0,
  126617. _vq_quantmap__8c0_s_p7_0,
  126618. 3,
  126619. 3
  126620. };
  126621. static static_codebook _8c0_s_p7_0 = {
  126622. 4, 81,
  126623. _vq_lengthlist__8c0_s_p7_0,
  126624. 1, -529137664, 1618345984, 2, 0,
  126625. _vq_quantlist__8c0_s_p7_0,
  126626. NULL,
  126627. &_vq_auxt__8c0_s_p7_0,
  126628. NULL,
  126629. 0
  126630. };
  126631. static long _vq_quantlist__8c0_s_p7_1[] = {
  126632. 5,
  126633. 4,
  126634. 6,
  126635. 3,
  126636. 7,
  126637. 2,
  126638. 8,
  126639. 1,
  126640. 9,
  126641. 0,
  126642. 10,
  126643. };
  126644. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126645. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126646. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126647. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126648. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126649. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126650. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126651. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126652. 10,10,10, 9, 9, 9,10,10,10,
  126653. };
  126654. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126655. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126656. 3.5, 4.5,
  126657. };
  126658. static long _vq_quantmap__8c0_s_p7_1[] = {
  126659. 9, 7, 5, 3, 1, 0, 2, 4,
  126660. 6, 8, 10,
  126661. };
  126662. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126663. _vq_quantthresh__8c0_s_p7_1,
  126664. _vq_quantmap__8c0_s_p7_1,
  126665. 11,
  126666. 11
  126667. };
  126668. static static_codebook _8c0_s_p7_1 = {
  126669. 2, 121,
  126670. _vq_lengthlist__8c0_s_p7_1,
  126671. 1, -531365888, 1611661312, 4, 0,
  126672. _vq_quantlist__8c0_s_p7_1,
  126673. NULL,
  126674. &_vq_auxt__8c0_s_p7_1,
  126675. NULL,
  126676. 0
  126677. };
  126678. static long _vq_quantlist__8c0_s_p8_0[] = {
  126679. 6,
  126680. 5,
  126681. 7,
  126682. 4,
  126683. 8,
  126684. 3,
  126685. 9,
  126686. 2,
  126687. 10,
  126688. 1,
  126689. 11,
  126690. 0,
  126691. 12,
  126692. };
  126693. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126694. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126695. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126696. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126697. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126698. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126699. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126700. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126701. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126702. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126703. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126704. 0, 0,13,13,11,13,13,11,12,
  126705. };
  126706. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126707. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126708. 12.5, 17.5, 22.5, 27.5,
  126709. };
  126710. static long _vq_quantmap__8c0_s_p8_0[] = {
  126711. 11, 9, 7, 5, 3, 1, 0, 2,
  126712. 4, 6, 8, 10, 12,
  126713. };
  126714. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126715. _vq_quantthresh__8c0_s_p8_0,
  126716. _vq_quantmap__8c0_s_p8_0,
  126717. 13,
  126718. 13
  126719. };
  126720. static static_codebook _8c0_s_p8_0 = {
  126721. 2, 169,
  126722. _vq_lengthlist__8c0_s_p8_0,
  126723. 1, -526516224, 1616117760, 4, 0,
  126724. _vq_quantlist__8c0_s_p8_0,
  126725. NULL,
  126726. &_vq_auxt__8c0_s_p8_0,
  126727. NULL,
  126728. 0
  126729. };
  126730. static long _vq_quantlist__8c0_s_p8_1[] = {
  126731. 2,
  126732. 1,
  126733. 3,
  126734. 0,
  126735. 4,
  126736. };
  126737. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126738. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126739. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126740. };
  126741. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126742. -1.5, -0.5, 0.5, 1.5,
  126743. };
  126744. static long _vq_quantmap__8c0_s_p8_1[] = {
  126745. 3, 1, 0, 2, 4,
  126746. };
  126747. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126748. _vq_quantthresh__8c0_s_p8_1,
  126749. _vq_quantmap__8c0_s_p8_1,
  126750. 5,
  126751. 5
  126752. };
  126753. static static_codebook _8c0_s_p8_1 = {
  126754. 2, 25,
  126755. _vq_lengthlist__8c0_s_p8_1,
  126756. 1, -533725184, 1611661312, 3, 0,
  126757. _vq_quantlist__8c0_s_p8_1,
  126758. NULL,
  126759. &_vq_auxt__8c0_s_p8_1,
  126760. NULL,
  126761. 0
  126762. };
  126763. static long _vq_quantlist__8c0_s_p9_0[] = {
  126764. 1,
  126765. 0,
  126766. 2,
  126767. };
  126768. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126769. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126770. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126771. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126772. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126773. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126774. 7,
  126775. };
  126776. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126777. -157.5, 157.5,
  126778. };
  126779. static long _vq_quantmap__8c0_s_p9_0[] = {
  126780. 1, 0, 2,
  126781. };
  126782. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126783. _vq_quantthresh__8c0_s_p9_0,
  126784. _vq_quantmap__8c0_s_p9_0,
  126785. 3,
  126786. 3
  126787. };
  126788. static static_codebook _8c0_s_p9_0 = {
  126789. 4, 81,
  126790. _vq_lengthlist__8c0_s_p9_0,
  126791. 1, -518803456, 1628680192, 2, 0,
  126792. _vq_quantlist__8c0_s_p9_0,
  126793. NULL,
  126794. &_vq_auxt__8c0_s_p9_0,
  126795. NULL,
  126796. 0
  126797. };
  126798. static long _vq_quantlist__8c0_s_p9_1[] = {
  126799. 7,
  126800. 6,
  126801. 8,
  126802. 5,
  126803. 9,
  126804. 4,
  126805. 10,
  126806. 3,
  126807. 11,
  126808. 2,
  126809. 12,
  126810. 1,
  126811. 13,
  126812. 0,
  126813. 14,
  126814. };
  126815. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126816. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126817. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126818. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126819. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126820. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126821. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126822. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126823. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126824. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126825. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126826. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126828. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126829. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126830. 11,
  126831. };
  126832. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126833. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126834. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126835. };
  126836. static long _vq_quantmap__8c0_s_p9_1[] = {
  126837. 13, 11, 9, 7, 5, 3, 1, 0,
  126838. 2, 4, 6, 8, 10, 12, 14,
  126839. };
  126840. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126841. _vq_quantthresh__8c0_s_p9_1,
  126842. _vq_quantmap__8c0_s_p9_1,
  126843. 15,
  126844. 15
  126845. };
  126846. static static_codebook _8c0_s_p9_1 = {
  126847. 2, 225,
  126848. _vq_lengthlist__8c0_s_p9_1,
  126849. 1, -520986624, 1620377600, 4, 0,
  126850. _vq_quantlist__8c0_s_p9_1,
  126851. NULL,
  126852. &_vq_auxt__8c0_s_p9_1,
  126853. NULL,
  126854. 0
  126855. };
  126856. static long _vq_quantlist__8c0_s_p9_2[] = {
  126857. 10,
  126858. 9,
  126859. 11,
  126860. 8,
  126861. 12,
  126862. 7,
  126863. 13,
  126864. 6,
  126865. 14,
  126866. 5,
  126867. 15,
  126868. 4,
  126869. 16,
  126870. 3,
  126871. 17,
  126872. 2,
  126873. 18,
  126874. 1,
  126875. 19,
  126876. 0,
  126877. 20,
  126878. };
  126879. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126880. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126881. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126882. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126883. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126884. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126885. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126886. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126887. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126888. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126889. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126890. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126891. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126892. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126893. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126894. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126895. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126896. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126897. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126898. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126899. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126900. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126901. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126902. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126903. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126904. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126905. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126906. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126907. 10,11, 9,11,10, 9,10, 9,10,
  126908. };
  126909. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126910. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126911. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126912. 6.5, 7.5, 8.5, 9.5,
  126913. };
  126914. static long _vq_quantmap__8c0_s_p9_2[] = {
  126915. 19, 17, 15, 13, 11, 9, 7, 5,
  126916. 3, 1, 0, 2, 4, 6, 8, 10,
  126917. 12, 14, 16, 18, 20,
  126918. };
  126919. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126920. _vq_quantthresh__8c0_s_p9_2,
  126921. _vq_quantmap__8c0_s_p9_2,
  126922. 21,
  126923. 21
  126924. };
  126925. static static_codebook _8c0_s_p9_2 = {
  126926. 2, 441,
  126927. _vq_lengthlist__8c0_s_p9_2,
  126928. 1, -529268736, 1611661312, 5, 0,
  126929. _vq_quantlist__8c0_s_p9_2,
  126930. NULL,
  126931. &_vq_auxt__8c0_s_p9_2,
  126932. NULL,
  126933. 0
  126934. };
  126935. static long _huff_lengthlist__8c0_s_single[] = {
  126936. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126937. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126938. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126939. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126940. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126941. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126942. 17,16,17,17,
  126943. };
  126944. static static_codebook _huff_book__8c0_s_single = {
  126945. 2, 100,
  126946. _huff_lengthlist__8c0_s_single,
  126947. 0, 0, 0, 0, 0,
  126948. NULL,
  126949. NULL,
  126950. NULL,
  126951. NULL,
  126952. 0
  126953. };
  126954. static long _vq_quantlist__8c1_s_p1_0[] = {
  126955. 1,
  126956. 0,
  126957. 2,
  126958. };
  126959. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126960. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126961. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126966. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126971. 0, 0, 0, 0, 7, 9, 8, 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, 5, 8, 8, 0, 0, 0, 0,
  127006. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  127011. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  127016. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  127052. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127057. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127062. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127370. 0,
  127371. };
  127372. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127373. -0.5, 0.5,
  127374. };
  127375. static long _vq_quantmap__8c1_s_p1_0[] = {
  127376. 1, 0, 2,
  127377. };
  127378. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127379. _vq_quantthresh__8c1_s_p1_0,
  127380. _vq_quantmap__8c1_s_p1_0,
  127381. 3,
  127382. 3
  127383. };
  127384. static static_codebook _8c1_s_p1_0 = {
  127385. 8, 6561,
  127386. _vq_lengthlist__8c1_s_p1_0,
  127387. 1, -535822336, 1611661312, 2, 0,
  127388. _vq_quantlist__8c1_s_p1_0,
  127389. NULL,
  127390. &_vq_auxt__8c1_s_p1_0,
  127391. NULL,
  127392. 0
  127393. };
  127394. static long _vq_quantlist__8c1_s_p2_0[] = {
  127395. 2,
  127396. 1,
  127397. 3,
  127398. 0,
  127399. 4,
  127400. };
  127401. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127441. 0,
  127442. };
  127443. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127444. -1.5, -0.5, 0.5, 1.5,
  127445. };
  127446. static long _vq_quantmap__8c1_s_p2_0[] = {
  127447. 3, 1, 0, 2, 4,
  127448. };
  127449. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127450. _vq_quantthresh__8c1_s_p2_0,
  127451. _vq_quantmap__8c1_s_p2_0,
  127452. 5,
  127453. 5
  127454. };
  127455. static static_codebook _8c1_s_p2_0 = {
  127456. 4, 625,
  127457. _vq_lengthlist__8c1_s_p2_0,
  127458. 1, -533725184, 1611661312, 3, 0,
  127459. _vq_quantlist__8c1_s_p2_0,
  127460. NULL,
  127461. &_vq_auxt__8c1_s_p2_0,
  127462. NULL,
  127463. 0
  127464. };
  127465. static long _vq_quantlist__8c1_s_p3_0[] = {
  127466. 2,
  127467. 1,
  127468. 3,
  127469. 0,
  127470. 4,
  127471. };
  127472. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127473. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127476. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127479. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127512. 0,
  127513. };
  127514. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127515. -1.5, -0.5, 0.5, 1.5,
  127516. };
  127517. static long _vq_quantmap__8c1_s_p3_0[] = {
  127518. 3, 1, 0, 2, 4,
  127519. };
  127520. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127521. _vq_quantthresh__8c1_s_p3_0,
  127522. _vq_quantmap__8c1_s_p3_0,
  127523. 5,
  127524. 5
  127525. };
  127526. static static_codebook _8c1_s_p3_0 = {
  127527. 4, 625,
  127528. _vq_lengthlist__8c1_s_p3_0,
  127529. 1, -533725184, 1611661312, 3, 0,
  127530. _vq_quantlist__8c1_s_p3_0,
  127531. NULL,
  127532. &_vq_auxt__8c1_s_p3_0,
  127533. NULL,
  127534. 0
  127535. };
  127536. static long _vq_quantlist__8c1_s_p4_0[] = {
  127537. 4,
  127538. 3,
  127539. 5,
  127540. 2,
  127541. 6,
  127542. 1,
  127543. 7,
  127544. 0,
  127545. 8,
  127546. };
  127547. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127548. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127549. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127550. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127551. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127552. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127553. 0,
  127554. };
  127555. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127556. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127557. };
  127558. static long _vq_quantmap__8c1_s_p4_0[] = {
  127559. 7, 5, 3, 1, 0, 2, 4, 6,
  127560. 8,
  127561. };
  127562. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127563. _vq_quantthresh__8c1_s_p4_0,
  127564. _vq_quantmap__8c1_s_p4_0,
  127565. 9,
  127566. 9
  127567. };
  127568. static static_codebook _8c1_s_p4_0 = {
  127569. 2, 81,
  127570. _vq_lengthlist__8c1_s_p4_0,
  127571. 1, -531628032, 1611661312, 4, 0,
  127572. _vq_quantlist__8c1_s_p4_0,
  127573. NULL,
  127574. &_vq_auxt__8c1_s_p4_0,
  127575. NULL,
  127576. 0
  127577. };
  127578. static long _vq_quantlist__8c1_s_p5_0[] = {
  127579. 4,
  127580. 3,
  127581. 5,
  127582. 2,
  127583. 6,
  127584. 1,
  127585. 7,
  127586. 0,
  127587. 8,
  127588. };
  127589. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127590. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127591. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127592. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127593. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127594. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127595. 10,
  127596. };
  127597. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127598. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127599. };
  127600. static long _vq_quantmap__8c1_s_p5_0[] = {
  127601. 7, 5, 3, 1, 0, 2, 4, 6,
  127602. 8,
  127603. };
  127604. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127605. _vq_quantthresh__8c1_s_p5_0,
  127606. _vq_quantmap__8c1_s_p5_0,
  127607. 9,
  127608. 9
  127609. };
  127610. static static_codebook _8c1_s_p5_0 = {
  127611. 2, 81,
  127612. _vq_lengthlist__8c1_s_p5_0,
  127613. 1, -531628032, 1611661312, 4, 0,
  127614. _vq_quantlist__8c1_s_p5_0,
  127615. NULL,
  127616. &_vq_auxt__8c1_s_p5_0,
  127617. NULL,
  127618. 0
  127619. };
  127620. static long _vq_quantlist__8c1_s_p6_0[] = {
  127621. 8,
  127622. 7,
  127623. 9,
  127624. 6,
  127625. 10,
  127626. 5,
  127627. 11,
  127628. 4,
  127629. 12,
  127630. 3,
  127631. 13,
  127632. 2,
  127633. 14,
  127634. 1,
  127635. 15,
  127636. 0,
  127637. 16,
  127638. };
  127639. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127640. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127641. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127642. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127643. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127644. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127645. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127646. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127647. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127648. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127649. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127650. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127651. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127652. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127653. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127654. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127655. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127656. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127657. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127658. 14,
  127659. };
  127660. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127661. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127662. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127663. };
  127664. static long _vq_quantmap__8c1_s_p6_0[] = {
  127665. 15, 13, 11, 9, 7, 5, 3, 1,
  127666. 0, 2, 4, 6, 8, 10, 12, 14,
  127667. 16,
  127668. };
  127669. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127670. _vq_quantthresh__8c1_s_p6_0,
  127671. _vq_quantmap__8c1_s_p6_0,
  127672. 17,
  127673. 17
  127674. };
  127675. static static_codebook _8c1_s_p6_0 = {
  127676. 2, 289,
  127677. _vq_lengthlist__8c1_s_p6_0,
  127678. 1, -529530880, 1611661312, 5, 0,
  127679. _vq_quantlist__8c1_s_p6_0,
  127680. NULL,
  127681. &_vq_auxt__8c1_s_p6_0,
  127682. NULL,
  127683. 0
  127684. };
  127685. static long _vq_quantlist__8c1_s_p7_0[] = {
  127686. 1,
  127687. 0,
  127688. 2,
  127689. };
  127690. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127691. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127692. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127693. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127694. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127695. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127696. 9,
  127697. };
  127698. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127699. -5.5, 5.5,
  127700. };
  127701. static long _vq_quantmap__8c1_s_p7_0[] = {
  127702. 1, 0, 2,
  127703. };
  127704. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127705. _vq_quantthresh__8c1_s_p7_0,
  127706. _vq_quantmap__8c1_s_p7_0,
  127707. 3,
  127708. 3
  127709. };
  127710. static static_codebook _8c1_s_p7_0 = {
  127711. 4, 81,
  127712. _vq_lengthlist__8c1_s_p7_0,
  127713. 1, -529137664, 1618345984, 2, 0,
  127714. _vq_quantlist__8c1_s_p7_0,
  127715. NULL,
  127716. &_vq_auxt__8c1_s_p7_0,
  127717. NULL,
  127718. 0
  127719. };
  127720. static long _vq_quantlist__8c1_s_p7_1[] = {
  127721. 5,
  127722. 4,
  127723. 6,
  127724. 3,
  127725. 7,
  127726. 2,
  127727. 8,
  127728. 1,
  127729. 9,
  127730. 0,
  127731. 10,
  127732. };
  127733. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127734. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127735. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127736. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127737. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127738. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127739. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127740. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127741. 10,10,10, 8, 8, 8, 8, 8, 8,
  127742. };
  127743. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127744. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127745. 3.5, 4.5,
  127746. };
  127747. static long _vq_quantmap__8c1_s_p7_1[] = {
  127748. 9, 7, 5, 3, 1, 0, 2, 4,
  127749. 6, 8, 10,
  127750. };
  127751. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127752. _vq_quantthresh__8c1_s_p7_1,
  127753. _vq_quantmap__8c1_s_p7_1,
  127754. 11,
  127755. 11
  127756. };
  127757. static static_codebook _8c1_s_p7_1 = {
  127758. 2, 121,
  127759. _vq_lengthlist__8c1_s_p7_1,
  127760. 1, -531365888, 1611661312, 4, 0,
  127761. _vq_quantlist__8c1_s_p7_1,
  127762. NULL,
  127763. &_vq_auxt__8c1_s_p7_1,
  127764. NULL,
  127765. 0
  127766. };
  127767. static long _vq_quantlist__8c1_s_p8_0[] = {
  127768. 6,
  127769. 5,
  127770. 7,
  127771. 4,
  127772. 8,
  127773. 3,
  127774. 9,
  127775. 2,
  127776. 10,
  127777. 1,
  127778. 11,
  127779. 0,
  127780. 12,
  127781. };
  127782. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127783. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127784. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127785. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127786. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127787. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127788. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127789. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127790. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127791. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127792. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127793. 0,12,12,11,10,12,11,13,12,
  127794. };
  127795. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127796. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127797. 12.5, 17.5, 22.5, 27.5,
  127798. };
  127799. static long _vq_quantmap__8c1_s_p8_0[] = {
  127800. 11, 9, 7, 5, 3, 1, 0, 2,
  127801. 4, 6, 8, 10, 12,
  127802. };
  127803. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127804. _vq_quantthresh__8c1_s_p8_0,
  127805. _vq_quantmap__8c1_s_p8_0,
  127806. 13,
  127807. 13
  127808. };
  127809. static static_codebook _8c1_s_p8_0 = {
  127810. 2, 169,
  127811. _vq_lengthlist__8c1_s_p8_0,
  127812. 1, -526516224, 1616117760, 4, 0,
  127813. _vq_quantlist__8c1_s_p8_0,
  127814. NULL,
  127815. &_vq_auxt__8c1_s_p8_0,
  127816. NULL,
  127817. 0
  127818. };
  127819. static long _vq_quantlist__8c1_s_p8_1[] = {
  127820. 2,
  127821. 1,
  127822. 3,
  127823. 0,
  127824. 4,
  127825. };
  127826. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127827. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127828. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127829. };
  127830. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127831. -1.5, -0.5, 0.5, 1.5,
  127832. };
  127833. static long _vq_quantmap__8c1_s_p8_1[] = {
  127834. 3, 1, 0, 2, 4,
  127835. };
  127836. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127837. _vq_quantthresh__8c1_s_p8_1,
  127838. _vq_quantmap__8c1_s_p8_1,
  127839. 5,
  127840. 5
  127841. };
  127842. static static_codebook _8c1_s_p8_1 = {
  127843. 2, 25,
  127844. _vq_lengthlist__8c1_s_p8_1,
  127845. 1, -533725184, 1611661312, 3, 0,
  127846. _vq_quantlist__8c1_s_p8_1,
  127847. NULL,
  127848. &_vq_auxt__8c1_s_p8_1,
  127849. NULL,
  127850. 0
  127851. };
  127852. static long _vq_quantlist__8c1_s_p9_0[] = {
  127853. 6,
  127854. 5,
  127855. 7,
  127856. 4,
  127857. 8,
  127858. 3,
  127859. 9,
  127860. 2,
  127861. 10,
  127862. 1,
  127863. 11,
  127864. 0,
  127865. 12,
  127866. };
  127867. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127868. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127869. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127871. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127872. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127873. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127874. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127875. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127876. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127877. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127878. 10,10,10,10,10, 9, 9, 9, 9,
  127879. };
  127880. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127881. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127882. 787.5, 1102.5, 1417.5, 1732.5,
  127883. };
  127884. static long _vq_quantmap__8c1_s_p9_0[] = {
  127885. 11, 9, 7, 5, 3, 1, 0, 2,
  127886. 4, 6, 8, 10, 12,
  127887. };
  127888. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127889. _vq_quantthresh__8c1_s_p9_0,
  127890. _vq_quantmap__8c1_s_p9_0,
  127891. 13,
  127892. 13
  127893. };
  127894. static static_codebook _8c1_s_p9_0 = {
  127895. 2, 169,
  127896. _vq_lengthlist__8c1_s_p9_0,
  127897. 1, -513964032, 1628680192, 4, 0,
  127898. _vq_quantlist__8c1_s_p9_0,
  127899. NULL,
  127900. &_vq_auxt__8c1_s_p9_0,
  127901. NULL,
  127902. 0
  127903. };
  127904. static long _vq_quantlist__8c1_s_p9_1[] = {
  127905. 7,
  127906. 6,
  127907. 8,
  127908. 5,
  127909. 9,
  127910. 4,
  127911. 10,
  127912. 3,
  127913. 11,
  127914. 2,
  127915. 12,
  127916. 1,
  127917. 13,
  127918. 0,
  127919. 14,
  127920. };
  127921. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127922. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127923. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127924. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127925. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127926. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127927. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127928. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127929. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127930. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127931. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127932. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127933. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127934. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127935. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127936. 15,
  127937. };
  127938. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127939. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127940. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127941. };
  127942. static long _vq_quantmap__8c1_s_p9_1[] = {
  127943. 13, 11, 9, 7, 5, 3, 1, 0,
  127944. 2, 4, 6, 8, 10, 12, 14,
  127945. };
  127946. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127947. _vq_quantthresh__8c1_s_p9_1,
  127948. _vq_quantmap__8c1_s_p9_1,
  127949. 15,
  127950. 15
  127951. };
  127952. static static_codebook _8c1_s_p9_1 = {
  127953. 2, 225,
  127954. _vq_lengthlist__8c1_s_p9_1,
  127955. 1, -520986624, 1620377600, 4, 0,
  127956. _vq_quantlist__8c1_s_p9_1,
  127957. NULL,
  127958. &_vq_auxt__8c1_s_p9_1,
  127959. NULL,
  127960. 0
  127961. };
  127962. static long _vq_quantlist__8c1_s_p9_2[] = {
  127963. 10,
  127964. 9,
  127965. 11,
  127966. 8,
  127967. 12,
  127968. 7,
  127969. 13,
  127970. 6,
  127971. 14,
  127972. 5,
  127973. 15,
  127974. 4,
  127975. 16,
  127976. 3,
  127977. 17,
  127978. 2,
  127979. 18,
  127980. 1,
  127981. 19,
  127982. 0,
  127983. 20,
  127984. };
  127985. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127986. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127987. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127988. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127989. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127990. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127991. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127992. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127993. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127994. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127995. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127996. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127997. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127998. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127999. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  128000. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  128001. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  128002. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128003. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  128004. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  128005. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  128006. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128007. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  128008. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  128009. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128010. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  128011. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  128012. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  128013. 10,10,10,10,10,10,10,10,10,
  128014. };
  128015. static float _vq_quantthresh__8c1_s_p9_2[] = {
  128016. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128017. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128018. 6.5, 7.5, 8.5, 9.5,
  128019. };
  128020. static long _vq_quantmap__8c1_s_p9_2[] = {
  128021. 19, 17, 15, 13, 11, 9, 7, 5,
  128022. 3, 1, 0, 2, 4, 6, 8, 10,
  128023. 12, 14, 16, 18, 20,
  128024. };
  128025. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  128026. _vq_quantthresh__8c1_s_p9_2,
  128027. _vq_quantmap__8c1_s_p9_2,
  128028. 21,
  128029. 21
  128030. };
  128031. static static_codebook _8c1_s_p9_2 = {
  128032. 2, 441,
  128033. _vq_lengthlist__8c1_s_p9_2,
  128034. 1, -529268736, 1611661312, 5, 0,
  128035. _vq_quantlist__8c1_s_p9_2,
  128036. NULL,
  128037. &_vq_auxt__8c1_s_p9_2,
  128038. NULL,
  128039. 0
  128040. };
  128041. static long _huff_lengthlist__8c1_s_single[] = {
  128042. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  128043. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  128044. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  128045. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  128046. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  128047. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  128048. 9, 7, 7, 8,
  128049. };
  128050. static static_codebook _huff_book__8c1_s_single = {
  128051. 2, 100,
  128052. _huff_lengthlist__8c1_s_single,
  128053. 0, 0, 0, 0, 0,
  128054. NULL,
  128055. NULL,
  128056. NULL,
  128057. NULL,
  128058. 0
  128059. };
  128060. static long _huff_lengthlist__44c2_s_long[] = {
  128061. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  128062. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  128063. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  128064. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  128065. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  128066. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  128067. 10, 8, 8, 9,
  128068. };
  128069. static static_codebook _huff_book__44c2_s_long = {
  128070. 2, 100,
  128071. _huff_lengthlist__44c2_s_long,
  128072. 0, 0, 0, 0, 0,
  128073. NULL,
  128074. NULL,
  128075. NULL,
  128076. NULL,
  128077. 0
  128078. };
  128079. static long _vq_quantlist__44c2_s_p1_0[] = {
  128080. 1,
  128081. 0,
  128082. 2,
  128083. };
  128084. static long _vq_lengthlist__44c2_s_p1_0[] = {
  128085. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128086. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128091. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128096. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  128131. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  128136. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  128141. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128177. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128182. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128187. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128495. 0,
  128496. };
  128497. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128498. -0.5, 0.5,
  128499. };
  128500. static long _vq_quantmap__44c2_s_p1_0[] = {
  128501. 1, 0, 2,
  128502. };
  128503. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128504. _vq_quantthresh__44c2_s_p1_0,
  128505. _vq_quantmap__44c2_s_p1_0,
  128506. 3,
  128507. 3
  128508. };
  128509. static static_codebook _44c2_s_p1_0 = {
  128510. 8, 6561,
  128511. _vq_lengthlist__44c2_s_p1_0,
  128512. 1, -535822336, 1611661312, 2, 0,
  128513. _vq_quantlist__44c2_s_p1_0,
  128514. NULL,
  128515. &_vq_auxt__44c2_s_p1_0,
  128516. NULL,
  128517. 0
  128518. };
  128519. static long _vq_quantlist__44c2_s_p2_0[] = {
  128520. 2,
  128521. 1,
  128522. 3,
  128523. 0,
  128524. 4,
  128525. };
  128526. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128527. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128528. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128529. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128530. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128531. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128536. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128537. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128538. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128539. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128544. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128545. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128546. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128552. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128553. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128554. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128566. 0,
  128567. };
  128568. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128569. -1.5, -0.5, 0.5, 1.5,
  128570. };
  128571. static long _vq_quantmap__44c2_s_p2_0[] = {
  128572. 3, 1, 0, 2, 4,
  128573. };
  128574. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128575. _vq_quantthresh__44c2_s_p2_0,
  128576. _vq_quantmap__44c2_s_p2_0,
  128577. 5,
  128578. 5
  128579. };
  128580. static static_codebook _44c2_s_p2_0 = {
  128581. 4, 625,
  128582. _vq_lengthlist__44c2_s_p2_0,
  128583. 1, -533725184, 1611661312, 3, 0,
  128584. _vq_quantlist__44c2_s_p2_0,
  128585. NULL,
  128586. &_vq_auxt__44c2_s_p2_0,
  128587. NULL,
  128588. 0
  128589. };
  128590. static long _vq_quantlist__44c2_s_p3_0[] = {
  128591. 2,
  128592. 1,
  128593. 3,
  128594. 0,
  128595. 4,
  128596. };
  128597. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128598. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128601. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128604. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128637. 0,
  128638. };
  128639. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128640. -1.5, -0.5, 0.5, 1.5,
  128641. };
  128642. static long _vq_quantmap__44c2_s_p3_0[] = {
  128643. 3, 1, 0, 2, 4,
  128644. };
  128645. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128646. _vq_quantthresh__44c2_s_p3_0,
  128647. _vq_quantmap__44c2_s_p3_0,
  128648. 5,
  128649. 5
  128650. };
  128651. static static_codebook _44c2_s_p3_0 = {
  128652. 4, 625,
  128653. _vq_lengthlist__44c2_s_p3_0,
  128654. 1, -533725184, 1611661312, 3, 0,
  128655. _vq_quantlist__44c2_s_p3_0,
  128656. NULL,
  128657. &_vq_auxt__44c2_s_p3_0,
  128658. NULL,
  128659. 0
  128660. };
  128661. static long _vq_quantlist__44c2_s_p4_0[] = {
  128662. 4,
  128663. 3,
  128664. 5,
  128665. 2,
  128666. 6,
  128667. 1,
  128668. 7,
  128669. 0,
  128670. 8,
  128671. };
  128672. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128673. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128674. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128675. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128676. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128677. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128678. 0,
  128679. };
  128680. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128681. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128682. };
  128683. static long _vq_quantmap__44c2_s_p4_0[] = {
  128684. 7, 5, 3, 1, 0, 2, 4, 6,
  128685. 8,
  128686. };
  128687. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128688. _vq_quantthresh__44c2_s_p4_0,
  128689. _vq_quantmap__44c2_s_p4_0,
  128690. 9,
  128691. 9
  128692. };
  128693. static static_codebook _44c2_s_p4_0 = {
  128694. 2, 81,
  128695. _vq_lengthlist__44c2_s_p4_0,
  128696. 1, -531628032, 1611661312, 4, 0,
  128697. _vq_quantlist__44c2_s_p4_0,
  128698. NULL,
  128699. &_vq_auxt__44c2_s_p4_0,
  128700. NULL,
  128701. 0
  128702. };
  128703. static long _vq_quantlist__44c2_s_p5_0[] = {
  128704. 4,
  128705. 3,
  128706. 5,
  128707. 2,
  128708. 6,
  128709. 1,
  128710. 7,
  128711. 0,
  128712. 8,
  128713. };
  128714. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128715. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128716. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128717. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128718. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128719. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128720. 11,
  128721. };
  128722. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128723. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128724. };
  128725. static long _vq_quantmap__44c2_s_p5_0[] = {
  128726. 7, 5, 3, 1, 0, 2, 4, 6,
  128727. 8,
  128728. };
  128729. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128730. _vq_quantthresh__44c2_s_p5_0,
  128731. _vq_quantmap__44c2_s_p5_0,
  128732. 9,
  128733. 9
  128734. };
  128735. static static_codebook _44c2_s_p5_0 = {
  128736. 2, 81,
  128737. _vq_lengthlist__44c2_s_p5_0,
  128738. 1, -531628032, 1611661312, 4, 0,
  128739. _vq_quantlist__44c2_s_p5_0,
  128740. NULL,
  128741. &_vq_auxt__44c2_s_p5_0,
  128742. NULL,
  128743. 0
  128744. };
  128745. static long _vq_quantlist__44c2_s_p6_0[] = {
  128746. 8,
  128747. 7,
  128748. 9,
  128749. 6,
  128750. 10,
  128751. 5,
  128752. 11,
  128753. 4,
  128754. 12,
  128755. 3,
  128756. 13,
  128757. 2,
  128758. 14,
  128759. 1,
  128760. 15,
  128761. 0,
  128762. 16,
  128763. };
  128764. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128765. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128766. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128767. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128768. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128769. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128770. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128771. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128772. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128773. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128774. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128775. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128776. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128777. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128778. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128779. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128780. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128781. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128782. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128783. 14,
  128784. };
  128785. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128786. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128787. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128788. };
  128789. static long _vq_quantmap__44c2_s_p6_0[] = {
  128790. 15, 13, 11, 9, 7, 5, 3, 1,
  128791. 0, 2, 4, 6, 8, 10, 12, 14,
  128792. 16,
  128793. };
  128794. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128795. _vq_quantthresh__44c2_s_p6_0,
  128796. _vq_quantmap__44c2_s_p6_0,
  128797. 17,
  128798. 17
  128799. };
  128800. static static_codebook _44c2_s_p6_0 = {
  128801. 2, 289,
  128802. _vq_lengthlist__44c2_s_p6_0,
  128803. 1, -529530880, 1611661312, 5, 0,
  128804. _vq_quantlist__44c2_s_p6_0,
  128805. NULL,
  128806. &_vq_auxt__44c2_s_p6_0,
  128807. NULL,
  128808. 0
  128809. };
  128810. static long _vq_quantlist__44c2_s_p7_0[] = {
  128811. 1,
  128812. 0,
  128813. 2,
  128814. };
  128815. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128816. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128817. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128818. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128819. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128820. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128821. 11,
  128822. };
  128823. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128824. -5.5, 5.5,
  128825. };
  128826. static long _vq_quantmap__44c2_s_p7_0[] = {
  128827. 1, 0, 2,
  128828. };
  128829. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128830. _vq_quantthresh__44c2_s_p7_0,
  128831. _vq_quantmap__44c2_s_p7_0,
  128832. 3,
  128833. 3
  128834. };
  128835. static static_codebook _44c2_s_p7_0 = {
  128836. 4, 81,
  128837. _vq_lengthlist__44c2_s_p7_0,
  128838. 1, -529137664, 1618345984, 2, 0,
  128839. _vq_quantlist__44c2_s_p7_0,
  128840. NULL,
  128841. &_vq_auxt__44c2_s_p7_0,
  128842. NULL,
  128843. 0
  128844. };
  128845. static long _vq_quantlist__44c2_s_p7_1[] = {
  128846. 5,
  128847. 4,
  128848. 6,
  128849. 3,
  128850. 7,
  128851. 2,
  128852. 8,
  128853. 1,
  128854. 9,
  128855. 0,
  128856. 10,
  128857. };
  128858. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128859. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128860. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128861. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128862. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128863. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128864. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128865. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128866. 10,10,10, 8, 8, 8, 8, 8, 8,
  128867. };
  128868. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128869. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128870. 3.5, 4.5,
  128871. };
  128872. static long _vq_quantmap__44c2_s_p7_1[] = {
  128873. 9, 7, 5, 3, 1, 0, 2, 4,
  128874. 6, 8, 10,
  128875. };
  128876. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128877. _vq_quantthresh__44c2_s_p7_1,
  128878. _vq_quantmap__44c2_s_p7_1,
  128879. 11,
  128880. 11
  128881. };
  128882. static static_codebook _44c2_s_p7_1 = {
  128883. 2, 121,
  128884. _vq_lengthlist__44c2_s_p7_1,
  128885. 1, -531365888, 1611661312, 4, 0,
  128886. _vq_quantlist__44c2_s_p7_1,
  128887. NULL,
  128888. &_vq_auxt__44c2_s_p7_1,
  128889. NULL,
  128890. 0
  128891. };
  128892. static long _vq_quantlist__44c2_s_p8_0[] = {
  128893. 6,
  128894. 5,
  128895. 7,
  128896. 4,
  128897. 8,
  128898. 3,
  128899. 9,
  128900. 2,
  128901. 10,
  128902. 1,
  128903. 11,
  128904. 0,
  128905. 12,
  128906. };
  128907. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128908. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128909. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128910. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128911. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128912. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128913. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128914. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128915. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128916. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128917. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128918. 0,12,12,12,12,13,12,14,14,
  128919. };
  128920. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128921. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128922. 12.5, 17.5, 22.5, 27.5,
  128923. };
  128924. static long _vq_quantmap__44c2_s_p8_0[] = {
  128925. 11, 9, 7, 5, 3, 1, 0, 2,
  128926. 4, 6, 8, 10, 12,
  128927. };
  128928. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128929. _vq_quantthresh__44c2_s_p8_0,
  128930. _vq_quantmap__44c2_s_p8_0,
  128931. 13,
  128932. 13
  128933. };
  128934. static static_codebook _44c2_s_p8_0 = {
  128935. 2, 169,
  128936. _vq_lengthlist__44c2_s_p8_0,
  128937. 1, -526516224, 1616117760, 4, 0,
  128938. _vq_quantlist__44c2_s_p8_0,
  128939. NULL,
  128940. &_vq_auxt__44c2_s_p8_0,
  128941. NULL,
  128942. 0
  128943. };
  128944. static long _vq_quantlist__44c2_s_p8_1[] = {
  128945. 2,
  128946. 1,
  128947. 3,
  128948. 0,
  128949. 4,
  128950. };
  128951. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128952. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128953. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128954. };
  128955. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128956. -1.5, -0.5, 0.5, 1.5,
  128957. };
  128958. static long _vq_quantmap__44c2_s_p8_1[] = {
  128959. 3, 1, 0, 2, 4,
  128960. };
  128961. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128962. _vq_quantthresh__44c2_s_p8_1,
  128963. _vq_quantmap__44c2_s_p8_1,
  128964. 5,
  128965. 5
  128966. };
  128967. static static_codebook _44c2_s_p8_1 = {
  128968. 2, 25,
  128969. _vq_lengthlist__44c2_s_p8_1,
  128970. 1, -533725184, 1611661312, 3, 0,
  128971. _vq_quantlist__44c2_s_p8_1,
  128972. NULL,
  128973. &_vq_auxt__44c2_s_p8_1,
  128974. NULL,
  128975. 0
  128976. };
  128977. static long _vq_quantlist__44c2_s_p9_0[] = {
  128978. 6,
  128979. 5,
  128980. 7,
  128981. 4,
  128982. 8,
  128983. 3,
  128984. 9,
  128985. 2,
  128986. 10,
  128987. 1,
  128988. 11,
  128989. 0,
  128990. 12,
  128991. };
  128992. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128993. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128994. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128995. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128996. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128997. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128998. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128999. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129000. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129001. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129002. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129003. 11,11,11,11,11,11,11,11,11,
  129004. };
  129005. static float _vq_quantthresh__44c2_s_p9_0[] = {
  129006. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  129007. 552.5, 773.5, 994.5, 1215.5,
  129008. };
  129009. static long _vq_quantmap__44c2_s_p9_0[] = {
  129010. 11, 9, 7, 5, 3, 1, 0, 2,
  129011. 4, 6, 8, 10, 12,
  129012. };
  129013. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  129014. _vq_quantthresh__44c2_s_p9_0,
  129015. _vq_quantmap__44c2_s_p9_0,
  129016. 13,
  129017. 13
  129018. };
  129019. static static_codebook _44c2_s_p9_0 = {
  129020. 2, 169,
  129021. _vq_lengthlist__44c2_s_p9_0,
  129022. 1, -514541568, 1627103232, 4, 0,
  129023. _vq_quantlist__44c2_s_p9_0,
  129024. NULL,
  129025. &_vq_auxt__44c2_s_p9_0,
  129026. NULL,
  129027. 0
  129028. };
  129029. static long _vq_quantlist__44c2_s_p9_1[] = {
  129030. 6,
  129031. 5,
  129032. 7,
  129033. 4,
  129034. 8,
  129035. 3,
  129036. 9,
  129037. 2,
  129038. 10,
  129039. 1,
  129040. 11,
  129041. 0,
  129042. 12,
  129043. };
  129044. static long _vq_lengthlist__44c2_s_p9_1[] = {
  129045. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  129046. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  129047. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  129048. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  129049. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  129050. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  129051. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  129052. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  129053. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  129054. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  129055. 17,13,12,12,10,13,11,14,14,
  129056. };
  129057. static float _vq_quantthresh__44c2_s_p9_1[] = {
  129058. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  129059. 42.5, 59.5, 76.5, 93.5,
  129060. };
  129061. static long _vq_quantmap__44c2_s_p9_1[] = {
  129062. 11, 9, 7, 5, 3, 1, 0, 2,
  129063. 4, 6, 8, 10, 12,
  129064. };
  129065. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  129066. _vq_quantthresh__44c2_s_p9_1,
  129067. _vq_quantmap__44c2_s_p9_1,
  129068. 13,
  129069. 13
  129070. };
  129071. static static_codebook _44c2_s_p9_1 = {
  129072. 2, 169,
  129073. _vq_lengthlist__44c2_s_p9_1,
  129074. 1, -522616832, 1620115456, 4, 0,
  129075. _vq_quantlist__44c2_s_p9_1,
  129076. NULL,
  129077. &_vq_auxt__44c2_s_p9_1,
  129078. NULL,
  129079. 0
  129080. };
  129081. static long _vq_quantlist__44c2_s_p9_2[] = {
  129082. 8,
  129083. 7,
  129084. 9,
  129085. 6,
  129086. 10,
  129087. 5,
  129088. 11,
  129089. 4,
  129090. 12,
  129091. 3,
  129092. 13,
  129093. 2,
  129094. 14,
  129095. 1,
  129096. 15,
  129097. 0,
  129098. 16,
  129099. };
  129100. static long _vq_lengthlist__44c2_s_p9_2[] = {
  129101. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129102. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129103. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  129104. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  129105. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  129106. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129107. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  129108. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  129109. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  129110. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  129111. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  129112. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  129113. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  129114. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  129115. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  129116. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  129117. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  129118. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  129119. 10,
  129120. };
  129121. static float _vq_quantthresh__44c2_s_p9_2[] = {
  129122. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129123. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129124. };
  129125. static long _vq_quantmap__44c2_s_p9_2[] = {
  129126. 15, 13, 11, 9, 7, 5, 3, 1,
  129127. 0, 2, 4, 6, 8, 10, 12, 14,
  129128. 16,
  129129. };
  129130. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  129131. _vq_quantthresh__44c2_s_p9_2,
  129132. _vq_quantmap__44c2_s_p9_2,
  129133. 17,
  129134. 17
  129135. };
  129136. static static_codebook _44c2_s_p9_2 = {
  129137. 2, 289,
  129138. _vq_lengthlist__44c2_s_p9_2,
  129139. 1, -529530880, 1611661312, 5, 0,
  129140. _vq_quantlist__44c2_s_p9_2,
  129141. NULL,
  129142. &_vq_auxt__44c2_s_p9_2,
  129143. NULL,
  129144. 0
  129145. };
  129146. static long _huff_lengthlist__44c2_s_short[] = {
  129147. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  129148. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  129149. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  129150. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  129151. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  129152. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  129153. 6, 8, 9,12,
  129154. };
  129155. static static_codebook _huff_book__44c2_s_short = {
  129156. 2, 100,
  129157. _huff_lengthlist__44c2_s_short,
  129158. 0, 0, 0, 0, 0,
  129159. NULL,
  129160. NULL,
  129161. NULL,
  129162. NULL,
  129163. 0
  129164. };
  129165. static long _huff_lengthlist__44c3_s_long[] = {
  129166. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  129167. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  129168. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  129169. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  129170. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  129171. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  129172. 9, 8, 8, 8,
  129173. };
  129174. static static_codebook _huff_book__44c3_s_long = {
  129175. 2, 100,
  129176. _huff_lengthlist__44c3_s_long,
  129177. 0, 0, 0, 0, 0,
  129178. NULL,
  129179. NULL,
  129180. NULL,
  129181. NULL,
  129182. 0
  129183. };
  129184. static long _vq_quantlist__44c3_s_p1_0[] = {
  129185. 1,
  129186. 0,
  129187. 2,
  129188. };
  129189. static long _vq_lengthlist__44c3_s_p1_0[] = {
  129190. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129191. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129196. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129201. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  129236. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  129241. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  129246. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129282. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129287. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129292. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129600. 0,
  129601. };
  129602. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129603. -0.5, 0.5,
  129604. };
  129605. static long _vq_quantmap__44c3_s_p1_0[] = {
  129606. 1, 0, 2,
  129607. };
  129608. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129609. _vq_quantthresh__44c3_s_p1_0,
  129610. _vq_quantmap__44c3_s_p1_0,
  129611. 3,
  129612. 3
  129613. };
  129614. static static_codebook _44c3_s_p1_0 = {
  129615. 8, 6561,
  129616. _vq_lengthlist__44c3_s_p1_0,
  129617. 1, -535822336, 1611661312, 2, 0,
  129618. _vq_quantlist__44c3_s_p1_0,
  129619. NULL,
  129620. &_vq_auxt__44c3_s_p1_0,
  129621. NULL,
  129622. 0
  129623. };
  129624. static long _vq_quantlist__44c3_s_p2_0[] = {
  129625. 2,
  129626. 1,
  129627. 3,
  129628. 0,
  129629. 4,
  129630. };
  129631. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129632. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129633. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129634. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129635. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129636. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129641. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129642. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129643. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129644. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129649. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129650. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129651. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129657. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129658. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129659. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129671. 0,
  129672. };
  129673. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129674. -1.5, -0.5, 0.5, 1.5,
  129675. };
  129676. static long _vq_quantmap__44c3_s_p2_0[] = {
  129677. 3, 1, 0, 2, 4,
  129678. };
  129679. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129680. _vq_quantthresh__44c3_s_p2_0,
  129681. _vq_quantmap__44c3_s_p2_0,
  129682. 5,
  129683. 5
  129684. };
  129685. static static_codebook _44c3_s_p2_0 = {
  129686. 4, 625,
  129687. _vq_lengthlist__44c3_s_p2_0,
  129688. 1, -533725184, 1611661312, 3, 0,
  129689. _vq_quantlist__44c3_s_p2_0,
  129690. NULL,
  129691. &_vq_auxt__44c3_s_p2_0,
  129692. NULL,
  129693. 0
  129694. };
  129695. static long _vq_quantlist__44c3_s_p3_0[] = {
  129696. 2,
  129697. 1,
  129698. 3,
  129699. 0,
  129700. 4,
  129701. };
  129702. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129703. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129706. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129709. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129742. 0,
  129743. };
  129744. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129745. -1.5, -0.5, 0.5, 1.5,
  129746. };
  129747. static long _vq_quantmap__44c3_s_p3_0[] = {
  129748. 3, 1, 0, 2, 4,
  129749. };
  129750. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129751. _vq_quantthresh__44c3_s_p3_0,
  129752. _vq_quantmap__44c3_s_p3_0,
  129753. 5,
  129754. 5
  129755. };
  129756. static static_codebook _44c3_s_p3_0 = {
  129757. 4, 625,
  129758. _vq_lengthlist__44c3_s_p3_0,
  129759. 1, -533725184, 1611661312, 3, 0,
  129760. _vq_quantlist__44c3_s_p3_0,
  129761. NULL,
  129762. &_vq_auxt__44c3_s_p3_0,
  129763. NULL,
  129764. 0
  129765. };
  129766. static long _vq_quantlist__44c3_s_p4_0[] = {
  129767. 4,
  129768. 3,
  129769. 5,
  129770. 2,
  129771. 6,
  129772. 1,
  129773. 7,
  129774. 0,
  129775. 8,
  129776. };
  129777. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129778. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129779. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129780. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129781. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129782. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129783. 0,
  129784. };
  129785. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129786. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129787. };
  129788. static long _vq_quantmap__44c3_s_p4_0[] = {
  129789. 7, 5, 3, 1, 0, 2, 4, 6,
  129790. 8,
  129791. };
  129792. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129793. _vq_quantthresh__44c3_s_p4_0,
  129794. _vq_quantmap__44c3_s_p4_0,
  129795. 9,
  129796. 9
  129797. };
  129798. static static_codebook _44c3_s_p4_0 = {
  129799. 2, 81,
  129800. _vq_lengthlist__44c3_s_p4_0,
  129801. 1, -531628032, 1611661312, 4, 0,
  129802. _vq_quantlist__44c3_s_p4_0,
  129803. NULL,
  129804. &_vq_auxt__44c3_s_p4_0,
  129805. NULL,
  129806. 0
  129807. };
  129808. static long _vq_quantlist__44c3_s_p5_0[] = {
  129809. 4,
  129810. 3,
  129811. 5,
  129812. 2,
  129813. 6,
  129814. 1,
  129815. 7,
  129816. 0,
  129817. 8,
  129818. };
  129819. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129820. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129821. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129822. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129823. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129824. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129825. 11,
  129826. };
  129827. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129828. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129829. };
  129830. static long _vq_quantmap__44c3_s_p5_0[] = {
  129831. 7, 5, 3, 1, 0, 2, 4, 6,
  129832. 8,
  129833. };
  129834. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129835. _vq_quantthresh__44c3_s_p5_0,
  129836. _vq_quantmap__44c3_s_p5_0,
  129837. 9,
  129838. 9
  129839. };
  129840. static static_codebook _44c3_s_p5_0 = {
  129841. 2, 81,
  129842. _vq_lengthlist__44c3_s_p5_0,
  129843. 1, -531628032, 1611661312, 4, 0,
  129844. _vq_quantlist__44c3_s_p5_0,
  129845. NULL,
  129846. &_vq_auxt__44c3_s_p5_0,
  129847. NULL,
  129848. 0
  129849. };
  129850. static long _vq_quantlist__44c3_s_p6_0[] = {
  129851. 8,
  129852. 7,
  129853. 9,
  129854. 6,
  129855. 10,
  129856. 5,
  129857. 11,
  129858. 4,
  129859. 12,
  129860. 3,
  129861. 13,
  129862. 2,
  129863. 14,
  129864. 1,
  129865. 15,
  129866. 0,
  129867. 16,
  129868. };
  129869. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129870. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129871. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129872. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129873. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129874. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129875. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129876. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129877. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129878. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129879. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129880. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129881. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129882. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129883. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129884. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129885. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129886. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129887. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129888. 13,
  129889. };
  129890. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129891. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129892. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129893. };
  129894. static long _vq_quantmap__44c3_s_p6_0[] = {
  129895. 15, 13, 11, 9, 7, 5, 3, 1,
  129896. 0, 2, 4, 6, 8, 10, 12, 14,
  129897. 16,
  129898. };
  129899. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129900. _vq_quantthresh__44c3_s_p6_0,
  129901. _vq_quantmap__44c3_s_p6_0,
  129902. 17,
  129903. 17
  129904. };
  129905. static static_codebook _44c3_s_p6_0 = {
  129906. 2, 289,
  129907. _vq_lengthlist__44c3_s_p6_0,
  129908. 1, -529530880, 1611661312, 5, 0,
  129909. _vq_quantlist__44c3_s_p6_0,
  129910. NULL,
  129911. &_vq_auxt__44c3_s_p6_0,
  129912. NULL,
  129913. 0
  129914. };
  129915. static long _vq_quantlist__44c3_s_p7_0[] = {
  129916. 1,
  129917. 0,
  129918. 2,
  129919. };
  129920. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129921. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129922. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129923. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129924. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129925. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129926. 10,
  129927. };
  129928. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129929. -5.5, 5.5,
  129930. };
  129931. static long _vq_quantmap__44c3_s_p7_0[] = {
  129932. 1, 0, 2,
  129933. };
  129934. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129935. _vq_quantthresh__44c3_s_p7_0,
  129936. _vq_quantmap__44c3_s_p7_0,
  129937. 3,
  129938. 3
  129939. };
  129940. static static_codebook _44c3_s_p7_0 = {
  129941. 4, 81,
  129942. _vq_lengthlist__44c3_s_p7_0,
  129943. 1, -529137664, 1618345984, 2, 0,
  129944. _vq_quantlist__44c3_s_p7_0,
  129945. NULL,
  129946. &_vq_auxt__44c3_s_p7_0,
  129947. NULL,
  129948. 0
  129949. };
  129950. static long _vq_quantlist__44c3_s_p7_1[] = {
  129951. 5,
  129952. 4,
  129953. 6,
  129954. 3,
  129955. 7,
  129956. 2,
  129957. 8,
  129958. 1,
  129959. 9,
  129960. 0,
  129961. 10,
  129962. };
  129963. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129964. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129965. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129966. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129967. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129968. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129969. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129970. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129971. 10,10,10, 8, 8, 8, 8, 8, 8,
  129972. };
  129973. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129974. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129975. 3.5, 4.5,
  129976. };
  129977. static long _vq_quantmap__44c3_s_p7_1[] = {
  129978. 9, 7, 5, 3, 1, 0, 2, 4,
  129979. 6, 8, 10,
  129980. };
  129981. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129982. _vq_quantthresh__44c3_s_p7_1,
  129983. _vq_quantmap__44c3_s_p7_1,
  129984. 11,
  129985. 11
  129986. };
  129987. static static_codebook _44c3_s_p7_1 = {
  129988. 2, 121,
  129989. _vq_lengthlist__44c3_s_p7_1,
  129990. 1, -531365888, 1611661312, 4, 0,
  129991. _vq_quantlist__44c3_s_p7_1,
  129992. NULL,
  129993. &_vq_auxt__44c3_s_p7_1,
  129994. NULL,
  129995. 0
  129996. };
  129997. static long _vq_quantlist__44c3_s_p8_0[] = {
  129998. 6,
  129999. 5,
  130000. 7,
  130001. 4,
  130002. 8,
  130003. 3,
  130004. 9,
  130005. 2,
  130006. 10,
  130007. 1,
  130008. 11,
  130009. 0,
  130010. 12,
  130011. };
  130012. static long _vq_lengthlist__44c3_s_p8_0[] = {
  130013. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130014. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  130015. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130016. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130017. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  130018. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  130019. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  130020. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130021. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  130022. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  130023. 0,13,13,12,12,13,12,14,13,
  130024. };
  130025. static float _vq_quantthresh__44c3_s_p8_0[] = {
  130026. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130027. 12.5, 17.5, 22.5, 27.5,
  130028. };
  130029. static long _vq_quantmap__44c3_s_p8_0[] = {
  130030. 11, 9, 7, 5, 3, 1, 0, 2,
  130031. 4, 6, 8, 10, 12,
  130032. };
  130033. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  130034. _vq_quantthresh__44c3_s_p8_0,
  130035. _vq_quantmap__44c3_s_p8_0,
  130036. 13,
  130037. 13
  130038. };
  130039. static static_codebook _44c3_s_p8_0 = {
  130040. 2, 169,
  130041. _vq_lengthlist__44c3_s_p8_0,
  130042. 1, -526516224, 1616117760, 4, 0,
  130043. _vq_quantlist__44c3_s_p8_0,
  130044. NULL,
  130045. &_vq_auxt__44c3_s_p8_0,
  130046. NULL,
  130047. 0
  130048. };
  130049. static long _vq_quantlist__44c3_s_p8_1[] = {
  130050. 2,
  130051. 1,
  130052. 3,
  130053. 0,
  130054. 4,
  130055. };
  130056. static long _vq_lengthlist__44c3_s_p8_1[] = {
  130057. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  130058. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130059. };
  130060. static float _vq_quantthresh__44c3_s_p8_1[] = {
  130061. -1.5, -0.5, 0.5, 1.5,
  130062. };
  130063. static long _vq_quantmap__44c3_s_p8_1[] = {
  130064. 3, 1, 0, 2, 4,
  130065. };
  130066. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  130067. _vq_quantthresh__44c3_s_p8_1,
  130068. _vq_quantmap__44c3_s_p8_1,
  130069. 5,
  130070. 5
  130071. };
  130072. static static_codebook _44c3_s_p8_1 = {
  130073. 2, 25,
  130074. _vq_lengthlist__44c3_s_p8_1,
  130075. 1, -533725184, 1611661312, 3, 0,
  130076. _vq_quantlist__44c3_s_p8_1,
  130077. NULL,
  130078. &_vq_auxt__44c3_s_p8_1,
  130079. NULL,
  130080. 0
  130081. };
  130082. static long _vq_quantlist__44c3_s_p9_0[] = {
  130083. 6,
  130084. 5,
  130085. 7,
  130086. 4,
  130087. 8,
  130088. 3,
  130089. 9,
  130090. 2,
  130091. 10,
  130092. 1,
  130093. 11,
  130094. 0,
  130095. 12,
  130096. };
  130097. static long _vq_lengthlist__44c3_s_p9_0[] = {
  130098. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  130099. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  130100. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130101. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  130102. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130103. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130104. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130105. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130106. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  130107. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130108. 11,11,11,11,11,11,11,11,11,
  130109. };
  130110. static float _vq_quantthresh__44c3_s_p9_0[] = {
  130111. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  130112. 637.5, 892.5, 1147.5, 1402.5,
  130113. };
  130114. static long _vq_quantmap__44c3_s_p9_0[] = {
  130115. 11, 9, 7, 5, 3, 1, 0, 2,
  130116. 4, 6, 8, 10, 12,
  130117. };
  130118. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  130119. _vq_quantthresh__44c3_s_p9_0,
  130120. _vq_quantmap__44c3_s_p9_0,
  130121. 13,
  130122. 13
  130123. };
  130124. static static_codebook _44c3_s_p9_0 = {
  130125. 2, 169,
  130126. _vq_lengthlist__44c3_s_p9_0,
  130127. 1, -514332672, 1627381760, 4, 0,
  130128. _vq_quantlist__44c3_s_p9_0,
  130129. NULL,
  130130. &_vq_auxt__44c3_s_p9_0,
  130131. NULL,
  130132. 0
  130133. };
  130134. static long _vq_quantlist__44c3_s_p9_1[] = {
  130135. 7,
  130136. 6,
  130137. 8,
  130138. 5,
  130139. 9,
  130140. 4,
  130141. 10,
  130142. 3,
  130143. 11,
  130144. 2,
  130145. 12,
  130146. 1,
  130147. 13,
  130148. 0,
  130149. 14,
  130150. };
  130151. static long _vq_lengthlist__44c3_s_p9_1[] = {
  130152. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  130153. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  130154. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  130155. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  130156. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  130157. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  130158. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  130159. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  130160. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  130161. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  130162. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  130163. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  130164. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  130165. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  130166. 15,
  130167. };
  130168. static float _vq_quantthresh__44c3_s_p9_1[] = {
  130169. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  130170. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  130171. };
  130172. static long _vq_quantmap__44c3_s_p9_1[] = {
  130173. 13, 11, 9, 7, 5, 3, 1, 0,
  130174. 2, 4, 6, 8, 10, 12, 14,
  130175. };
  130176. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  130177. _vq_quantthresh__44c3_s_p9_1,
  130178. _vq_quantmap__44c3_s_p9_1,
  130179. 15,
  130180. 15
  130181. };
  130182. static static_codebook _44c3_s_p9_1 = {
  130183. 2, 225,
  130184. _vq_lengthlist__44c3_s_p9_1,
  130185. 1, -522338304, 1620115456, 4, 0,
  130186. _vq_quantlist__44c3_s_p9_1,
  130187. NULL,
  130188. &_vq_auxt__44c3_s_p9_1,
  130189. NULL,
  130190. 0
  130191. };
  130192. static long _vq_quantlist__44c3_s_p9_2[] = {
  130193. 8,
  130194. 7,
  130195. 9,
  130196. 6,
  130197. 10,
  130198. 5,
  130199. 11,
  130200. 4,
  130201. 12,
  130202. 3,
  130203. 13,
  130204. 2,
  130205. 14,
  130206. 1,
  130207. 15,
  130208. 0,
  130209. 16,
  130210. };
  130211. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130212. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130213. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130214. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130215. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130216. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130217. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130218. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130219. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130220. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130221. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130222. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130223. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130224. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130225. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130226. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130227. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130228. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130229. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130230. 10,
  130231. };
  130232. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130233. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130234. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130235. };
  130236. static long _vq_quantmap__44c3_s_p9_2[] = {
  130237. 15, 13, 11, 9, 7, 5, 3, 1,
  130238. 0, 2, 4, 6, 8, 10, 12, 14,
  130239. 16,
  130240. };
  130241. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130242. _vq_quantthresh__44c3_s_p9_2,
  130243. _vq_quantmap__44c3_s_p9_2,
  130244. 17,
  130245. 17
  130246. };
  130247. static static_codebook _44c3_s_p9_2 = {
  130248. 2, 289,
  130249. _vq_lengthlist__44c3_s_p9_2,
  130250. 1, -529530880, 1611661312, 5, 0,
  130251. _vq_quantlist__44c3_s_p9_2,
  130252. NULL,
  130253. &_vq_auxt__44c3_s_p9_2,
  130254. NULL,
  130255. 0
  130256. };
  130257. static long _huff_lengthlist__44c3_s_short[] = {
  130258. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130259. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130260. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130261. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130262. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130263. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130264. 6, 8, 9,11,
  130265. };
  130266. static static_codebook _huff_book__44c3_s_short = {
  130267. 2, 100,
  130268. _huff_lengthlist__44c3_s_short,
  130269. 0, 0, 0, 0, 0,
  130270. NULL,
  130271. NULL,
  130272. NULL,
  130273. NULL,
  130274. 0
  130275. };
  130276. static long _huff_lengthlist__44c4_s_long[] = {
  130277. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130278. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130279. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130280. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130281. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130282. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130283. 9, 8, 7, 7,
  130284. };
  130285. static static_codebook _huff_book__44c4_s_long = {
  130286. 2, 100,
  130287. _huff_lengthlist__44c4_s_long,
  130288. 0, 0, 0, 0, 0,
  130289. NULL,
  130290. NULL,
  130291. NULL,
  130292. NULL,
  130293. 0
  130294. };
  130295. static long _vq_quantlist__44c4_s_p1_0[] = {
  130296. 1,
  130297. 0,
  130298. 2,
  130299. };
  130300. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130301. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130302. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130307. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130312. 0, 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0,
  130347. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  130352. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  130357. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130393. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130398. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130403. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130711. 0,
  130712. };
  130713. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130714. -0.5, 0.5,
  130715. };
  130716. static long _vq_quantmap__44c4_s_p1_0[] = {
  130717. 1, 0, 2,
  130718. };
  130719. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130720. _vq_quantthresh__44c4_s_p1_0,
  130721. _vq_quantmap__44c4_s_p1_0,
  130722. 3,
  130723. 3
  130724. };
  130725. static static_codebook _44c4_s_p1_0 = {
  130726. 8, 6561,
  130727. _vq_lengthlist__44c4_s_p1_0,
  130728. 1, -535822336, 1611661312, 2, 0,
  130729. _vq_quantlist__44c4_s_p1_0,
  130730. NULL,
  130731. &_vq_auxt__44c4_s_p1_0,
  130732. NULL,
  130733. 0
  130734. };
  130735. static long _vq_quantlist__44c4_s_p2_0[] = {
  130736. 2,
  130737. 1,
  130738. 3,
  130739. 0,
  130740. 4,
  130741. };
  130742. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130743. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130744. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130745. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130746. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130747. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130752. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130753. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130754. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130755. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130760. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130761. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130762. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130768. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130769. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130770. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130782. 0,
  130783. };
  130784. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130785. -1.5, -0.5, 0.5, 1.5,
  130786. };
  130787. static long _vq_quantmap__44c4_s_p2_0[] = {
  130788. 3, 1, 0, 2, 4,
  130789. };
  130790. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130791. _vq_quantthresh__44c4_s_p2_0,
  130792. _vq_quantmap__44c4_s_p2_0,
  130793. 5,
  130794. 5
  130795. };
  130796. static static_codebook _44c4_s_p2_0 = {
  130797. 4, 625,
  130798. _vq_lengthlist__44c4_s_p2_0,
  130799. 1, -533725184, 1611661312, 3, 0,
  130800. _vq_quantlist__44c4_s_p2_0,
  130801. NULL,
  130802. &_vq_auxt__44c4_s_p2_0,
  130803. NULL,
  130804. 0
  130805. };
  130806. static long _vq_quantlist__44c4_s_p3_0[] = {
  130807. 2,
  130808. 1,
  130809. 3,
  130810. 0,
  130811. 4,
  130812. };
  130813. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130814. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130817. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130853. 0,
  130854. };
  130855. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130856. -1.5, -0.5, 0.5, 1.5,
  130857. };
  130858. static long _vq_quantmap__44c4_s_p3_0[] = {
  130859. 3, 1, 0, 2, 4,
  130860. };
  130861. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130862. _vq_quantthresh__44c4_s_p3_0,
  130863. _vq_quantmap__44c4_s_p3_0,
  130864. 5,
  130865. 5
  130866. };
  130867. static static_codebook _44c4_s_p3_0 = {
  130868. 4, 625,
  130869. _vq_lengthlist__44c4_s_p3_0,
  130870. 1, -533725184, 1611661312, 3, 0,
  130871. _vq_quantlist__44c4_s_p3_0,
  130872. NULL,
  130873. &_vq_auxt__44c4_s_p3_0,
  130874. NULL,
  130875. 0
  130876. };
  130877. static long _vq_quantlist__44c4_s_p4_0[] = {
  130878. 4,
  130879. 3,
  130880. 5,
  130881. 2,
  130882. 6,
  130883. 1,
  130884. 7,
  130885. 0,
  130886. 8,
  130887. };
  130888. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130889. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130890. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130891. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130892. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130893. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130894. 0,
  130895. };
  130896. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130897. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130898. };
  130899. static long _vq_quantmap__44c4_s_p4_0[] = {
  130900. 7, 5, 3, 1, 0, 2, 4, 6,
  130901. 8,
  130902. };
  130903. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130904. _vq_quantthresh__44c4_s_p4_0,
  130905. _vq_quantmap__44c4_s_p4_0,
  130906. 9,
  130907. 9
  130908. };
  130909. static static_codebook _44c4_s_p4_0 = {
  130910. 2, 81,
  130911. _vq_lengthlist__44c4_s_p4_0,
  130912. 1, -531628032, 1611661312, 4, 0,
  130913. _vq_quantlist__44c4_s_p4_0,
  130914. NULL,
  130915. &_vq_auxt__44c4_s_p4_0,
  130916. NULL,
  130917. 0
  130918. };
  130919. static long _vq_quantlist__44c4_s_p5_0[] = {
  130920. 4,
  130921. 3,
  130922. 5,
  130923. 2,
  130924. 6,
  130925. 1,
  130926. 7,
  130927. 0,
  130928. 8,
  130929. };
  130930. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130931. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130932. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130933. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130934. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130935. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130936. 10,
  130937. };
  130938. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130939. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130940. };
  130941. static long _vq_quantmap__44c4_s_p5_0[] = {
  130942. 7, 5, 3, 1, 0, 2, 4, 6,
  130943. 8,
  130944. };
  130945. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130946. _vq_quantthresh__44c4_s_p5_0,
  130947. _vq_quantmap__44c4_s_p5_0,
  130948. 9,
  130949. 9
  130950. };
  130951. static static_codebook _44c4_s_p5_0 = {
  130952. 2, 81,
  130953. _vq_lengthlist__44c4_s_p5_0,
  130954. 1, -531628032, 1611661312, 4, 0,
  130955. _vq_quantlist__44c4_s_p5_0,
  130956. NULL,
  130957. &_vq_auxt__44c4_s_p5_0,
  130958. NULL,
  130959. 0
  130960. };
  130961. static long _vq_quantlist__44c4_s_p6_0[] = {
  130962. 8,
  130963. 7,
  130964. 9,
  130965. 6,
  130966. 10,
  130967. 5,
  130968. 11,
  130969. 4,
  130970. 12,
  130971. 3,
  130972. 13,
  130973. 2,
  130974. 14,
  130975. 1,
  130976. 15,
  130977. 0,
  130978. 16,
  130979. };
  130980. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130981. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130982. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130983. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130984. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130985. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130986. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130987. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130988. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130989. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130990. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130991. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130992. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130993. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130994. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130995. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130996. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130997. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130999. 13,
  131000. };
  131001. static float _vq_quantthresh__44c4_s_p6_0[] = {
  131002. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131003. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131004. };
  131005. static long _vq_quantmap__44c4_s_p6_0[] = {
  131006. 15, 13, 11, 9, 7, 5, 3, 1,
  131007. 0, 2, 4, 6, 8, 10, 12, 14,
  131008. 16,
  131009. };
  131010. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  131011. _vq_quantthresh__44c4_s_p6_0,
  131012. _vq_quantmap__44c4_s_p6_0,
  131013. 17,
  131014. 17
  131015. };
  131016. static static_codebook _44c4_s_p6_0 = {
  131017. 2, 289,
  131018. _vq_lengthlist__44c4_s_p6_0,
  131019. 1, -529530880, 1611661312, 5, 0,
  131020. _vq_quantlist__44c4_s_p6_0,
  131021. NULL,
  131022. &_vq_auxt__44c4_s_p6_0,
  131023. NULL,
  131024. 0
  131025. };
  131026. static long _vq_quantlist__44c4_s_p7_0[] = {
  131027. 1,
  131028. 0,
  131029. 2,
  131030. };
  131031. static long _vq_lengthlist__44c4_s_p7_0[] = {
  131032. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131033. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131034. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131035. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131036. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131037. 10,
  131038. };
  131039. static float _vq_quantthresh__44c4_s_p7_0[] = {
  131040. -5.5, 5.5,
  131041. };
  131042. static long _vq_quantmap__44c4_s_p7_0[] = {
  131043. 1, 0, 2,
  131044. };
  131045. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  131046. _vq_quantthresh__44c4_s_p7_0,
  131047. _vq_quantmap__44c4_s_p7_0,
  131048. 3,
  131049. 3
  131050. };
  131051. static static_codebook _44c4_s_p7_0 = {
  131052. 4, 81,
  131053. _vq_lengthlist__44c4_s_p7_0,
  131054. 1, -529137664, 1618345984, 2, 0,
  131055. _vq_quantlist__44c4_s_p7_0,
  131056. NULL,
  131057. &_vq_auxt__44c4_s_p7_0,
  131058. NULL,
  131059. 0
  131060. };
  131061. static long _vq_quantlist__44c4_s_p7_1[] = {
  131062. 5,
  131063. 4,
  131064. 6,
  131065. 3,
  131066. 7,
  131067. 2,
  131068. 8,
  131069. 1,
  131070. 9,
  131071. 0,
  131072. 10,
  131073. };
  131074. static long _vq_lengthlist__44c4_s_p7_1[] = {
  131075. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  131076. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131077. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131078. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  131079. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131080. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131081. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  131082. 10,10,10, 8, 8, 8, 8, 9, 9,
  131083. };
  131084. static float _vq_quantthresh__44c4_s_p7_1[] = {
  131085. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131086. 3.5, 4.5,
  131087. };
  131088. static long _vq_quantmap__44c4_s_p7_1[] = {
  131089. 9, 7, 5, 3, 1, 0, 2, 4,
  131090. 6, 8, 10,
  131091. };
  131092. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  131093. _vq_quantthresh__44c4_s_p7_1,
  131094. _vq_quantmap__44c4_s_p7_1,
  131095. 11,
  131096. 11
  131097. };
  131098. static static_codebook _44c4_s_p7_1 = {
  131099. 2, 121,
  131100. _vq_lengthlist__44c4_s_p7_1,
  131101. 1, -531365888, 1611661312, 4, 0,
  131102. _vq_quantlist__44c4_s_p7_1,
  131103. NULL,
  131104. &_vq_auxt__44c4_s_p7_1,
  131105. NULL,
  131106. 0
  131107. };
  131108. static long _vq_quantlist__44c4_s_p8_0[] = {
  131109. 6,
  131110. 5,
  131111. 7,
  131112. 4,
  131113. 8,
  131114. 3,
  131115. 9,
  131116. 2,
  131117. 10,
  131118. 1,
  131119. 11,
  131120. 0,
  131121. 12,
  131122. };
  131123. static long _vq_lengthlist__44c4_s_p8_0[] = {
  131124. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131125. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  131126. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131127. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131128. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  131129. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  131130. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  131131. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131132. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  131133. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131134. 0,13,12,12,12,12,12,13,13,
  131135. };
  131136. static float _vq_quantthresh__44c4_s_p8_0[] = {
  131137. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131138. 12.5, 17.5, 22.5, 27.5,
  131139. };
  131140. static long _vq_quantmap__44c4_s_p8_0[] = {
  131141. 11, 9, 7, 5, 3, 1, 0, 2,
  131142. 4, 6, 8, 10, 12,
  131143. };
  131144. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  131145. _vq_quantthresh__44c4_s_p8_0,
  131146. _vq_quantmap__44c4_s_p8_0,
  131147. 13,
  131148. 13
  131149. };
  131150. static static_codebook _44c4_s_p8_0 = {
  131151. 2, 169,
  131152. _vq_lengthlist__44c4_s_p8_0,
  131153. 1, -526516224, 1616117760, 4, 0,
  131154. _vq_quantlist__44c4_s_p8_0,
  131155. NULL,
  131156. &_vq_auxt__44c4_s_p8_0,
  131157. NULL,
  131158. 0
  131159. };
  131160. static long _vq_quantlist__44c4_s_p8_1[] = {
  131161. 2,
  131162. 1,
  131163. 3,
  131164. 0,
  131165. 4,
  131166. };
  131167. static long _vq_lengthlist__44c4_s_p8_1[] = {
  131168. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  131169. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131170. };
  131171. static float _vq_quantthresh__44c4_s_p8_1[] = {
  131172. -1.5, -0.5, 0.5, 1.5,
  131173. };
  131174. static long _vq_quantmap__44c4_s_p8_1[] = {
  131175. 3, 1, 0, 2, 4,
  131176. };
  131177. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  131178. _vq_quantthresh__44c4_s_p8_1,
  131179. _vq_quantmap__44c4_s_p8_1,
  131180. 5,
  131181. 5
  131182. };
  131183. static static_codebook _44c4_s_p8_1 = {
  131184. 2, 25,
  131185. _vq_lengthlist__44c4_s_p8_1,
  131186. 1, -533725184, 1611661312, 3, 0,
  131187. _vq_quantlist__44c4_s_p8_1,
  131188. NULL,
  131189. &_vq_auxt__44c4_s_p8_1,
  131190. NULL,
  131191. 0
  131192. };
  131193. static long _vq_quantlist__44c4_s_p9_0[] = {
  131194. 6,
  131195. 5,
  131196. 7,
  131197. 4,
  131198. 8,
  131199. 3,
  131200. 9,
  131201. 2,
  131202. 10,
  131203. 1,
  131204. 11,
  131205. 0,
  131206. 12,
  131207. };
  131208. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131209. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131210. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131211. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131212. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131213. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131214. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131215. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131216. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131217. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131218. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131219. 12,12,12,12,12,12,12,12,12,
  131220. };
  131221. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131222. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131223. 787.5, 1102.5, 1417.5, 1732.5,
  131224. };
  131225. static long _vq_quantmap__44c4_s_p9_0[] = {
  131226. 11, 9, 7, 5, 3, 1, 0, 2,
  131227. 4, 6, 8, 10, 12,
  131228. };
  131229. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131230. _vq_quantthresh__44c4_s_p9_0,
  131231. _vq_quantmap__44c4_s_p9_0,
  131232. 13,
  131233. 13
  131234. };
  131235. static static_codebook _44c4_s_p9_0 = {
  131236. 2, 169,
  131237. _vq_lengthlist__44c4_s_p9_0,
  131238. 1, -513964032, 1628680192, 4, 0,
  131239. _vq_quantlist__44c4_s_p9_0,
  131240. NULL,
  131241. &_vq_auxt__44c4_s_p9_0,
  131242. NULL,
  131243. 0
  131244. };
  131245. static long _vq_quantlist__44c4_s_p9_1[] = {
  131246. 7,
  131247. 6,
  131248. 8,
  131249. 5,
  131250. 9,
  131251. 4,
  131252. 10,
  131253. 3,
  131254. 11,
  131255. 2,
  131256. 12,
  131257. 1,
  131258. 13,
  131259. 0,
  131260. 14,
  131261. };
  131262. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131263. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131264. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131265. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131266. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131267. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131268. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131269. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131270. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131271. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131272. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131273. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131274. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131275. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131276. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131277. 15,
  131278. };
  131279. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131280. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131281. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131282. };
  131283. static long _vq_quantmap__44c4_s_p9_1[] = {
  131284. 13, 11, 9, 7, 5, 3, 1, 0,
  131285. 2, 4, 6, 8, 10, 12, 14,
  131286. };
  131287. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131288. _vq_quantthresh__44c4_s_p9_1,
  131289. _vq_quantmap__44c4_s_p9_1,
  131290. 15,
  131291. 15
  131292. };
  131293. static static_codebook _44c4_s_p9_1 = {
  131294. 2, 225,
  131295. _vq_lengthlist__44c4_s_p9_1,
  131296. 1, -520986624, 1620377600, 4, 0,
  131297. _vq_quantlist__44c4_s_p9_1,
  131298. NULL,
  131299. &_vq_auxt__44c4_s_p9_1,
  131300. NULL,
  131301. 0
  131302. };
  131303. static long _vq_quantlist__44c4_s_p9_2[] = {
  131304. 10,
  131305. 9,
  131306. 11,
  131307. 8,
  131308. 12,
  131309. 7,
  131310. 13,
  131311. 6,
  131312. 14,
  131313. 5,
  131314. 15,
  131315. 4,
  131316. 16,
  131317. 3,
  131318. 17,
  131319. 2,
  131320. 18,
  131321. 1,
  131322. 19,
  131323. 0,
  131324. 20,
  131325. };
  131326. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131327. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131328. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131329. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131330. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131331. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131332. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131333. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131334. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131335. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131336. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131337. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131338. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131339. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131340. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131341. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131342. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131343. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131344. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131345. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131346. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131347. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131348. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131349. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131350. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131351. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131352. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131353. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131354. 10,10,10,10,10,10,10,10,10,
  131355. };
  131356. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131357. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131358. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131359. 6.5, 7.5, 8.5, 9.5,
  131360. };
  131361. static long _vq_quantmap__44c4_s_p9_2[] = {
  131362. 19, 17, 15, 13, 11, 9, 7, 5,
  131363. 3, 1, 0, 2, 4, 6, 8, 10,
  131364. 12, 14, 16, 18, 20,
  131365. };
  131366. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131367. _vq_quantthresh__44c4_s_p9_2,
  131368. _vq_quantmap__44c4_s_p9_2,
  131369. 21,
  131370. 21
  131371. };
  131372. static static_codebook _44c4_s_p9_2 = {
  131373. 2, 441,
  131374. _vq_lengthlist__44c4_s_p9_2,
  131375. 1, -529268736, 1611661312, 5, 0,
  131376. _vq_quantlist__44c4_s_p9_2,
  131377. NULL,
  131378. &_vq_auxt__44c4_s_p9_2,
  131379. NULL,
  131380. 0
  131381. };
  131382. static long _huff_lengthlist__44c4_s_short[] = {
  131383. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131384. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131385. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131386. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131387. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131388. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131389. 7, 9,12,17,
  131390. };
  131391. static static_codebook _huff_book__44c4_s_short = {
  131392. 2, 100,
  131393. _huff_lengthlist__44c4_s_short,
  131394. 0, 0, 0, 0, 0,
  131395. NULL,
  131396. NULL,
  131397. NULL,
  131398. NULL,
  131399. 0
  131400. };
  131401. static long _huff_lengthlist__44c5_s_long[] = {
  131402. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131403. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131404. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131405. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131406. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131407. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131408. 9, 8, 7, 7,
  131409. };
  131410. static static_codebook _huff_book__44c5_s_long = {
  131411. 2, 100,
  131412. _huff_lengthlist__44c5_s_long,
  131413. 0, 0, 0, 0, 0,
  131414. NULL,
  131415. NULL,
  131416. NULL,
  131417. NULL,
  131418. 0
  131419. };
  131420. static long _vq_quantlist__44c5_s_p1_0[] = {
  131421. 1,
  131422. 0,
  131423. 2,
  131424. };
  131425. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131426. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131427. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131432. 0, 0, 0, 7, 8, 9, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131437. 0, 0, 0, 0, 7, 9, 9, 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, 4, 7, 7, 0, 0, 0, 0,
  131472. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  131477. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  131482. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131518. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131523. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131528. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131836. 0,
  131837. };
  131838. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131839. -0.5, 0.5,
  131840. };
  131841. static long _vq_quantmap__44c5_s_p1_0[] = {
  131842. 1, 0, 2,
  131843. };
  131844. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131845. _vq_quantthresh__44c5_s_p1_0,
  131846. _vq_quantmap__44c5_s_p1_0,
  131847. 3,
  131848. 3
  131849. };
  131850. static static_codebook _44c5_s_p1_0 = {
  131851. 8, 6561,
  131852. _vq_lengthlist__44c5_s_p1_0,
  131853. 1, -535822336, 1611661312, 2, 0,
  131854. _vq_quantlist__44c5_s_p1_0,
  131855. NULL,
  131856. &_vq_auxt__44c5_s_p1_0,
  131857. NULL,
  131858. 0
  131859. };
  131860. static long _vq_quantlist__44c5_s_p2_0[] = {
  131861. 2,
  131862. 1,
  131863. 3,
  131864. 0,
  131865. 4,
  131866. };
  131867. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131868. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131869. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131870. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131871. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131872. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131877. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131878. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131879. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131880. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131885. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131886. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131887. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131893. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131894. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131895. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131907. 0,
  131908. };
  131909. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131910. -1.5, -0.5, 0.5, 1.5,
  131911. };
  131912. static long _vq_quantmap__44c5_s_p2_0[] = {
  131913. 3, 1, 0, 2, 4,
  131914. };
  131915. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131916. _vq_quantthresh__44c5_s_p2_0,
  131917. _vq_quantmap__44c5_s_p2_0,
  131918. 5,
  131919. 5
  131920. };
  131921. static static_codebook _44c5_s_p2_0 = {
  131922. 4, 625,
  131923. _vq_lengthlist__44c5_s_p2_0,
  131924. 1, -533725184, 1611661312, 3, 0,
  131925. _vq_quantlist__44c5_s_p2_0,
  131926. NULL,
  131927. &_vq_auxt__44c5_s_p2_0,
  131928. NULL,
  131929. 0
  131930. };
  131931. static long _vq_quantlist__44c5_s_p3_0[] = {
  131932. 2,
  131933. 1,
  131934. 3,
  131935. 0,
  131936. 4,
  131937. };
  131938. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131939. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131942. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131945. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131978. 0,
  131979. };
  131980. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131981. -1.5, -0.5, 0.5, 1.5,
  131982. };
  131983. static long _vq_quantmap__44c5_s_p3_0[] = {
  131984. 3, 1, 0, 2, 4,
  131985. };
  131986. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131987. _vq_quantthresh__44c5_s_p3_0,
  131988. _vq_quantmap__44c5_s_p3_0,
  131989. 5,
  131990. 5
  131991. };
  131992. static static_codebook _44c5_s_p3_0 = {
  131993. 4, 625,
  131994. _vq_lengthlist__44c5_s_p3_0,
  131995. 1, -533725184, 1611661312, 3, 0,
  131996. _vq_quantlist__44c5_s_p3_0,
  131997. NULL,
  131998. &_vq_auxt__44c5_s_p3_0,
  131999. NULL,
  132000. 0
  132001. };
  132002. static long _vq_quantlist__44c5_s_p4_0[] = {
  132003. 4,
  132004. 3,
  132005. 5,
  132006. 2,
  132007. 6,
  132008. 1,
  132009. 7,
  132010. 0,
  132011. 8,
  132012. };
  132013. static long _vq_lengthlist__44c5_s_p4_0[] = {
  132014. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  132015. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  132016. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  132017. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  132018. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132019. 0,
  132020. };
  132021. static float _vq_quantthresh__44c5_s_p4_0[] = {
  132022. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132023. };
  132024. static long _vq_quantmap__44c5_s_p4_0[] = {
  132025. 7, 5, 3, 1, 0, 2, 4, 6,
  132026. 8,
  132027. };
  132028. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  132029. _vq_quantthresh__44c5_s_p4_0,
  132030. _vq_quantmap__44c5_s_p4_0,
  132031. 9,
  132032. 9
  132033. };
  132034. static static_codebook _44c5_s_p4_0 = {
  132035. 2, 81,
  132036. _vq_lengthlist__44c5_s_p4_0,
  132037. 1, -531628032, 1611661312, 4, 0,
  132038. _vq_quantlist__44c5_s_p4_0,
  132039. NULL,
  132040. &_vq_auxt__44c5_s_p4_0,
  132041. NULL,
  132042. 0
  132043. };
  132044. static long _vq_quantlist__44c5_s_p5_0[] = {
  132045. 4,
  132046. 3,
  132047. 5,
  132048. 2,
  132049. 6,
  132050. 1,
  132051. 7,
  132052. 0,
  132053. 8,
  132054. };
  132055. static long _vq_lengthlist__44c5_s_p5_0[] = {
  132056. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132057. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  132058. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  132059. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  132060. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132061. 10,
  132062. };
  132063. static float _vq_quantthresh__44c5_s_p5_0[] = {
  132064. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132065. };
  132066. static long _vq_quantmap__44c5_s_p5_0[] = {
  132067. 7, 5, 3, 1, 0, 2, 4, 6,
  132068. 8,
  132069. };
  132070. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  132071. _vq_quantthresh__44c5_s_p5_0,
  132072. _vq_quantmap__44c5_s_p5_0,
  132073. 9,
  132074. 9
  132075. };
  132076. static static_codebook _44c5_s_p5_0 = {
  132077. 2, 81,
  132078. _vq_lengthlist__44c5_s_p5_0,
  132079. 1, -531628032, 1611661312, 4, 0,
  132080. _vq_quantlist__44c5_s_p5_0,
  132081. NULL,
  132082. &_vq_auxt__44c5_s_p5_0,
  132083. NULL,
  132084. 0
  132085. };
  132086. static long _vq_quantlist__44c5_s_p6_0[] = {
  132087. 8,
  132088. 7,
  132089. 9,
  132090. 6,
  132091. 10,
  132092. 5,
  132093. 11,
  132094. 4,
  132095. 12,
  132096. 3,
  132097. 13,
  132098. 2,
  132099. 14,
  132100. 1,
  132101. 15,
  132102. 0,
  132103. 16,
  132104. };
  132105. static long _vq_lengthlist__44c5_s_p6_0[] = {
  132106. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  132107. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  132108. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  132109. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132110. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132111. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132112. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  132113. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  132114. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132115. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132116. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  132117. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  132118. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132119. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132120. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  132121. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  132122. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  132123. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  132124. 13,
  132125. };
  132126. static float _vq_quantthresh__44c5_s_p6_0[] = {
  132127. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132128. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132129. };
  132130. static long _vq_quantmap__44c5_s_p6_0[] = {
  132131. 15, 13, 11, 9, 7, 5, 3, 1,
  132132. 0, 2, 4, 6, 8, 10, 12, 14,
  132133. 16,
  132134. };
  132135. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  132136. _vq_quantthresh__44c5_s_p6_0,
  132137. _vq_quantmap__44c5_s_p6_0,
  132138. 17,
  132139. 17
  132140. };
  132141. static static_codebook _44c5_s_p6_0 = {
  132142. 2, 289,
  132143. _vq_lengthlist__44c5_s_p6_0,
  132144. 1, -529530880, 1611661312, 5, 0,
  132145. _vq_quantlist__44c5_s_p6_0,
  132146. NULL,
  132147. &_vq_auxt__44c5_s_p6_0,
  132148. NULL,
  132149. 0
  132150. };
  132151. static long _vq_quantlist__44c5_s_p7_0[] = {
  132152. 1,
  132153. 0,
  132154. 2,
  132155. };
  132156. static long _vq_lengthlist__44c5_s_p7_0[] = {
  132157. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132158. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132159. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132160. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  132161. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  132162. 10,
  132163. };
  132164. static float _vq_quantthresh__44c5_s_p7_0[] = {
  132165. -5.5, 5.5,
  132166. };
  132167. static long _vq_quantmap__44c5_s_p7_0[] = {
  132168. 1, 0, 2,
  132169. };
  132170. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  132171. _vq_quantthresh__44c5_s_p7_0,
  132172. _vq_quantmap__44c5_s_p7_0,
  132173. 3,
  132174. 3
  132175. };
  132176. static static_codebook _44c5_s_p7_0 = {
  132177. 4, 81,
  132178. _vq_lengthlist__44c5_s_p7_0,
  132179. 1, -529137664, 1618345984, 2, 0,
  132180. _vq_quantlist__44c5_s_p7_0,
  132181. NULL,
  132182. &_vq_auxt__44c5_s_p7_0,
  132183. NULL,
  132184. 0
  132185. };
  132186. static long _vq_quantlist__44c5_s_p7_1[] = {
  132187. 5,
  132188. 4,
  132189. 6,
  132190. 3,
  132191. 7,
  132192. 2,
  132193. 8,
  132194. 1,
  132195. 9,
  132196. 0,
  132197. 10,
  132198. };
  132199. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132200. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132201. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132202. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132203. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132204. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132205. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132206. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132207. 10,10,10, 8, 8, 8, 8, 8, 8,
  132208. };
  132209. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132210. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132211. 3.5, 4.5,
  132212. };
  132213. static long _vq_quantmap__44c5_s_p7_1[] = {
  132214. 9, 7, 5, 3, 1, 0, 2, 4,
  132215. 6, 8, 10,
  132216. };
  132217. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132218. _vq_quantthresh__44c5_s_p7_1,
  132219. _vq_quantmap__44c5_s_p7_1,
  132220. 11,
  132221. 11
  132222. };
  132223. static static_codebook _44c5_s_p7_1 = {
  132224. 2, 121,
  132225. _vq_lengthlist__44c5_s_p7_1,
  132226. 1, -531365888, 1611661312, 4, 0,
  132227. _vq_quantlist__44c5_s_p7_1,
  132228. NULL,
  132229. &_vq_auxt__44c5_s_p7_1,
  132230. NULL,
  132231. 0
  132232. };
  132233. static long _vq_quantlist__44c5_s_p8_0[] = {
  132234. 6,
  132235. 5,
  132236. 7,
  132237. 4,
  132238. 8,
  132239. 3,
  132240. 9,
  132241. 2,
  132242. 10,
  132243. 1,
  132244. 11,
  132245. 0,
  132246. 12,
  132247. };
  132248. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132249. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132250. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132251. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132252. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132253. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132254. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132255. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132256. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132257. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132258. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132259. 0,12,12,12,12,12,12,13,13,
  132260. };
  132261. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132262. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132263. 12.5, 17.5, 22.5, 27.5,
  132264. };
  132265. static long _vq_quantmap__44c5_s_p8_0[] = {
  132266. 11, 9, 7, 5, 3, 1, 0, 2,
  132267. 4, 6, 8, 10, 12,
  132268. };
  132269. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132270. _vq_quantthresh__44c5_s_p8_0,
  132271. _vq_quantmap__44c5_s_p8_0,
  132272. 13,
  132273. 13
  132274. };
  132275. static static_codebook _44c5_s_p8_0 = {
  132276. 2, 169,
  132277. _vq_lengthlist__44c5_s_p8_0,
  132278. 1, -526516224, 1616117760, 4, 0,
  132279. _vq_quantlist__44c5_s_p8_0,
  132280. NULL,
  132281. &_vq_auxt__44c5_s_p8_0,
  132282. NULL,
  132283. 0
  132284. };
  132285. static long _vq_quantlist__44c5_s_p8_1[] = {
  132286. 2,
  132287. 1,
  132288. 3,
  132289. 0,
  132290. 4,
  132291. };
  132292. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132293. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132294. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132295. };
  132296. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132297. -1.5, -0.5, 0.5, 1.5,
  132298. };
  132299. static long _vq_quantmap__44c5_s_p8_1[] = {
  132300. 3, 1, 0, 2, 4,
  132301. };
  132302. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132303. _vq_quantthresh__44c5_s_p8_1,
  132304. _vq_quantmap__44c5_s_p8_1,
  132305. 5,
  132306. 5
  132307. };
  132308. static static_codebook _44c5_s_p8_1 = {
  132309. 2, 25,
  132310. _vq_lengthlist__44c5_s_p8_1,
  132311. 1, -533725184, 1611661312, 3, 0,
  132312. _vq_quantlist__44c5_s_p8_1,
  132313. NULL,
  132314. &_vq_auxt__44c5_s_p8_1,
  132315. NULL,
  132316. 0
  132317. };
  132318. static long _vq_quantlist__44c5_s_p9_0[] = {
  132319. 7,
  132320. 6,
  132321. 8,
  132322. 5,
  132323. 9,
  132324. 4,
  132325. 10,
  132326. 3,
  132327. 11,
  132328. 2,
  132329. 12,
  132330. 1,
  132331. 13,
  132332. 0,
  132333. 14,
  132334. };
  132335. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132336. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132337. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132338. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132339. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132340. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132341. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132342. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132343. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132344. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132345. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132346. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132347. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132348. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132349. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132350. 12,
  132351. };
  132352. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132353. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132354. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132355. };
  132356. static long _vq_quantmap__44c5_s_p9_0[] = {
  132357. 13, 11, 9, 7, 5, 3, 1, 0,
  132358. 2, 4, 6, 8, 10, 12, 14,
  132359. };
  132360. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132361. _vq_quantthresh__44c5_s_p9_0,
  132362. _vq_quantmap__44c5_s_p9_0,
  132363. 15,
  132364. 15
  132365. };
  132366. static static_codebook _44c5_s_p9_0 = {
  132367. 2, 225,
  132368. _vq_lengthlist__44c5_s_p9_0,
  132369. 1, -512522752, 1628852224, 4, 0,
  132370. _vq_quantlist__44c5_s_p9_0,
  132371. NULL,
  132372. &_vq_auxt__44c5_s_p9_0,
  132373. NULL,
  132374. 0
  132375. };
  132376. static long _vq_quantlist__44c5_s_p9_1[] = {
  132377. 8,
  132378. 7,
  132379. 9,
  132380. 6,
  132381. 10,
  132382. 5,
  132383. 11,
  132384. 4,
  132385. 12,
  132386. 3,
  132387. 13,
  132388. 2,
  132389. 14,
  132390. 1,
  132391. 15,
  132392. 0,
  132393. 16,
  132394. };
  132395. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132396. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132397. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132398. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132399. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132400. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132401. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132402. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132403. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132404. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132405. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132406. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132407. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132408. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132409. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132410. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132411. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132412. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132413. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132414. 15,
  132415. };
  132416. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132417. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132418. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132419. };
  132420. static long _vq_quantmap__44c5_s_p9_1[] = {
  132421. 15, 13, 11, 9, 7, 5, 3, 1,
  132422. 0, 2, 4, 6, 8, 10, 12, 14,
  132423. 16,
  132424. };
  132425. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132426. _vq_quantthresh__44c5_s_p9_1,
  132427. _vq_quantmap__44c5_s_p9_1,
  132428. 17,
  132429. 17
  132430. };
  132431. static static_codebook _44c5_s_p9_1 = {
  132432. 2, 289,
  132433. _vq_lengthlist__44c5_s_p9_1,
  132434. 1, -520814592, 1620377600, 5, 0,
  132435. _vq_quantlist__44c5_s_p9_1,
  132436. NULL,
  132437. &_vq_auxt__44c5_s_p9_1,
  132438. NULL,
  132439. 0
  132440. };
  132441. static long _vq_quantlist__44c5_s_p9_2[] = {
  132442. 10,
  132443. 9,
  132444. 11,
  132445. 8,
  132446. 12,
  132447. 7,
  132448. 13,
  132449. 6,
  132450. 14,
  132451. 5,
  132452. 15,
  132453. 4,
  132454. 16,
  132455. 3,
  132456. 17,
  132457. 2,
  132458. 18,
  132459. 1,
  132460. 19,
  132461. 0,
  132462. 20,
  132463. };
  132464. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132465. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132466. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132467. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132468. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132469. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132470. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132471. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132472. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132473. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132474. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132475. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132476. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132477. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132478. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132479. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132480. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132481. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132482. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132483. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132484. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132485. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132486. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132487. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132488. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132489. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132490. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132491. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132492. 10,10,10,10,10,10,10,10,10,
  132493. };
  132494. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132495. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132496. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132497. 6.5, 7.5, 8.5, 9.5,
  132498. };
  132499. static long _vq_quantmap__44c5_s_p9_2[] = {
  132500. 19, 17, 15, 13, 11, 9, 7, 5,
  132501. 3, 1, 0, 2, 4, 6, 8, 10,
  132502. 12, 14, 16, 18, 20,
  132503. };
  132504. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132505. _vq_quantthresh__44c5_s_p9_2,
  132506. _vq_quantmap__44c5_s_p9_2,
  132507. 21,
  132508. 21
  132509. };
  132510. static static_codebook _44c5_s_p9_2 = {
  132511. 2, 441,
  132512. _vq_lengthlist__44c5_s_p9_2,
  132513. 1, -529268736, 1611661312, 5, 0,
  132514. _vq_quantlist__44c5_s_p9_2,
  132515. NULL,
  132516. &_vq_auxt__44c5_s_p9_2,
  132517. NULL,
  132518. 0
  132519. };
  132520. static long _huff_lengthlist__44c5_s_short[] = {
  132521. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132522. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132523. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132524. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132525. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132526. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132527. 6, 8,11,16,
  132528. };
  132529. static static_codebook _huff_book__44c5_s_short = {
  132530. 2, 100,
  132531. _huff_lengthlist__44c5_s_short,
  132532. 0, 0, 0, 0, 0,
  132533. NULL,
  132534. NULL,
  132535. NULL,
  132536. NULL,
  132537. 0
  132538. };
  132539. static long _huff_lengthlist__44c6_s_long[] = {
  132540. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132541. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132542. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132543. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132544. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132545. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132546. 11,10,10,12,
  132547. };
  132548. static static_codebook _huff_book__44c6_s_long = {
  132549. 2, 100,
  132550. _huff_lengthlist__44c6_s_long,
  132551. 0, 0, 0, 0, 0,
  132552. NULL,
  132553. NULL,
  132554. NULL,
  132555. NULL,
  132556. 0
  132557. };
  132558. static long _vq_quantlist__44c6_s_p1_0[] = {
  132559. 1,
  132560. 0,
  132561. 2,
  132562. };
  132563. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132564. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132565. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132566. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132567. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132568. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132569. 8,
  132570. };
  132571. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132572. -0.5, 0.5,
  132573. };
  132574. static long _vq_quantmap__44c6_s_p1_0[] = {
  132575. 1, 0, 2,
  132576. };
  132577. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132578. _vq_quantthresh__44c6_s_p1_0,
  132579. _vq_quantmap__44c6_s_p1_0,
  132580. 3,
  132581. 3
  132582. };
  132583. static static_codebook _44c6_s_p1_0 = {
  132584. 4, 81,
  132585. _vq_lengthlist__44c6_s_p1_0,
  132586. 1, -535822336, 1611661312, 2, 0,
  132587. _vq_quantlist__44c6_s_p1_0,
  132588. NULL,
  132589. &_vq_auxt__44c6_s_p1_0,
  132590. NULL,
  132591. 0
  132592. };
  132593. static long _vq_quantlist__44c6_s_p2_0[] = {
  132594. 2,
  132595. 1,
  132596. 3,
  132597. 0,
  132598. 4,
  132599. };
  132600. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132601. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132602. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132603. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132604. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132605. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132606. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132607. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132608. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132610. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132611. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132612. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132613. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132614. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132615. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132616. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132618. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132619. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132620. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132621. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132622. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132623. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132624. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132626. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132627. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132628. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132629. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132630. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132631. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132632. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132637. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132638. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132639. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132640. 13,
  132641. };
  132642. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132643. -1.5, -0.5, 0.5, 1.5,
  132644. };
  132645. static long _vq_quantmap__44c6_s_p2_0[] = {
  132646. 3, 1, 0, 2, 4,
  132647. };
  132648. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132649. _vq_quantthresh__44c6_s_p2_0,
  132650. _vq_quantmap__44c6_s_p2_0,
  132651. 5,
  132652. 5
  132653. };
  132654. static static_codebook _44c6_s_p2_0 = {
  132655. 4, 625,
  132656. _vq_lengthlist__44c6_s_p2_0,
  132657. 1, -533725184, 1611661312, 3, 0,
  132658. _vq_quantlist__44c6_s_p2_0,
  132659. NULL,
  132660. &_vq_auxt__44c6_s_p2_0,
  132661. NULL,
  132662. 0
  132663. };
  132664. static long _vq_quantlist__44c6_s_p3_0[] = {
  132665. 4,
  132666. 3,
  132667. 5,
  132668. 2,
  132669. 6,
  132670. 1,
  132671. 7,
  132672. 0,
  132673. 8,
  132674. };
  132675. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132676. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132677. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132678. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132679. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132681. 0,
  132682. };
  132683. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132684. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132685. };
  132686. static long _vq_quantmap__44c6_s_p3_0[] = {
  132687. 7, 5, 3, 1, 0, 2, 4, 6,
  132688. 8,
  132689. };
  132690. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132691. _vq_quantthresh__44c6_s_p3_0,
  132692. _vq_quantmap__44c6_s_p3_0,
  132693. 9,
  132694. 9
  132695. };
  132696. static static_codebook _44c6_s_p3_0 = {
  132697. 2, 81,
  132698. _vq_lengthlist__44c6_s_p3_0,
  132699. 1, -531628032, 1611661312, 4, 0,
  132700. _vq_quantlist__44c6_s_p3_0,
  132701. NULL,
  132702. &_vq_auxt__44c6_s_p3_0,
  132703. NULL,
  132704. 0
  132705. };
  132706. static long _vq_quantlist__44c6_s_p4_0[] = {
  132707. 8,
  132708. 7,
  132709. 9,
  132710. 6,
  132711. 10,
  132712. 5,
  132713. 11,
  132714. 4,
  132715. 12,
  132716. 3,
  132717. 13,
  132718. 2,
  132719. 14,
  132720. 1,
  132721. 15,
  132722. 0,
  132723. 16,
  132724. };
  132725. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132726. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132727. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132728. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132729. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132730. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132731. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132732. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132733. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132734. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132735. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132744. 0,
  132745. };
  132746. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132747. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132748. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132749. };
  132750. static long _vq_quantmap__44c6_s_p4_0[] = {
  132751. 15, 13, 11, 9, 7, 5, 3, 1,
  132752. 0, 2, 4, 6, 8, 10, 12, 14,
  132753. 16,
  132754. };
  132755. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132756. _vq_quantthresh__44c6_s_p4_0,
  132757. _vq_quantmap__44c6_s_p4_0,
  132758. 17,
  132759. 17
  132760. };
  132761. static static_codebook _44c6_s_p4_0 = {
  132762. 2, 289,
  132763. _vq_lengthlist__44c6_s_p4_0,
  132764. 1, -529530880, 1611661312, 5, 0,
  132765. _vq_quantlist__44c6_s_p4_0,
  132766. NULL,
  132767. &_vq_auxt__44c6_s_p4_0,
  132768. NULL,
  132769. 0
  132770. };
  132771. static long _vq_quantlist__44c6_s_p5_0[] = {
  132772. 1,
  132773. 0,
  132774. 2,
  132775. };
  132776. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132777. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132778. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132779. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132780. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132781. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132782. 12,
  132783. };
  132784. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132785. -5.5, 5.5,
  132786. };
  132787. static long _vq_quantmap__44c6_s_p5_0[] = {
  132788. 1, 0, 2,
  132789. };
  132790. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132791. _vq_quantthresh__44c6_s_p5_0,
  132792. _vq_quantmap__44c6_s_p5_0,
  132793. 3,
  132794. 3
  132795. };
  132796. static static_codebook _44c6_s_p5_0 = {
  132797. 4, 81,
  132798. _vq_lengthlist__44c6_s_p5_0,
  132799. 1, -529137664, 1618345984, 2, 0,
  132800. _vq_quantlist__44c6_s_p5_0,
  132801. NULL,
  132802. &_vq_auxt__44c6_s_p5_0,
  132803. NULL,
  132804. 0
  132805. };
  132806. static long _vq_quantlist__44c6_s_p5_1[] = {
  132807. 5,
  132808. 4,
  132809. 6,
  132810. 3,
  132811. 7,
  132812. 2,
  132813. 8,
  132814. 1,
  132815. 9,
  132816. 0,
  132817. 10,
  132818. };
  132819. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132820. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132821. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132822. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132823. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132824. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132825. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132826. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132827. 11,10,10, 7, 7, 8, 8, 8, 8,
  132828. };
  132829. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132830. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132831. 3.5, 4.5,
  132832. };
  132833. static long _vq_quantmap__44c6_s_p5_1[] = {
  132834. 9, 7, 5, 3, 1, 0, 2, 4,
  132835. 6, 8, 10,
  132836. };
  132837. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132838. _vq_quantthresh__44c6_s_p5_1,
  132839. _vq_quantmap__44c6_s_p5_1,
  132840. 11,
  132841. 11
  132842. };
  132843. static static_codebook _44c6_s_p5_1 = {
  132844. 2, 121,
  132845. _vq_lengthlist__44c6_s_p5_1,
  132846. 1, -531365888, 1611661312, 4, 0,
  132847. _vq_quantlist__44c6_s_p5_1,
  132848. NULL,
  132849. &_vq_auxt__44c6_s_p5_1,
  132850. NULL,
  132851. 0
  132852. };
  132853. static long _vq_quantlist__44c6_s_p6_0[] = {
  132854. 6,
  132855. 5,
  132856. 7,
  132857. 4,
  132858. 8,
  132859. 3,
  132860. 9,
  132861. 2,
  132862. 10,
  132863. 1,
  132864. 11,
  132865. 0,
  132866. 12,
  132867. };
  132868. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132869. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132870. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132871. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132872. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132873. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132874. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132879. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132880. };
  132881. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132882. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132883. 12.5, 17.5, 22.5, 27.5,
  132884. };
  132885. static long _vq_quantmap__44c6_s_p6_0[] = {
  132886. 11, 9, 7, 5, 3, 1, 0, 2,
  132887. 4, 6, 8, 10, 12,
  132888. };
  132889. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132890. _vq_quantthresh__44c6_s_p6_0,
  132891. _vq_quantmap__44c6_s_p6_0,
  132892. 13,
  132893. 13
  132894. };
  132895. static static_codebook _44c6_s_p6_0 = {
  132896. 2, 169,
  132897. _vq_lengthlist__44c6_s_p6_0,
  132898. 1, -526516224, 1616117760, 4, 0,
  132899. _vq_quantlist__44c6_s_p6_0,
  132900. NULL,
  132901. &_vq_auxt__44c6_s_p6_0,
  132902. NULL,
  132903. 0
  132904. };
  132905. static long _vq_quantlist__44c6_s_p6_1[] = {
  132906. 2,
  132907. 1,
  132908. 3,
  132909. 0,
  132910. 4,
  132911. };
  132912. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132913. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132914. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132915. };
  132916. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132917. -1.5, -0.5, 0.5, 1.5,
  132918. };
  132919. static long _vq_quantmap__44c6_s_p6_1[] = {
  132920. 3, 1, 0, 2, 4,
  132921. };
  132922. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132923. _vq_quantthresh__44c6_s_p6_1,
  132924. _vq_quantmap__44c6_s_p6_1,
  132925. 5,
  132926. 5
  132927. };
  132928. static static_codebook _44c6_s_p6_1 = {
  132929. 2, 25,
  132930. _vq_lengthlist__44c6_s_p6_1,
  132931. 1, -533725184, 1611661312, 3, 0,
  132932. _vq_quantlist__44c6_s_p6_1,
  132933. NULL,
  132934. &_vq_auxt__44c6_s_p6_1,
  132935. NULL,
  132936. 0
  132937. };
  132938. static long _vq_quantlist__44c6_s_p7_0[] = {
  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_p7_0[] = {
  132954. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132955. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132956. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132957. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132958. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132959. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132960. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132961. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132962. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132963. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132964. 20,13,13,13,13,13,13,14,14,
  132965. };
  132966. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132967. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132968. 27.5, 38.5, 49.5, 60.5,
  132969. };
  132970. static long _vq_quantmap__44c6_s_p7_0[] = {
  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_p7_0 = {
  132975. _vq_quantthresh__44c6_s_p7_0,
  132976. _vq_quantmap__44c6_s_p7_0,
  132977. 13,
  132978. 13
  132979. };
  132980. static static_codebook _44c6_s_p7_0 = {
  132981. 2, 169,
  132982. _vq_lengthlist__44c6_s_p7_0,
  132983. 1, -523206656, 1618345984, 4, 0,
  132984. _vq_quantlist__44c6_s_p7_0,
  132985. NULL,
  132986. &_vq_auxt__44c6_s_p7_0,
  132987. NULL,
  132988. 0
  132989. };
  132990. static long _vq_quantlist__44c6_s_p7_1[] = {
  132991. 5,
  132992. 4,
  132993. 6,
  132994. 3,
  132995. 7,
  132996. 2,
  132997. 8,
  132998. 1,
  132999. 9,
  133000. 0,
  133001. 10,
  133002. };
  133003. static long _vq_lengthlist__44c6_s_p7_1[] = {
  133004. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  133005. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  133006. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  133007. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  133008. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  133009. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  133010. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  133011. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  133012. };
  133013. static float _vq_quantthresh__44c6_s_p7_1[] = {
  133014. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133015. 3.5, 4.5,
  133016. };
  133017. static long _vq_quantmap__44c6_s_p7_1[] = {
  133018. 9, 7, 5, 3, 1, 0, 2, 4,
  133019. 6, 8, 10,
  133020. };
  133021. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  133022. _vq_quantthresh__44c6_s_p7_1,
  133023. _vq_quantmap__44c6_s_p7_1,
  133024. 11,
  133025. 11
  133026. };
  133027. static static_codebook _44c6_s_p7_1 = {
  133028. 2, 121,
  133029. _vq_lengthlist__44c6_s_p7_1,
  133030. 1, -531365888, 1611661312, 4, 0,
  133031. _vq_quantlist__44c6_s_p7_1,
  133032. NULL,
  133033. &_vq_auxt__44c6_s_p7_1,
  133034. NULL,
  133035. 0
  133036. };
  133037. static long _vq_quantlist__44c6_s_p8_0[] = {
  133038. 7,
  133039. 6,
  133040. 8,
  133041. 5,
  133042. 9,
  133043. 4,
  133044. 10,
  133045. 3,
  133046. 11,
  133047. 2,
  133048. 12,
  133049. 1,
  133050. 13,
  133051. 0,
  133052. 14,
  133053. };
  133054. static long _vq_lengthlist__44c6_s_p8_0[] = {
  133055. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  133056. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  133057. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  133058. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  133059. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  133060. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  133061. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  133062. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  133063. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  133064. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  133065. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  133066. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  133067. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  133068. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  133069. 14,
  133070. };
  133071. static float _vq_quantthresh__44c6_s_p8_0[] = {
  133072. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133073. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133074. };
  133075. static long _vq_quantmap__44c6_s_p8_0[] = {
  133076. 13, 11, 9, 7, 5, 3, 1, 0,
  133077. 2, 4, 6, 8, 10, 12, 14,
  133078. };
  133079. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  133080. _vq_quantthresh__44c6_s_p8_0,
  133081. _vq_quantmap__44c6_s_p8_0,
  133082. 15,
  133083. 15
  133084. };
  133085. static static_codebook _44c6_s_p8_0 = {
  133086. 2, 225,
  133087. _vq_lengthlist__44c6_s_p8_0,
  133088. 1, -520986624, 1620377600, 4, 0,
  133089. _vq_quantlist__44c6_s_p8_0,
  133090. NULL,
  133091. &_vq_auxt__44c6_s_p8_0,
  133092. NULL,
  133093. 0
  133094. };
  133095. static long _vq_quantlist__44c6_s_p8_1[] = {
  133096. 10,
  133097. 9,
  133098. 11,
  133099. 8,
  133100. 12,
  133101. 7,
  133102. 13,
  133103. 6,
  133104. 14,
  133105. 5,
  133106. 15,
  133107. 4,
  133108. 16,
  133109. 3,
  133110. 17,
  133111. 2,
  133112. 18,
  133113. 1,
  133114. 19,
  133115. 0,
  133116. 20,
  133117. };
  133118. static long _vq_lengthlist__44c6_s_p8_1[] = {
  133119. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  133120. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  133121. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133122. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133123. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133124. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  133125. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  133126. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  133127. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133128. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133129. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  133130. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  133131. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  133132. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  133133. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  133134. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  133135. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  133136. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  133137. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  133138. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  133139. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  133140. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  133141. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  133142. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  133143. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  133144. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  133145. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  133146. 10,10,10,10,10,10,10,10,10,
  133147. };
  133148. static float _vq_quantthresh__44c6_s_p8_1[] = {
  133149. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133150. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133151. 6.5, 7.5, 8.5, 9.5,
  133152. };
  133153. static long _vq_quantmap__44c6_s_p8_1[] = {
  133154. 19, 17, 15, 13, 11, 9, 7, 5,
  133155. 3, 1, 0, 2, 4, 6, 8, 10,
  133156. 12, 14, 16, 18, 20,
  133157. };
  133158. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  133159. _vq_quantthresh__44c6_s_p8_1,
  133160. _vq_quantmap__44c6_s_p8_1,
  133161. 21,
  133162. 21
  133163. };
  133164. static static_codebook _44c6_s_p8_1 = {
  133165. 2, 441,
  133166. _vq_lengthlist__44c6_s_p8_1,
  133167. 1, -529268736, 1611661312, 5, 0,
  133168. _vq_quantlist__44c6_s_p8_1,
  133169. NULL,
  133170. &_vq_auxt__44c6_s_p8_1,
  133171. NULL,
  133172. 0
  133173. };
  133174. static long _vq_quantlist__44c6_s_p9_0[] = {
  133175. 6,
  133176. 5,
  133177. 7,
  133178. 4,
  133179. 8,
  133180. 3,
  133181. 9,
  133182. 2,
  133183. 10,
  133184. 1,
  133185. 11,
  133186. 0,
  133187. 12,
  133188. };
  133189. static long _vq_lengthlist__44c6_s_p9_0[] = {
  133190. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  133191. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  133192. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133193. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133194. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133195. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133196. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133197. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133198. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133199. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133200. 10,10,10,10,10,10,10,10,10,
  133201. };
  133202. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133203. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133204. 1592.5, 2229.5, 2866.5, 3503.5,
  133205. };
  133206. static long _vq_quantmap__44c6_s_p9_0[] = {
  133207. 11, 9, 7, 5, 3, 1, 0, 2,
  133208. 4, 6, 8, 10, 12,
  133209. };
  133210. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133211. _vq_quantthresh__44c6_s_p9_0,
  133212. _vq_quantmap__44c6_s_p9_0,
  133213. 13,
  133214. 13
  133215. };
  133216. static static_codebook _44c6_s_p9_0 = {
  133217. 2, 169,
  133218. _vq_lengthlist__44c6_s_p9_0,
  133219. 1, -511845376, 1630791680, 4, 0,
  133220. _vq_quantlist__44c6_s_p9_0,
  133221. NULL,
  133222. &_vq_auxt__44c6_s_p9_0,
  133223. NULL,
  133224. 0
  133225. };
  133226. static long _vq_quantlist__44c6_s_p9_1[] = {
  133227. 6,
  133228. 5,
  133229. 7,
  133230. 4,
  133231. 8,
  133232. 3,
  133233. 9,
  133234. 2,
  133235. 10,
  133236. 1,
  133237. 11,
  133238. 0,
  133239. 12,
  133240. };
  133241. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133242. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133243. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133244. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133245. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133246. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133247. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133248. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133249. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133250. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133251. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133252. 15,12,10,11,11,13,11,12,13,
  133253. };
  133254. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133255. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133256. 122.5, 171.5, 220.5, 269.5,
  133257. };
  133258. static long _vq_quantmap__44c6_s_p9_1[] = {
  133259. 11, 9, 7, 5, 3, 1, 0, 2,
  133260. 4, 6, 8, 10, 12,
  133261. };
  133262. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133263. _vq_quantthresh__44c6_s_p9_1,
  133264. _vq_quantmap__44c6_s_p9_1,
  133265. 13,
  133266. 13
  133267. };
  133268. static static_codebook _44c6_s_p9_1 = {
  133269. 2, 169,
  133270. _vq_lengthlist__44c6_s_p9_1,
  133271. 1, -518889472, 1622704128, 4, 0,
  133272. _vq_quantlist__44c6_s_p9_1,
  133273. NULL,
  133274. &_vq_auxt__44c6_s_p9_1,
  133275. NULL,
  133276. 0
  133277. };
  133278. static long _vq_quantlist__44c6_s_p9_2[] = {
  133279. 24,
  133280. 23,
  133281. 25,
  133282. 22,
  133283. 26,
  133284. 21,
  133285. 27,
  133286. 20,
  133287. 28,
  133288. 19,
  133289. 29,
  133290. 18,
  133291. 30,
  133292. 17,
  133293. 31,
  133294. 16,
  133295. 32,
  133296. 15,
  133297. 33,
  133298. 14,
  133299. 34,
  133300. 13,
  133301. 35,
  133302. 12,
  133303. 36,
  133304. 11,
  133305. 37,
  133306. 10,
  133307. 38,
  133308. 9,
  133309. 39,
  133310. 8,
  133311. 40,
  133312. 7,
  133313. 41,
  133314. 6,
  133315. 42,
  133316. 5,
  133317. 43,
  133318. 4,
  133319. 44,
  133320. 3,
  133321. 45,
  133322. 2,
  133323. 46,
  133324. 1,
  133325. 47,
  133326. 0,
  133327. 48,
  133328. };
  133329. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133330. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133331. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133332. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133333. 7,
  133334. };
  133335. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133336. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133337. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133338. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133339. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133340. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133341. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133342. };
  133343. static long _vq_quantmap__44c6_s_p9_2[] = {
  133344. 47, 45, 43, 41, 39, 37, 35, 33,
  133345. 31, 29, 27, 25, 23, 21, 19, 17,
  133346. 15, 13, 11, 9, 7, 5, 3, 1,
  133347. 0, 2, 4, 6, 8, 10, 12, 14,
  133348. 16, 18, 20, 22, 24, 26, 28, 30,
  133349. 32, 34, 36, 38, 40, 42, 44, 46,
  133350. 48,
  133351. };
  133352. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133353. _vq_quantthresh__44c6_s_p9_2,
  133354. _vq_quantmap__44c6_s_p9_2,
  133355. 49,
  133356. 49
  133357. };
  133358. static static_codebook _44c6_s_p9_2 = {
  133359. 1, 49,
  133360. _vq_lengthlist__44c6_s_p9_2,
  133361. 1, -526909440, 1611661312, 6, 0,
  133362. _vq_quantlist__44c6_s_p9_2,
  133363. NULL,
  133364. &_vq_auxt__44c6_s_p9_2,
  133365. NULL,
  133366. 0
  133367. };
  133368. static long _huff_lengthlist__44c6_s_short[] = {
  133369. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133370. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133371. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133372. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133373. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133374. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133375. 9,10,17,18,
  133376. };
  133377. static static_codebook _huff_book__44c6_s_short = {
  133378. 2, 100,
  133379. _huff_lengthlist__44c6_s_short,
  133380. 0, 0, 0, 0, 0,
  133381. NULL,
  133382. NULL,
  133383. NULL,
  133384. NULL,
  133385. 0
  133386. };
  133387. static long _huff_lengthlist__44c7_s_long[] = {
  133388. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133389. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133390. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133391. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133392. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133393. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133394. 11,10,10,12,
  133395. };
  133396. static static_codebook _huff_book__44c7_s_long = {
  133397. 2, 100,
  133398. _huff_lengthlist__44c7_s_long,
  133399. 0, 0, 0, 0, 0,
  133400. NULL,
  133401. NULL,
  133402. NULL,
  133403. NULL,
  133404. 0
  133405. };
  133406. static long _vq_quantlist__44c7_s_p1_0[] = {
  133407. 1,
  133408. 0,
  133409. 2,
  133410. };
  133411. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133412. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133413. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133414. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133415. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133416. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133417. 8,
  133418. };
  133419. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133420. -0.5, 0.5,
  133421. };
  133422. static long _vq_quantmap__44c7_s_p1_0[] = {
  133423. 1, 0, 2,
  133424. };
  133425. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133426. _vq_quantthresh__44c7_s_p1_0,
  133427. _vq_quantmap__44c7_s_p1_0,
  133428. 3,
  133429. 3
  133430. };
  133431. static static_codebook _44c7_s_p1_0 = {
  133432. 4, 81,
  133433. _vq_lengthlist__44c7_s_p1_0,
  133434. 1, -535822336, 1611661312, 2, 0,
  133435. _vq_quantlist__44c7_s_p1_0,
  133436. NULL,
  133437. &_vq_auxt__44c7_s_p1_0,
  133438. NULL,
  133439. 0
  133440. };
  133441. static long _vq_quantlist__44c7_s_p2_0[] = {
  133442. 2,
  133443. 1,
  133444. 3,
  133445. 0,
  133446. 4,
  133447. };
  133448. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133449. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133450. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133451. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133452. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133453. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133454. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133455. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133456. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133458. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133459. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133460. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133461. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133462. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133463. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133464. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133466. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133467. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133468. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133469. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133470. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133471. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133472. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133474. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133475. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133476. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133477. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133478. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133479. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133480. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133485. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133486. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133487. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133488. 13,
  133489. };
  133490. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133491. -1.5, -0.5, 0.5, 1.5,
  133492. };
  133493. static long _vq_quantmap__44c7_s_p2_0[] = {
  133494. 3, 1, 0, 2, 4,
  133495. };
  133496. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133497. _vq_quantthresh__44c7_s_p2_0,
  133498. _vq_quantmap__44c7_s_p2_0,
  133499. 5,
  133500. 5
  133501. };
  133502. static static_codebook _44c7_s_p2_0 = {
  133503. 4, 625,
  133504. _vq_lengthlist__44c7_s_p2_0,
  133505. 1, -533725184, 1611661312, 3, 0,
  133506. _vq_quantlist__44c7_s_p2_0,
  133507. NULL,
  133508. &_vq_auxt__44c7_s_p2_0,
  133509. NULL,
  133510. 0
  133511. };
  133512. static long _vq_quantlist__44c7_s_p3_0[] = {
  133513. 4,
  133514. 3,
  133515. 5,
  133516. 2,
  133517. 6,
  133518. 1,
  133519. 7,
  133520. 0,
  133521. 8,
  133522. };
  133523. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133524. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133525. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133526. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133527. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133529. 0,
  133530. };
  133531. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133532. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133533. };
  133534. static long _vq_quantmap__44c7_s_p3_0[] = {
  133535. 7, 5, 3, 1, 0, 2, 4, 6,
  133536. 8,
  133537. };
  133538. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133539. _vq_quantthresh__44c7_s_p3_0,
  133540. _vq_quantmap__44c7_s_p3_0,
  133541. 9,
  133542. 9
  133543. };
  133544. static static_codebook _44c7_s_p3_0 = {
  133545. 2, 81,
  133546. _vq_lengthlist__44c7_s_p3_0,
  133547. 1, -531628032, 1611661312, 4, 0,
  133548. _vq_quantlist__44c7_s_p3_0,
  133549. NULL,
  133550. &_vq_auxt__44c7_s_p3_0,
  133551. NULL,
  133552. 0
  133553. };
  133554. static long _vq_quantlist__44c7_s_p4_0[] = {
  133555. 8,
  133556. 7,
  133557. 9,
  133558. 6,
  133559. 10,
  133560. 5,
  133561. 11,
  133562. 4,
  133563. 12,
  133564. 3,
  133565. 13,
  133566. 2,
  133567. 14,
  133568. 1,
  133569. 15,
  133570. 0,
  133571. 16,
  133572. };
  133573. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133574. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133575. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133576. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133577. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133578. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133579. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133580. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133581. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133582. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133583. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133592. 0,
  133593. };
  133594. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133595. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133596. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133597. };
  133598. static long _vq_quantmap__44c7_s_p4_0[] = {
  133599. 15, 13, 11, 9, 7, 5, 3, 1,
  133600. 0, 2, 4, 6, 8, 10, 12, 14,
  133601. 16,
  133602. };
  133603. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133604. _vq_quantthresh__44c7_s_p4_0,
  133605. _vq_quantmap__44c7_s_p4_0,
  133606. 17,
  133607. 17
  133608. };
  133609. static static_codebook _44c7_s_p4_0 = {
  133610. 2, 289,
  133611. _vq_lengthlist__44c7_s_p4_0,
  133612. 1, -529530880, 1611661312, 5, 0,
  133613. _vq_quantlist__44c7_s_p4_0,
  133614. NULL,
  133615. &_vq_auxt__44c7_s_p4_0,
  133616. NULL,
  133617. 0
  133618. };
  133619. static long _vq_quantlist__44c7_s_p5_0[] = {
  133620. 1,
  133621. 0,
  133622. 2,
  133623. };
  133624. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133625. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133626. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133627. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133628. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133629. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133630. 12,
  133631. };
  133632. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133633. -5.5, 5.5,
  133634. };
  133635. static long _vq_quantmap__44c7_s_p5_0[] = {
  133636. 1, 0, 2,
  133637. };
  133638. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133639. _vq_quantthresh__44c7_s_p5_0,
  133640. _vq_quantmap__44c7_s_p5_0,
  133641. 3,
  133642. 3
  133643. };
  133644. static static_codebook _44c7_s_p5_0 = {
  133645. 4, 81,
  133646. _vq_lengthlist__44c7_s_p5_0,
  133647. 1, -529137664, 1618345984, 2, 0,
  133648. _vq_quantlist__44c7_s_p5_0,
  133649. NULL,
  133650. &_vq_auxt__44c7_s_p5_0,
  133651. NULL,
  133652. 0
  133653. };
  133654. static long _vq_quantlist__44c7_s_p5_1[] = {
  133655. 5,
  133656. 4,
  133657. 6,
  133658. 3,
  133659. 7,
  133660. 2,
  133661. 8,
  133662. 1,
  133663. 9,
  133664. 0,
  133665. 10,
  133666. };
  133667. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133668. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133669. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133670. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133671. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133672. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133673. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133674. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133675. 11,11,11, 7, 7, 8, 8, 8, 8,
  133676. };
  133677. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133678. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133679. 3.5, 4.5,
  133680. };
  133681. static long _vq_quantmap__44c7_s_p5_1[] = {
  133682. 9, 7, 5, 3, 1, 0, 2, 4,
  133683. 6, 8, 10,
  133684. };
  133685. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133686. _vq_quantthresh__44c7_s_p5_1,
  133687. _vq_quantmap__44c7_s_p5_1,
  133688. 11,
  133689. 11
  133690. };
  133691. static static_codebook _44c7_s_p5_1 = {
  133692. 2, 121,
  133693. _vq_lengthlist__44c7_s_p5_1,
  133694. 1, -531365888, 1611661312, 4, 0,
  133695. _vq_quantlist__44c7_s_p5_1,
  133696. NULL,
  133697. &_vq_auxt__44c7_s_p5_1,
  133698. NULL,
  133699. 0
  133700. };
  133701. static long _vq_quantlist__44c7_s_p6_0[] = {
  133702. 6,
  133703. 5,
  133704. 7,
  133705. 4,
  133706. 8,
  133707. 3,
  133708. 9,
  133709. 2,
  133710. 10,
  133711. 1,
  133712. 11,
  133713. 0,
  133714. 12,
  133715. };
  133716. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133717. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133718. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133719. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133720. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133721. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133722. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133727. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133728. };
  133729. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133730. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133731. 12.5, 17.5, 22.5, 27.5,
  133732. };
  133733. static long _vq_quantmap__44c7_s_p6_0[] = {
  133734. 11, 9, 7, 5, 3, 1, 0, 2,
  133735. 4, 6, 8, 10, 12,
  133736. };
  133737. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133738. _vq_quantthresh__44c7_s_p6_0,
  133739. _vq_quantmap__44c7_s_p6_0,
  133740. 13,
  133741. 13
  133742. };
  133743. static static_codebook _44c7_s_p6_0 = {
  133744. 2, 169,
  133745. _vq_lengthlist__44c7_s_p6_0,
  133746. 1, -526516224, 1616117760, 4, 0,
  133747. _vq_quantlist__44c7_s_p6_0,
  133748. NULL,
  133749. &_vq_auxt__44c7_s_p6_0,
  133750. NULL,
  133751. 0
  133752. };
  133753. static long _vq_quantlist__44c7_s_p6_1[] = {
  133754. 2,
  133755. 1,
  133756. 3,
  133757. 0,
  133758. 4,
  133759. };
  133760. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133761. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133762. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133763. };
  133764. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133765. -1.5, -0.5, 0.5, 1.5,
  133766. };
  133767. static long _vq_quantmap__44c7_s_p6_1[] = {
  133768. 3, 1, 0, 2, 4,
  133769. };
  133770. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133771. _vq_quantthresh__44c7_s_p6_1,
  133772. _vq_quantmap__44c7_s_p6_1,
  133773. 5,
  133774. 5
  133775. };
  133776. static static_codebook _44c7_s_p6_1 = {
  133777. 2, 25,
  133778. _vq_lengthlist__44c7_s_p6_1,
  133779. 1, -533725184, 1611661312, 3, 0,
  133780. _vq_quantlist__44c7_s_p6_1,
  133781. NULL,
  133782. &_vq_auxt__44c7_s_p6_1,
  133783. NULL,
  133784. 0
  133785. };
  133786. static long _vq_quantlist__44c7_s_p7_0[] = {
  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_p7_0[] = {
  133802. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133803. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133804. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133805. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133806. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133807. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133808. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133809. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133810. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133811. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133812. 19,13,13,13,13,14,14,15,15,
  133813. };
  133814. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133815. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133816. 27.5, 38.5, 49.5, 60.5,
  133817. };
  133818. static long _vq_quantmap__44c7_s_p7_0[] = {
  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_p7_0 = {
  133823. _vq_quantthresh__44c7_s_p7_0,
  133824. _vq_quantmap__44c7_s_p7_0,
  133825. 13,
  133826. 13
  133827. };
  133828. static static_codebook _44c7_s_p7_0 = {
  133829. 2, 169,
  133830. _vq_lengthlist__44c7_s_p7_0,
  133831. 1, -523206656, 1618345984, 4, 0,
  133832. _vq_quantlist__44c7_s_p7_0,
  133833. NULL,
  133834. &_vq_auxt__44c7_s_p7_0,
  133835. NULL,
  133836. 0
  133837. };
  133838. static long _vq_quantlist__44c7_s_p7_1[] = {
  133839. 5,
  133840. 4,
  133841. 6,
  133842. 3,
  133843. 7,
  133844. 2,
  133845. 8,
  133846. 1,
  133847. 9,
  133848. 0,
  133849. 10,
  133850. };
  133851. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133852. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133853. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133854. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133855. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133856. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133857. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133858. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133859. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133860. };
  133861. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133862. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133863. 3.5, 4.5,
  133864. };
  133865. static long _vq_quantmap__44c7_s_p7_1[] = {
  133866. 9, 7, 5, 3, 1, 0, 2, 4,
  133867. 6, 8, 10,
  133868. };
  133869. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133870. _vq_quantthresh__44c7_s_p7_1,
  133871. _vq_quantmap__44c7_s_p7_1,
  133872. 11,
  133873. 11
  133874. };
  133875. static static_codebook _44c7_s_p7_1 = {
  133876. 2, 121,
  133877. _vq_lengthlist__44c7_s_p7_1,
  133878. 1, -531365888, 1611661312, 4, 0,
  133879. _vq_quantlist__44c7_s_p7_1,
  133880. NULL,
  133881. &_vq_auxt__44c7_s_p7_1,
  133882. NULL,
  133883. 0
  133884. };
  133885. static long _vq_quantlist__44c7_s_p8_0[] = {
  133886. 7,
  133887. 6,
  133888. 8,
  133889. 5,
  133890. 9,
  133891. 4,
  133892. 10,
  133893. 3,
  133894. 11,
  133895. 2,
  133896. 12,
  133897. 1,
  133898. 13,
  133899. 0,
  133900. 14,
  133901. };
  133902. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133903. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133904. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133905. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133906. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133907. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133908. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133909. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133910. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133911. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133912. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133913. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133914. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133915. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133916. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133917. 14,
  133918. };
  133919. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133920. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133921. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133922. };
  133923. static long _vq_quantmap__44c7_s_p8_0[] = {
  133924. 13, 11, 9, 7, 5, 3, 1, 0,
  133925. 2, 4, 6, 8, 10, 12, 14,
  133926. };
  133927. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133928. _vq_quantthresh__44c7_s_p8_0,
  133929. _vq_quantmap__44c7_s_p8_0,
  133930. 15,
  133931. 15
  133932. };
  133933. static static_codebook _44c7_s_p8_0 = {
  133934. 2, 225,
  133935. _vq_lengthlist__44c7_s_p8_0,
  133936. 1, -520986624, 1620377600, 4, 0,
  133937. _vq_quantlist__44c7_s_p8_0,
  133938. NULL,
  133939. &_vq_auxt__44c7_s_p8_0,
  133940. NULL,
  133941. 0
  133942. };
  133943. static long _vq_quantlist__44c7_s_p8_1[] = {
  133944. 10,
  133945. 9,
  133946. 11,
  133947. 8,
  133948. 12,
  133949. 7,
  133950. 13,
  133951. 6,
  133952. 14,
  133953. 5,
  133954. 15,
  133955. 4,
  133956. 16,
  133957. 3,
  133958. 17,
  133959. 2,
  133960. 18,
  133961. 1,
  133962. 19,
  133963. 0,
  133964. 20,
  133965. };
  133966. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133967. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133968. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133969. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133970. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133971. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133972. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133973. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133974. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133975. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133976. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133977. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133978. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133979. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133980. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133981. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133982. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133983. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133984. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133985. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133986. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133987. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133988. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133989. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133990. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133991. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133992. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133993. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133994. 10,10,10,10,10,10,10,10,10,
  133995. };
  133996. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133997. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133998. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133999. 6.5, 7.5, 8.5, 9.5,
  134000. };
  134001. static long _vq_quantmap__44c7_s_p8_1[] = {
  134002. 19, 17, 15, 13, 11, 9, 7, 5,
  134003. 3, 1, 0, 2, 4, 6, 8, 10,
  134004. 12, 14, 16, 18, 20,
  134005. };
  134006. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  134007. _vq_quantthresh__44c7_s_p8_1,
  134008. _vq_quantmap__44c7_s_p8_1,
  134009. 21,
  134010. 21
  134011. };
  134012. static static_codebook _44c7_s_p8_1 = {
  134013. 2, 441,
  134014. _vq_lengthlist__44c7_s_p8_1,
  134015. 1, -529268736, 1611661312, 5, 0,
  134016. _vq_quantlist__44c7_s_p8_1,
  134017. NULL,
  134018. &_vq_auxt__44c7_s_p8_1,
  134019. NULL,
  134020. 0
  134021. };
  134022. static long _vq_quantlist__44c7_s_p9_0[] = {
  134023. 6,
  134024. 5,
  134025. 7,
  134026. 4,
  134027. 8,
  134028. 3,
  134029. 9,
  134030. 2,
  134031. 10,
  134032. 1,
  134033. 11,
  134034. 0,
  134035. 12,
  134036. };
  134037. static long _vq_lengthlist__44c7_s_p9_0[] = {
  134038. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  134039. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  134040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134046. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134048. 11,11,11,11,11,11,11,11,11,
  134049. };
  134050. static float _vq_quantthresh__44c7_s_p9_0[] = {
  134051. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  134052. 1592.5, 2229.5, 2866.5, 3503.5,
  134053. };
  134054. static long _vq_quantmap__44c7_s_p9_0[] = {
  134055. 11, 9, 7, 5, 3, 1, 0, 2,
  134056. 4, 6, 8, 10, 12,
  134057. };
  134058. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  134059. _vq_quantthresh__44c7_s_p9_0,
  134060. _vq_quantmap__44c7_s_p9_0,
  134061. 13,
  134062. 13
  134063. };
  134064. static static_codebook _44c7_s_p9_0 = {
  134065. 2, 169,
  134066. _vq_lengthlist__44c7_s_p9_0,
  134067. 1, -511845376, 1630791680, 4, 0,
  134068. _vq_quantlist__44c7_s_p9_0,
  134069. NULL,
  134070. &_vq_auxt__44c7_s_p9_0,
  134071. NULL,
  134072. 0
  134073. };
  134074. static long _vq_quantlist__44c7_s_p9_1[] = {
  134075. 6,
  134076. 5,
  134077. 7,
  134078. 4,
  134079. 8,
  134080. 3,
  134081. 9,
  134082. 2,
  134083. 10,
  134084. 1,
  134085. 11,
  134086. 0,
  134087. 12,
  134088. };
  134089. static long _vq_lengthlist__44c7_s_p9_1[] = {
  134090. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  134091. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  134092. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  134093. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  134094. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  134095. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  134096. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  134097. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  134098. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  134099. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  134100. 15,11,11,10,10,12,12,12,12,
  134101. };
  134102. static float _vq_quantthresh__44c7_s_p9_1[] = {
  134103. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  134104. 122.5, 171.5, 220.5, 269.5,
  134105. };
  134106. static long _vq_quantmap__44c7_s_p9_1[] = {
  134107. 11, 9, 7, 5, 3, 1, 0, 2,
  134108. 4, 6, 8, 10, 12,
  134109. };
  134110. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  134111. _vq_quantthresh__44c7_s_p9_1,
  134112. _vq_quantmap__44c7_s_p9_1,
  134113. 13,
  134114. 13
  134115. };
  134116. static static_codebook _44c7_s_p9_1 = {
  134117. 2, 169,
  134118. _vq_lengthlist__44c7_s_p9_1,
  134119. 1, -518889472, 1622704128, 4, 0,
  134120. _vq_quantlist__44c7_s_p9_1,
  134121. NULL,
  134122. &_vq_auxt__44c7_s_p9_1,
  134123. NULL,
  134124. 0
  134125. };
  134126. static long _vq_quantlist__44c7_s_p9_2[] = {
  134127. 24,
  134128. 23,
  134129. 25,
  134130. 22,
  134131. 26,
  134132. 21,
  134133. 27,
  134134. 20,
  134135. 28,
  134136. 19,
  134137. 29,
  134138. 18,
  134139. 30,
  134140. 17,
  134141. 31,
  134142. 16,
  134143. 32,
  134144. 15,
  134145. 33,
  134146. 14,
  134147. 34,
  134148. 13,
  134149. 35,
  134150. 12,
  134151. 36,
  134152. 11,
  134153. 37,
  134154. 10,
  134155. 38,
  134156. 9,
  134157. 39,
  134158. 8,
  134159. 40,
  134160. 7,
  134161. 41,
  134162. 6,
  134163. 42,
  134164. 5,
  134165. 43,
  134166. 4,
  134167. 44,
  134168. 3,
  134169. 45,
  134170. 2,
  134171. 46,
  134172. 1,
  134173. 47,
  134174. 0,
  134175. 48,
  134176. };
  134177. static long _vq_lengthlist__44c7_s_p9_2[] = {
  134178. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  134179. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134180. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134181. 7,
  134182. };
  134183. static float _vq_quantthresh__44c7_s_p9_2[] = {
  134184. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134185. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134186. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134187. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134188. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134189. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134190. };
  134191. static long _vq_quantmap__44c7_s_p9_2[] = {
  134192. 47, 45, 43, 41, 39, 37, 35, 33,
  134193. 31, 29, 27, 25, 23, 21, 19, 17,
  134194. 15, 13, 11, 9, 7, 5, 3, 1,
  134195. 0, 2, 4, 6, 8, 10, 12, 14,
  134196. 16, 18, 20, 22, 24, 26, 28, 30,
  134197. 32, 34, 36, 38, 40, 42, 44, 46,
  134198. 48,
  134199. };
  134200. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134201. _vq_quantthresh__44c7_s_p9_2,
  134202. _vq_quantmap__44c7_s_p9_2,
  134203. 49,
  134204. 49
  134205. };
  134206. static static_codebook _44c7_s_p9_2 = {
  134207. 1, 49,
  134208. _vq_lengthlist__44c7_s_p9_2,
  134209. 1, -526909440, 1611661312, 6, 0,
  134210. _vq_quantlist__44c7_s_p9_2,
  134211. NULL,
  134212. &_vq_auxt__44c7_s_p9_2,
  134213. NULL,
  134214. 0
  134215. };
  134216. static long _huff_lengthlist__44c7_s_short[] = {
  134217. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134218. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134219. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134220. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134221. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134222. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134223. 10, 9,11,14,
  134224. };
  134225. static static_codebook _huff_book__44c7_s_short = {
  134226. 2, 100,
  134227. _huff_lengthlist__44c7_s_short,
  134228. 0, 0, 0, 0, 0,
  134229. NULL,
  134230. NULL,
  134231. NULL,
  134232. NULL,
  134233. 0
  134234. };
  134235. static long _huff_lengthlist__44c8_s_long[] = {
  134236. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134237. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134238. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134239. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134240. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134241. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134242. 11, 9, 9,10,
  134243. };
  134244. static static_codebook _huff_book__44c8_s_long = {
  134245. 2, 100,
  134246. _huff_lengthlist__44c8_s_long,
  134247. 0, 0, 0, 0, 0,
  134248. NULL,
  134249. NULL,
  134250. NULL,
  134251. NULL,
  134252. 0
  134253. };
  134254. static long _vq_quantlist__44c8_s_p1_0[] = {
  134255. 1,
  134256. 0,
  134257. 2,
  134258. };
  134259. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134260. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134261. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134262. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134263. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134264. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134265. 8,
  134266. };
  134267. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134268. -0.5, 0.5,
  134269. };
  134270. static long _vq_quantmap__44c8_s_p1_0[] = {
  134271. 1, 0, 2,
  134272. };
  134273. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134274. _vq_quantthresh__44c8_s_p1_0,
  134275. _vq_quantmap__44c8_s_p1_0,
  134276. 3,
  134277. 3
  134278. };
  134279. static static_codebook _44c8_s_p1_0 = {
  134280. 4, 81,
  134281. _vq_lengthlist__44c8_s_p1_0,
  134282. 1, -535822336, 1611661312, 2, 0,
  134283. _vq_quantlist__44c8_s_p1_0,
  134284. NULL,
  134285. &_vq_auxt__44c8_s_p1_0,
  134286. NULL,
  134287. 0
  134288. };
  134289. static long _vq_quantlist__44c8_s_p2_0[] = {
  134290. 2,
  134291. 1,
  134292. 3,
  134293. 0,
  134294. 4,
  134295. };
  134296. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134297. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134298. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134299. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134300. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134301. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134302. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134303. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134304. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134306. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134307. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134308. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134309. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134310. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134311. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134312. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134314. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134315. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134316. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134317. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134318. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134319. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134320. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134322. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134323. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134324. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134325. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134326. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134327. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134328. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134333. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134334. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134335. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134336. 13,
  134337. };
  134338. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134339. -1.5, -0.5, 0.5, 1.5,
  134340. };
  134341. static long _vq_quantmap__44c8_s_p2_0[] = {
  134342. 3, 1, 0, 2, 4,
  134343. };
  134344. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134345. _vq_quantthresh__44c8_s_p2_0,
  134346. _vq_quantmap__44c8_s_p2_0,
  134347. 5,
  134348. 5
  134349. };
  134350. static static_codebook _44c8_s_p2_0 = {
  134351. 4, 625,
  134352. _vq_lengthlist__44c8_s_p2_0,
  134353. 1, -533725184, 1611661312, 3, 0,
  134354. _vq_quantlist__44c8_s_p2_0,
  134355. NULL,
  134356. &_vq_auxt__44c8_s_p2_0,
  134357. NULL,
  134358. 0
  134359. };
  134360. static long _vq_quantlist__44c8_s_p3_0[] = {
  134361. 4,
  134362. 3,
  134363. 5,
  134364. 2,
  134365. 6,
  134366. 1,
  134367. 7,
  134368. 0,
  134369. 8,
  134370. };
  134371. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134372. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134373. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134374. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134375. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134377. 0,
  134378. };
  134379. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134380. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134381. };
  134382. static long _vq_quantmap__44c8_s_p3_0[] = {
  134383. 7, 5, 3, 1, 0, 2, 4, 6,
  134384. 8,
  134385. };
  134386. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134387. _vq_quantthresh__44c8_s_p3_0,
  134388. _vq_quantmap__44c8_s_p3_0,
  134389. 9,
  134390. 9
  134391. };
  134392. static static_codebook _44c8_s_p3_0 = {
  134393. 2, 81,
  134394. _vq_lengthlist__44c8_s_p3_0,
  134395. 1, -531628032, 1611661312, 4, 0,
  134396. _vq_quantlist__44c8_s_p3_0,
  134397. NULL,
  134398. &_vq_auxt__44c8_s_p3_0,
  134399. NULL,
  134400. 0
  134401. };
  134402. static long _vq_quantlist__44c8_s_p4_0[] = {
  134403. 8,
  134404. 7,
  134405. 9,
  134406. 6,
  134407. 10,
  134408. 5,
  134409. 11,
  134410. 4,
  134411. 12,
  134412. 3,
  134413. 13,
  134414. 2,
  134415. 14,
  134416. 1,
  134417. 15,
  134418. 0,
  134419. 16,
  134420. };
  134421. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134422. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134423. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134424. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134425. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134426. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134427. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134428. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134429. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134430. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134431. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134440. 0,
  134441. };
  134442. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134443. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134444. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134445. };
  134446. static long _vq_quantmap__44c8_s_p4_0[] = {
  134447. 15, 13, 11, 9, 7, 5, 3, 1,
  134448. 0, 2, 4, 6, 8, 10, 12, 14,
  134449. 16,
  134450. };
  134451. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134452. _vq_quantthresh__44c8_s_p4_0,
  134453. _vq_quantmap__44c8_s_p4_0,
  134454. 17,
  134455. 17
  134456. };
  134457. static static_codebook _44c8_s_p4_0 = {
  134458. 2, 289,
  134459. _vq_lengthlist__44c8_s_p4_0,
  134460. 1, -529530880, 1611661312, 5, 0,
  134461. _vq_quantlist__44c8_s_p4_0,
  134462. NULL,
  134463. &_vq_auxt__44c8_s_p4_0,
  134464. NULL,
  134465. 0
  134466. };
  134467. static long _vq_quantlist__44c8_s_p5_0[] = {
  134468. 1,
  134469. 0,
  134470. 2,
  134471. };
  134472. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134473. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134474. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134475. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134476. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134477. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134478. 12,
  134479. };
  134480. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134481. -5.5, 5.5,
  134482. };
  134483. static long _vq_quantmap__44c8_s_p5_0[] = {
  134484. 1, 0, 2,
  134485. };
  134486. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134487. _vq_quantthresh__44c8_s_p5_0,
  134488. _vq_quantmap__44c8_s_p5_0,
  134489. 3,
  134490. 3
  134491. };
  134492. static static_codebook _44c8_s_p5_0 = {
  134493. 4, 81,
  134494. _vq_lengthlist__44c8_s_p5_0,
  134495. 1, -529137664, 1618345984, 2, 0,
  134496. _vq_quantlist__44c8_s_p5_0,
  134497. NULL,
  134498. &_vq_auxt__44c8_s_p5_0,
  134499. NULL,
  134500. 0
  134501. };
  134502. static long _vq_quantlist__44c8_s_p5_1[] = {
  134503. 5,
  134504. 4,
  134505. 6,
  134506. 3,
  134507. 7,
  134508. 2,
  134509. 8,
  134510. 1,
  134511. 9,
  134512. 0,
  134513. 10,
  134514. };
  134515. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134516. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134517. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134518. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134519. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134520. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134521. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134522. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134523. 11,11,11, 7, 7, 7, 7, 8, 8,
  134524. };
  134525. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134526. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134527. 3.5, 4.5,
  134528. };
  134529. static long _vq_quantmap__44c8_s_p5_1[] = {
  134530. 9, 7, 5, 3, 1, 0, 2, 4,
  134531. 6, 8, 10,
  134532. };
  134533. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134534. _vq_quantthresh__44c8_s_p5_1,
  134535. _vq_quantmap__44c8_s_p5_1,
  134536. 11,
  134537. 11
  134538. };
  134539. static static_codebook _44c8_s_p5_1 = {
  134540. 2, 121,
  134541. _vq_lengthlist__44c8_s_p5_1,
  134542. 1, -531365888, 1611661312, 4, 0,
  134543. _vq_quantlist__44c8_s_p5_1,
  134544. NULL,
  134545. &_vq_auxt__44c8_s_p5_1,
  134546. NULL,
  134547. 0
  134548. };
  134549. static long _vq_quantlist__44c8_s_p6_0[] = {
  134550. 6,
  134551. 5,
  134552. 7,
  134553. 4,
  134554. 8,
  134555. 3,
  134556. 9,
  134557. 2,
  134558. 10,
  134559. 1,
  134560. 11,
  134561. 0,
  134562. 12,
  134563. };
  134564. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134565. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134566. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134567. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134568. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134569. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134570. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134575. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134576. };
  134577. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134578. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134579. 12.5, 17.5, 22.5, 27.5,
  134580. };
  134581. static long _vq_quantmap__44c8_s_p6_0[] = {
  134582. 11, 9, 7, 5, 3, 1, 0, 2,
  134583. 4, 6, 8, 10, 12,
  134584. };
  134585. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134586. _vq_quantthresh__44c8_s_p6_0,
  134587. _vq_quantmap__44c8_s_p6_0,
  134588. 13,
  134589. 13
  134590. };
  134591. static static_codebook _44c8_s_p6_0 = {
  134592. 2, 169,
  134593. _vq_lengthlist__44c8_s_p6_0,
  134594. 1, -526516224, 1616117760, 4, 0,
  134595. _vq_quantlist__44c8_s_p6_0,
  134596. NULL,
  134597. &_vq_auxt__44c8_s_p6_0,
  134598. NULL,
  134599. 0
  134600. };
  134601. static long _vq_quantlist__44c8_s_p6_1[] = {
  134602. 2,
  134603. 1,
  134604. 3,
  134605. 0,
  134606. 4,
  134607. };
  134608. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134609. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134610. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134611. };
  134612. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134613. -1.5, -0.5, 0.5, 1.5,
  134614. };
  134615. static long _vq_quantmap__44c8_s_p6_1[] = {
  134616. 3, 1, 0, 2, 4,
  134617. };
  134618. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134619. _vq_quantthresh__44c8_s_p6_1,
  134620. _vq_quantmap__44c8_s_p6_1,
  134621. 5,
  134622. 5
  134623. };
  134624. static static_codebook _44c8_s_p6_1 = {
  134625. 2, 25,
  134626. _vq_lengthlist__44c8_s_p6_1,
  134627. 1, -533725184, 1611661312, 3, 0,
  134628. _vq_quantlist__44c8_s_p6_1,
  134629. NULL,
  134630. &_vq_auxt__44c8_s_p6_1,
  134631. NULL,
  134632. 0
  134633. };
  134634. static long _vq_quantlist__44c8_s_p7_0[] = {
  134635. 6,
  134636. 5,
  134637. 7,
  134638. 4,
  134639. 8,
  134640. 3,
  134641. 9,
  134642. 2,
  134643. 10,
  134644. 1,
  134645. 11,
  134646. 0,
  134647. 12,
  134648. };
  134649. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134650. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134651. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134652. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134653. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134654. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134655. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134656. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134657. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134658. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134659. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134660. 20,13,13,13,13,14,13,15,15,
  134661. };
  134662. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134663. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134664. 27.5, 38.5, 49.5, 60.5,
  134665. };
  134666. static long _vq_quantmap__44c8_s_p7_0[] = {
  134667. 11, 9, 7, 5, 3, 1, 0, 2,
  134668. 4, 6, 8, 10, 12,
  134669. };
  134670. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134671. _vq_quantthresh__44c8_s_p7_0,
  134672. _vq_quantmap__44c8_s_p7_0,
  134673. 13,
  134674. 13
  134675. };
  134676. static static_codebook _44c8_s_p7_0 = {
  134677. 2, 169,
  134678. _vq_lengthlist__44c8_s_p7_0,
  134679. 1, -523206656, 1618345984, 4, 0,
  134680. _vq_quantlist__44c8_s_p7_0,
  134681. NULL,
  134682. &_vq_auxt__44c8_s_p7_0,
  134683. NULL,
  134684. 0
  134685. };
  134686. static long _vq_quantlist__44c8_s_p7_1[] = {
  134687. 5,
  134688. 4,
  134689. 6,
  134690. 3,
  134691. 7,
  134692. 2,
  134693. 8,
  134694. 1,
  134695. 9,
  134696. 0,
  134697. 10,
  134698. };
  134699. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134700. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134701. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134702. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134703. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134704. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134705. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134706. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134707. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134708. };
  134709. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134710. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134711. 3.5, 4.5,
  134712. };
  134713. static long _vq_quantmap__44c8_s_p7_1[] = {
  134714. 9, 7, 5, 3, 1, 0, 2, 4,
  134715. 6, 8, 10,
  134716. };
  134717. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134718. _vq_quantthresh__44c8_s_p7_1,
  134719. _vq_quantmap__44c8_s_p7_1,
  134720. 11,
  134721. 11
  134722. };
  134723. static static_codebook _44c8_s_p7_1 = {
  134724. 2, 121,
  134725. _vq_lengthlist__44c8_s_p7_1,
  134726. 1, -531365888, 1611661312, 4, 0,
  134727. _vq_quantlist__44c8_s_p7_1,
  134728. NULL,
  134729. &_vq_auxt__44c8_s_p7_1,
  134730. NULL,
  134731. 0
  134732. };
  134733. static long _vq_quantlist__44c8_s_p8_0[] = {
  134734. 7,
  134735. 6,
  134736. 8,
  134737. 5,
  134738. 9,
  134739. 4,
  134740. 10,
  134741. 3,
  134742. 11,
  134743. 2,
  134744. 12,
  134745. 1,
  134746. 13,
  134747. 0,
  134748. 14,
  134749. };
  134750. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134751. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134752. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134753. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134754. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134755. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134756. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134757. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134758. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134759. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134760. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134761. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134762. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134763. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134764. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134765. 15,
  134766. };
  134767. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134768. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134769. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134770. };
  134771. static long _vq_quantmap__44c8_s_p8_0[] = {
  134772. 13, 11, 9, 7, 5, 3, 1, 0,
  134773. 2, 4, 6, 8, 10, 12, 14,
  134774. };
  134775. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134776. _vq_quantthresh__44c8_s_p8_0,
  134777. _vq_quantmap__44c8_s_p8_0,
  134778. 15,
  134779. 15
  134780. };
  134781. static static_codebook _44c8_s_p8_0 = {
  134782. 2, 225,
  134783. _vq_lengthlist__44c8_s_p8_0,
  134784. 1, -520986624, 1620377600, 4, 0,
  134785. _vq_quantlist__44c8_s_p8_0,
  134786. NULL,
  134787. &_vq_auxt__44c8_s_p8_0,
  134788. NULL,
  134789. 0
  134790. };
  134791. static long _vq_quantlist__44c8_s_p8_1[] = {
  134792. 10,
  134793. 9,
  134794. 11,
  134795. 8,
  134796. 12,
  134797. 7,
  134798. 13,
  134799. 6,
  134800. 14,
  134801. 5,
  134802. 15,
  134803. 4,
  134804. 16,
  134805. 3,
  134806. 17,
  134807. 2,
  134808. 18,
  134809. 1,
  134810. 19,
  134811. 0,
  134812. 20,
  134813. };
  134814. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134815. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134816. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134817. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134818. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134819. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134820. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134821. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134822. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134823. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134824. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134825. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134826. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134827. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134828. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134829. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134830. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134831. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134832. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134833. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134834. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134835. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134836. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134837. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134838. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134839. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134840. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134841. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134842. 10, 9, 9,10,10, 9,10, 9, 9,
  134843. };
  134844. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134845. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134846. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134847. 6.5, 7.5, 8.5, 9.5,
  134848. };
  134849. static long _vq_quantmap__44c8_s_p8_1[] = {
  134850. 19, 17, 15, 13, 11, 9, 7, 5,
  134851. 3, 1, 0, 2, 4, 6, 8, 10,
  134852. 12, 14, 16, 18, 20,
  134853. };
  134854. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134855. _vq_quantthresh__44c8_s_p8_1,
  134856. _vq_quantmap__44c8_s_p8_1,
  134857. 21,
  134858. 21
  134859. };
  134860. static static_codebook _44c8_s_p8_1 = {
  134861. 2, 441,
  134862. _vq_lengthlist__44c8_s_p8_1,
  134863. 1, -529268736, 1611661312, 5, 0,
  134864. _vq_quantlist__44c8_s_p8_1,
  134865. NULL,
  134866. &_vq_auxt__44c8_s_p8_1,
  134867. NULL,
  134868. 0
  134869. };
  134870. static long _vq_quantlist__44c8_s_p9_0[] = {
  134871. 8,
  134872. 7,
  134873. 9,
  134874. 6,
  134875. 10,
  134876. 5,
  134877. 11,
  134878. 4,
  134879. 12,
  134880. 3,
  134881. 13,
  134882. 2,
  134883. 14,
  134884. 1,
  134885. 15,
  134886. 0,
  134887. 16,
  134888. };
  134889. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134890. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134891. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134892. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134893. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134894. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134895. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134896. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134897. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134898. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134899. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134900. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134901. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134902. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134903. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134904. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134905. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134906. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134907. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134908. 10,
  134909. };
  134910. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134911. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134912. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134913. };
  134914. static long _vq_quantmap__44c8_s_p9_0[] = {
  134915. 15, 13, 11, 9, 7, 5, 3, 1,
  134916. 0, 2, 4, 6, 8, 10, 12, 14,
  134917. 16,
  134918. };
  134919. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134920. _vq_quantthresh__44c8_s_p9_0,
  134921. _vq_quantmap__44c8_s_p9_0,
  134922. 17,
  134923. 17
  134924. };
  134925. static static_codebook _44c8_s_p9_0 = {
  134926. 2, 289,
  134927. _vq_lengthlist__44c8_s_p9_0,
  134928. 1, -509798400, 1631393792, 5, 0,
  134929. _vq_quantlist__44c8_s_p9_0,
  134930. NULL,
  134931. &_vq_auxt__44c8_s_p9_0,
  134932. NULL,
  134933. 0
  134934. };
  134935. static long _vq_quantlist__44c8_s_p9_1[] = {
  134936. 9,
  134937. 8,
  134938. 10,
  134939. 7,
  134940. 11,
  134941. 6,
  134942. 12,
  134943. 5,
  134944. 13,
  134945. 4,
  134946. 14,
  134947. 3,
  134948. 15,
  134949. 2,
  134950. 16,
  134951. 1,
  134952. 17,
  134953. 0,
  134954. 18,
  134955. };
  134956. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134957. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134958. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134959. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134960. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134961. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134962. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134963. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134964. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134965. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134966. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134967. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134968. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134969. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134970. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134971. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134972. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134973. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134974. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134975. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134976. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134977. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134978. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134979. 14,13,13,14,14,15,14,15,14,
  134980. };
  134981. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134982. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134983. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134984. 367.5, 416.5,
  134985. };
  134986. static long _vq_quantmap__44c8_s_p9_1[] = {
  134987. 17, 15, 13, 11, 9, 7, 5, 3,
  134988. 1, 0, 2, 4, 6, 8, 10, 12,
  134989. 14, 16, 18,
  134990. };
  134991. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134992. _vq_quantthresh__44c8_s_p9_1,
  134993. _vq_quantmap__44c8_s_p9_1,
  134994. 19,
  134995. 19
  134996. };
  134997. static static_codebook _44c8_s_p9_1 = {
  134998. 2, 361,
  134999. _vq_lengthlist__44c8_s_p9_1,
  135000. 1, -518287360, 1622704128, 5, 0,
  135001. _vq_quantlist__44c8_s_p9_1,
  135002. NULL,
  135003. &_vq_auxt__44c8_s_p9_1,
  135004. NULL,
  135005. 0
  135006. };
  135007. static long _vq_quantlist__44c8_s_p9_2[] = {
  135008. 24,
  135009. 23,
  135010. 25,
  135011. 22,
  135012. 26,
  135013. 21,
  135014. 27,
  135015. 20,
  135016. 28,
  135017. 19,
  135018. 29,
  135019. 18,
  135020. 30,
  135021. 17,
  135022. 31,
  135023. 16,
  135024. 32,
  135025. 15,
  135026. 33,
  135027. 14,
  135028. 34,
  135029. 13,
  135030. 35,
  135031. 12,
  135032. 36,
  135033. 11,
  135034. 37,
  135035. 10,
  135036. 38,
  135037. 9,
  135038. 39,
  135039. 8,
  135040. 40,
  135041. 7,
  135042. 41,
  135043. 6,
  135044. 42,
  135045. 5,
  135046. 43,
  135047. 4,
  135048. 44,
  135049. 3,
  135050. 45,
  135051. 2,
  135052. 46,
  135053. 1,
  135054. 47,
  135055. 0,
  135056. 48,
  135057. };
  135058. static long _vq_lengthlist__44c8_s_p9_2[] = {
  135059. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135060. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135061. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135062. 7,
  135063. };
  135064. static float _vq_quantthresh__44c8_s_p9_2[] = {
  135065. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135066. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135067. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135068. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135069. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135070. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135071. };
  135072. static long _vq_quantmap__44c8_s_p9_2[] = {
  135073. 47, 45, 43, 41, 39, 37, 35, 33,
  135074. 31, 29, 27, 25, 23, 21, 19, 17,
  135075. 15, 13, 11, 9, 7, 5, 3, 1,
  135076. 0, 2, 4, 6, 8, 10, 12, 14,
  135077. 16, 18, 20, 22, 24, 26, 28, 30,
  135078. 32, 34, 36, 38, 40, 42, 44, 46,
  135079. 48,
  135080. };
  135081. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  135082. _vq_quantthresh__44c8_s_p9_2,
  135083. _vq_quantmap__44c8_s_p9_2,
  135084. 49,
  135085. 49
  135086. };
  135087. static static_codebook _44c8_s_p9_2 = {
  135088. 1, 49,
  135089. _vq_lengthlist__44c8_s_p9_2,
  135090. 1, -526909440, 1611661312, 6, 0,
  135091. _vq_quantlist__44c8_s_p9_2,
  135092. NULL,
  135093. &_vq_auxt__44c8_s_p9_2,
  135094. NULL,
  135095. 0
  135096. };
  135097. static long _huff_lengthlist__44c8_s_short[] = {
  135098. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  135099. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  135100. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  135101. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  135102. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  135103. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  135104. 10, 9,11,14,
  135105. };
  135106. static static_codebook _huff_book__44c8_s_short = {
  135107. 2, 100,
  135108. _huff_lengthlist__44c8_s_short,
  135109. 0, 0, 0, 0, 0,
  135110. NULL,
  135111. NULL,
  135112. NULL,
  135113. NULL,
  135114. 0
  135115. };
  135116. static long _huff_lengthlist__44c9_s_long[] = {
  135117. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  135118. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  135119. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  135120. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  135121. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  135122. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  135123. 10, 9, 8, 9,
  135124. };
  135125. static static_codebook _huff_book__44c9_s_long = {
  135126. 2, 100,
  135127. _huff_lengthlist__44c9_s_long,
  135128. 0, 0, 0, 0, 0,
  135129. NULL,
  135130. NULL,
  135131. NULL,
  135132. NULL,
  135133. 0
  135134. };
  135135. static long _vq_quantlist__44c9_s_p1_0[] = {
  135136. 1,
  135137. 0,
  135138. 2,
  135139. };
  135140. static long _vq_lengthlist__44c9_s_p1_0[] = {
  135141. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  135142. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  135143. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  135144. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  135145. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  135146. 7,
  135147. };
  135148. static float _vq_quantthresh__44c9_s_p1_0[] = {
  135149. -0.5, 0.5,
  135150. };
  135151. static long _vq_quantmap__44c9_s_p1_0[] = {
  135152. 1, 0, 2,
  135153. };
  135154. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  135155. _vq_quantthresh__44c9_s_p1_0,
  135156. _vq_quantmap__44c9_s_p1_0,
  135157. 3,
  135158. 3
  135159. };
  135160. static static_codebook _44c9_s_p1_0 = {
  135161. 4, 81,
  135162. _vq_lengthlist__44c9_s_p1_0,
  135163. 1, -535822336, 1611661312, 2, 0,
  135164. _vq_quantlist__44c9_s_p1_0,
  135165. NULL,
  135166. &_vq_auxt__44c9_s_p1_0,
  135167. NULL,
  135168. 0
  135169. };
  135170. static long _vq_quantlist__44c9_s_p2_0[] = {
  135171. 2,
  135172. 1,
  135173. 3,
  135174. 0,
  135175. 4,
  135176. };
  135177. static long _vq_lengthlist__44c9_s_p2_0[] = {
  135178. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  135179. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  135180. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  135181. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  135182. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  135183. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  135184. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  135185. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  135186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135187. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  135188. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  135189. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  135190. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  135191. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  135192. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135193. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  135194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135195. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135196. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135197. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135198. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135199. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135200. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135201. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135203. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135204. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135205. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135206. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135207. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135208. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135209. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135214. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135215. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135216. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135217. 12,
  135218. };
  135219. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135220. -1.5, -0.5, 0.5, 1.5,
  135221. };
  135222. static long _vq_quantmap__44c9_s_p2_0[] = {
  135223. 3, 1, 0, 2, 4,
  135224. };
  135225. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135226. _vq_quantthresh__44c9_s_p2_0,
  135227. _vq_quantmap__44c9_s_p2_0,
  135228. 5,
  135229. 5
  135230. };
  135231. static static_codebook _44c9_s_p2_0 = {
  135232. 4, 625,
  135233. _vq_lengthlist__44c9_s_p2_0,
  135234. 1, -533725184, 1611661312, 3, 0,
  135235. _vq_quantlist__44c9_s_p2_0,
  135236. NULL,
  135237. &_vq_auxt__44c9_s_p2_0,
  135238. NULL,
  135239. 0
  135240. };
  135241. static long _vq_quantlist__44c9_s_p3_0[] = {
  135242. 4,
  135243. 3,
  135244. 5,
  135245. 2,
  135246. 6,
  135247. 1,
  135248. 7,
  135249. 0,
  135250. 8,
  135251. };
  135252. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135253. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135254. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135255. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135256. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135258. 0,
  135259. };
  135260. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135261. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135262. };
  135263. static long _vq_quantmap__44c9_s_p3_0[] = {
  135264. 7, 5, 3, 1, 0, 2, 4, 6,
  135265. 8,
  135266. };
  135267. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135268. _vq_quantthresh__44c9_s_p3_0,
  135269. _vq_quantmap__44c9_s_p3_0,
  135270. 9,
  135271. 9
  135272. };
  135273. static static_codebook _44c9_s_p3_0 = {
  135274. 2, 81,
  135275. _vq_lengthlist__44c9_s_p3_0,
  135276. 1, -531628032, 1611661312, 4, 0,
  135277. _vq_quantlist__44c9_s_p3_0,
  135278. NULL,
  135279. &_vq_auxt__44c9_s_p3_0,
  135280. NULL,
  135281. 0
  135282. };
  135283. static long _vq_quantlist__44c9_s_p4_0[] = {
  135284. 8,
  135285. 7,
  135286. 9,
  135287. 6,
  135288. 10,
  135289. 5,
  135290. 11,
  135291. 4,
  135292. 12,
  135293. 3,
  135294. 13,
  135295. 2,
  135296. 14,
  135297. 1,
  135298. 15,
  135299. 0,
  135300. 16,
  135301. };
  135302. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135303. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135304. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135305. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135306. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135307. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135308. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135309. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135310. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135311. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135312. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135321. 0,
  135322. };
  135323. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135324. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135325. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135326. };
  135327. static long _vq_quantmap__44c9_s_p4_0[] = {
  135328. 15, 13, 11, 9, 7, 5, 3, 1,
  135329. 0, 2, 4, 6, 8, 10, 12, 14,
  135330. 16,
  135331. };
  135332. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135333. _vq_quantthresh__44c9_s_p4_0,
  135334. _vq_quantmap__44c9_s_p4_0,
  135335. 17,
  135336. 17
  135337. };
  135338. static static_codebook _44c9_s_p4_0 = {
  135339. 2, 289,
  135340. _vq_lengthlist__44c9_s_p4_0,
  135341. 1, -529530880, 1611661312, 5, 0,
  135342. _vq_quantlist__44c9_s_p4_0,
  135343. NULL,
  135344. &_vq_auxt__44c9_s_p4_0,
  135345. NULL,
  135346. 0
  135347. };
  135348. static long _vq_quantlist__44c9_s_p5_0[] = {
  135349. 1,
  135350. 0,
  135351. 2,
  135352. };
  135353. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135354. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135355. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135356. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135357. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135358. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135359. 12,
  135360. };
  135361. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135362. -5.5, 5.5,
  135363. };
  135364. static long _vq_quantmap__44c9_s_p5_0[] = {
  135365. 1, 0, 2,
  135366. };
  135367. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135368. _vq_quantthresh__44c9_s_p5_0,
  135369. _vq_quantmap__44c9_s_p5_0,
  135370. 3,
  135371. 3
  135372. };
  135373. static static_codebook _44c9_s_p5_0 = {
  135374. 4, 81,
  135375. _vq_lengthlist__44c9_s_p5_0,
  135376. 1, -529137664, 1618345984, 2, 0,
  135377. _vq_quantlist__44c9_s_p5_0,
  135378. NULL,
  135379. &_vq_auxt__44c9_s_p5_0,
  135380. NULL,
  135381. 0
  135382. };
  135383. static long _vq_quantlist__44c9_s_p5_1[] = {
  135384. 5,
  135385. 4,
  135386. 6,
  135387. 3,
  135388. 7,
  135389. 2,
  135390. 8,
  135391. 1,
  135392. 9,
  135393. 0,
  135394. 10,
  135395. };
  135396. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135397. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135398. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135399. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135400. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135401. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135402. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135403. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135404. 11,11,11, 7, 7, 7, 7, 7, 7,
  135405. };
  135406. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135407. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135408. 3.5, 4.5,
  135409. };
  135410. static long _vq_quantmap__44c9_s_p5_1[] = {
  135411. 9, 7, 5, 3, 1, 0, 2, 4,
  135412. 6, 8, 10,
  135413. };
  135414. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135415. _vq_quantthresh__44c9_s_p5_1,
  135416. _vq_quantmap__44c9_s_p5_1,
  135417. 11,
  135418. 11
  135419. };
  135420. static static_codebook _44c9_s_p5_1 = {
  135421. 2, 121,
  135422. _vq_lengthlist__44c9_s_p5_1,
  135423. 1, -531365888, 1611661312, 4, 0,
  135424. _vq_quantlist__44c9_s_p5_1,
  135425. NULL,
  135426. &_vq_auxt__44c9_s_p5_1,
  135427. NULL,
  135428. 0
  135429. };
  135430. static long _vq_quantlist__44c9_s_p6_0[] = {
  135431. 6,
  135432. 5,
  135433. 7,
  135434. 4,
  135435. 8,
  135436. 3,
  135437. 9,
  135438. 2,
  135439. 10,
  135440. 1,
  135441. 11,
  135442. 0,
  135443. 12,
  135444. };
  135445. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135446. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135447. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135448. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135449. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135450. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135451. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135456. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135457. };
  135458. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135459. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135460. 12.5, 17.5, 22.5, 27.5,
  135461. };
  135462. static long _vq_quantmap__44c9_s_p6_0[] = {
  135463. 11, 9, 7, 5, 3, 1, 0, 2,
  135464. 4, 6, 8, 10, 12,
  135465. };
  135466. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135467. _vq_quantthresh__44c9_s_p6_0,
  135468. _vq_quantmap__44c9_s_p6_0,
  135469. 13,
  135470. 13
  135471. };
  135472. static static_codebook _44c9_s_p6_0 = {
  135473. 2, 169,
  135474. _vq_lengthlist__44c9_s_p6_0,
  135475. 1, -526516224, 1616117760, 4, 0,
  135476. _vq_quantlist__44c9_s_p6_0,
  135477. NULL,
  135478. &_vq_auxt__44c9_s_p6_0,
  135479. NULL,
  135480. 0
  135481. };
  135482. static long _vq_quantlist__44c9_s_p6_1[] = {
  135483. 2,
  135484. 1,
  135485. 3,
  135486. 0,
  135487. 4,
  135488. };
  135489. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135490. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135491. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135492. };
  135493. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135494. -1.5, -0.5, 0.5, 1.5,
  135495. };
  135496. static long _vq_quantmap__44c9_s_p6_1[] = {
  135497. 3, 1, 0, 2, 4,
  135498. };
  135499. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135500. _vq_quantthresh__44c9_s_p6_1,
  135501. _vq_quantmap__44c9_s_p6_1,
  135502. 5,
  135503. 5
  135504. };
  135505. static static_codebook _44c9_s_p6_1 = {
  135506. 2, 25,
  135507. _vq_lengthlist__44c9_s_p6_1,
  135508. 1, -533725184, 1611661312, 3, 0,
  135509. _vq_quantlist__44c9_s_p6_1,
  135510. NULL,
  135511. &_vq_auxt__44c9_s_p6_1,
  135512. NULL,
  135513. 0
  135514. };
  135515. static long _vq_quantlist__44c9_s_p7_0[] = {
  135516. 6,
  135517. 5,
  135518. 7,
  135519. 4,
  135520. 8,
  135521. 3,
  135522. 9,
  135523. 2,
  135524. 10,
  135525. 1,
  135526. 11,
  135527. 0,
  135528. 12,
  135529. };
  135530. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135531. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135532. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135533. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135534. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135535. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135536. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135537. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135538. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135539. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135540. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135541. 19,12,12,12,12,13,13,14,14,
  135542. };
  135543. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135544. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135545. 27.5, 38.5, 49.5, 60.5,
  135546. };
  135547. static long _vq_quantmap__44c9_s_p7_0[] = {
  135548. 11, 9, 7, 5, 3, 1, 0, 2,
  135549. 4, 6, 8, 10, 12,
  135550. };
  135551. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135552. _vq_quantthresh__44c9_s_p7_0,
  135553. _vq_quantmap__44c9_s_p7_0,
  135554. 13,
  135555. 13
  135556. };
  135557. static static_codebook _44c9_s_p7_0 = {
  135558. 2, 169,
  135559. _vq_lengthlist__44c9_s_p7_0,
  135560. 1, -523206656, 1618345984, 4, 0,
  135561. _vq_quantlist__44c9_s_p7_0,
  135562. NULL,
  135563. &_vq_auxt__44c9_s_p7_0,
  135564. NULL,
  135565. 0
  135566. };
  135567. static long _vq_quantlist__44c9_s_p7_1[] = {
  135568. 5,
  135569. 4,
  135570. 6,
  135571. 3,
  135572. 7,
  135573. 2,
  135574. 8,
  135575. 1,
  135576. 9,
  135577. 0,
  135578. 10,
  135579. };
  135580. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135581. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135582. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135583. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135584. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135585. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135586. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135587. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135588. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135589. };
  135590. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135591. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135592. 3.5, 4.5,
  135593. };
  135594. static long _vq_quantmap__44c9_s_p7_1[] = {
  135595. 9, 7, 5, 3, 1, 0, 2, 4,
  135596. 6, 8, 10,
  135597. };
  135598. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135599. _vq_quantthresh__44c9_s_p7_1,
  135600. _vq_quantmap__44c9_s_p7_1,
  135601. 11,
  135602. 11
  135603. };
  135604. static static_codebook _44c9_s_p7_1 = {
  135605. 2, 121,
  135606. _vq_lengthlist__44c9_s_p7_1,
  135607. 1, -531365888, 1611661312, 4, 0,
  135608. _vq_quantlist__44c9_s_p7_1,
  135609. NULL,
  135610. &_vq_auxt__44c9_s_p7_1,
  135611. NULL,
  135612. 0
  135613. };
  135614. static long _vq_quantlist__44c9_s_p8_0[] = {
  135615. 7,
  135616. 6,
  135617. 8,
  135618. 5,
  135619. 9,
  135620. 4,
  135621. 10,
  135622. 3,
  135623. 11,
  135624. 2,
  135625. 12,
  135626. 1,
  135627. 13,
  135628. 0,
  135629. 14,
  135630. };
  135631. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135632. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135633. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135634. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135635. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135636. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135637. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135638. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135639. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135640. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135641. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135642. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135643. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135644. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135645. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135646. 14,
  135647. };
  135648. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135649. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135650. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135651. };
  135652. static long _vq_quantmap__44c9_s_p8_0[] = {
  135653. 13, 11, 9, 7, 5, 3, 1, 0,
  135654. 2, 4, 6, 8, 10, 12, 14,
  135655. };
  135656. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135657. _vq_quantthresh__44c9_s_p8_0,
  135658. _vq_quantmap__44c9_s_p8_0,
  135659. 15,
  135660. 15
  135661. };
  135662. static static_codebook _44c9_s_p8_0 = {
  135663. 2, 225,
  135664. _vq_lengthlist__44c9_s_p8_0,
  135665. 1, -520986624, 1620377600, 4, 0,
  135666. _vq_quantlist__44c9_s_p8_0,
  135667. NULL,
  135668. &_vq_auxt__44c9_s_p8_0,
  135669. NULL,
  135670. 0
  135671. };
  135672. static long _vq_quantlist__44c9_s_p8_1[] = {
  135673. 10,
  135674. 9,
  135675. 11,
  135676. 8,
  135677. 12,
  135678. 7,
  135679. 13,
  135680. 6,
  135681. 14,
  135682. 5,
  135683. 15,
  135684. 4,
  135685. 16,
  135686. 3,
  135687. 17,
  135688. 2,
  135689. 18,
  135690. 1,
  135691. 19,
  135692. 0,
  135693. 20,
  135694. };
  135695. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135696. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135697. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135698. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135699. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135700. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135701. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135702. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135703. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135704. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135705. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135706. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135707. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135708. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135709. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135710. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135711. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135712. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135713. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135714. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135715. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135716. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135717. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135718. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135719. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135720. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135721. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135722. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135723. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135724. };
  135725. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135726. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135727. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135728. 6.5, 7.5, 8.5, 9.5,
  135729. };
  135730. static long _vq_quantmap__44c9_s_p8_1[] = {
  135731. 19, 17, 15, 13, 11, 9, 7, 5,
  135732. 3, 1, 0, 2, 4, 6, 8, 10,
  135733. 12, 14, 16, 18, 20,
  135734. };
  135735. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135736. _vq_quantthresh__44c9_s_p8_1,
  135737. _vq_quantmap__44c9_s_p8_1,
  135738. 21,
  135739. 21
  135740. };
  135741. static static_codebook _44c9_s_p8_1 = {
  135742. 2, 441,
  135743. _vq_lengthlist__44c9_s_p8_1,
  135744. 1, -529268736, 1611661312, 5, 0,
  135745. _vq_quantlist__44c9_s_p8_1,
  135746. NULL,
  135747. &_vq_auxt__44c9_s_p8_1,
  135748. NULL,
  135749. 0
  135750. };
  135751. static long _vq_quantlist__44c9_s_p9_0[] = {
  135752. 9,
  135753. 8,
  135754. 10,
  135755. 7,
  135756. 11,
  135757. 6,
  135758. 12,
  135759. 5,
  135760. 13,
  135761. 4,
  135762. 14,
  135763. 3,
  135764. 15,
  135765. 2,
  135766. 16,
  135767. 1,
  135768. 17,
  135769. 0,
  135770. 18,
  135771. };
  135772. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135773. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135774. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135775. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135776. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135777. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135778. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135779. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135780. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135781. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135782. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135783. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135784. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135785. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135786. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135787. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135788. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135789. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135791. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135793. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135794. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135795. 11,11,11,11,11,11,11,11,11,
  135796. };
  135797. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135798. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135799. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135800. 6982.5, 7913.5,
  135801. };
  135802. static long _vq_quantmap__44c9_s_p9_0[] = {
  135803. 17, 15, 13, 11, 9, 7, 5, 3,
  135804. 1, 0, 2, 4, 6, 8, 10, 12,
  135805. 14, 16, 18,
  135806. };
  135807. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135808. _vq_quantthresh__44c9_s_p9_0,
  135809. _vq_quantmap__44c9_s_p9_0,
  135810. 19,
  135811. 19
  135812. };
  135813. static static_codebook _44c9_s_p9_0 = {
  135814. 2, 361,
  135815. _vq_lengthlist__44c9_s_p9_0,
  135816. 1, -508535424, 1631393792, 5, 0,
  135817. _vq_quantlist__44c9_s_p9_0,
  135818. NULL,
  135819. &_vq_auxt__44c9_s_p9_0,
  135820. NULL,
  135821. 0
  135822. };
  135823. static long _vq_quantlist__44c9_s_p9_1[] = {
  135824. 9,
  135825. 8,
  135826. 10,
  135827. 7,
  135828. 11,
  135829. 6,
  135830. 12,
  135831. 5,
  135832. 13,
  135833. 4,
  135834. 14,
  135835. 3,
  135836. 15,
  135837. 2,
  135838. 16,
  135839. 1,
  135840. 17,
  135841. 0,
  135842. 18,
  135843. };
  135844. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135845. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135846. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135847. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135848. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135849. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135850. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135851. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135852. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135853. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135854. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135855. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135856. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135857. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135858. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135859. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135860. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135861. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135862. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135863. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135864. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135865. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135866. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135867. 13,13,13,14,13,14,15,15,15,
  135868. };
  135869. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135870. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135871. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135872. 367.5, 416.5,
  135873. };
  135874. static long _vq_quantmap__44c9_s_p9_1[] = {
  135875. 17, 15, 13, 11, 9, 7, 5, 3,
  135876. 1, 0, 2, 4, 6, 8, 10, 12,
  135877. 14, 16, 18,
  135878. };
  135879. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135880. _vq_quantthresh__44c9_s_p9_1,
  135881. _vq_quantmap__44c9_s_p9_1,
  135882. 19,
  135883. 19
  135884. };
  135885. static static_codebook _44c9_s_p9_1 = {
  135886. 2, 361,
  135887. _vq_lengthlist__44c9_s_p9_1,
  135888. 1, -518287360, 1622704128, 5, 0,
  135889. _vq_quantlist__44c9_s_p9_1,
  135890. NULL,
  135891. &_vq_auxt__44c9_s_p9_1,
  135892. NULL,
  135893. 0
  135894. };
  135895. static long _vq_quantlist__44c9_s_p9_2[] = {
  135896. 24,
  135897. 23,
  135898. 25,
  135899. 22,
  135900. 26,
  135901. 21,
  135902. 27,
  135903. 20,
  135904. 28,
  135905. 19,
  135906. 29,
  135907. 18,
  135908. 30,
  135909. 17,
  135910. 31,
  135911. 16,
  135912. 32,
  135913. 15,
  135914. 33,
  135915. 14,
  135916. 34,
  135917. 13,
  135918. 35,
  135919. 12,
  135920. 36,
  135921. 11,
  135922. 37,
  135923. 10,
  135924. 38,
  135925. 9,
  135926. 39,
  135927. 8,
  135928. 40,
  135929. 7,
  135930. 41,
  135931. 6,
  135932. 42,
  135933. 5,
  135934. 43,
  135935. 4,
  135936. 44,
  135937. 3,
  135938. 45,
  135939. 2,
  135940. 46,
  135941. 1,
  135942. 47,
  135943. 0,
  135944. 48,
  135945. };
  135946. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135947. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135948. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135949. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135950. 7,
  135951. };
  135952. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135953. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135954. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135955. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135956. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135957. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135958. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135959. };
  135960. static long _vq_quantmap__44c9_s_p9_2[] = {
  135961. 47, 45, 43, 41, 39, 37, 35, 33,
  135962. 31, 29, 27, 25, 23, 21, 19, 17,
  135963. 15, 13, 11, 9, 7, 5, 3, 1,
  135964. 0, 2, 4, 6, 8, 10, 12, 14,
  135965. 16, 18, 20, 22, 24, 26, 28, 30,
  135966. 32, 34, 36, 38, 40, 42, 44, 46,
  135967. 48,
  135968. };
  135969. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135970. _vq_quantthresh__44c9_s_p9_2,
  135971. _vq_quantmap__44c9_s_p9_2,
  135972. 49,
  135973. 49
  135974. };
  135975. static static_codebook _44c9_s_p9_2 = {
  135976. 1, 49,
  135977. _vq_lengthlist__44c9_s_p9_2,
  135978. 1, -526909440, 1611661312, 6, 0,
  135979. _vq_quantlist__44c9_s_p9_2,
  135980. NULL,
  135981. &_vq_auxt__44c9_s_p9_2,
  135982. NULL,
  135983. 0
  135984. };
  135985. static long _huff_lengthlist__44c9_s_short[] = {
  135986. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135987. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135988. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135989. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135990. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135991. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135992. 9, 8,10,13,
  135993. };
  135994. static static_codebook _huff_book__44c9_s_short = {
  135995. 2, 100,
  135996. _huff_lengthlist__44c9_s_short,
  135997. 0, 0, 0, 0, 0,
  135998. NULL,
  135999. NULL,
  136000. NULL,
  136001. NULL,
  136002. 0
  136003. };
  136004. static long _huff_lengthlist__44c0_s_long[] = {
  136005. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  136006. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  136007. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  136008. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  136009. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  136010. 12,
  136011. };
  136012. static static_codebook _huff_book__44c0_s_long = {
  136013. 2, 81,
  136014. _huff_lengthlist__44c0_s_long,
  136015. 0, 0, 0, 0, 0,
  136016. NULL,
  136017. NULL,
  136018. NULL,
  136019. NULL,
  136020. 0
  136021. };
  136022. static long _vq_quantlist__44c0_s_p1_0[] = {
  136023. 1,
  136024. 0,
  136025. 2,
  136026. };
  136027. static long _vq_lengthlist__44c0_s_p1_0[] = {
  136028. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136029. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136034. 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136039. 0, 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0,
  136074. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  136079. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  136084. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136120. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136125. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  136130. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136438. 0,
  136439. };
  136440. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136441. -0.5, 0.5,
  136442. };
  136443. static long _vq_quantmap__44c0_s_p1_0[] = {
  136444. 1, 0, 2,
  136445. };
  136446. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136447. _vq_quantthresh__44c0_s_p1_0,
  136448. _vq_quantmap__44c0_s_p1_0,
  136449. 3,
  136450. 3
  136451. };
  136452. static static_codebook _44c0_s_p1_0 = {
  136453. 8, 6561,
  136454. _vq_lengthlist__44c0_s_p1_0,
  136455. 1, -535822336, 1611661312, 2, 0,
  136456. _vq_quantlist__44c0_s_p1_0,
  136457. NULL,
  136458. &_vq_auxt__44c0_s_p1_0,
  136459. NULL,
  136460. 0
  136461. };
  136462. static long _vq_quantlist__44c0_s_p2_0[] = {
  136463. 2,
  136464. 1,
  136465. 3,
  136466. 0,
  136467. 4,
  136468. };
  136469. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136470. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136473. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136476. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136509. 0,
  136510. };
  136511. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136512. -1.5, -0.5, 0.5, 1.5,
  136513. };
  136514. static long _vq_quantmap__44c0_s_p2_0[] = {
  136515. 3, 1, 0, 2, 4,
  136516. };
  136517. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136518. _vq_quantthresh__44c0_s_p2_0,
  136519. _vq_quantmap__44c0_s_p2_0,
  136520. 5,
  136521. 5
  136522. };
  136523. static static_codebook _44c0_s_p2_0 = {
  136524. 4, 625,
  136525. _vq_lengthlist__44c0_s_p2_0,
  136526. 1, -533725184, 1611661312, 3, 0,
  136527. _vq_quantlist__44c0_s_p2_0,
  136528. NULL,
  136529. &_vq_auxt__44c0_s_p2_0,
  136530. NULL,
  136531. 0
  136532. };
  136533. static long _vq_quantlist__44c0_s_p3_0[] = {
  136534. 4,
  136535. 3,
  136536. 5,
  136537. 2,
  136538. 6,
  136539. 1,
  136540. 7,
  136541. 0,
  136542. 8,
  136543. };
  136544. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136545. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136546. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136547. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136548. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136549. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136550. 0,
  136551. };
  136552. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136553. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136554. };
  136555. static long _vq_quantmap__44c0_s_p3_0[] = {
  136556. 7, 5, 3, 1, 0, 2, 4, 6,
  136557. 8,
  136558. };
  136559. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136560. _vq_quantthresh__44c0_s_p3_0,
  136561. _vq_quantmap__44c0_s_p3_0,
  136562. 9,
  136563. 9
  136564. };
  136565. static static_codebook _44c0_s_p3_0 = {
  136566. 2, 81,
  136567. _vq_lengthlist__44c0_s_p3_0,
  136568. 1, -531628032, 1611661312, 4, 0,
  136569. _vq_quantlist__44c0_s_p3_0,
  136570. NULL,
  136571. &_vq_auxt__44c0_s_p3_0,
  136572. NULL,
  136573. 0
  136574. };
  136575. static long _vq_quantlist__44c0_s_p4_0[] = {
  136576. 4,
  136577. 3,
  136578. 5,
  136579. 2,
  136580. 6,
  136581. 1,
  136582. 7,
  136583. 0,
  136584. 8,
  136585. };
  136586. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136587. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136588. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136589. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136590. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136591. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136592. 10,
  136593. };
  136594. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136595. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136596. };
  136597. static long _vq_quantmap__44c0_s_p4_0[] = {
  136598. 7, 5, 3, 1, 0, 2, 4, 6,
  136599. 8,
  136600. };
  136601. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136602. _vq_quantthresh__44c0_s_p4_0,
  136603. _vq_quantmap__44c0_s_p4_0,
  136604. 9,
  136605. 9
  136606. };
  136607. static static_codebook _44c0_s_p4_0 = {
  136608. 2, 81,
  136609. _vq_lengthlist__44c0_s_p4_0,
  136610. 1, -531628032, 1611661312, 4, 0,
  136611. _vq_quantlist__44c0_s_p4_0,
  136612. NULL,
  136613. &_vq_auxt__44c0_s_p4_0,
  136614. NULL,
  136615. 0
  136616. };
  136617. static long _vq_quantlist__44c0_s_p5_0[] = {
  136618. 8,
  136619. 7,
  136620. 9,
  136621. 6,
  136622. 10,
  136623. 5,
  136624. 11,
  136625. 4,
  136626. 12,
  136627. 3,
  136628. 13,
  136629. 2,
  136630. 14,
  136631. 1,
  136632. 15,
  136633. 0,
  136634. 16,
  136635. };
  136636. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136637. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136638. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136639. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136640. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136641. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136642. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136643. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136644. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136645. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136646. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136647. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136648. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136649. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136650. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136651. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136652. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136653. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136654. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136655. 14,
  136656. };
  136657. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136658. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136659. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136660. };
  136661. static long _vq_quantmap__44c0_s_p5_0[] = {
  136662. 15, 13, 11, 9, 7, 5, 3, 1,
  136663. 0, 2, 4, 6, 8, 10, 12, 14,
  136664. 16,
  136665. };
  136666. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136667. _vq_quantthresh__44c0_s_p5_0,
  136668. _vq_quantmap__44c0_s_p5_0,
  136669. 17,
  136670. 17
  136671. };
  136672. static static_codebook _44c0_s_p5_0 = {
  136673. 2, 289,
  136674. _vq_lengthlist__44c0_s_p5_0,
  136675. 1, -529530880, 1611661312, 5, 0,
  136676. _vq_quantlist__44c0_s_p5_0,
  136677. NULL,
  136678. &_vq_auxt__44c0_s_p5_0,
  136679. NULL,
  136680. 0
  136681. };
  136682. static long _vq_quantlist__44c0_s_p6_0[] = {
  136683. 1,
  136684. 0,
  136685. 2,
  136686. };
  136687. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136688. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136689. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136690. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136691. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136692. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136693. 10,
  136694. };
  136695. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136696. -5.5, 5.5,
  136697. };
  136698. static long _vq_quantmap__44c0_s_p6_0[] = {
  136699. 1, 0, 2,
  136700. };
  136701. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136702. _vq_quantthresh__44c0_s_p6_0,
  136703. _vq_quantmap__44c0_s_p6_0,
  136704. 3,
  136705. 3
  136706. };
  136707. static static_codebook _44c0_s_p6_0 = {
  136708. 4, 81,
  136709. _vq_lengthlist__44c0_s_p6_0,
  136710. 1, -529137664, 1618345984, 2, 0,
  136711. _vq_quantlist__44c0_s_p6_0,
  136712. NULL,
  136713. &_vq_auxt__44c0_s_p6_0,
  136714. NULL,
  136715. 0
  136716. };
  136717. static long _vq_quantlist__44c0_s_p6_1[] = {
  136718. 5,
  136719. 4,
  136720. 6,
  136721. 3,
  136722. 7,
  136723. 2,
  136724. 8,
  136725. 1,
  136726. 9,
  136727. 0,
  136728. 10,
  136729. };
  136730. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136731. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136732. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136733. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136734. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136735. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136736. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136737. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136738. 10,10,10, 8, 8, 8, 8, 8, 8,
  136739. };
  136740. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136741. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136742. 3.5, 4.5,
  136743. };
  136744. static long _vq_quantmap__44c0_s_p6_1[] = {
  136745. 9, 7, 5, 3, 1, 0, 2, 4,
  136746. 6, 8, 10,
  136747. };
  136748. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136749. _vq_quantthresh__44c0_s_p6_1,
  136750. _vq_quantmap__44c0_s_p6_1,
  136751. 11,
  136752. 11
  136753. };
  136754. static static_codebook _44c0_s_p6_1 = {
  136755. 2, 121,
  136756. _vq_lengthlist__44c0_s_p6_1,
  136757. 1, -531365888, 1611661312, 4, 0,
  136758. _vq_quantlist__44c0_s_p6_1,
  136759. NULL,
  136760. &_vq_auxt__44c0_s_p6_1,
  136761. NULL,
  136762. 0
  136763. };
  136764. static long _vq_quantlist__44c0_s_p7_0[] = {
  136765. 6,
  136766. 5,
  136767. 7,
  136768. 4,
  136769. 8,
  136770. 3,
  136771. 9,
  136772. 2,
  136773. 10,
  136774. 1,
  136775. 11,
  136776. 0,
  136777. 12,
  136778. };
  136779. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136780. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136781. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136782. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136783. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136784. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136785. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136786. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136787. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136788. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136789. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136790. 0,12,12,11,11,12,12,13,13,
  136791. };
  136792. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136793. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136794. 12.5, 17.5, 22.5, 27.5,
  136795. };
  136796. static long _vq_quantmap__44c0_s_p7_0[] = {
  136797. 11, 9, 7, 5, 3, 1, 0, 2,
  136798. 4, 6, 8, 10, 12,
  136799. };
  136800. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136801. _vq_quantthresh__44c0_s_p7_0,
  136802. _vq_quantmap__44c0_s_p7_0,
  136803. 13,
  136804. 13
  136805. };
  136806. static static_codebook _44c0_s_p7_0 = {
  136807. 2, 169,
  136808. _vq_lengthlist__44c0_s_p7_0,
  136809. 1, -526516224, 1616117760, 4, 0,
  136810. _vq_quantlist__44c0_s_p7_0,
  136811. NULL,
  136812. &_vq_auxt__44c0_s_p7_0,
  136813. NULL,
  136814. 0
  136815. };
  136816. static long _vq_quantlist__44c0_s_p7_1[] = {
  136817. 2,
  136818. 1,
  136819. 3,
  136820. 0,
  136821. 4,
  136822. };
  136823. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136824. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136825. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136826. };
  136827. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136828. -1.5, -0.5, 0.5, 1.5,
  136829. };
  136830. static long _vq_quantmap__44c0_s_p7_1[] = {
  136831. 3, 1, 0, 2, 4,
  136832. };
  136833. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136834. _vq_quantthresh__44c0_s_p7_1,
  136835. _vq_quantmap__44c0_s_p7_1,
  136836. 5,
  136837. 5
  136838. };
  136839. static static_codebook _44c0_s_p7_1 = {
  136840. 2, 25,
  136841. _vq_lengthlist__44c0_s_p7_1,
  136842. 1, -533725184, 1611661312, 3, 0,
  136843. _vq_quantlist__44c0_s_p7_1,
  136844. NULL,
  136845. &_vq_auxt__44c0_s_p7_1,
  136846. NULL,
  136847. 0
  136848. };
  136849. static long _vq_quantlist__44c0_s_p8_0[] = {
  136850. 2,
  136851. 1,
  136852. 3,
  136853. 0,
  136854. 4,
  136855. };
  136856. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136857. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136858. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136859. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136860. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136861. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136862. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136863. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136864. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136865. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136866. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136867. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136868. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136869. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136870. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136872. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136873. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136874. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136875. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136876. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136877. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136878. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136879. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136880. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136881. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136882. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136883. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136884. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136885. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136886. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136887. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136888. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136889. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136890. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136891. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136892. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136893. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136894. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136895. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136896. 11,
  136897. };
  136898. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136899. -331.5, -110.5, 110.5, 331.5,
  136900. };
  136901. static long _vq_quantmap__44c0_s_p8_0[] = {
  136902. 3, 1, 0, 2, 4,
  136903. };
  136904. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136905. _vq_quantthresh__44c0_s_p8_0,
  136906. _vq_quantmap__44c0_s_p8_0,
  136907. 5,
  136908. 5
  136909. };
  136910. static static_codebook _44c0_s_p8_0 = {
  136911. 4, 625,
  136912. _vq_lengthlist__44c0_s_p8_0,
  136913. 1, -518283264, 1627103232, 3, 0,
  136914. _vq_quantlist__44c0_s_p8_0,
  136915. NULL,
  136916. &_vq_auxt__44c0_s_p8_0,
  136917. NULL,
  136918. 0
  136919. };
  136920. static long _vq_quantlist__44c0_s_p8_1[] = {
  136921. 6,
  136922. 5,
  136923. 7,
  136924. 4,
  136925. 8,
  136926. 3,
  136927. 9,
  136928. 2,
  136929. 10,
  136930. 1,
  136931. 11,
  136932. 0,
  136933. 12,
  136934. };
  136935. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136936. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136937. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136938. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136939. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136940. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136941. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136942. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136943. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136944. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136945. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136946. 16,13,13,12,12,14,14,15,13,
  136947. };
  136948. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136949. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136950. 42.5, 59.5, 76.5, 93.5,
  136951. };
  136952. static long _vq_quantmap__44c0_s_p8_1[] = {
  136953. 11, 9, 7, 5, 3, 1, 0, 2,
  136954. 4, 6, 8, 10, 12,
  136955. };
  136956. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136957. _vq_quantthresh__44c0_s_p8_1,
  136958. _vq_quantmap__44c0_s_p8_1,
  136959. 13,
  136960. 13
  136961. };
  136962. static static_codebook _44c0_s_p8_1 = {
  136963. 2, 169,
  136964. _vq_lengthlist__44c0_s_p8_1,
  136965. 1, -522616832, 1620115456, 4, 0,
  136966. _vq_quantlist__44c0_s_p8_1,
  136967. NULL,
  136968. &_vq_auxt__44c0_s_p8_1,
  136969. NULL,
  136970. 0
  136971. };
  136972. static long _vq_quantlist__44c0_s_p8_2[] = {
  136973. 8,
  136974. 7,
  136975. 9,
  136976. 6,
  136977. 10,
  136978. 5,
  136979. 11,
  136980. 4,
  136981. 12,
  136982. 3,
  136983. 13,
  136984. 2,
  136985. 14,
  136986. 1,
  136987. 15,
  136988. 0,
  136989. 16,
  136990. };
  136991. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136992. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136993. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136994. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136995. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136996. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136997. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136998. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136999. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  137000. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  137001. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  137002. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  137003. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137004. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  137005. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  137006. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  137007. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  137008. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  137009. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  137010. 10,
  137011. };
  137012. static float _vq_quantthresh__44c0_s_p8_2[] = {
  137013. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137014. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137015. };
  137016. static long _vq_quantmap__44c0_s_p8_2[] = {
  137017. 15, 13, 11, 9, 7, 5, 3, 1,
  137018. 0, 2, 4, 6, 8, 10, 12, 14,
  137019. 16,
  137020. };
  137021. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  137022. _vq_quantthresh__44c0_s_p8_2,
  137023. _vq_quantmap__44c0_s_p8_2,
  137024. 17,
  137025. 17
  137026. };
  137027. static static_codebook _44c0_s_p8_2 = {
  137028. 2, 289,
  137029. _vq_lengthlist__44c0_s_p8_2,
  137030. 1, -529530880, 1611661312, 5, 0,
  137031. _vq_quantlist__44c0_s_p8_2,
  137032. NULL,
  137033. &_vq_auxt__44c0_s_p8_2,
  137034. NULL,
  137035. 0
  137036. };
  137037. static long _huff_lengthlist__44c0_s_short[] = {
  137038. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  137039. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  137040. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  137041. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  137042. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  137043. 12,
  137044. };
  137045. static static_codebook _huff_book__44c0_s_short = {
  137046. 2, 81,
  137047. _huff_lengthlist__44c0_s_short,
  137048. 0, 0, 0, 0, 0,
  137049. NULL,
  137050. NULL,
  137051. NULL,
  137052. NULL,
  137053. 0
  137054. };
  137055. static long _huff_lengthlist__44c0_sm_long[] = {
  137056. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  137057. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  137058. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  137059. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  137060. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  137061. 13,
  137062. };
  137063. static static_codebook _huff_book__44c0_sm_long = {
  137064. 2, 81,
  137065. _huff_lengthlist__44c0_sm_long,
  137066. 0, 0, 0, 0, 0,
  137067. NULL,
  137068. NULL,
  137069. NULL,
  137070. NULL,
  137071. 0
  137072. };
  137073. static long _vq_quantlist__44c0_sm_p1_0[] = {
  137074. 1,
  137075. 0,
  137076. 2,
  137077. };
  137078. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  137079. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137080. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137085. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137090. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  137125. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  137130. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  137135. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137171. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137176. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137181. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137489. 0,
  137490. };
  137491. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137492. -0.5, 0.5,
  137493. };
  137494. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137495. 1, 0, 2,
  137496. };
  137497. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137498. _vq_quantthresh__44c0_sm_p1_0,
  137499. _vq_quantmap__44c0_sm_p1_0,
  137500. 3,
  137501. 3
  137502. };
  137503. static static_codebook _44c0_sm_p1_0 = {
  137504. 8, 6561,
  137505. _vq_lengthlist__44c0_sm_p1_0,
  137506. 1, -535822336, 1611661312, 2, 0,
  137507. _vq_quantlist__44c0_sm_p1_0,
  137508. NULL,
  137509. &_vq_auxt__44c0_sm_p1_0,
  137510. NULL,
  137511. 0
  137512. };
  137513. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137514. 2,
  137515. 1,
  137516. 3,
  137517. 0,
  137518. 4,
  137519. };
  137520. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137521. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137524. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137527. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137560. 0,
  137561. };
  137562. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137563. -1.5, -0.5, 0.5, 1.5,
  137564. };
  137565. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137566. 3, 1, 0, 2, 4,
  137567. };
  137568. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137569. _vq_quantthresh__44c0_sm_p2_0,
  137570. _vq_quantmap__44c0_sm_p2_0,
  137571. 5,
  137572. 5
  137573. };
  137574. static static_codebook _44c0_sm_p2_0 = {
  137575. 4, 625,
  137576. _vq_lengthlist__44c0_sm_p2_0,
  137577. 1, -533725184, 1611661312, 3, 0,
  137578. _vq_quantlist__44c0_sm_p2_0,
  137579. NULL,
  137580. &_vq_auxt__44c0_sm_p2_0,
  137581. NULL,
  137582. 0
  137583. };
  137584. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137585. 4,
  137586. 3,
  137587. 5,
  137588. 2,
  137589. 6,
  137590. 1,
  137591. 7,
  137592. 0,
  137593. 8,
  137594. };
  137595. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137596. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137597. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137598. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137599. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137600. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137601. 0,
  137602. };
  137603. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137604. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137605. };
  137606. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137607. 7, 5, 3, 1, 0, 2, 4, 6,
  137608. 8,
  137609. };
  137610. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137611. _vq_quantthresh__44c0_sm_p3_0,
  137612. _vq_quantmap__44c0_sm_p3_0,
  137613. 9,
  137614. 9
  137615. };
  137616. static static_codebook _44c0_sm_p3_0 = {
  137617. 2, 81,
  137618. _vq_lengthlist__44c0_sm_p3_0,
  137619. 1, -531628032, 1611661312, 4, 0,
  137620. _vq_quantlist__44c0_sm_p3_0,
  137621. NULL,
  137622. &_vq_auxt__44c0_sm_p3_0,
  137623. NULL,
  137624. 0
  137625. };
  137626. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137627. 4,
  137628. 3,
  137629. 5,
  137630. 2,
  137631. 6,
  137632. 1,
  137633. 7,
  137634. 0,
  137635. 8,
  137636. };
  137637. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137638. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137639. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137640. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137641. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137642. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137643. 11,
  137644. };
  137645. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137646. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137647. };
  137648. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137649. 7, 5, 3, 1, 0, 2, 4, 6,
  137650. 8,
  137651. };
  137652. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137653. _vq_quantthresh__44c0_sm_p4_0,
  137654. _vq_quantmap__44c0_sm_p4_0,
  137655. 9,
  137656. 9
  137657. };
  137658. static static_codebook _44c0_sm_p4_0 = {
  137659. 2, 81,
  137660. _vq_lengthlist__44c0_sm_p4_0,
  137661. 1, -531628032, 1611661312, 4, 0,
  137662. _vq_quantlist__44c0_sm_p4_0,
  137663. NULL,
  137664. &_vq_auxt__44c0_sm_p4_0,
  137665. NULL,
  137666. 0
  137667. };
  137668. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137669. 8,
  137670. 7,
  137671. 9,
  137672. 6,
  137673. 10,
  137674. 5,
  137675. 11,
  137676. 4,
  137677. 12,
  137678. 3,
  137679. 13,
  137680. 2,
  137681. 14,
  137682. 1,
  137683. 15,
  137684. 0,
  137685. 16,
  137686. };
  137687. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137688. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137689. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137690. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137691. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137692. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137693. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137694. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137695. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137696. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137697. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137698. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137699. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137700. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137701. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137702. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137703. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137704. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137705. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137706. 14,
  137707. };
  137708. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137709. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137710. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137711. };
  137712. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137713. 15, 13, 11, 9, 7, 5, 3, 1,
  137714. 0, 2, 4, 6, 8, 10, 12, 14,
  137715. 16,
  137716. };
  137717. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137718. _vq_quantthresh__44c0_sm_p5_0,
  137719. _vq_quantmap__44c0_sm_p5_0,
  137720. 17,
  137721. 17
  137722. };
  137723. static static_codebook _44c0_sm_p5_0 = {
  137724. 2, 289,
  137725. _vq_lengthlist__44c0_sm_p5_0,
  137726. 1, -529530880, 1611661312, 5, 0,
  137727. _vq_quantlist__44c0_sm_p5_0,
  137728. NULL,
  137729. &_vq_auxt__44c0_sm_p5_0,
  137730. NULL,
  137731. 0
  137732. };
  137733. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137734. 1,
  137735. 0,
  137736. 2,
  137737. };
  137738. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137739. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137740. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137741. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137742. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137743. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137744. 11,
  137745. };
  137746. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137747. -5.5, 5.5,
  137748. };
  137749. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137750. 1, 0, 2,
  137751. };
  137752. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137753. _vq_quantthresh__44c0_sm_p6_0,
  137754. _vq_quantmap__44c0_sm_p6_0,
  137755. 3,
  137756. 3
  137757. };
  137758. static static_codebook _44c0_sm_p6_0 = {
  137759. 4, 81,
  137760. _vq_lengthlist__44c0_sm_p6_0,
  137761. 1, -529137664, 1618345984, 2, 0,
  137762. _vq_quantlist__44c0_sm_p6_0,
  137763. NULL,
  137764. &_vq_auxt__44c0_sm_p6_0,
  137765. NULL,
  137766. 0
  137767. };
  137768. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137769. 5,
  137770. 4,
  137771. 6,
  137772. 3,
  137773. 7,
  137774. 2,
  137775. 8,
  137776. 1,
  137777. 9,
  137778. 0,
  137779. 10,
  137780. };
  137781. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137782. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137783. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137784. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137785. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137786. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137787. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137788. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137789. 10,10,10, 8, 8, 8, 8, 8, 8,
  137790. };
  137791. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137792. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137793. 3.5, 4.5,
  137794. };
  137795. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137796. 9, 7, 5, 3, 1, 0, 2, 4,
  137797. 6, 8, 10,
  137798. };
  137799. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137800. _vq_quantthresh__44c0_sm_p6_1,
  137801. _vq_quantmap__44c0_sm_p6_1,
  137802. 11,
  137803. 11
  137804. };
  137805. static static_codebook _44c0_sm_p6_1 = {
  137806. 2, 121,
  137807. _vq_lengthlist__44c0_sm_p6_1,
  137808. 1, -531365888, 1611661312, 4, 0,
  137809. _vq_quantlist__44c0_sm_p6_1,
  137810. NULL,
  137811. &_vq_auxt__44c0_sm_p6_1,
  137812. NULL,
  137813. 0
  137814. };
  137815. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137816. 6,
  137817. 5,
  137818. 7,
  137819. 4,
  137820. 8,
  137821. 3,
  137822. 9,
  137823. 2,
  137824. 10,
  137825. 1,
  137826. 11,
  137827. 0,
  137828. 12,
  137829. };
  137830. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137831. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137832. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137833. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137834. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137835. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137836. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137837. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137838. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137839. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137840. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137841. 0,12,12,11,11,13,12,14,14,
  137842. };
  137843. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137844. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137845. 12.5, 17.5, 22.5, 27.5,
  137846. };
  137847. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137848. 11, 9, 7, 5, 3, 1, 0, 2,
  137849. 4, 6, 8, 10, 12,
  137850. };
  137851. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137852. _vq_quantthresh__44c0_sm_p7_0,
  137853. _vq_quantmap__44c0_sm_p7_0,
  137854. 13,
  137855. 13
  137856. };
  137857. static static_codebook _44c0_sm_p7_0 = {
  137858. 2, 169,
  137859. _vq_lengthlist__44c0_sm_p7_0,
  137860. 1, -526516224, 1616117760, 4, 0,
  137861. _vq_quantlist__44c0_sm_p7_0,
  137862. NULL,
  137863. &_vq_auxt__44c0_sm_p7_0,
  137864. NULL,
  137865. 0
  137866. };
  137867. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137868. 2,
  137869. 1,
  137870. 3,
  137871. 0,
  137872. 4,
  137873. };
  137874. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137875. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137876. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137877. };
  137878. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137879. -1.5, -0.5, 0.5, 1.5,
  137880. };
  137881. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137882. 3, 1, 0, 2, 4,
  137883. };
  137884. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137885. _vq_quantthresh__44c0_sm_p7_1,
  137886. _vq_quantmap__44c0_sm_p7_1,
  137887. 5,
  137888. 5
  137889. };
  137890. static static_codebook _44c0_sm_p7_1 = {
  137891. 2, 25,
  137892. _vq_lengthlist__44c0_sm_p7_1,
  137893. 1, -533725184, 1611661312, 3, 0,
  137894. _vq_quantlist__44c0_sm_p7_1,
  137895. NULL,
  137896. &_vq_auxt__44c0_sm_p7_1,
  137897. NULL,
  137898. 0
  137899. };
  137900. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137901. 4,
  137902. 3,
  137903. 5,
  137904. 2,
  137905. 6,
  137906. 1,
  137907. 7,
  137908. 0,
  137909. 8,
  137910. };
  137911. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137912. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137913. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137914. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137915. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137916. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137917. 12,
  137918. };
  137919. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137920. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137921. };
  137922. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137923. 7, 5, 3, 1, 0, 2, 4, 6,
  137924. 8,
  137925. };
  137926. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137927. _vq_quantthresh__44c0_sm_p8_0,
  137928. _vq_quantmap__44c0_sm_p8_0,
  137929. 9,
  137930. 9
  137931. };
  137932. static static_codebook _44c0_sm_p8_0 = {
  137933. 2, 81,
  137934. _vq_lengthlist__44c0_sm_p8_0,
  137935. 1, -516186112, 1627103232, 4, 0,
  137936. _vq_quantlist__44c0_sm_p8_0,
  137937. NULL,
  137938. &_vq_auxt__44c0_sm_p8_0,
  137939. NULL,
  137940. 0
  137941. };
  137942. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137943. 6,
  137944. 5,
  137945. 7,
  137946. 4,
  137947. 8,
  137948. 3,
  137949. 9,
  137950. 2,
  137951. 10,
  137952. 1,
  137953. 11,
  137954. 0,
  137955. 12,
  137956. };
  137957. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137958. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137959. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137960. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137961. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137962. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137963. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137964. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137965. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137966. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137967. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137968. 20,13,13,12,12,16,13,15,13,
  137969. };
  137970. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137971. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137972. 42.5, 59.5, 76.5, 93.5,
  137973. };
  137974. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137975. 11, 9, 7, 5, 3, 1, 0, 2,
  137976. 4, 6, 8, 10, 12,
  137977. };
  137978. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137979. _vq_quantthresh__44c0_sm_p8_1,
  137980. _vq_quantmap__44c0_sm_p8_1,
  137981. 13,
  137982. 13
  137983. };
  137984. static static_codebook _44c0_sm_p8_1 = {
  137985. 2, 169,
  137986. _vq_lengthlist__44c0_sm_p8_1,
  137987. 1, -522616832, 1620115456, 4, 0,
  137988. _vq_quantlist__44c0_sm_p8_1,
  137989. NULL,
  137990. &_vq_auxt__44c0_sm_p8_1,
  137991. NULL,
  137992. 0
  137993. };
  137994. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137995. 8,
  137996. 7,
  137997. 9,
  137998. 6,
  137999. 10,
  138000. 5,
  138001. 11,
  138002. 4,
  138003. 12,
  138004. 3,
  138005. 13,
  138006. 2,
  138007. 14,
  138008. 1,
  138009. 15,
  138010. 0,
  138011. 16,
  138012. };
  138013. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  138014. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138015. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138016. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138017. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138018. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138019. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138020. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138021. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  138022. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  138023. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  138024. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  138025. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  138026. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  138027. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  138028. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138029. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  138030. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138031. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  138032. 9,
  138033. };
  138034. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  138035. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138036. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138037. };
  138038. static long _vq_quantmap__44c0_sm_p8_2[] = {
  138039. 15, 13, 11, 9, 7, 5, 3, 1,
  138040. 0, 2, 4, 6, 8, 10, 12, 14,
  138041. 16,
  138042. };
  138043. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  138044. _vq_quantthresh__44c0_sm_p8_2,
  138045. _vq_quantmap__44c0_sm_p8_2,
  138046. 17,
  138047. 17
  138048. };
  138049. static static_codebook _44c0_sm_p8_2 = {
  138050. 2, 289,
  138051. _vq_lengthlist__44c0_sm_p8_2,
  138052. 1, -529530880, 1611661312, 5, 0,
  138053. _vq_quantlist__44c0_sm_p8_2,
  138054. NULL,
  138055. &_vq_auxt__44c0_sm_p8_2,
  138056. NULL,
  138057. 0
  138058. };
  138059. static long _huff_lengthlist__44c0_sm_short[] = {
  138060. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  138061. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  138062. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  138063. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  138064. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  138065. 12,
  138066. };
  138067. static static_codebook _huff_book__44c0_sm_short = {
  138068. 2, 81,
  138069. _huff_lengthlist__44c0_sm_short,
  138070. 0, 0, 0, 0, 0,
  138071. NULL,
  138072. NULL,
  138073. NULL,
  138074. NULL,
  138075. 0
  138076. };
  138077. static long _huff_lengthlist__44c1_s_long[] = {
  138078. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  138079. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  138080. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  138081. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  138082. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  138083. 11,
  138084. };
  138085. static static_codebook _huff_book__44c1_s_long = {
  138086. 2, 81,
  138087. _huff_lengthlist__44c1_s_long,
  138088. 0, 0, 0, 0, 0,
  138089. NULL,
  138090. NULL,
  138091. NULL,
  138092. NULL,
  138093. 0
  138094. };
  138095. static long _vq_quantlist__44c1_s_p1_0[] = {
  138096. 1,
  138097. 0,
  138098. 2,
  138099. };
  138100. static long _vq_lengthlist__44c1_s_p1_0[] = {
  138101. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  138102. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138107. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138112. 0, 0, 0, 0, 7, 8, 8, 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, 4, 7, 7, 0, 0, 0, 0,
  138147. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  138152. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  138157. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138193. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138198. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138203. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138511. 0,
  138512. };
  138513. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138514. -0.5, 0.5,
  138515. };
  138516. static long _vq_quantmap__44c1_s_p1_0[] = {
  138517. 1, 0, 2,
  138518. };
  138519. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138520. _vq_quantthresh__44c1_s_p1_0,
  138521. _vq_quantmap__44c1_s_p1_0,
  138522. 3,
  138523. 3
  138524. };
  138525. static static_codebook _44c1_s_p1_0 = {
  138526. 8, 6561,
  138527. _vq_lengthlist__44c1_s_p1_0,
  138528. 1, -535822336, 1611661312, 2, 0,
  138529. _vq_quantlist__44c1_s_p1_0,
  138530. NULL,
  138531. &_vq_auxt__44c1_s_p1_0,
  138532. NULL,
  138533. 0
  138534. };
  138535. static long _vq_quantlist__44c1_s_p2_0[] = {
  138536. 2,
  138537. 1,
  138538. 3,
  138539. 0,
  138540. 4,
  138541. };
  138542. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138543. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138546. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138549. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138582. 0,
  138583. };
  138584. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138585. -1.5, -0.5, 0.5, 1.5,
  138586. };
  138587. static long _vq_quantmap__44c1_s_p2_0[] = {
  138588. 3, 1, 0, 2, 4,
  138589. };
  138590. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138591. _vq_quantthresh__44c1_s_p2_0,
  138592. _vq_quantmap__44c1_s_p2_0,
  138593. 5,
  138594. 5
  138595. };
  138596. static static_codebook _44c1_s_p2_0 = {
  138597. 4, 625,
  138598. _vq_lengthlist__44c1_s_p2_0,
  138599. 1, -533725184, 1611661312, 3, 0,
  138600. _vq_quantlist__44c1_s_p2_0,
  138601. NULL,
  138602. &_vq_auxt__44c1_s_p2_0,
  138603. NULL,
  138604. 0
  138605. };
  138606. static long _vq_quantlist__44c1_s_p3_0[] = {
  138607. 4,
  138608. 3,
  138609. 5,
  138610. 2,
  138611. 6,
  138612. 1,
  138613. 7,
  138614. 0,
  138615. 8,
  138616. };
  138617. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138618. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138619. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138620. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138621. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138622. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138623. 0,
  138624. };
  138625. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138626. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138627. };
  138628. static long _vq_quantmap__44c1_s_p3_0[] = {
  138629. 7, 5, 3, 1, 0, 2, 4, 6,
  138630. 8,
  138631. };
  138632. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138633. _vq_quantthresh__44c1_s_p3_0,
  138634. _vq_quantmap__44c1_s_p3_0,
  138635. 9,
  138636. 9
  138637. };
  138638. static static_codebook _44c1_s_p3_0 = {
  138639. 2, 81,
  138640. _vq_lengthlist__44c1_s_p3_0,
  138641. 1, -531628032, 1611661312, 4, 0,
  138642. _vq_quantlist__44c1_s_p3_0,
  138643. NULL,
  138644. &_vq_auxt__44c1_s_p3_0,
  138645. NULL,
  138646. 0
  138647. };
  138648. static long _vq_quantlist__44c1_s_p4_0[] = {
  138649. 4,
  138650. 3,
  138651. 5,
  138652. 2,
  138653. 6,
  138654. 1,
  138655. 7,
  138656. 0,
  138657. 8,
  138658. };
  138659. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138660. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138661. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138662. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138663. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138664. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138665. 11,
  138666. };
  138667. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138668. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138669. };
  138670. static long _vq_quantmap__44c1_s_p4_0[] = {
  138671. 7, 5, 3, 1, 0, 2, 4, 6,
  138672. 8,
  138673. };
  138674. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138675. _vq_quantthresh__44c1_s_p4_0,
  138676. _vq_quantmap__44c1_s_p4_0,
  138677. 9,
  138678. 9
  138679. };
  138680. static static_codebook _44c1_s_p4_0 = {
  138681. 2, 81,
  138682. _vq_lengthlist__44c1_s_p4_0,
  138683. 1, -531628032, 1611661312, 4, 0,
  138684. _vq_quantlist__44c1_s_p4_0,
  138685. NULL,
  138686. &_vq_auxt__44c1_s_p4_0,
  138687. NULL,
  138688. 0
  138689. };
  138690. static long _vq_quantlist__44c1_s_p5_0[] = {
  138691. 8,
  138692. 7,
  138693. 9,
  138694. 6,
  138695. 10,
  138696. 5,
  138697. 11,
  138698. 4,
  138699. 12,
  138700. 3,
  138701. 13,
  138702. 2,
  138703. 14,
  138704. 1,
  138705. 15,
  138706. 0,
  138707. 16,
  138708. };
  138709. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138710. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138711. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138712. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138713. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138714. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138715. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138716. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138717. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138718. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138719. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138720. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138721. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138722. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138723. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138724. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138725. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138726. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138727. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138728. 14,
  138729. };
  138730. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138731. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138732. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138733. };
  138734. static long _vq_quantmap__44c1_s_p5_0[] = {
  138735. 15, 13, 11, 9, 7, 5, 3, 1,
  138736. 0, 2, 4, 6, 8, 10, 12, 14,
  138737. 16,
  138738. };
  138739. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138740. _vq_quantthresh__44c1_s_p5_0,
  138741. _vq_quantmap__44c1_s_p5_0,
  138742. 17,
  138743. 17
  138744. };
  138745. static static_codebook _44c1_s_p5_0 = {
  138746. 2, 289,
  138747. _vq_lengthlist__44c1_s_p5_0,
  138748. 1, -529530880, 1611661312, 5, 0,
  138749. _vq_quantlist__44c1_s_p5_0,
  138750. NULL,
  138751. &_vq_auxt__44c1_s_p5_0,
  138752. NULL,
  138753. 0
  138754. };
  138755. static long _vq_quantlist__44c1_s_p6_0[] = {
  138756. 1,
  138757. 0,
  138758. 2,
  138759. };
  138760. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138761. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138762. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138763. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138764. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138765. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138766. 11,
  138767. };
  138768. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138769. -5.5, 5.5,
  138770. };
  138771. static long _vq_quantmap__44c1_s_p6_0[] = {
  138772. 1, 0, 2,
  138773. };
  138774. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138775. _vq_quantthresh__44c1_s_p6_0,
  138776. _vq_quantmap__44c1_s_p6_0,
  138777. 3,
  138778. 3
  138779. };
  138780. static static_codebook _44c1_s_p6_0 = {
  138781. 4, 81,
  138782. _vq_lengthlist__44c1_s_p6_0,
  138783. 1, -529137664, 1618345984, 2, 0,
  138784. _vq_quantlist__44c1_s_p6_0,
  138785. NULL,
  138786. &_vq_auxt__44c1_s_p6_0,
  138787. NULL,
  138788. 0
  138789. };
  138790. static long _vq_quantlist__44c1_s_p6_1[] = {
  138791. 5,
  138792. 4,
  138793. 6,
  138794. 3,
  138795. 7,
  138796. 2,
  138797. 8,
  138798. 1,
  138799. 9,
  138800. 0,
  138801. 10,
  138802. };
  138803. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138804. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138805. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138806. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138807. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138808. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138809. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138810. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138811. 10,10,10, 8, 8, 8, 8, 8, 8,
  138812. };
  138813. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138814. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138815. 3.5, 4.5,
  138816. };
  138817. static long _vq_quantmap__44c1_s_p6_1[] = {
  138818. 9, 7, 5, 3, 1, 0, 2, 4,
  138819. 6, 8, 10,
  138820. };
  138821. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138822. _vq_quantthresh__44c1_s_p6_1,
  138823. _vq_quantmap__44c1_s_p6_1,
  138824. 11,
  138825. 11
  138826. };
  138827. static static_codebook _44c1_s_p6_1 = {
  138828. 2, 121,
  138829. _vq_lengthlist__44c1_s_p6_1,
  138830. 1, -531365888, 1611661312, 4, 0,
  138831. _vq_quantlist__44c1_s_p6_1,
  138832. NULL,
  138833. &_vq_auxt__44c1_s_p6_1,
  138834. NULL,
  138835. 0
  138836. };
  138837. static long _vq_quantlist__44c1_s_p7_0[] = {
  138838. 6,
  138839. 5,
  138840. 7,
  138841. 4,
  138842. 8,
  138843. 3,
  138844. 9,
  138845. 2,
  138846. 10,
  138847. 1,
  138848. 11,
  138849. 0,
  138850. 12,
  138851. };
  138852. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138853. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138854. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138855. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138856. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138857. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138858. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138859. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138860. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138861. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138862. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138863. 0,12,11,11,11,13,10,14,13,
  138864. };
  138865. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138866. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138867. 12.5, 17.5, 22.5, 27.5,
  138868. };
  138869. static long _vq_quantmap__44c1_s_p7_0[] = {
  138870. 11, 9, 7, 5, 3, 1, 0, 2,
  138871. 4, 6, 8, 10, 12,
  138872. };
  138873. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138874. _vq_quantthresh__44c1_s_p7_0,
  138875. _vq_quantmap__44c1_s_p7_0,
  138876. 13,
  138877. 13
  138878. };
  138879. static static_codebook _44c1_s_p7_0 = {
  138880. 2, 169,
  138881. _vq_lengthlist__44c1_s_p7_0,
  138882. 1, -526516224, 1616117760, 4, 0,
  138883. _vq_quantlist__44c1_s_p7_0,
  138884. NULL,
  138885. &_vq_auxt__44c1_s_p7_0,
  138886. NULL,
  138887. 0
  138888. };
  138889. static long _vq_quantlist__44c1_s_p7_1[] = {
  138890. 2,
  138891. 1,
  138892. 3,
  138893. 0,
  138894. 4,
  138895. };
  138896. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138897. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138898. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138899. };
  138900. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138901. -1.5, -0.5, 0.5, 1.5,
  138902. };
  138903. static long _vq_quantmap__44c1_s_p7_1[] = {
  138904. 3, 1, 0, 2, 4,
  138905. };
  138906. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138907. _vq_quantthresh__44c1_s_p7_1,
  138908. _vq_quantmap__44c1_s_p7_1,
  138909. 5,
  138910. 5
  138911. };
  138912. static static_codebook _44c1_s_p7_1 = {
  138913. 2, 25,
  138914. _vq_lengthlist__44c1_s_p7_1,
  138915. 1, -533725184, 1611661312, 3, 0,
  138916. _vq_quantlist__44c1_s_p7_1,
  138917. NULL,
  138918. &_vq_auxt__44c1_s_p7_1,
  138919. NULL,
  138920. 0
  138921. };
  138922. static long _vq_quantlist__44c1_s_p8_0[] = {
  138923. 6,
  138924. 5,
  138925. 7,
  138926. 4,
  138927. 8,
  138928. 3,
  138929. 9,
  138930. 2,
  138931. 10,
  138932. 1,
  138933. 11,
  138934. 0,
  138935. 12,
  138936. };
  138937. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138938. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138939. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138940. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138941. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138942. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138943. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138944. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138945. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138946. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138947. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138948. 10,10,10,10,10,10,10,10,10,
  138949. };
  138950. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138951. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138952. 552.5, 773.5, 994.5, 1215.5,
  138953. };
  138954. static long _vq_quantmap__44c1_s_p8_0[] = {
  138955. 11, 9, 7, 5, 3, 1, 0, 2,
  138956. 4, 6, 8, 10, 12,
  138957. };
  138958. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138959. _vq_quantthresh__44c1_s_p8_0,
  138960. _vq_quantmap__44c1_s_p8_0,
  138961. 13,
  138962. 13
  138963. };
  138964. static static_codebook _44c1_s_p8_0 = {
  138965. 2, 169,
  138966. _vq_lengthlist__44c1_s_p8_0,
  138967. 1, -514541568, 1627103232, 4, 0,
  138968. _vq_quantlist__44c1_s_p8_0,
  138969. NULL,
  138970. &_vq_auxt__44c1_s_p8_0,
  138971. NULL,
  138972. 0
  138973. };
  138974. static long _vq_quantlist__44c1_s_p8_1[] = {
  138975. 6,
  138976. 5,
  138977. 7,
  138978. 4,
  138979. 8,
  138980. 3,
  138981. 9,
  138982. 2,
  138983. 10,
  138984. 1,
  138985. 11,
  138986. 0,
  138987. 12,
  138988. };
  138989. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138990. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138991. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138992. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138993. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138994. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138995. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138996. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138997. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138998. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138999. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  139000. 16,13,12,12,11,14,12,15,13,
  139001. };
  139002. static float _vq_quantthresh__44c1_s_p8_1[] = {
  139003. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139004. 42.5, 59.5, 76.5, 93.5,
  139005. };
  139006. static long _vq_quantmap__44c1_s_p8_1[] = {
  139007. 11, 9, 7, 5, 3, 1, 0, 2,
  139008. 4, 6, 8, 10, 12,
  139009. };
  139010. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  139011. _vq_quantthresh__44c1_s_p8_1,
  139012. _vq_quantmap__44c1_s_p8_1,
  139013. 13,
  139014. 13
  139015. };
  139016. static static_codebook _44c1_s_p8_1 = {
  139017. 2, 169,
  139018. _vq_lengthlist__44c1_s_p8_1,
  139019. 1, -522616832, 1620115456, 4, 0,
  139020. _vq_quantlist__44c1_s_p8_1,
  139021. NULL,
  139022. &_vq_auxt__44c1_s_p8_1,
  139023. NULL,
  139024. 0
  139025. };
  139026. static long _vq_quantlist__44c1_s_p8_2[] = {
  139027. 8,
  139028. 7,
  139029. 9,
  139030. 6,
  139031. 10,
  139032. 5,
  139033. 11,
  139034. 4,
  139035. 12,
  139036. 3,
  139037. 13,
  139038. 2,
  139039. 14,
  139040. 1,
  139041. 15,
  139042. 0,
  139043. 16,
  139044. };
  139045. static long _vq_lengthlist__44c1_s_p8_2[] = {
  139046. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139047. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139048. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  139049. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139050. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  139051. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139052. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139053. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  139054. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  139055. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139056. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  139057. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  139058. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  139059. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  139060. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139061. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  139062. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139063. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  139064. 9,
  139065. };
  139066. static float _vq_quantthresh__44c1_s_p8_2[] = {
  139067. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139068. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139069. };
  139070. static long _vq_quantmap__44c1_s_p8_2[] = {
  139071. 15, 13, 11, 9, 7, 5, 3, 1,
  139072. 0, 2, 4, 6, 8, 10, 12, 14,
  139073. 16,
  139074. };
  139075. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  139076. _vq_quantthresh__44c1_s_p8_2,
  139077. _vq_quantmap__44c1_s_p8_2,
  139078. 17,
  139079. 17
  139080. };
  139081. static static_codebook _44c1_s_p8_2 = {
  139082. 2, 289,
  139083. _vq_lengthlist__44c1_s_p8_2,
  139084. 1, -529530880, 1611661312, 5, 0,
  139085. _vq_quantlist__44c1_s_p8_2,
  139086. NULL,
  139087. &_vq_auxt__44c1_s_p8_2,
  139088. NULL,
  139089. 0
  139090. };
  139091. static long _huff_lengthlist__44c1_s_short[] = {
  139092. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  139093. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  139094. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  139095. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  139096. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  139097. 11,
  139098. };
  139099. static static_codebook _huff_book__44c1_s_short = {
  139100. 2, 81,
  139101. _huff_lengthlist__44c1_s_short,
  139102. 0, 0, 0, 0, 0,
  139103. NULL,
  139104. NULL,
  139105. NULL,
  139106. NULL,
  139107. 0
  139108. };
  139109. static long _huff_lengthlist__44c1_sm_long[] = {
  139110. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  139111. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  139112. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  139113. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  139114. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  139115. 11,
  139116. };
  139117. static static_codebook _huff_book__44c1_sm_long = {
  139118. 2, 81,
  139119. _huff_lengthlist__44c1_sm_long,
  139120. 0, 0, 0, 0, 0,
  139121. NULL,
  139122. NULL,
  139123. NULL,
  139124. NULL,
  139125. 0
  139126. };
  139127. static long _vq_quantlist__44c1_sm_p1_0[] = {
  139128. 1,
  139129. 0,
  139130. 2,
  139131. };
  139132. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  139133. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139134. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139139. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  139144. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  139179. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  139184. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  139189. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139225. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139230. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139235. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139543. 0,
  139544. };
  139545. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139546. -0.5, 0.5,
  139547. };
  139548. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139549. 1, 0, 2,
  139550. };
  139551. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139552. _vq_quantthresh__44c1_sm_p1_0,
  139553. _vq_quantmap__44c1_sm_p1_0,
  139554. 3,
  139555. 3
  139556. };
  139557. static static_codebook _44c1_sm_p1_0 = {
  139558. 8, 6561,
  139559. _vq_lengthlist__44c1_sm_p1_0,
  139560. 1, -535822336, 1611661312, 2, 0,
  139561. _vq_quantlist__44c1_sm_p1_0,
  139562. NULL,
  139563. &_vq_auxt__44c1_sm_p1_0,
  139564. NULL,
  139565. 0
  139566. };
  139567. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139568. 2,
  139569. 1,
  139570. 3,
  139571. 0,
  139572. 4,
  139573. };
  139574. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139575. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139578. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139581. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139614. 0,
  139615. };
  139616. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139617. -1.5, -0.5, 0.5, 1.5,
  139618. };
  139619. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139620. 3, 1, 0, 2, 4,
  139621. };
  139622. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139623. _vq_quantthresh__44c1_sm_p2_0,
  139624. _vq_quantmap__44c1_sm_p2_0,
  139625. 5,
  139626. 5
  139627. };
  139628. static static_codebook _44c1_sm_p2_0 = {
  139629. 4, 625,
  139630. _vq_lengthlist__44c1_sm_p2_0,
  139631. 1, -533725184, 1611661312, 3, 0,
  139632. _vq_quantlist__44c1_sm_p2_0,
  139633. NULL,
  139634. &_vq_auxt__44c1_sm_p2_0,
  139635. NULL,
  139636. 0
  139637. };
  139638. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139639. 4,
  139640. 3,
  139641. 5,
  139642. 2,
  139643. 6,
  139644. 1,
  139645. 7,
  139646. 0,
  139647. 8,
  139648. };
  139649. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139650. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139651. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139652. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139653. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139654. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139655. 0,
  139656. };
  139657. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139658. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139659. };
  139660. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139661. 7, 5, 3, 1, 0, 2, 4, 6,
  139662. 8,
  139663. };
  139664. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139665. _vq_quantthresh__44c1_sm_p3_0,
  139666. _vq_quantmap__44c1_sm_p3_0,
  139667. 9,
  139668. 9
  139669. };
  139670. static static_codebook _44c1_sm_p3_0 = {
  139671. 2, 81,
  139672. _vq_lengthlist__44c1_sm_p3_0,
  139673. 1, -531628032, 1611661312, 4, 0,
  139674. _vq_quantlist__44c1_sm_p3_0,
  139675. NULL,
  139676. &_vq_auxt__44c1_sm_p3_0,
  139677. NULL,
  139678. 0
  139679. };
  139680. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139681. 4,
  139682. 3,
  139683. 5,
  139684. 2,
  139685. 6,
  139686. 1,
  139687. 7,
  139688. 0,
  139689. 8,
  139690. };
  139691. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139692. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139693. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139694. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139695. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139696. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139697. 11,
  139698. };
  139699. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139700. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139701. };
  139702. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139703. 7, 5, 3, 1, 0, 2, 4, 6,
  139704. 8,
  139705. };
  139706. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139707. _vq_quantthresh__44c1_sm_p4_0,
  139708. _vq_quantmap__44c1_sm_p4_0,
  139709. 9,
  139710. 9
  139711. };
  139712. static static_codebook _44c1_sm_p4_0 = {
  139713. 2, 81,
  139714. _vq_lengthlist__44c1_sm_p4_0,
  139715. 1, -531628032, 1611661312, 4, 0,
  139716. _vq_quantlist__44c1_sm_p4_0,
  139717. NULL,
  139718. &_vq_auxt__44c1_sm_p4_0,
  139719. NULL,
  139720. 0
  139721. };
  139722. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139723. 8,
  139724. 7,
  139725. 9,
  139726. 6,
  139727. 10,
  139728. 5,
  139729. 11,
  139730. 4,
  139731. 12,
  139732. 3,
  139733. 13,
  139734. 2,
  139735. 14,
  139736. 1,
  139737. 15,
  139738. 0,
  139739. 16,
  139740. };
  139741. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139742. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139743. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139744. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139745. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139746. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139747. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139748. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139749. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139750. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139751. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139752. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139753. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139754. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139755. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139756. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139757. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139758. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139759. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139760. 14,
  139761. };
  139762. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139763. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139764. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139765. };
  139766. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139767. 15, 13, 11, 9, 7, 5, 3, 1,
  139768. 0, 2, 4, 6, 8, 10, 12, 14,
  139769. 16,
  139770. };
  139771. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139772. _vq_quantthresh__44c1_sm_p5_0,
  139773. _vq_quantmap__44c1_sm_p5_0,
  139774. 17,
  139775. 17
  139776. };
  139777. static static_codebook _44c1_sm_p5_0 = {
  139778. 2, 289,
  139779. _vq_lengthlist__44c1_sm_p5_0,
  139780. 1, -529530880, 1611661312, 5, 0,
  139781. _vq_quantlist__44c1_sm_p5_0,
  139782. NULL,
  139783. &_vq_auxt__44c1_sm_p5_0,
  139784. NULL,
  139785. 0
  139786. };
  139787. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139788. 1,
  139789. 0,
  139790. 2,
  139791. };
  139792. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139793. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139794. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139795. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139796. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139797. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139798. 11,
  139799. };
  139800. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139801. -5.5, 5.5,
  139802. };
  139803. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139804. 1, 0, 2,
  139805. };
  139806. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139807. _vq_quantthresh__44c1_sm_p6_0,
  139808. _vq_quantmap__44c1_sm_p6_0,
  139809. 3,
  139810. 3
  139811. };
  139812. static static_codebook _44c1_sm_p6_0 = {
  139813. 4, 81,
  139814. _vq_lengthlist__44c1_sm_p6_0,
  139815. 1, -529137664, 1618345984, 2, 0,
  139816. _vq_quantlist__44c1_sm_p6_0,
  139817. NULL,
  139818. &_vq_auxt__44c1_sm_p6_0,
  139819. NULL,
  139820. 0
  139821. };
  139822. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139823. 5,
  139824. 4,
  139825. 6,
  139826. 3,
  139827. 7,
  139828. 2,
  139829. 8,
  139830. 1,
  139831. 9,
  139832. 0,
  139833. 10,
  139834. };
  139835. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139836. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139837. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139838. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139839. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139840. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139841. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139842. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139843. 10,10,10, 8, 8, 8, 8, 8, 8,
  139844. };
  139845. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139846. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139847. 3.5, 4.5,
  139848. };
  139849. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139850. 9, 7, 5, 3, 1, 0, 2, 4,
  139851. 6, 8, 10,
  139852. };
  139853. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139854. _vq_quantthresh__44c1_sm_p6_1,
  139855. _vq_quantmap__44c1_sm_p6_1,
  139856. 11,
  139857. 11
  139858. };
  139859. static static_codebook _44c1_sm_p6_1 = {
  139860. 2, 121,
  139861. _vq_lengthlist__44c1_sm_p6_1,
  139862. 1, -531365888, 1611661312, 4, 0,
  139863. _vq_quantlist__44c1_sm_p6_1,
  139864. NULL,
  139865. &_vq_auxt__44c1_sm_p6_1,
  139866. NULL,
  139867. 0
  139868. };
  139869. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139870. 6,
  139871. 5,
  139872. 7,
  139873. 4,
  139874. 8,
  139875. 3,
  139876. 9,
  139877. 2,
  139878. 10,
  139879. 1,
  139880. 11,
  139881. 0,
  139882. 12,
  139883. };
  139884. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139885. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139886. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139887. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139888. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139889. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139890. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139891. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139892. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139893. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139894. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139895. 0,12,12,11,11,13,12,14,13,
  139896. };
  139897. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139898. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139899. 12.5, 17.5, 22.5, 27.5,
  139900. };
  139901. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139902. 11, 9, 7, 5, 3, 1, 0, 2,
  139903. 4, 6, 8, 10, 12,
  139904. };
  139905. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139906. _vq_quantthresh__44c1_sm_p7_0,
  139907. _vq_quantmap__44c1_sm_p7_0,
  139908. 13,
  139909. 13
  139910. };
  139911. static static_codebook _44c1_sm_p7_0 = {
  139912. 2, 169,
  139913. _vq_lengthlist__44c1_sm_p7_0,
  139914. 1, -526516224, 1616117760, 4, 0,
  139915. _vq_quantlist__44c1_sm_p7_0,
  139916. NULL,
  139917. &_vq_auxt__44c1_sm_p7_0,
  139918. NULL,
  139919. 0
  139920. };
  139921. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139922. 2,
  139923. 1,
  139924. 3,
  139925. 0,
  139926. 4,
  139927. };
  139928. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139929. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139930. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139931. };
  139932. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139933. -1.5, -0.5, 0.5, 1.5,
  139934. };
  139935. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139936. 3, 1, 0, 2, 4,
  139937. };
  139938. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139939. _vq_quantthresh__44c1_sm_p7_1,
  139940. _vq_quantmap__44c1_sm_p7_1,
  139941. 5,
  139942. 5
  139943. };
  139944. static static_codebook _44c1_sm_p7_1 = {
  139945. 2, 25,
  139946. _vq_lengthlist__44c1_sm_p7_1,
  139947. 1, -533725184, 1611661312, 3, 0,
  139948. _vq_quantlist__44c1_sm_p7_1,
  139949. NULL,
  139950. &_vq_auxt__44c1_sm_p7_1,
  139951. NULL,
  139952. 0
  139953. };
  139954. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139955. 6,
  139956. 5,
  139957. 7,
  139958. 4,
  139959. 8,
  139960. 3,
  139961. 9,
  139962. 2,
  139963. 10,
  139964. 1,
  139965. 11,
  139966. 0,
  139967. 12,
  139968. };
  139969. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139970. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139971. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139972. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139973. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139974. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139975. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139976. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139977. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139978. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139979. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139980. 13,13,13,13,13,13,13,13,13,
  139981. };
  139982. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139983. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139984. 552.5, 773.5, 994.5, 1215.5,
  139985. };
  139986. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139987. 11, 9, 7, 5, 3, 1, 0, 2,
  139988. 4, 6, 8, 10, 12,
  139989. };
  139990. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139991. _vq_quantthresh__44c1_sm_p8_0,
  139992. _vq_quantmap__44c1_sm_p8_0,
  139993. 13,
  139994. 13
  139995. };
  139996. static static_codebook _44c1_sm_p8_0 = {
  139997. 2, 169,
  139998. _vq_lengthlist__44c1_sm_p8_0,
  139999. 1, -514541568, 1627103232, 4, 0,
  140000. _vq_quantlist__44c1_sm_p8_0,
  140001. NULL,
  140002. &_vq_auxt__44c1_sm_p8_0,
  140003. NULL,
  140004. 0
  140005. };
  140006. static long _vq_quantlist__44c1_sm_p8_1[] = {
  140007. 6,
  140008. 5,
  140009. 7,
  140010. 4,
  140011. 8,
  140012. 3,
  140013. 9,
  140014. 2,
  140015. 10,
  140016. 1,
  140017. 11,
  140018. 0,
  140019. 12,
  140020. };
  140021. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  140022. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  140023. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  140024. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  140025. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  140026. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  140027. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  140028. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  140029. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  140030. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  140031. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  140032. 20,13,12,12,12,14,12,14,13,
  140033. };
  140034. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  140035. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140036. 42.5, 59.5, 76.5, 93.5,
  140037. };
  140038. static long _vq_quantmap__44c1_sm_p8_1[] = {
  140039. 11, 9, 7, 5, 3, 1, 0, 2,
  140040. 4, 6, 8, 10, 12,
  140041. };
  140042. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  140043. _vq_quantthresh__44c1_sm_p8_1,
  140044. _vq_quantmap__44c1_sm_p8_1,
  140045. 13,
  140046. 13
  140047. };
  140048. static static_codebook _44c1_sm_p8_1 = {
  140049. 2, 169,
  140050. _vq_lengthlist__44c1_sm_p8_1,
  140051. 1, -522616832, 1620115456, 4, 0,
  140052. _vq_quantlist__44c1_sm_p8_1,
  140053. NULL,
  140054. &_vq_auxt__44c1_sm_p8_1,
  140055. NULL,
  140056. 0
  140057. };
  140058. static long _vq_quantlist__44c1_sm_p8_2[] = {
  140059. 8,
  140060. 7,
  140061. 9,
  140062. 6,
  140063. 10,
  140064. 5,
  140065. 11,
  140066. 4,
  140067. 12,
  140068. 3,
  140069. 13,
  140070. 2,
  140071. 14,
  140072. 1,
  140073. 15,
  140074. 0,
  140075. 16,
  140076. };
  140077. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  140078. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  140079. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140080. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  140081. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  140082. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140083. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  140084. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  140085. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  140086. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  140087. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  140088. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  140089. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  140090. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  140091. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  140092. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  140093. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  140094. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  140095. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  140096. 9,
  140097. };
  140098. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  140099. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140100. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140101. };
  140102. static long _vq_quantmap__44c1_sm_p8_2[] = {
  140103. 15, 13, 11, 9, 7, 5, 3, 1,
  140104. 0, 2, 4, 6, 8, 10, 12, 14,
  140105. 16,
  140106. };
  140107. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  140108. _vq_quantthresh__44c1_sm_p8_2,
  140109. _vq_quantmap__44c1_sm_p8_2,
  140110. 17,
  140111. 17
  140112. };
  140113. static static_codebook _44c1_sm_p8_2 = {
  140114. 2, 289,
  140115. _vq_lengthlist__44c1_sm_p8_2,
  140116. 1, -529530880, 1611661312, 5, 0,
  140117. _vq_quantlist__44c1_sm_p8_2,
  140118. NULL,
  140119. &_vq_auxt__44c1_sm_p8_2,
  140120. NULL,
  140121. 0
  140122. };
  140123. static long _huff_lengthlist__44c1_sm_short[] = {
  140124. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  140125. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  140126. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  140127. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  140128. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  140129. 11,
  140130. };
  140131. static static_codebook _huff_book__44c1_sm_short = {
  140132. 2, 81,
  140133. _huff_lengthlist__44c1_sm_short,
  140134. 0, 0, 0, 0, 0,
  140135. NULL,
  140136. NULL,
  140137. NULL,
  140138. NULL,
  140139. 0
  140140. };
  140141. static long _huff_lengthlist__44cn1_s_long[] = {
  140142. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  140143. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  140144. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  140145. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  140146. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  140147. 20,
  140148. };
  140149. static static_codebook _huff_book__44cn1_s_long = {
  140150. 2, 81,
  140151. _huff_lengthlist__44cn1_s_long,
  140152. 0, 0, 0, 0, 0,
  140153. NULL,
  140154. NULL,
  140155. NULL,
  140156. NULL,
  140157. 0
  140158. };
  140159. static long _vq_quantlist__44cn1_s_p1_0[] = {
  140160. 1,
  140161. 0,
  140162. 2,
  140163. };
  140164. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  140165. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140166. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140171. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  140176. 0, 0, 0, 0, 8,10, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  140211. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  140216. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  140221. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140257. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140262. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140267. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140575. 0,
  140576. };
  140577. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140578. -0.5, 0.5,
  140579. };
  140580. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140581. 1, 0, 2,
  140582. };
  140583. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140584. _vq_quantthresh__44cn1_s_p1_0,
  140585. _vq_quantmap__44cn1_s_p1_0,
  140586. 3,
  140587. 3
  140588. };
  140589. static static_codebook _44cn1_s_p1_0 = {
  140590. 8, 6561,
  140591. _vq_lengthlist__44cn1_s_p1_0,
  140592. 1, -535822336, 1611661312, 2, 0,
  140593. _vq_quantlist__44cn1_s_p1_0,
  140594. NULL,
  140595. &_vq_auxt__44cn1_s_p1_0,
  140596. NULL,
  140597. 0
  140598. };
  140599. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140600. 2,
  140601. 1,
  140602. 3,
  140603. 0,
  140604. 4,
  140605. };
  140606. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140607. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140610. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140613. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140646. 0,
  140647. };
  140648. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140649. -1.5, -0.5, 0.5, 1.5,
  140650. };
  140651. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140652. 3, 1, 0, 2, 4,
  140653. };
  140654. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140655. _vq_quantthresh__44cn1_s_p2_0,
  140656. _vq_quantmap__44cn1_s_p2_0,
  140657. 5,
  140658. 5
  140659. };
  140660. static static_codebook _44cn1_s_p2_0 = {
  140661. 4, 625,
  140662. _vq_lengthlist__44cn1_s_p2_0,
  140663. 1, -533725184, 1611661312, 3, 0,
  140664. _vq_quantlist__44cn1_s_p2_0,
  140665. NULL,
  140666. &_vq_auxt__44cn1_s_p2_0,
  140667. NULL,
  140668. 0
  140669. };
  140670. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140671. 4,
  140672. 3,
  140673. 5,
  140674. 2,
  140675. 6,
  140676. 1,
  140677. 7,
  140678. 0,
  140679. 8,
  140680. };
  140681. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140682. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140683. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140684. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140685. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140686. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140687. 0,
  140688. };
  140689. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140690. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140691. };
  140692. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140693. 7, 5, 3, 1, 0, 2, 4, 6,
  140694. 8,
  140695. };
  140696. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140697. _vq_quantthresh__44cn1_s_p3_0,
  140698. _vq_quantmap__44cn1_s_p3_0,
  140699. 9,
  140700. 9
  140701. };
  140702. static static_codebook _44cn1_s_p3_0 = {
  140703. 2, 81,
  140704. _vq_lengthlist__44cn1_s_p3_0,
  140705. 1, -531628032, 1611661312, 4, 0,
  140706. _vq_quantlist__44cn1_s_p3_0,
  140707. NULL,
  140708. &_vq_auxt__44cn1_s_p3_0,
  140709. NULL,
  140710. 0
  140711. };
  140712. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140713. 4,
  140714. 3,
  140715. 5,
  140716. 2,
  140717. 6,
  140718. 1,
  140719. 7,
  140720. 0,
  140721. 8,
  140722. };
  140723. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140724. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140725. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140726. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140727. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140728. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140729. 11,
  140730. };
  140731. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140732. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140733. };
  140734. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140735. 7, 5, 3, 1, 0, 2, 4, 6,
  140736. 8,
  140737. };
  140738. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140739. _vq_quantthresh__44cn1_s_p4_0,
  140740. _vq_quantmap__44cn1_s_p4_0,
  140741. 9,
  140742. 9
  140743. };
  140744. static static_codebook _44cn1_s_p4_0 = {
  140745. 2, 81,
  140746. _vq_lengthlist__44cn1_s_p4_0,
  140747. 1, -531628032, 1611661312, 4, 0,
  140748. _vq_quantlist__44cn1_s_p4_0,
  140749. NULL,
  140750. &_vq_auxt__44cn1_s_p4_0,
  140751. NULL,
  140752. 0
  140753. };
  140754. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140755. 8,
  140756. 7,
  140757. 9,
  140758. 6,
  140759. 10,
  140760. 5,
  140761. 11,
  140762. 4,
  140763. 12,
  140764. 3,
  140765. 13,
  140766. 2,
  140767. 14,
  140768. 1,
  140769. 15,
  140770. 0,
  140771. 16,
  140772. };
  140773. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140774. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140775. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140776. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140777. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140778. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140779. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140780. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140781. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140782. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140783. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140784. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140785. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140786. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140787. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140788. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140789. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140790. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140791. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140792. 14,
  140793. };
  140794. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140795. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140796. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140797. };
  140798. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140799. 15, 13, 11, 9, 7, 5, 3, 1,
  140800. 0, 2, 4, 6, 8, 10, 12, 14,
  140801. 16,
  140802. };
  140803. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140804. _vq_quantthresh__44cn1_s_p5_0,
  140805. _vq_quantmap__44cn1_s_p5_0,
  140806. 17,
  140807. 17
  140808. };
  140809. static static_codebook _44cn1_s_p5_0 = {
  140810. 2, 289,
  140811. _vq_lengthlist__44cn1_s_p5_0,
  140812. 1, -529530880, 1611661312, 5, 0,
  140813. _vq_quantlist__44cn1_s_p5_0,
  140814. NULL,
  140815. &_vq_auxt__44cn1_s_p5_0,
  140816. NULL,
  140817. 0
  140818. };
  140819. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140820. 1,
  140821. 0,
  140822. 2,
  140823. };
  140824. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140825. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140826. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140827. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140828. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140829. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140830. 10,
  140831. };
  140832. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140833. -5.5, 5.5,
  140834. };
  140835. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140836. 1, 0, 2,
  140837. };
  140838. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140839. _vq_quantthresh__44cn1_s_p6_0,
  140840. _vq_quantmap__44cn1_s_p6_0,
  140841. 3,
  140842. 3
  140843. };
  140844. static static_codebook _44cn1_s_p6_0 = {
  140845. 4, 81,
  140846. _vq_lengthlist__44cn1_s_p6_0,
  140847. 1, -529137664, 1618345984, 2, 0,
  140848. _vq_quantlist__44cn1_s_p6_0,
  140849. NULL,
  140850. &_vq_auxt__44cn1_s_p6_0,
  140851. NULL,
  140852. 0
  140853. };
  140854. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140855. 5,
  140856. 4,
  140857. 6,
  140858. 3,
  140859. 7,
  140860. 2,
  140861. 8,
  140862. 1,
  140863. 9,
  140864. 0,
  140865. 10,
  140866. };
  140867. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140868. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140869. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140870. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140871. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140872. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140873. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140874. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140875. 10,10,10, 9, 9, 9, 9, 9, 9,
  140876. };
  140877. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140878. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140879. 3.5, 4.5,
  140880. };
  140881. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140882. 9, 7, 5, 3, 1, 0, 2, 4,
  140883. 6, 8, 10,
  140884. };
  140885. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140886. _vq_quantthresh__44cn1_s_p6_1,
  140887. _vq_quantmap__44cn1_s_p6_1,
  140888. 11,
  140889. 11
  140890. };
  140891. static static_codebook _44cn1_s_p6_1 = {
  140892. 2, 121,
  140893. _vq_lengthlist__44cn1_s_p6_1,
  140894. 1, -531365888, 1611661312, 4, 0,
  140895. _vq_quantlist__44cn1_s_p6_1,
  140896. NULL,
  140897. &_vq_auxt__44cn1_s_p6_1,
  140898. NULL,
  140899. 0
  140900. };
  140901. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140902. 6,
  140903. 5,
  140904. 7,
  140905. 4,
  140906. 8,
  140907. 3,
  140908. 9,
  140909. 2,
  140910. 10,
  140911. 1,
  140912. 11,
  140913. 0,
  140914. 12,
  140915. };
  140916. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140917. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140918. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140919. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140920. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140921. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140922. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140923. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140924. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140925. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140926. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140927. 0,13,13,12,12,13,13,13,14,
  140928. };
  140929. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140930. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140931. 12.5, 17.5, 22.5, 27.5,
  140932. };
  140933. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140934. 11, 9, 7, 5, 3, 1, 0, 2,
  140935. 4, 6, 8, 10, 12,
  140936. };
  140937. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140938. _vq_quantthresh__44cn1_s_p7_0,
  140939. _vq_quantmap__44cn1_s_p7_0,
  140940. 13,
  140941. 13
  140942. };
  140943. static static_codebook _44cn1_s_p7_0 = {
  140944. 2, 169,
  140945. _vq_lengthlist__44cn1_s_p7_0,
  140946. 1, -526516224, 1616117760, 4, 0,
  140947. _vq_quantlist__44cn1_s_p7_0,
  140948. NULL,
  140949. &_vq_auxt__44cn1_s_p7_0,
  140950. NULL,
  140951. 0
  140952. };
  140953. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140954. 2,
  140955. 1,
  140956. 3,
  140957. 0,
  140958. 4,
  140959. };
  140960. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140961. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140962. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140963. };
  140964. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140965. -1.5, -0.5, 0.5, 1.5,
  140966. };
  140967. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140968. 3, 1, 0, 2, 4,
  140969. };
  140970. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140971. _vq_quantthresh__44cn1_s_p7_1,
  140972. _vq_quantmap__44cn1_s_p7_1,
  140973. 5,
  140974. 5
  140975. };
  140976. static static_codebook _44cn1_s_p7_1 = {
  140977. 2, 25,
  140978. _vq_lengthlist__44cn1_s_p7_1,
  140979. 1, -533725184, 1611661312, 3, 0,
  140980. _vq_quantlist__44cn1_s_p7_1,
  140981. NULL,
  140982. &_vq_auxt__44cn1_s_p7_1,
  140983. NULL,
  140984. 0
  140985. };
  140986. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140987. 2,
  140988. 1,
  140989. 3,
  140990. 0,
  140991. 4,
  140992. };
  140993. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140994. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140995. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140996. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140997. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140998. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140999. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141000. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141001. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  141002. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141003. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  141004. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  141005. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141006. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141007. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141008. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141009. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  141010. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141013. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141014. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141015. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141016. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141017. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141019. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141020. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141021. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141022. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141023. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141024. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141025. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141026. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141027. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  141028. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141029. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141030. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141031. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141032. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141033. 12,
  141034. };
  141035. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  141036. -331.5, -110.5, 110.5, 331.5,
  141037. };
  141038. static long _vq_quantmap__44cn1_s_p8_0[] = {
  141039. 3, 1, 0, 2, 4,
  141040. };
  141041. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  141042. _vq_quantthresh__44cn1_s_p8_0,
  141043. _vq_quantmap__44cn1_s_p8_0,
  141044. 5,
  141045. 5
  141046. };
  141047. static static_codebook _44cn1_s_p8_0 = {
  141048. 4, 625,
  141049. _vq_lengthlist__44cn1_s_p8_0,
  141050. 1, -518283264, 1627103232, 3, 0,
  141051. _vq_quantlist__44cn1_s_p8_0,
  141052. NULL,
  141053. &_vq_auxt__44cn1_s_p8_0,
  141054. NULL,
  141055. 0
  141056. };
  141057. static long _vq_quantlist__44cn1_s_p8_1[] = {
  141058. 6,
  141059. 5,
  141060. 7,
  141061. 4,
  141062. 8,
  141063. 3,
  141064. 9,
  141065. 2,
  141066. 10,
  141067. 1,
  141068. 11,
  141069. 0,
  141070. 12,
  141071. };
  141072. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  141073. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  141074. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  141075. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  141076. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  141077. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  141078. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  141079. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  141080. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  141081. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  141082. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  141083. 15,12,12,11,11,14,12,13,14,
  141084. };
  141085. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  141086. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141087. 42.5, 59.5, 76.5, 93.5,
  141088. };
  141089. static long _vq_quantmap__44cn1_s_p8_1[] = {
  141090. 11, 9, 7, 5, 3, 1, 0, 2,
  141091. 4, 6, 8, 10, 12,
  141092. };
  141093. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  141094. _vq_quantthresh__44cn1_s_p8_1,
  141095. _vq_quantmap__44cn1_s_p8_1,
  141096. 13,
  141097. 13
  141098. };
  141099. static static_codebook _44cn1_s_p8_1 = {
  141100. 2, 169,
  141101. _vq_lengthlist__44cn1_s_p8_1,
  141102. 1, -522616832, 1620115456, 4, 0,
  141103. _vq_quantlist__44cn1_s_p8_1,
  141104. NULL,
  141105. &_vq_auxt__44cn1_s_p8_1,
  141106. NULL,
  141107. 0
  141108. };
  141109. static long _vq_quantlist__44cn1_s_p8_2[] = {
  141110. 8,
  141111. 7,
  141112. 9,
  141113. 6,
  141114. 10,
  141115. 5,
  141116. 11,
  141117. 4,
  141118. 12,
  141119. 3,
  141120. 13,
  141121. 2,
  141122. 14,
  141123. 1,
  141124. 15,
  141125. 0,
  141126. 16,
  141127. };
  141128. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  141129. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141130. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  141131. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  141132. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  141133. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  141134. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  141135. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  141136. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  141137. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  141138. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  141139. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  141140. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  141141. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  141142. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  141143. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  141144. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141145. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141146. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  141147. 9,
  141148. };
  141149. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  141150. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141151. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141152. };
  141153. static long _vq_quantmap__44cn1_s_p8_2[] = {
  141154. 15, 13, 11, 9, 7, 5, 3, 1,
  141155. 0, 2, 4, 6, 8, 10, 12, 14,
  141156. 16,
  141157. };
  141158. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  141159. _vq_quantthresh__44cn1_s_p8_2,
  141160. _vq_quantmap__44cn1_s_p8_2,
  141161. 17,
  141162. 17
  141163. };
  141164. static static_codebook _44cn1_s_p8_2 = {
  141165. 2, 289,
  141166. _vq_lengthlist__44cn1_s_p8_2,
  141167. 1, -529530880, 1611661312, 5, 0,
  141168. _vq_quantlist__44cn1_s_p8_2,
  141169. NULL,
  141170. &_vq_auxt__44cn1_s_p8_2,
  141171. NULL,
  141172. 0
  141173. };
  141174. static long _huff_lengthlist__44cn1_s_short[] = {
  141175. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  141176. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  141177. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  141178. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  141179. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  141180. 10,
  141181. };
  141182. static static_codebook _huff_book__44cn1_s_short = {
  141183. 2, 81,
  141184. _huff_lengthlist__44cn1_s_short,
  141185. 0, 0, 0, 0, 0,
  141186. NULL,
  141187. NULL,
  141188. NULL,
  141189. NULL,
  141190. 0
  141191. };
  141192. static long _huff_lengthlist__44cn1_sm_long[] = {
  141193. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141194. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141195. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141196. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141197. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141198. 17,
  141199. };
  141200. static static_codebook _huff_book__44cn1_sm_long = {
  141201. 2, 81,
  141202. _huff_lengthlist__44cn1_sm_long,
  141203. 0, 0, 0, 0, 0,
  141204. NULL,
  141205. NULL,
  141206. NULL,
  141207. NULL,
  141208. 0
  141209. };
  141210. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141211. 1,
  141212. 0,
  141213. 2,
  141214. };
  141215. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141216. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141217. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141222. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141227. 0, 0, 0, 0, 8, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  141262. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  141267. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  141272. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141308. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141313. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141318. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141626. 0,
  141627. };
  141628. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141629. -0.5, 0.5,
  141630. };
  141631. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141632. 1, 0, 2,
  141633. };
  141634. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141635. _vq_quantthresh__44cn1_sm_p1_0,
  141636. _vq_quantmap__44cn1_sm_p1_0,
  141637. 3,
  141638. 3
  141639. };
  141640. static static_codebook _44cn1_sm_p1_0 = {
  141641. 8, 6561,
  141642. _vq_lengthlist__44cn1_sm_p1_0,
  141643. 1, -535822336, 1611661312, 2, 0,
  141644. _vq_quantlist__44cn1_sm_p1_0,
  141645. NULL,
  141646. &_vq_auxt__44cn1_sm_p1_0,
  141647. NULL,
  141648. 0
  141649. };
  141650. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141651. 2,
  141652. 1,
  141653. 3,
  141654. 0,
  141655. 4,
  141656. };
  141657. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141658. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141661. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141664. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141697. 0,
  141698. };
  141699. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141700. -1.5, -0.5, 0.5, 1.5,
  141701. };
  141702. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141703. 3, 1, 0, 2, 4,
  141704. };
  141705. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141706. _vq_quantthresh__44cn1_sm_p2_0,
  141707. _vq_quantmap__44cn1_sm_p2_0,
  141708. 5,
  141709. 5
  141710. };
  141711. static static_codebook _44cn1_sm_p2_0 = {
  141712. 4, 625,
  141713. _vq_lengthlist__44cn1_sm_p2_0,
  141714. 1, -533725184, 1611661312, 3, 0,
  141715. _vq_quantlist__44cn1_sm_p2_0,
  141716. NULL,
  141717. &_vq_auxt__44cn1_sm_p2_0,
  141718. NULL,
  141719. 0
  141720. };
  141721. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141722. 4,
  141723. 3,
  141724. 5,
  141725. 2,
  141726. 6,
  141727. 1,
  141728. 7,
  141729. 0,
  141730. 8,
  141731. };
  141732. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141733. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141734. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141735. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141736. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141737. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141738. 0,
  141739. };
  141740. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141741. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141742. };
  141743. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141744. 7, 5, 3, 1, 0, 2, 4, 6,
  141745. 8,
  141746. };
  141747. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141748. _vq_quantthresh__44cn1_sm_p3_0,
  141749. _vq_quantmap__44cn1_sm_p3_0,
  141750. 9,
  141751. 9
  141752. };
  141753. static static_codebook _44cn1_sm_p3_0 = {
  141754. 2, 81,
  141755. _vq_lengthlist__44cn1_sm_p3_0,
  141756. 1, -531628032, 1611661312, 4, 0,
  141757. _vq_quantlist__44cn1_sm_p3_0,
  141758. NULL,
  141759. &_vq_auxt__44cn1_sm_p3_0,
  141760. NULL,
  141761. 0
  141762. };
  141763. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141764. 4,
  141765. 3,
  141766. 5,
  141767. 2,
  141768. 6,
  141769. 1,
  141770. 7,
  141771. 0,
  141772. 8,
  141773. };
  141774. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141775. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141776. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141777. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141778. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141779. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141780. 11,
  141781. };
  141782. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141783. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141784. };
  141785. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141786. 7, 5, 3, 1, 0, 2, 4, 6,
  141787. 8,
  141788. };
  141789. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141790. _vq_quantthresh__44cn1_sm_p4_0,
  141791. _vq_quantmap__44cn1_sm_p4_0,
  141792. 9,
  141793. 9
  141794. };
  141795. static static_codebook _44cn1_sm_p4_0 = {
  141796. 2, 81,
  141797. _vq_lengthlist__44cn1_sm_p4_0,
  141798. 1, -531628032, 1611661312, 4, 0,
  141799. _vq_quantlist__44cn1_sm_p4_0,
  141800. NULL,
  141801. &_vq_auxt__44cn1_sm_p4_0,
  141802. NULL,
  141803. 0
  141804. };
  141805. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141806. 8,
  141807. 7,
  141808. 9,
  141809. 6,
  141810. 10,
  141811. 5,
  141812. 11,
  141813. 4,
  141814. 12,
  141815. 3,
  141816. 13,
  141817. 2,
  141818. 14,
  141819. 1,
  141820. 15,
  141821. 0,
  141822. 16,
  141823. };
  141824. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141825. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141826. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141827. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141828. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141829. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141830. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141831. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141832. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141833. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141834. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141835. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141836. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141837. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141838. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141839. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141840. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141841. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141842. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141843. 14,
  141844. };
  141845. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141846. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141847. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141848. };
  141849. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141850. 15, 13, 11, 9, 7, 5, 3, 1,
  141851. 0, 2, 4, 6, 8, 10, 12, 14,
  141852. 16,
  141853. };
  141854. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141855. _vq_quantthresh__44cn1_sm_p5_0,
  141856. _vq_quantmap__44cn1_sm_p5_0,
  141857. 17,
  141858. 17
  141859. };
  141860. static static_codebook _44cn1_sm_p5_0 = {
  141861. 2, 289,
  141862. _vq_lengthlist__44cn1_sm_p5_0,
  141863. 1, -529530880, 1611661312, 5, 0,
  141864. _vq_quantlist__44cn1_sm_p5_0,
  141865. NULL,
  141866. &_vq_auxt__44cn1_sm_p5_0,
  141867. NULL,
  141868. 0
  141869. };
  141870. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141871. 1,
  141872. 0,
  141873. 2,
  141874. };
  141875. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141876. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141877. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141878. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141879. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141880. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141881. 10,
  141882. };
  141883. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141884. -5.5, 5.5,
  141885. };
  141886. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141887. 1, 0, 2,
  141888. };
  141889. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141890. _vq_quantthresh__44cn1_sm_p6_0,
  141891. _vq_quantmap__44cn1_sm_p6_0,
  141892. 3,
  141893. 3
  141894. };
  141895. static static_codebook _44cn1_sm_p6_0 = {
  141896. 4, 81,
  141897. _vq_lengthlist__44cn1_sm_p6_0,
  141898. 1, -529137664, 1618345984, 2, 0,
  141899. _vq_quantlist__44cn1_sm_p6_0,
  141900. NULL,
  141901. &_vq_auxt__44cn1_sm_p6_0,
  141902. NULL,
  141903. 0
  141904. };
  141905. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141906. 5,
  141907. 4,
  141908. 6,
  141909. 3,
  141910. 7,
  141911. 2,
  141912. 8,
  141913. 1,
  141914. 9,
  141915. 0,
  141916. 10,
  141917. };
  141918. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141919. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141920. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141921. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141922. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141923. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141924. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141925. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141926. 10,10,10, 8, 9, 8, 8, 9, 8,
  141927. };
  141928. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141929. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141930. 3.5, 4.5,
  141931. };
  141932. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141933. 9, 7, 5, 3, 1, 0, 2, 4,
  141934. 6, 8, 10,
  141935. };
  141936. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141937. _vq_quantthresh__44cn1_sm_p6_1,
  141938. _vq_quantmap__44cn1_sm_p6_1,
  141939. 11,
  141940. 11
  141941. };
  141942. static static_codebook _44cn1_sm_p6_1 = {
  141943. 2, 121,
  141944. _vq_lengthlist__44cn1_sm_p6_1,
  141945. 1, -531365888, 1611661312, 4, 0,
  141946. _vq_quantlist__44cn1_sm_p6_1,
  141947. NULL,
  141948. &_vq_auxt__44cn1_sm_p6_1,
  141949. NULL,
  141950. 0
  141951. };
  141952. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141953. 6,
  141954. 5,
  141955. 7,
  141956. 4,
  141957. 8,
  141958. 3,
  141959. 9,
  141960. 2,
  141961. 10,
  141962. 1,
  141963. 11,
  141964. 0,
  141965. 12,
  141966. };
  141967. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141968. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141969. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141970. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141971. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141972. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141973. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141974. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141975. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141976. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141977. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141978. 0,13,12,12,12,13,13,13,14,
  141979. };
  141980. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141981. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141982. 12.5, 17.5, 22.5, 27.5,
  141983. };
  141984. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141985. 11, 9, 7, 5, 3, 1, 0, 2,
  141986. 4, 6, 8, 10, 12,
  141987. };
  141988. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141989. _vq_quantthresh__44cn1_sm_p7_0,
  141990. _vq_quantmap__44cn1_sm_p7_0,
  141991. 13,
  141992. 13
  141993. };
  141994. static static_codebook _44cn1_sm_p7_0 = {
  141995. 2, 169,
  141996. _vq_lengthlist__44cn1_sm_p7_0,
  141997. 1, -526516224, 1616117760, 4, 0,
  141998. _vq_quantlist__44cn1_sm_p7_0,
  141999. NULL,
  142000. &_vq_auxt__44cn1_sm_p7_0,
  142001. NULL,
  142002. 0
  142003. };
  142004. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  142005. 2,
  142006. 1,
  142007. 3,
  142008. 0,
  142009. 4,
  142010. };
  142011. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  142012. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  142013. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  142014. };
  142015. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  142016. -1.5, -0.5, 0.5, 1.5,
  142017. };
  142018. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  142019. 3, 1, 0, 2, 4,
  142020. };
  142021. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  142022. _vq_quantthresh__44cn1_sm_p7_1,
  142023. _vq_quantmap__44cn1_sm_p7_1,
  142024. 5,
  142025. 5
  142026. };
  142027. static static_codebook _44cn1_sm_p7_1 = {
  142028. 2, 25,
  142029. _vq_lengthlist__44cn1_sm_p7_1,
  142030. 1, -533725184, 1611661312, 3, 0,
  142031. _vq_quantlist__44cn1_sm_p7_1,
  142032. NULL,
  142033. &_vq_auxt__44cn1_sm_p7_1,
  142034. NULL,
  142035. 0
  142036. };
  142037. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  142038. 4,
  142039. 3,
  142040. 5,
  142041. 2,
  142042. 6,
  142043. 1,
  142044. 7,
  142045. 0,
  142046. 8,
  142047. };
  142048. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  142049. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  142050. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  142051. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  142052. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  142053. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  142054. 14,
  142055. };
  142056. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  142057. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  142058. };
  142059. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  142060. 7, 5, 3, 1, 0, 2, 4, 6,
  142061. 8,
  142062. };
  142063. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  142064. _vq_quantthresh__44cn1_sm_p8_0,
  142065. _vq_quantmap__44cn1_sm_p8_0,
  142066. 9,
  142067. 9
  142068. };
  142069. static static_codebook _44cn1_sm_p8_0 = {
  142070. 2, 81,
  142071. _vq_lengthlist__44cn1_sm_p8_0,
  142072. 1, -516186112, 1627103232, 4, 0,
  142073. _vq_quantlist__44cn1_sm_p8_0,
  142074. NULL,
  142075. &_vq_auxt__44cn1_sm_p8_0,
  142076. NULL,
  142077. 0
  142078. };
  142079. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  142080. 6,
  142081. 5,
  142082. 7,
  142083. 4,
  142084. 8,
  142085. 3,
  142086. 9,
  142087. 2,
  142088. 10,
  142089. 1,
  142090. 11,
  142091. 0,
  142092. 12,
  142093. };
  142094. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  142095. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  142096. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  142097. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  142098. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  142099. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  142100. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  142101. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  142102. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  142103. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  142104. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  142105. 17,12,12,11,10,13,11,13,13,
  142106. };
  142107. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  142108. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  142109. 42.5, 59.5, 76.5, 93.5,
  142110. };
  142111. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  142112. 11, 9, 7, 5, 3, 1, 0, 2,
  142113. 4, 6, 8, 10, 12,
  142114. };
  142115. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  142116. _vq_quantthresh__44cn1_sm_p8_1,
  142117. _vq_quantmap__44cn1_sm_p8_1,
  142118. 13,
  142119. 13
  142120. };
  142121. static static_codebook _44cn1_sm_p8_1 = {
  142122. 2, 169,
  142123. _vq_lengthlist__44cn1_sm_p8_1,
  142124. 1, -522616832, 1620115456, 4, 0,
  142125. _vq_quantlist__44cn1_sm_p8_1,
  142126. NULL,
  142127. &_vq_auxt__44cn1_sm_p8_1,
  142128. NULL,
  142129. 0
  142130. };
  142131. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  142132. 8,
  142133. 7,
  142134. 9,
  142135. 6,
  142136. 10,
  142137. 5,
  142138. 11,
  142139. 4,
  142140. 12,
  142141. 3,
  142142. 13,
  142143. 2,
  142144. 14,
  142145. 1,
  142146. 15,
  142147. 0,
  142148. 16,
  142149. };
  142150. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  142151. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142152. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  142153. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  142154. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  142155. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  142156. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  142157. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  142158. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  142159. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  142160. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  142161. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  142162. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  142163. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  142164. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  142165. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  142166. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  142167. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142168. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  142169. 9,
  142170. };
  142171. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  142172. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142173. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142174. };
  142175. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  142176. 15, 13, 11, 9, 7, 5, 3, 1,
  142177. 0, 2, 4, 6, 8, 10, 12, 14,
  142178. 16,
  142179. };
  142180. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  142181. _vq_quantthresh__44cn1_sm_p8_2,
  142182. _vq_quantmap__44cn1_sm_p8_2,
  142183. 17,
  142184. 17
  142185. };
  142186. static static_codebook _44cn1_sm_p8_2 = {
  142187. 2, 289,
  142188. _vq_lengthlist__44cn1_sm_p8_2,
  142189. 1, -529530880, 1611661312, 5, 0,
  142190. _vq_quantlist__44cn1_sm_p8_2,
  142191. NULL,
  142192. &_vq_auxt__44cn1_sm_p8_2,
  142193. NULL,
  142194. 0
  142195. };
  142196. static long _huff_lengthlist__44cn1_sm_short[] = {
  142197. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142198. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142199. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142200. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142201. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142202. 9,
  142203. };
  142204. static static_codebook _huff_book__44cn1_sm_short = {
  142205. 2, 81,
  142206. _huff_lengthlist__44cn1_sm_short,
  142207. 0, 0, 0, 0, 0,
  142208. NULL,
  142209. NULL,
  142210. NULL,
  142211. NULL,
  142212. 0
  142213. };
  142214. /*** End of inlined file: res_books_stereo.h ***/
  142215. /***** residue backends *********************************************/
  142216. static vorbis_info_residue0 _residue_44_low={
  142217. 0,-1, -1, 9,-1,
  142218. /* 0 1 2 3 4 5 6 7 */
  142219. {0},
  142220. {-1},
  142221. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142222. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142223. };
  142224. static vorbis_info_residue0 _residue_44_mid={
  142225. 0,-1, -1, 10,-1,
  142226. /* 0 1 2 3 4 5 6 7 8 */
  142227. {0},
  142228. {-1},
  142229. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142230. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142231. };
  142232. static vorbis_info_residue0 _residue_44_high={
  142233. 0,-1, -1, 10,-1,
  142234. /* 0 1 2 3 4 5 6 7 8 */
  142235. {0},
  142236. {-1},
  142237. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142238. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142239. };
  142240. static static_bookblock _resbook_44s_n1={
  142241. {
  142242. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142243. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142244. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142245. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142246. }
  142247. };
  142248. static static_bookblock _resbook_44sm_n1={
  142249. {
  142250. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142251. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142252. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142253. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142254. }
  142255. };
  142256. static static_bookblock _resbook_44s_0={
  142257. {
  142258. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142259. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142260. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142261. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142262. }
  142263. };
  142264. static static_bookblock _resbook_44sm_0={
  142265. {
  142266. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142267. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142268. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142269. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142270. }
  142271. };
  142272. static static_bookblock _resbook_44s_1={
  142273. {
  142274. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142275. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142276. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142277. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142278. }
  142279. };
  142280. static static_bookblock _resbook_44sm_1={
  142281. {
  142282. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142283. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142284. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142285. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142286. }
  142287. };
  142288. static static_bookblock _resbook_44s_2={
  142289. {
  142290. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142291. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142292. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142293. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142294. }
  142295. };
  142296. static static_bookblock _resbook_44s_3={
  142297. {
  142298. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142299. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142300. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142301. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142302. }
  142303. };
  142304. static static_bookblock _resbook_44s_4={
  142305. {
  142306. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142307. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142308. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142309. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142310. }
  142311. };
  142312. static static_bookblock _resbook_44s_5={
  142313. {
  142314. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142315. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142316. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142317. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142318. }
  142319. };
  142320. static static_bookblock _resbook_44s_6={
  142321. {
  142322. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142323. {0,0,&_44c6_s_p4_0},
  142324. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142325. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142326. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142327. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142328. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142329. }
  142330. };
  142331. static static_bookblock _resbook_44s_7={
  142332. {
  142333. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142334. {0,0,&_44c7_s_p4_0},
  142335. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142336. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142337. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142338. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142339. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142340. }
  142341. };
  142342. static static_bookblock _resbook_44s_8={
  142343. {
  142344. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142345. {0,0,&_44c8_s_p4_0},
  142346. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142347. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142348. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142349. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142350. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142351. }
  142352. };
  142353. static static_bookblock _resbook_44s_9={
  142354. {
  142355. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142356. {0,0,&_44c9_s_p4_0},
  142357. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142358. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142359. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142360. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142361. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142362. }
  142363. };
  142364. static vorbis_residue_template _res_44s_n1[]={
  142365. {2,0, &_residue_44_low,
  142366. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142367. &_resbook_44s_n1,&_resbook_44sm_n1},
  142368. {2,0, &_residue_44_low,
  142369. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142370. &_resbook_44s_n1,&_resbook_44sm_n1}
  142371. };
  142372. static vorbis_residue_template _res_44s_0[]={
  142373. {2,0, &_residue_44_low,
  142374. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142375. &_resbook_44s_0,&_resbook_44sm_0},
  142376. {2,0, &_residue_44_low,
  142377. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142378. &_resbook_44s_0,&_resbook_44sm_0}
  142379. };
  142380. static vorbis_residue_template _res_44s_1[]={
  142381. {2,0, &_residue_44_low,
  142382. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142383. &_resbook_44s_1,&_resbook_44sm_1},
  142384. {2,0, &_residue_44_low,
  142385. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142386. &_resbook_44s_1,&_resbook_44sm_1}
  142387. };
  142388. static vorbis_residue_template _res_44s_2[]={
  142389. {2,0, &_residue_44_mid,
  142390. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142391. &_resbook_44s_2,&_resbook_44s_2},
  142392. {2,0, &_residue_44_mid,
  142393. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142394. &_resbook_44s_2,&_resbook_44s_2}
  142395. };
  142396. static vorbis_residue_template _res_44s_3[]={
  142397. {2,0, &_residue_44_mid,
  142398. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142399. &_resbook_44s_3,&_resbook_44s_3},
  142400. {2,0, &_residue_44_mid,
  142401. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142402. &_resbook_44s_3,&_resbook_44s_3}
  142403. };
  142404. static vorbis_residue_template _res_44s_4[]={
  142405. {2,0, &_residue_44_mid,
  142406. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142407. &_resbook_44s_4,&_resbook_44s_4},
  142408. {2,0, &_residue_44_mid,
  142409. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142410. &_resbook_44s_4,&_resbook_44s_4}
  142411. };
  142412. static vorbis_residue_template _res_44s_5[]={
  142413. {2,0, &_residue_44_mid,
  142414. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142415. &_resbook_44s_5,&_resbook_44s_5},
  142416. {2,0, &_residue_44_mid,
  142417. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142418. &_resbook_44s_5,&_resbook_44s_5}
  142419. };
  142420. static vorbis_residue_template _res_44s_6[]={
  142421. {2,0, &_residue_44_high,
  142422. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142423. &_resbook_44s_6,&_resbook_44s_6},
  142424. {2,0, &_residue_44_high,
  142425. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142426. &_resbook_44s_6,&_resbook_44s_6}
  142427. };
  142428. static vorbis_residue_template _res_44s_7[]={
  142429. {2,0, &_residue_44_high,
  142430. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142431. &_resbook_44s_7,&_resbook_44s_7},
  142432. {2,0, &_residue_44_high,
  142433. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142434. &_resbook_44s_7,&_resbook_44s_7}
  142435. };
  142436. static vorbis_residue_template _res_44s_8[]={
  142437. {2,0, &_residue_44_high,
  142438. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142439. &_resbook_44s_8,&_resbook_44s_8},
  142440. {2,0, &_residue_44_high,
  142441. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142442. &_resbook_44s_8,&_resbook_44s_8}
  142443. };
  142444. static vorbis_residue_template _res_44s_9[]={
  142445. {2,0, &_residue_44_high,
  142446. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142447. &_resbook_44s_9,&_resbook_44s_9},
  142448. {2,0, &_residue_44_high,
  142449. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142450. &_resbook_44s_9,&_resbook_44s_9}
  142451. };
  142452. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142453. { _map_nominal, _res_44s_n1 }, /* -1 */
  142454. { _map_nominal, _res_44s_0 }, /* 0 */
  142455. { _map_nominal, _res_44s_1 }, /* 1 */
  142456. { _map_nominal, _res_44s_2 }, /* 2 */
  142457. { _map_nominal, _res_44s_3 }, /* 3 */
  142458. { _map_nominal, _res_44s_4 }, /* 4 */
  142459. { _map_nominal, _res_44s_5 }, /* 5 */
  142460. { _map_nominal, _res_44s_6 }, /* 6 */
  142461. { _map_nominal, _res_44s_7 }, /* 7 */
  142462. { _map_nominal, _res_44s_8 }, /* 8 */
  142463. { _map_nominal, _res_44s_9 }, /* 9 */
  142464. };
  142465. /*** End of inlined file: residue_44.h ***/
  142466. /*** Start of inlined file: psych_44.h ***/
  142467. /* preecho trigger settings *****************************************/
  142468. static vorbis_info_psy_global _psy_global_44[5]={
  142469. {8, /* lines per eighth octave */
  142470. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142471. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142472. -6.f,
  142473. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142474. },
  142475. {8, /* lines per eighth octave */
  142476. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142477. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142478. -6.f,
  142479. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142480. },
  142481. {8, /* lines per eighth octave */
  142482. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142483. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142484. -6.f,
  142485. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142486. },
  142487. {8, /* lines per eighth octave */
  142488. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142489. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142490. -6.f,
  142491. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142492. },
  142493. {8, /* lines per eighth octave */
  142494. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142495. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142496. -6.f,
  142497. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142498. },
  142499. };
  142500. /* noise compander lookups * low, mid, high quality ****************/
  142501. static compandblock _psy_compand_44[6]={
  142502. /* sub-mode Z short */
  142503. {{
  142504. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142505. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142506. 16,17,18,19,20,21,22, 23, /* 23dB */
  142507. 24,25,26,27,28,29,30, 31, /* 31dB */
  142508. 32,33,34,35,36,37,38, 39, /* 39dB */
  142509. }},
  142510. /* mode_Z nominal short */
  142511. {{
  142512. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142513. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142514. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142515. 15,16,17,17,17,18,18, 19, /* 31dB */
  142516. 19,19,20,21,22,23,24, 25, /* 39dB */
  142517. }},
  142518. /* mode A short */
  142519. {{
  142520. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142521. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142522. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142523. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142524. 11,12,13,14,15,16,17, 18, /* 39dB */
  142525. }},
  142526. /* sub-mode Z long */
  142527. {{
  142528. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142529. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142530. 16,17,18,19,20,21,22, 23, /* 23dB */
  142531. 24,25,26,27,28,29,30, 31, /* 31dB */
  142532. 32,33,34,35,36,37,38, 39, /* 39dB */
  142533. }},
  142534. /* mode_Z nominal long */
  142535. {{
  142536. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142537. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142538. 13,14,14,14,15,15,15, 15, /* 23dB */
  142539. 16,16,17,17,17,18,18, 19, /* 31dB */
  142540. 19,19,20,21,22,23,24, 25, /* 39dB */
  142541. }},
  142542. /* mode A long */
  142543. {{
  142544. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142545. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142546. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142547. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142548. 11,12,13,14,15,16,17, 18, /* 39dB */
  142549. }}
  142550. };
  142551. /* tonal masking curve level adjustments *************************/
  142552. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142553. /* 63 125 250 500 1 2 4 8 16 */
  142554. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142555. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142556. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142557. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142558. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142559. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142560. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142561. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142562. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142563. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142564. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142565. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142566. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142567. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142568. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142569. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142570. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142571. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142572. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142573. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142574. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142575. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142576. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142577. };
  142578. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142579. /* 63 125 250 500 1 2 4 8 16 */
  142580. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142581. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142582. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142583. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142584. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142585. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142586. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142587. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142588. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142589. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142590. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142591. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142592. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142593. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142594. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142595. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142596. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142597. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142598. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142599. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142600. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142601. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142602. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142603. };
  142604. /* noise bias (transition block) */
  142605. static noise3 _psy_noisebias_trans[12]={
  142606. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142607. /* -1 */
  142608. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142609. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142610. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142611. /* 0
  142612. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142613. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142614. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142615. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142616. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142617. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142618. /* 1
  142619. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142620. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142621. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142622. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142623. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142624. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142625. /* 2
  142626. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142627. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142628. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142629. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142630. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142631. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142632. /* 3
  142633. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142634. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142635. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142636. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142637. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142638. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142639. /* 4
  142640. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142641. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142642. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142643. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142644. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142645. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142646. /* 5
  142647. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142648. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142649. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142650. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142651. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142652. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142653. /* 6
  142654. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142655. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142656. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142657. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142658. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142659. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142660. /* 7
  142661. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142662. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142663. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142664. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142665. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142666. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142667. /* 8
  142668. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142669. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142670. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142671. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142672. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142673. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142674. /* 9
  142675. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142676. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142677. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142678. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142679. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142680. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142681. /* 10 */
  142682. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142683. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142684. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142685. };
  142686. /* noise bias (long block) */
  142687. static noise3 _psy_noisebias_long[12]={
  142688. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142689. /* -1 */
  142690. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142691. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142692. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142693. /* 0 */
  142694. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142695. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142696. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142697. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142698. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142699. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142700. /* 1 */
  142701. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142702. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142703. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142704. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142705. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142706. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142707. /* 2 */
  142708. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142709. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142710. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142711. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142712. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142713. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142714. /* 3 */
  142715. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142716. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142717. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142718. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142719. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142720. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142721. /* 4 */
  142722. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142723. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142724. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142725. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142726. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142727. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142728. /* 5 */
  142729. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142730. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142731. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142732. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142733. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142734. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142735. /* 6 */
  142736. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142737. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142738. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142739. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142740. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142741. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142742. /* 7 */
  142743. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142744. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142745. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142746. /* 8 */
  142747. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142748. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142749. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142750. /* 9 */
  142751. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142752. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142753. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142754. /* 10 */
  142755. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142756. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142757. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142758. };
  142759. /* noise bias (impulse block) */
  142760. static noise3 _psy_noisebias_impulse[12]={
  142761. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142762. /* -1 */
  142763. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142764. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142765. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142766. /* 0 */
  142767. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142768. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142769. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142770. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142771. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142772. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142773. /* 1 */
  142774. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142775. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142776. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142777. /* 2 */
  142778. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142779. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142780. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142781. /* 3 */
  142782. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142783. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142784. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142785. /* 4 */
  142786. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142787. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142788. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142789. /* 5 */
  142790. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142791. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142792. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142793. /* 6
  142794. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142795. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142796. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142797. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142798. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142799. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142800. /* 7 */
  142801. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142802. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142803. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142804. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142805. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142806. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142807. /* 8 */
  142808. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142809. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142810. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142811. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142812. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142813. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142814. /* 9 */
  142815. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142816. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142817. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142818. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142819. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142820. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142821. /* 10 */
  142822. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142823. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142824. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142825. };
  142826. /* noise bias (padding block) */
  142827. static noise3 _psy_noisebias_padding[12]={
  142828. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142829. /* -1 */
  142830. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142831. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142832. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142833. /* 0 */
  142834. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142835. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142836. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142837. /* 1 */
  142838. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142839. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142840. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142841. /* 2 */
  142842. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142843. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142844. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142845. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142846. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142847. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142848. /* 3 */
  142849. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142850. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142851. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142852. /* 4 */
  142853. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142854. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142855. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142856. /* 5 */
  142857. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142858. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142859. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142860. /* 6 */
  142861. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142862. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142863. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142864. /* 7 */
  142865. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142866. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142867. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142868. /* 8 */
  142869. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142870. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142871. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142872. /* 9 */
  142873. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142874. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142875. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142876. /* 10 */
  142877. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142878. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142879. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142880. };
  142881. static noiseguard _psy_noiseguards_44[4]={
  142882. {3,3,15},
  142883. {3,3,15},
  142884. {10,10,100},
  142885. {10,10,100},
  142886. };
  142887. static int _psy_tone_suppress[12]={
  142888. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142889. };
  142890. static int _psy_tone_0dB[12]={
  142891. 90,90,95,95,95,95,105,105,105,105,105,105,
  142892. };
  142893. static int _psy_noise_suppress[12]={
  142894. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142895. };
  142896. static vorbis_info_psy _psy_info_template={
  142897. /* blockflag */
  142898. -1,
  142899. /* ath_adjatt, ath_maxatt */
  142900. -140.,-140.,
  142901. /* tonemask att boost/decay,suppr,curves */
  142902. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142903. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142904. 1, -0.f, .5f, .5f, 0,0,0,
  142905. /* noiseoffset*3, noisecompand, max_curve_dB */
  142906. {{-1},{-1},{-1}},{-1},105.f,
  142907. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142908. 0,0,-1,-1,0.,
  142909. };
  142910. /* ath ****************/
  142911. static int _psy_ath_floater[12]={
  142912. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142913. };
  142914. static int _psy_ath_abs[12]={
  142915. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142916. };
  142917. /* stereo setup. These don't map directly to quality level, there's
  142918. an additional indirection as several of the below may be used in a
  142919. single bitmanaged stream
  142920. ****************/
  142921. /* various stereo possibilities */
  142922. /* stereo mode by base quality level */
  142923. static adj_stereo _psy_stereo_modes_44[12]={
  142924. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142925. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142926. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142927. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142928. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142929. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142930. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142931. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142932. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142933. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142934. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142935. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142936. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142937. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142938. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142939. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142940. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142941. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142942. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142943. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142944. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142945. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142946. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142947. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142948. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142949. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142950. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142951. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142952. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142953. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142954. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142955. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142956. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142957. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142958. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142959. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142960. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142961. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142962. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142963. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142964. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142965. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142966. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142967. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142968. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142969. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142970. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142971. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142972. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142973. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142974. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142975. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142976. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142977. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142978. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142979. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142980. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142981. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142982. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142983. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142984. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142985. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142986. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142987. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142988. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142989. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142990. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142991. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142992. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142993. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142994. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142995. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142996. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142997. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142998. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142999. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143000. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143001. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143002. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143003. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  143004. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143005. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143006. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143007. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143008. };
  143009. /* tone master attenuation by base quality mode and bitrate tweak */
  143010. static att3 _psy_tone_masteratt_44[12]={
  143011. {{ 35, 21, 9}, 0, 0}, /* -1 */
  143012. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  143013. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  143014. {{ 25, 12, 2}, 0, 0}, /* 1 */
  143015. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  143016. {{ 20, 9, -3}, 0, 0}, /* 2 */
  143017. {{ 20, 9, -4}, 0, 0}, /* 3 */
  143018. {{ 20, 9, -4}, 0, 0}, /* 4 */
  143019. {{ 20, 6, -6}, 0, 0}, /* 5 */
  143020. {{ 20, 3, -10}, 0, 0}, /* 6 */
  143021. {{ 18, 1, -14}, 0, 0}, /* 7 */
  143022. {{ 18, 0, -16}, 0, 0}, /* 8 */
  143023. {{ 18, -2, -16}, 0, 0}, /* 9 */
  143024. {{ 12, -2, -20}, 0, 0}, /* 10 */
  143025. };
  143026. /* lowpass by mode **************/
  143027. static double _psy_lowpass_44[12]={
  143028. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  143029. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  143030. };
  143031. /* noise normalization **********/
  143032. static int _noise_start_short_44[11]={
  143033. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  143034. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  143035. };
  143036. static int _noise_start_long_44[11]={
  143037. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  143038. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  143039. };
  143040. static int _noise_part_short_44[11]={
  143041. 8,8,8,8,8,8,8,8,8,8,8
  143042. };
  143043. static int _noise_part_long_44[11]={
  143044. 32,32,32,32,32,32,32,32,32,32,32
  143045. };
  143046. static double _noise_thresh_44[11]={
  143047. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  143048. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  143049. };
  143050. static double _noise_thresh_5only[2]={
  143051. .5,.5,
  143052. };
  143053. /*** End of inlined file: psych_44.h ***/
  143054. static double rate_mapping_44_stereo[12]={
  143055. 22500.,32000.,40000.,48000.,56000.,64000.,
  143056. 80000.,96000.,112000.,128000.,160000.,250001.
  143057. };
  143058. static double quality_mapping_44[12]={
  143059. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  143060. };
  143061. static int blocksize_short_44[11]={
  143062. 512,256,256,256,256,256,256,256,256,256,256
  143063. };
  143064. static int blocksize_long_44[11]={
  143065. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  143066. };
  143067. static double _psy_compand_short_mapping[12]={
  143068. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  143069. };
  143070. static double _psy_compand_long_mapping[12]={
  143071. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  143072. };
  143073. static double _global_mapping_44[12]={
  143074. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  143075. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  143076. };
  143077. static int _floor_short_mapping_44[11]={
  143078. 1,0,0,2,2,4,5,5,5,5,5
  143079. };
  143080. static int _floor_long_mapping_44[11]={
  143081. 8,7,7,7,7,7,7,7,7,7,7
  143082. };
  143083. ve_setup_data_template ve_setup_44_stereo={
  143084. 11,
  143085. rate_mapping_44_stereo,
  143086. quality_mapping_44,
  143087. 2,
  143088. 40000,
  143089. 50000,
  143090. blocksize_short_44,
  143091. blocksize_long_44,
  143092. _psy_tone_masteratt_44,
  143093. _psy_tone_0dB,
  143094. _psy_tone_suppress,
  143095. _vp_tonemask_adj_otherblock,
  143096. _vp_tonemask_adj_longblock,
  143097. _vp_tonemask_adj_otherblock,
  143098. _psy_noiseguards_44,
  143099. _psy_noisebias_impulse,
  143100. _psy_noisebias_padding,
  143101. _psy_noisebias_trans,
  143102. _psy_noisebias_long,
  143103. _psy_noise_suppress,
  143104. _psy_compand_44,
  143105. _psy_compand_short_mapping,
  143106. _psy_compand_long_mapping,
  143107. {_noise_start_short_44,_noise_start_long_44},
  143108. {_noise_part_short_44,_noise_part_long_44},
  143109. _noise_thresh_44,
  143110. _psy_ath_floater,
  143111. _psy_ath_abs,
  143112. _psy_lowpass_44,
  143113. _psy_global_44,
  143114. _global_mapping_44,
  143115. _psy_stereo_modes_44,
  143116. _floor_books,
  143117. _floor,
  143118. _floor_short_mapping_44,
  143119. _floor_long_mapping_44,
  143120. _mapres_template_44_stereo
  143121. };
  143122. /*** End of inlined file: setup_44.h ***/
  143123. /*** Start of inlined file: setup_44u.h ***/
  143124. /*** Start of inlined file: residue_44u.h ***/
  143125. /*** Start of inlined file: res_books_uncoupled.h ***/
  143126. static long _vq_quantlist__16u0__p1_0[] = {
  143127. 1,
  143128. 0,
  143129. 2,
  143130. };
  143131. static long _vq_lengthlist__16u0__p1_0[] = {
  143132. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  143133. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  143134. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  143135. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  143136. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  143137. 12,
  143138. };
  143139. static float _vq_quantthresh__16u0__p1_0[] = {
  143140. -0.5, 0.5,
  143141. };
  143142. static long _vq_quantmap__16u0__p1_0[] = {
  143143. 1, 0, 2,
  143144. };
  143145. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  143146. _vq_quantthresh__16u0__p1_0,
  143147. _vq_quantmap__16u0__p1_0,
  143148. 3,
  143149. 3
  143150. };
  143151. static static_codebook _16u0__p1_0 = {
  143152. 4, 81,
  143153. _vq_lengthlist__16u0__p1_0,
  143154. 1, -535822336, 1611661312, 2, 0,
  143155. _vq_quantlist__16u0__p1_0,
  143156. NULL,
  143157. &_vq_auxt__16u0__p1_0,
  143158. NULL,
  143159. 0
  143160. };
  143161. static long _vq_quantlist__16u0__p2_0[] = {
  143162. 1,
  143163. 0,
  143164. 2,
  143165. };
  143166. static long _vq_lengthlist__16u0__p2_0[] = {
  143167. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  143168. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  143169. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  143170. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  143171. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  143172. 8,
  143173. };
  143174. static float _vq_quantthresh__16u0__p2_0[] = {
  143175. -0.5, 0.5,
  143176. };
  143177. static long _vq_quantmap__16u0__p2_0[] = {
  143178. 1, 0, 2,
  143179. };
  143180. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  143181. _vq_quantthresh__16u0__p2_0,
  143182. _vq_quantmap__16u0__p2_0,
  143183. 3,
  143184. 3
  143185. };
  143186. static static_codebook _16u0__p2_0 = {
  143187. 4, 81,
  143188. _vq_lengthlist__16u0__p2_0,
  143189. 1, -535822336, 1611661312, 2, 0,
  143190. _vq_quantlist__16u0__p2_0,
  143191. NULL,
  143192. &_vq_auxt__16u0__p2_0,
  143193. NULL,
  143194. 0
  143195. };
  143196. static long _vq_quantlist__16u0__p3_0[] = {
  143197. 2,
  143198. 1,
  143199. 3,
  143200. 0,
  143201. 4,
  143202. };
  143203. static long _vq_lengthlist__16u0__p3_0[] = {
  143204. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143205. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143206. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143207. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143208. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143209. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143210. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143211. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143212. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143213. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143214. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143215. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143216. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143217. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143218. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143219. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143220. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143221. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143222. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143223. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143224. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143225. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143226. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143227. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143228. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143229. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143230. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143231. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143232. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143233. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143234. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143235. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143236. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143237. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143238. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143239. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143240. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143241. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143242. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143243. 18,
  143244. };
  143245. static float _vq_quantthresh__16u0__p3_0[] = {
  143246. -1.5, -0.5, 0.5, 1.5,
  143247. };
  143248. static long _vq_quantmap__16u0__p3_0[] = {
  143249. 3, 1, 0, 2, 4,
  143250. };
  143251. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143252. _vq_quantthresh__16u0__p3_0,
  143253. _vq_quantmap__16u0__p3_0,
  143254. 5,
  143255. 5
  143256. };
  143257. static static_codebook _16u0__p3_0 = {
  143258. 4, 625,
  143259. _vq_lengthlist__16u0__p3_0,
  143260. 1, -533725184, 1611661312, 3, 0,
  143261. _vq_quantlist__16u0__p3_0,
  143262. NULL,
  143263. &_vq_auxt__16u0__p3_0,
  143264. NULL,
  143265. 0
  143266. };
  143267. static long _vq_quantlist__16u0__p4_0[] = {
  143268. 2,
  143269. 1,
  143270. 3,
  143271. 0,
  143272. 4,
  143273. };
  143274. static long _vq_lengthlist__16u0__p4_0[] = {
  143275. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143276. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143277. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143278. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143279. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143280. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143281. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143282. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143283. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143284. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143285. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143286. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143287. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143288. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143289. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143290. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143291. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143292. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143293. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143294. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143295. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143296. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143297. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143298. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143299. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143300. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143301. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143302. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143303. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143304. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143305. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143306. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143307. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143308. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143309. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143310. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143311. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143312. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143313. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143314. 11,
  143315. };
  143316. static float _vq_quantthresh__16u0__p4_0[] = {
  143317. -1.5, -0.5, 0.5, 1.5,
  143318. };
  143319. static long _vq_quantmap__16u0__p4_0[] = {
  143320. 3, 1, 0, 2, 4,
  143321. };
  143322. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143323. _vq_quantthresh__16u0__p4_0,
  143324. _vq_quantmap__16u0__p4_0,
  143325. 5,
  143326. 5
  143327. };
  143328. static static_codebook _16u0__p4_0 = {
  143329. 4, 625,
  143330. _vq_lengthlist__16u0__p4_0,
  143331. 1, -533725184, 1611661312, 3, 0,
  143332. _vq_quantlist__16u0__p4_0,
  143333. NULL,
  143334. &_vq_auxt__16u0__p4_0,
  143335. NULL,
  143336. 0
  143337. };
  143338. static long _vq_quantlist__16u0__p5_0[] = {
  143339. 4,
  143340. 3,
  143341. 5,
  143342. 2,
  143343. 6,
  143344. 1,
  143345. 7,
  143346. 0,
  143347. 8,
  143348. };
  143349. static long _vq_lengthlist__16u0__p5_0[] = {
  143350. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143351. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143352. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143353. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143354. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143355. 12,
  143356. };
  143357. static float _vq_quantthresh__16u0__p5_0[] = {
  143358. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143359. };
  143360. static long _vq_quantmap__16u0__p5_0[] = {
  143361. 7, 5, 3, 1, 0, 2, 4, 6,
  143362. 8,
  143363. };
  143364. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143365. _vq_quantthresh__16u0__p5_0,
  143366. _vq_quantmap__16u0__p5_0,
  143367. 9,
  143368. 9
  143369. };
  143370. static static_codebook _16u0__p5_0 = {
  143371. 2, 81,
  143372. _vq_lengthlist__16u0__p5_0,
  143373. 1, -531628032, 1611661312, 4, 0,
  143374. _vq_quantlist__16u0__p5_0,
  143375. NULL,
  143376. &_vq_auxt__16u0__p5_0,
  143377. NULL,
  143378. 0
  143379. };
  143380. static long _vq_quantlist__16u0__p6_0[] = {
  143381. 6,
  143382. 5,
  143383. 7,
  143384. 4,
  143385. 8,
  143386. 3,
  143387. 9,
  143388. 2,
  143389. 10,
  143390. 1,
  143391. 11,
  143392. 0,
  143393. 12,
  143394. };
  143395. static long _vq_lengthlist__16u0__p6_0[] = {
  143396. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143397. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143398. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143399. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143400. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143401. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143402. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143403. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143404. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143405. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143406. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143407. };
  143408. static float _vq_quantthresh__16u0__p6_0[] = {
  143409. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143410. 12.5, 17.5, 22.5, 27.5,
  143411. };
  143412. static long _vq_quantmap__16u0__p6_0[] = {
  143413. 11, 9, 7, 5, 3, 1, 0, 2,
  143414. 4, 6, 8, 10, 12,
  143415. };
  143416. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143417. _vq_quantthresh__16u0__p6_0,
  143418. _vq_quantmap__16u0__p6_0,
  143419. 13,
  143420. 13
  143421. };
  143422. static static_codebook _16u0__p6_0 = {
  143423. 2, 169,
  143424. _vq_lengthlist__16u0__p6_0,
  143425. 1, -526516224, 1616117760, 4, 0,
  143426. _vq_quantlist__16u0__p6_0,
  143427. NULL,
  143428. &_vq_auxt__16u0__p6_0,
  143429. NULL,
  143430. 0
  143431. };
  143432. static long _vq_quantlist__16u0__p6_1[] = {
  143433. 2,
  143434. 1,
  143435. 3,
  143436. 0,
  143437. 4,
  143438. };
  143439. static long _vq_lengthlist__16u0__p6_1[] = {
  143440. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143441. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143442. };
  143443. static float _vq_quantthresh__16u0__p6_1[] = {
  143444. -1.5, -0.5, 0.5, 1.5,
  143445. };
  143446. static long _vq_quantmap__16u0__p6_1[] = {
  143447. 3, 1, 0, 2, 4,
  143448. };
  143449. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143450. _vq_quantthresh__16u0__p6_1,
  143451. _vq_quantmap__16u0__p6_1,
  143452. 5,
  143453. 5
  143454. };
  143455. static static_codebook _16u0__p6_1 = {
  143456. 2, 25,
  143457. _vq_lengthlist__16u0__p6_1,
  143458. 1, -533725184, 1611661312, 3, 0,
  143459. _vq_quantlist__16u0__p6_1,
  143460. NULL,
  143461. &_vq_auxt__16u0__p6_1,
  143462. NULL,
  143463. 0
  143464. };
  143465. static long _vq_quantlist__16u0__p7_0[] = {
  143466. 1,
  143467. 0,
  143468. 2,
  143469. };
  143470. static long _vq_lengthlist__16u0__p7_0[] = {
  143471. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143472. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143473. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143474. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143475. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143476. 7,
  143477. };
  143478. static float _vq_quantthresh__16u0__p7_0[] = {
  143479. -157.5, 157.5,
  143480. };
  143481. static long _vq_quantmap__16u0__p7_0[] = {
  143482. 1, 0, 2,
  143483. };
  143484. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143485. _vq_quantthresh__16u0__p7_0,
  143486. _vq_quantmap__16u0__p7_0,
  143487. 3,
  143488. 3
  143489. };
  143490. static static_codebook _16u0__p7_0 = {
  143491. 4, 81,
  143492. _vq_lengthlist__16u0__p7_0,
  143493. 1, -518803456, 1628680192, 2, 0,
  143494. _vq_quantlist__16u0__p7_0,
  143495. NULL,
  143496. &_vq_auxt__16u0__p7_0,
  143497. NULL,
  143498. 0
  143499. };
  143500. static long _vq_quantlist__16u0__p7_1[] = {
  143501. 7,
  143502. 6,
  143503. 8,
  143504. 5,
  143505. 9,
  143506. 4,
  143507. 10,
  143508. 3,
  143509. 11,
  143510. 2,
  143511. 12,
  143512. 1,
  143513. 13,
  143514. 0,
  143515. 14,
  143516. };
  143517. static long _vq_lengthlist__16u0__p7_1[] = {
  143518. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143519. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143520. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143521. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143522. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143523. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143524. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143525. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143526. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143527. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143528. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143529. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143530. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143531. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143532. 10,
  143533. };
  143534. static float _vq_quantthresh__16u0__p7_1[] = {
  143535. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143536. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143537. };
  143538. static long _vq_quantmap__16u0__p7_1[] = {
  143539. 13, 11, 9, 7, 5, 3, 1, 0,
  143540. 2, 4, 6, 8, 10, 12, 14,
  143541. };
  143542. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143543. _vq_quantthresh__16u0__p7_1,
  143544. _vq_quantmap__16u0__p7_1,
  143545. 15,
  143546. 15
  143547. };
  143548. static static_codebook _16u0__p7_1 = {
  143549. 2, 225,
  143550. _vq_lengthlist__16u0__p7_1,
  143551. 1, -520986624, 1620377600, 4, 0,
  143552. _vq_quantlist__16u0__p7_1,
  143553. NULL,
  143554. &_vq_auxt__16u0__p7_1,
  143555. NULL,
  143556. 0
  143557. };
  143558. static long _vq_quantlist__16u0__p7_2[] = {
  143559. 10,
  143560. 9,
  143561. 11,
  143562. 8,
  143563. 12,
  143564. 7,
  143565. 13,
  143566. 6,
  143567. 14,
  143568. 5,
  143569. 15,
  143570. 4,
  143571. 16,
  143572. 3,
  143573. 17,
  143574. 2,
  143575. 18,
  143576. 1,
  143577. 19,
  143578. 0,
  143579. 20,
  143580. };
  143581. static long _vq_lengthlist__16u0__p7_2[] = {
  143582. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143583. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143584. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143585. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143586. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143587. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143588. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143589. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143590. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143591. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143592. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143593. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143594. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143595. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143596. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143597. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143598. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143599. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143600. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143601. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143602. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143603. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143604. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143605. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143606. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143607. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143608. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143609. 10,10,12,11,10,11,11,11,10,
  143610. };
  143611. static float _vq_quantthresh__16u0__p7_2[] = {
  143612. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143613. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143614. 6.5, 7.5, 8.5, 9.5,
  143615. };
  143616. static long _vq_quantmap__16u0__p7_2[] = {
  143617. 19, 17, 15, 13, 11, 9, 7, 5,
  143618. 3, 1, 0, 2, 4, 6, 8, 10,
  143619. 12, 14, 16, 18, 20,
  143620. };
  143621. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143622. _vq_quantthresh__16u0__p7_2,
  143623. _vq_quantmap__16u0__p7_2,
  143624. 21,
  143625. 21
  143626. };
  143627. static static_codebook _16u0__p7_2 = {
  143628. 2, 441,
  143629. _vq_lengthlist__16u0__p7_2,
  143630. 1, -529268736, 1611661312, 5, 0,
  143631. _vq_quantlist__16u0__p7_2,
  143632. NULL,
  143633. &_vq_auxt__16u0__p7_2,
  143634. NULL,
  143635. 0
  143636. };
  143637. static long _huff_lengthlist__16u0__single[] = {
  143638. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143639. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143640. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143641. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143642. };
  143643. static static_codebook _huff_book__16u0__single = {
  143644. 2, 64,
  143645. _huff_lengthlist__16u0__single,
  143646. 0, 0, 0, 0, 0,
  143647. NULL,
  143648. NULL,
  143649. NULL,
  143650. NULL,
  143651. 0
  143652. };
  143653. static long _huff_lengthlist__16u1__long[] = {
  143654. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143655. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143656. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143657. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143658. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143659. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143660. 16,13,16,18,
  143661. };
  143662. static static_codebook _huff_book__16u1__long = {
  143663. 2, 100,
  143664. _huff_lengthlist__16u1__long,
  143665. 0, 0, 0, 0, 0,
  143666. NULL,
  143667. NULL,
  143668. NULL,
  143669. NULL,
  143670. 0
  143671. };
  143672. static long _vq_quantlist__16u1__p1_0[] = {
  143673. 1,
  143674. 0,
  143675. 2,
  143676. };
  143677. static long _vq_lengthlist__16u1__p1_0[] = {
  143678. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143679. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143680. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143681. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143682. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143683. 11,
  143684. };
  143685. static float _vq_quantthresh__16u1__p1_0[] = {
  143686. -0.5, 0.5,
  143687. };
  143688. static long _vq_quantmap__16u1__p1_0[] = {
  143689. 1, 0, 2,
  143690. };
  143691. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143692. _vq_quantthresh__16u1__p1_0,
  143693. _vq_quantmap__16u1__p1_0,
  143694. 3,
  143695. 3
  143696. };
  143697. static static_codebook _16u1__p1_0 = {
  143698. 4, 81,
  143699. _vq_lengthlist__16u1__p1_0,
  143700. 1, -535822336, 1611661312, 2, 0,
  143701. _vq_quantlist__16u1__p1_0,
  143702. NULL,
  143703. &_vq_auxt__16u1__p1_0,
  143704. NULL,
  143705. 0
  143706. };
  143707. static long _vq_quantlist__16u1__p2_0[] = {
  143708. 1,
  143709. 0,
  143710. 2,
  143711. };
  143712. static long _vq_lengthlist__16u1__p2_0[] = {
  143713. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143714. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143715. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143716. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143717. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143718. 8,
  143719. };
  143720. static float _vq_quantthresh__16u1__p2_0[] = {
  143721. -0.5, 0.5,
  143722. };
  143723. static long _vq_quantmap__16u1__p2_0[] = {
  143724. 1, 0, 2,
  143725. };
  143726. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143727. _vq_quantthresh__16u1__p2_0,
  143728. _vq_quantmap__16u1__p2_0,
  143729. 3,
  143730. 3
  143731. };
  143732. static static_codebook _16u1__p2_0 = {
  143733. 4, 81,
  143734. _vq_lengthlist__16u1__p2_0,
  143735. 1, -535822336, 1611661312, 2, 0,
  143736. _vq_quantlist__16u1__p2_0,
  143737. NULL,
  143738. &_vq_auxt__16u1__p2_0,
  143739. NULL,
  143740. 0
  143741. };
  143742. static long _vq_quantlist__16u1__p3_0[] = {
  143743. 2,
  143744. 1,
  143745. 3,
  143746. 0,
  143747. 4,
  143748. };
  143749. static long _vq_lengthlist__16u1__p3_0[] = {
  143750. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143751. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143752. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143753. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143754. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143755. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143756. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143757. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143758. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143759. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143760. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143761. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143762. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143763. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143764. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143765. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143766. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143767. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143768. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143769. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143770. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143771. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143772. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143773. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143774. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143775. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143776. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143777. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143778. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143779. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143780. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143781. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143782. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143783. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143784. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143785. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143786. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143787. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143788. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143789. 16,
  143790. };
  143791. static float _vq_quantthresh__16u1__p3_0[] = {
  143792. -1.5, -0.5, 0.5, 1.5,
  143793. };
  143794. static long _vq_quantmap__16u1__p3_0[] = {
  143795. 3, 1, 0, 2, 4,
  143796. };
  143797. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143798. _vq_quantthresh__16u1__p3_0,
  143799. _vq_quantmap__16u1__p3_0,
  143800. 5,
  143801. 5
  143802. };
  143803. static static_codebook _16u1__p3_0 = {
  143804. 4, 625,
  143805. _vq_lengthlist__16u1__p3_0,
  143806. 1, -533725184, 1611661312, 3, 0,
  143807. _vq_quantlist__16u1__p3_0,
  143808. NULL,
  143809. &_vq_auxt__16u1__p3_0,
  143810. NULL,
  143811. 0
  143812. };
  143813. static long _vq_quantlist__16u1__p4_0[] = {
  143814. 2,
  143815. 1,
  143816. 3,
  143817. 0,
  143818. 4,
  143819. };
  143820. static long _vq_lengthlist__16u1__p4_0[] = {
  143821. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143822. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143823. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143824. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143825. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143826. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143827. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143828. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143829. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143830. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143831. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143832. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143833. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143834. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143835. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143836. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143837. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143838. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143839. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143840. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143841. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143842. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143843. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143844. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143845. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143846. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143847. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143848. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143849. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143850. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143851. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143852. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143853. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143854. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143855. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143856. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143857. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143858. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143859. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143860. 11,
  143861. };
  143862. static float _vq_quantthresh__16u1__p4_0[] = {
  143863. -1.5, -0.5, 0.5, 1.5,
  143864. };
  143865. static long _vq_quantmap__16u1__p4_0[] = {
  143866. 3, 1, 0, 2, 4,
  143867. };
  143868. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143869. _vq_quantthresh__16u1__p4_0,
  143870. _vq_quantmap__16u1__p4_0,
  143871. 5,
  143872. 5
  143873. };
  143874. static static_codebook _16u1__p4_0 = {
  143875. 4, 625,
  143876. _vq_lengthlist__16u1__p4_0,
  143877. 1, -533725184, 1611661312, 3, 0,
  143878. _vq_quantlist__16u1__p4_0,
  143879. NULL,
  143880. &_vq_auxt__16u1__p4_0,
  143881. NULL,
  143882. 0
  143883. };
  143884. static long _vq_quantlist__16u1__p5_0[] = {
  143885. 4,
  143886. 3,
  143887. 5,
  143888. 2,
  143889. 6,
  143890. 1,
  143891. 7,
  143892. 0,
  143893. 8,
  143894. };
  143895. static long _vq_lengthlist__16u1__p5_0[] = {
  143896. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143897. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143898. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143899. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143900. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143901. 13,
  143902. };
  143903. static float _vq_quantthresh__16u1__p5_0[] = {
  143904. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143905. };
  143906. static long _vq_quantmap__16u1__p5_0[] = {
  143907. 7, 5, 3, 1, 0, 2, 4, 6,
  143908. 8,
  143909. };
  143910. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143911. _vq_quantthresh__16u1__p5_0,
  143912. _vq_quantmap__16u1__p5_0,
  143913. 9,
  143914. 9
  143915. };
  143916. static static_codebook _16u1__p5_0 = {
  143917. 2, 81,
  143918. _vq_lengthlist__16u1__p5_0,
  143919. 1, -531628032, 1611661312, 4, 0,
  143920. _vq_quantlist__16u1__p5_0,
  143921. NULL,
  143922. &_vq_auxt__16u1__p5_0,
  143923. NULL,
  143924. 0
  143925. };
  143926. static long _vq_quantlist__16u1__p6_0[] = {
  143927. 4,
  143928. 3,
  143929. 5,
  143930. 2,
  143931. 6,
  143932. 1,
  143933. 7,
  143934. 0,
  143935. 8,
  143936. };
  143937. static long _vq_lengthlist__16u1__p6_0[] = {
  143938. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143939. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143940. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143941. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143942. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143943. 11,
  143944. };
  143945. static float _vq_quantthresh__16u1__p6_0[] = {
  143946. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143947. };
  143948. static long _vq_quantmap__16u1__p6_0[] = {
  143949. 7, 5, 3, 1, 0, 2, 4, 6,
  143950. 8,
  143951. };
  143952. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143953. _vq_quantthresh__16u1__p6_0,
  143954. _vq_quantmap__16u1__p6_0,
  143955. 9,
  143956. 9
  143957. };
  143958. static static_codebook _16u1__p6_0 = {
  143959. 2, 81,
  143960. _vq_lengthlist__16u1__p6_0,
  143961. 1, -531628032, 1611661312, 4, 0,
  143962. _vq_quantlist__16u1__p6_0,
  143963. NULL,
  143964. &_vq_auxt__16u1__p6_0,
  143965. NULL,
  143966. 0
  143967. };
  143968. static long _vq_quantlist__16u1__p7_0[] = {
  143969. 1,
  143970. 0,
  143971. 2,
  143972. };
  143973. static long _vq_lengthlist__16u1__p7_0[] = {
  143974. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143975. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143976. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143977. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143978. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143979. 13,
  143980. };
  143981. static float _vq_quantthresh__16u1__p7_0[] = {
  143982. -5.5, 5.5,
  143983. };
  143984. static long _vq_quantmap__16u1__p7_0[] = {
  143985. 1, 0, 2,
  143986. };
  143987. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143988. _vq_quantthresh__16u1__p7_0,
  143989. _vq_quantmap__16u1__p7_0,
  143990. 3,
  143991. 3
  143992. };
  143993. static static_codebook _16u1__p7_0 = {
  143994. 4, 81,
  143995. _vq_lengthlist__16u1__p7_0,
  143996. 1, -529137664, 1618345984, 2, 0,
  143997. _vq_quantlist__16u1__p7_0,
  143998. NULL,
  143999. &_vq_auxt__16u1__p7_0,
  144000. NULL,
  144001. 0
  144002. };
  144003. static long _vq_quantlist__16u1__p7_1[] = {
  144004. 5,
  144005. 4,
  144006. 6,
  144007. 3,
  144008. 7,
  144009. 2,
  144010. 8,
  144011. 1,
  144012. 9,
  144013. 0,
  144014. 10,
  144015. };
  144016. static long _vq_lengthlist__16u1__p7_1[] = {
  144017. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  144018. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  144019. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144020. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  144021. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  144022. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  144023. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  144024. 8, 9, 9,10,10,10,10,10,10,
  144025. };
  144026. static float _vq_quantthresh__16u1__p7_1[] = {
  144027. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144028. 3.5, 4.5,
  144029. };
  144030. static long _vq_quantmap__16u1__p7_1[] = {
  144031. 9, 7, 5, 3, 1, 0, 2, 4,
  144032. 6, 8, 10,
  144033. };
  144034. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  144035. _vq_quantthresh__16u1__p7_1,
  144036. _vq_quantmap__16u1__p7_1,
  144037. 11,
  144038. 11
  144039. };
  144040. static static_codebook _16u1__p7_1 = {
  144041. 2, 121,
  144042. _vq_lengthlist__16u1__p7_1,
  144043. 1, -531365888, 1611661312, 4, 0,
  144044. _vq_quantlist__16u1__p7_1,
  144045. NULL,
  144046. &_vq_auxt__16u1__p7_1,
  144047. NULL,
  144048. 0
  144049. };
  144050. static long _vq_quantlist__16u1__p8_0[] = {
  144051. 5,
  144052. 4,
  144053. 6,
  144054. 3,
  144055. 7,
  144056. 2,
  144057. 8,
  144058. 1,
  144059. 9,
  144060. 0,
  144061. 10,
  144062. };
  144063. static long _vq_lengthlist__16u1__p8_0[] = {
  144064. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  144065. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  144066. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  144067. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  144068. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  144069. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  144070. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  144071. 13,14,14,15,15,16,16,15,16,
  144072. };
  144073. static float _vq_quantthresh__16u1__p8_0[] = {
  144074. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144075. 38.5, 49.5,
  144076. };
  144077. static long _vq_quantmap__16u1__p8_0[] = {
  144078. 9, 7, 5, 3, 1, 0, 2, 4,
  144079. 6, 8, 10,
  144080. };
  144081. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  144082. _vq_quantthresh__16u1__p8_0,
  144083. _vq_quantmap__16u1__p8_0,
  144084. 11,
  144085. 11
  144086. };
  144087. static static_codebook _16u1__p8_0 = {
  144088. 2, 121,
  144089. _vq_lengthlist__16u1__p8_0,
  144090. 1, -524582912, 1618345984, 4, 0,
  144091. _vq_quantlist__16u1__p8_0,
  144092. NULL,
  144093. &_vq_auxt__16u1__p8_0,
  144094. NULL,
  144095. 0
  144096. };
  144097. static long _vq_quantlist__16u1__p8_1[] = {
  144098. 5,
  144099. 4,
  144100. 6,
  144101. 3,
  144102. 7,
  144103. 2,
  144104. 8,
  144105. 1,
  144106. 9,
  144107. 0,
  144108. 10,
  144109. };
  144110. static long _vq_lengthlist__16u1__p8_1[] = {
  144111. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  144112. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  144113. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  144114. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144115. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144116. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144117. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144118. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144119. };
  144120. static float _vq_quantthresh__16u1__p8_1[] = {
  144121. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144122. 3.5, 4.5,
  144123. };
  144124. static long _vq_quantmap__16u1__p8_1[] = {
  144125. 9, 7, 5, 3, 1, 0, 2, 4,
  144126. 6, 8, 10,
  144127. };
  144128. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  144129. _vq_quantthresh__16u1__p8_1,
  144130. _vq_quantmap__16u1__p8_1,
  144131. 11,
  144132. 11
  144133. };
  144134. static static_codebook _16u1__p8_1 = {
  144135. 2, 121,
  144136. _vq_lengthlist__16u1__p8_1,
  144137. 1, -531365888, 1611661312, 4, 0,
  144138. _vq_quantlist__16u1__p8_1,
  144139. NULL,
  144140. &_vq_auxt__16u1__p8_1,
  144141. NULL,
  144142. 0
  144143. };
  144144. static long _vq_quantlist__16u1__p9_0[] = {
  144145. 7,
  144146. 6,
  144147. 8,
  144148. 5,
  144149. 9,
  144150. 4,
  144151. 10,
  144152. 3,
  144153. 11,
  144154. 2,
  144155. 12,
  144156. 1,
  144157. 13,
  144158. 0,
  144159. 14,
  144160. };
  144161. static long _vq_lengthlist__16u1__p9_0[] = {
  144162. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144163. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144164. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144165. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144166. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144167. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144168. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144169. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144170. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144171. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144172. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144173. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144174. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144175. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144176. 8,
  144177. };
  144178. static float _vq_quantthresh__16u1__p9_0[] = {
  144179. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144180. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144181. };
  144182. static long _vq_quantmap__16u1__p9_0[] = {
  144183. 13, 11, 9, 7, 5, 3, 1, 0,
  144184. 2, 4, 6, 8, 10, 12, 14,
  144185. };
  144186. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  144187. _vq_quantthresh__16u1__p9_0,
  144188. _vq_quantmap__16u1__p9_0,
  144189. 15,
  144190. 15
  144191. };
  144192. static static_codebook _16u1__p9_0 = {
  144193. 2, 225,
  144194. _vq_lengthlist__16u1__p9_0,
  144195. 1, -514071552, 1627381760, 4, 0,
  144196. _vq_quantlist__16u1__p9_0,
  144197. NULL,
  144198. &_vq_auxt__16u1__p9_0,
  144199. NULL,
  144200. 0
  144201. };
  144202. static long _vq_quantlist__16u1__p9_1[] = {
  144203. 7,
  144204. 6,
  144205. 8,
  144206. 5,
  144207. 9,
  144208. 4,
  144209. 10,
  144210. 3,
  144211. 11,
  144212. 2,
  144213. 12,
  144214. 1,
  144215. 13,
  144216. 0,
  144217. 14,
  144218. };
  144219. static long _vq_lengthlist__16u1__p9_1[] = {
  144220. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144221. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144222. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144223. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144224. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144225. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144226. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144227. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144228. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144229. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144230. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144231. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144232. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144233. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144234. 9,
  144235. };
  144236. static float _vq_quantthresh__16u1__p9_1[] = {
  144237. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144238. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144239. };
  144240. static long _vq_quantmap__16u1__p9_1[] = {
  144241. 13, 11, 9, 7, 5, 3, 1, 0,
  144242. 2, 4, 6, 8, 10, 12, 14,
  144243. };
  144244. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144245. _vq_quantthresh__16u1__p9_1,
  144246. _vq_quantmap__16u1__p9_1,
  144247. 15,
  144248. 15
  144249. };
  144250. static static_codebook _16u1__p9_1 = {
  144251. 2, 225,
  144252. _vq_lengthlist__16u1__p9_1,
  144253. 1, -522338304, 1620115456, 4, 0,
  144254. _vq_quantlist__16u1__p9_1,
  144255. NULL,
  144256. &_vq_auxt__16u1__p9_1,
  144257. NULL,
  144258. 0
  144259. };
  144260. static long _vq_quantlist__16u1__p9_2[] = {
  144261. 8,
  144262. 7,
  144263. 9,
  144264. 6,
  144265. 10,
  144266. 5,
  144267. 11,
  144268. 4,
  144269. 12,
  144270. 3,
  144271. 13,
  144272. 2,
  144273. 14,
  144274. 1,
  144275. 15,
  144276. 0,
  144277. 16,
  144278. };
  144279. static long _vq_lengthlist__16u1__p9_2[] = {
  144280. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144281. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144282. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144283. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144284. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144285. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144286. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144287. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144288. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144289. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144290. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144291. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144292. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144293. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144294. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144295. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144296. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144297. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144298. 10,
  144299. };
  144300. static float _vq_quantthresh__16u1__p9_2[] = {
  144301. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144302. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144303. };
  144304. static long _vq_quantmap__16u1__p9_2[] = {
  144305. 15, 13, 11, 9, 7, 5, 3, 1,
  144306. 0, 2, 4, 6, 8, 10, 12, 14,
  144307. 16,
  144308. };
  144309. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144310. _vq_quantthresh__16u1__p9_2,
  144311. _vq_quantmap__16u1__p9_2,
  144312. 17,
  144313. 17
  144314. };
  144315. static static_codebook _16u1__p9_2 = {
  144316. 2, 289,
  144317. _vq_lengthlist__16u1__p9_2,
  144318. 1, -529530880, 1611661312, 5, 0,
  144319. _vq_quantlist__16u1__p9_2,
  144320. NULL,
  144321. &_vq_auxt__16u1__p9_2,
  144322. NULL,
  144323. 0
  144324. };
  144325. static long _huff_lengthlist__16u1__short[] = {
  144326. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144327. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144328. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144329. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144330. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144331. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144332. 16,16,16,16,
  144333. };
  144334. static static_codebook _huff_book__16u1__short = {
  144335. 2, 100,
  144336. _huff_lengthlist__16u1__short,
  144337. 0, 0, 0, 0, 0,
  144338. NULL,
  144339. NULL,
  144340. NULL,
  144341. NULL,
  144342. 0
  144343. };
  144344. static long _huff_lengthlist__16u2__long[] = {
  144345. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144346. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144347. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144348. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144349. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144350. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144351. 13,14,18,18,
  144352. };
  144353. static static_codebook _huff_book__16u2__long = {
  144354. 2, 100,
  144355. _huff_lengthlist__16u2__long,
  144356. 0, 0, 0, 0, 0,
  144357. NULL,
  144358. NULL,
  144359. NULL,
  144360. NULL,
  144361. 0
  144362. };
  144363. static long _huff_lengthlist__16u2__short[] = {
  144364. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144365. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144366. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144367. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144368. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144369. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144370. 16,16,16,16,
  144371. };
  144372. static static_codebook _huff_book__16u2__short = {
  144373. 2, 100,
  144374. _huff_lengthlist__16u2__short,
  144375. 0, 0, 0, 0, 0,
  144376. NULL,
  144377. NULL,
  144378. NULL,
  144379. NULL,
  144380. 0
  144381. };
  144382. static long _vq_quantlist__16u2_p1_0[] = {
  144383. 1,
  144384. 0,
  144385. 2,
  144386. };
  144387. static long _vq_lengthlist__16u2_p1_0[] = {
  144388. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144389. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144390. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144391. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144392. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144393. 10,
  144394. };
  144395. static float _vq_quantthresh__16u2_p1_0[] = {
  144396. -0.5, 0.5,
  144397. };
  144398. static long _vq_quantmap__16u2_p1_0[] = {
  144399. 1, 0, 2,
  144400. };
  144401. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144402. _vq_quantthresh__16u2_p1_0,
  144403. _vq_quantmap__16u2_p1_0,
  144404. 3,
  144405. 3
  144406. };
  144407. static static_codebook _16u2_p1_0 = {
  144408. 4, 81,
  144409. _vq_lengthlist__16u2_p1_0,
  144410. 1, -535822336, 1611661312, 2, 0,
  144411. _vq_quantlist__16u2_p1_0,
  144412. NULL,
  144413. &_vq_auxt__16u2_p1_0,
  144414. NULL,
  144415. 0
  144416. };
  144417. static long _vq_quantlist__16u2_p2_0[] = {
  144418. 2,
  144419. 1,
  144420. 3,
  144421. 0,
  144422. 4,
  144423. };
  144424. static long _vq_lengthlist__16u2_p2_0[] = {
  144425. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144426. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144427. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144428. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144429. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144430. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144431. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144432. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144433. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144434. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144435. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144436. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144437. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144438. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144439. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144440. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144441. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144442. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144443. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144444. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144445. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144446. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144447. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144448. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144449. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144450. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144451. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144452. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144453. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144454. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144455. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144456. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144457. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144458. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144459. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144460. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144461. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144462. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144463. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144464. 13,
  144465. };
  144466. static float _vq_quantthresh__16u2_p2_0[] = {
  144467. -1.5, -0.5, 0.5, 1.5,
  144468. };
  144469. static long _vq_quantmap__16u2_p2_0[] = {
  144470. 3, 1, 0, 2, 4,
  144471. };
  144472. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144473. _vq_quantthresh__16u2_p2_0,
  144474. _vq_quantmap__16u2_p2_0,
  144475. 5,
  144476. 5
  144477. };
  144478. static static_codebook _16u2_p2_0 = {
  144479. 4, 625,
  144480. _vq_lengthlist__16u2_p2_0,
  144481. 1, -533725184, 1611661312, 3, 0,
  144482. _vq_quantlist__16u2_p2_0,
  144483. NULL,
  144484. &_vq_auxt__16u2_p2_0,
  144485. NULL,
  144486. 0
  144487. };
  144488. static long _vq_quantlist__16u2_p3_0[] = {
  144489. 4,
  144490. 3,
  144491. 5,
  144492. 2,
  144493. 6,
  144494. 1,
  144495. 7,
  144496. 0,
  144497. 8,
  144498. };
  144499. static long _vq_lengthlist__16u2_p3_0[] = {
  144500. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144501. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144502. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144503. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144504. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144505. 11,
  144506. };
  144507. static float _vq_quantthresh__16u2_p3_0[] = {
  144508. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144509. };
  144510. static long _vq_quantmap__16u2_p3_0[] = {
  144511. 7, 5, 3, 1, 0, 2, 4, 6,
  144512. 8,
  144513. };
  144514. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144515. _vq_quantthresh__16u2_p3_0,
  144516. _vq_quantmap__16u2_p3_0,
  144517. 9,
  144518. 9
  144519. };
  144520. static static_codebook _16u2_p3_0 = {
  144521. 2, 81,
  144522. _vq_lengthlist__16u2_p3_0,
  144523. 1, -531628032, 1611661312, 4, 0,
  144524. _vq_quantlist__16u2_p3_0,
  144525. NULL,
  144526. &_vq_auxt__16u2_p3_0,
  144527. NULL,
  144528. 0
  144529. };
  144530. static long _vq_quantlist__16u2_p4_0[] = {
  144531. 8,
  144532. 7,
  144533. 9,
  144534. 6,
  144535. 10,
  144536. 5,
  144537. 11,
  144538. 4,
  144539. 12,
  144540. 3,
  144541. 13,
  144542. 2,
  144543. 14,
  144544. 1,
  144545. 15,
  144546. 0,
  144547. 16,
  144548. };
  144549. static long _vq_lengthlist__16u2_p4_0[] = {
  144550. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144551. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144552. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144553. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144554. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144555. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144556. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144557. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144558. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144559. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144560. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144561. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144562. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144563. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144564. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144565. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144566. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144567. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144568. 14,
  144569. };
  144570. static float _vq_quantthresh__16u2_p4_0[] = {
  144571. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144572. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144573. };
  144574. static long _vq_quantmap__16u2_p4_0[] = {
  144575. 15, 13, 11, 9, 7, 5, 3, 1,
  144576. 0, 2, 4, 6, 8, 10, 12, 14,
  144577. 16,
  144578. };
  144579. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144580. _vq_quantthresh__16u2_p4_0,
  144581. _vq_quantmap__16u2_p4_0,
  144582. 17,
  144583. 17
  144584. };
  144585. static static_codebook _16u2_p4_0 = {
  144586. 2, 289,
  144587. _vq_lengthlist__16u2_p4_0,
  144588. 1, -529530880, 1611661312, 5, 0,
  144589. _vq_quantlist__16u2_p4_0,
  144590. NULL,
  144591. &_vq_auxt__16u2_p4_0,
  144592. NULL,
  144593. 0
  144594. };
  144595. static long _vq_quantlist__16u2_p5_0[] = {
  144596. 1,
  144597. 0,
  144598. 2,
  144599. };
  144600. static long _vq_lengthlist__16u2_p5_0[] = {
  144601. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144602. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144603. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144604. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144605. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144606. 10,
  144607. };
  144608. static float _vq_quantthresh__16u2_p5_0[] = {
  144609. -5.5, 5.5,
  144610. };
  144611. static long _vq_quantmap__16u2_p5_0[] = {
  144612. 1, 0, 2,
  144613. };
  144614. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144615. _vq_quantthresh__16u2_p5_0,
  144616. _vq_quantmap__16u2_p5_0,
  144617. 3,
  144618. 3
  144619. };
  144620. static static_codebook _16u2_p5_0 = {
  144621. 4, 81,
  144622. _vq_lengthlist__16u2_p5_0,
  144623. 1, -529137664, 1618345984, 2, 0,
  144624. _vq_quantlist__16u2_p5_0,
  144625. NULL,
  144626. &_vq_auxt__16u2_p5_0,
  144627. NULL,
  144628. 0
  144629. };
  144630. static long _vq_quantlist__16u2_p5_1[] = {
  144631. 5,
  144632. 4,
  144633. 6,
  144634. 3,
  144635. 7,
  144636. 2,
  144637. 8,
  144638. 1,
  144639. 9,
  144640. 0,
  144641. 10,
  144642. };
  144643. static long _vq_lengthlist__16u2_p5_1[] = {
  144644. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144645. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144646. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144647. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144648. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144649. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144650. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144651. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144652. };
  144653. static float _vq_quantthresh__16u2_p5_1[] = {
  144654. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144655. 3.5, 4.5,
  144656. };
  144657. static long _vq_quantmap__16u2_p5_1[] = {
  144658. 9, 7, 5, 3, 1, 0, 2, 4,
  144659. 6, 8, 10,
  144660. };
  144661. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144662. _vq_quantthresh__16u2_p5_1,
  144663. _vq_quantmap__16u2_p5_1,
  144664. 11,
  144665. 11
  144666. };
  144667. static static_codebook _16u2_p5_1 = {
  144668. 2, 121,
  144669. _vq_lengthlist__16u2_p5_1,
  144670. 1, -531365888, 1611661312, 4, 0,
  144671. _vq_quantlist__16u2_p5_1,
  144672. NULL,
  144673. &_vq_auxt__16u2_p5_1,
  144674. NULL,
  144675. 0
  144676. };
  144677. static long _vq_quantlist__16u2_p6_0[] = {
  144678. 6,
  144679. 5,
  144680. 7,
  144681. 4,
  144682. 8,
  144683. 3,
  144684. 9,
  144685. 2,
  144686. 10,
  144687. 1,
  144688. 11,
  144689. 0,
  144690. 12,
  144691. };
  144692. static long _vq_lengthlist__16u2_p6_0[] = {
  144693. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144694. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144695. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144696. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144697. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144698. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144699. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144700. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144701. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144702. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144703. 12,13,13,14,14,14,14,15,15,
  144704. };
  144705. static float _vq_quantthresh__16u2_p6_0[] = {
  144706. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144707. 12.5, 17.5, 22.5, 27.5,
  144708. };
  144709. static long _vq_quantmap__16u2_p6_0[] = {
  144710. 11, 9, 7, 5, 3, 1, 0, 2,
  144711. 4, 6, 8, 10, 12,
  144712. };
  144713. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144714. _vq_quantthresh__16u2_p6_0,
  144715. _vq_quantmap__16u2_p6_0,
  144716. 13,
  144717. 13
  144718. };
  144719. static static_codebook _16u2_p6_0 = {
  144720. 2, 169,
  144721. _vq_lengthlist__16u2_p6_0,
  144722. 1, -526516224, 1616117760, 4, 0,
  144723. _vq_quantlist__16u2_p6_0,
  144724. NULL,
  144725. &_vq_auxt__16u2_p6_0,
  144726. NULL,
  144727. 0
  144728. };
  144729. static long _vq_quantlist__16u2_p6_1[] = {
  144730. 2,
  144731. 1,
  144732. 3,
  144733. 0,
  144734. 4,
  144735. };
  144736. static long _vq_lengthlist__16u2_p6_1[] = {
  144737. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144738. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144739. };
  144740. static float _vq_quantthresh__16u2_p6_1[] = {
  144741. -1.5, -0.5, 0.5, 1.5,
  144742. };
  144743. static long _vq_quantmap__16u2_p6_1[] = {
  144744. 3, 1, 0, 2, 4,
  144745. };
  144746. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144747. _vq_quantthresh__16u2_p6_1,
  144748. _vq_quantmap__16u2_p6_1,
  144749. 5,
  144750. 5
  144751. };
  144752. static static_codebook _16u2_p6_1 = {
  144753. 2, 25,
  144754. _vq_lengthlist__16u2_p6_1,
  144755. 1, -533725184, 1611661312, 3, 0,
  144756. _vq_quantlist__16u2_p6_1,
  144757. NULL,
  144758. &_vq_auxt__16u2_p6_1,
  144759. NULL,
  144760. 0
  144761. };
  144762. static long _vq_quantlist__16u2_p7_0[] = {
  144763. 6,
  144764. 5,
  144765. 7,
  144766. 4,
  144767. 8,
  144768. 3,
  144769. 9,
  144770. 2,
  144771. 10,
  144772. 1,
  144773. 11,
  144774. 0,
  144775. 12,
  144776. };
  144777. static long _vq_lengthlist__16u2_p7_0[] = {
  144778. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144779. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144780. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144781. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144782. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144783. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144784. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144785. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144786. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144787. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144788. 12,13,13,13,14,14,14,15,14,
  144789. };
  144790. static float _vq_quantthresh__16u2_p7_0[] = {
  144791. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144792. 27.5, 38.5, 49.5, 60.5,
  144793. };
  144794. static long _vq_quantmap__16u2_p7_0[] = {
  144795. 11, 9, 7, 5, 3, 1, 0, 2,
  144796. 4, 6, 8, 10, 12,
  144797. };
  144798. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144799. _vq_quantthresh__16u2_p7_0,
  144800. _vq_quantmap__16u2_p7_0,
  144801. 13,
  144802. 13
  144803. };
  144804. static static_codebook _16u2_p7_0 = {
  144805. 2, 169,
  144806. _vq_lengthlist__16u2_p7_0,
  144807. 1, -523206656, 1618345984, 4, 0,
  144808. _vq_quantlist__16u2_p7_0,
  144809. NULL,
  144810. &_vq_auxt__16u2_p7_0,
  144811. NULL,
  144812. 0
  144813. };
  144814. static long _vq_quantlist__16u2_p7_1[] = {
  144815. 5,
  144816. 4,
  144817. 6,
  144818. 3,
  144819. 7,
  144820. 2,
  144821. 8,
  144822. 1,
  144823. 9,
  144824. 0,
  144825. 10,
  144826. };
  144827. static long _vq_lengthlist__16u2_p7_1[] = {
  144828. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144829. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144830. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144831. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144832. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144833. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144834. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144835. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144836. };
  144837. static float _vq_quantthresh__16u2_p7_1[] = {
  144838. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144839. 3.5, 4.5,
  144840. };
  144841. static long _vq_quantmap__16u2_p7_1[] = {
  144842. 9, 7, 5, 3, 1, 0, 2, 4,
  144843. 6, 8, 10,
  144844. };
  144845. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144846. _vq_quantthresh__16u2_p7_1,
  144847. _vq_quantmap__16u2_p7_1,
  144848. 11,
  144849. 11
  144850. };
  144851. static static_codebook _16u2_p7_1 = {
  144852. 2, 121,
  144853. _vq_lengthlist__16u2_p7_1,
  144854. 1, -531365888, 1611661312, 4, 0,
  144855. _vq_quantlist__16u2_p7_1,
  144856. NULL,
  144857. &_vq_auxt__16u2_p7_1,
  144858. NULL,
  144859. 0
  144860. };
  144861. static long _vq_quantlist__16u2_p8_0[] = {
  144862. 7,
  144863. 6,
  144864. 8,
  144865. 5,
  144866. 9,
  144867. 4,
  144868. 10,
  144869. 3,
  144870. 11,
  144871. 2,
  144872. 12,
  144873. 1,
  144874. 13,
  144875. 0,
  144876. 14,
  144877. };
  144878. static long _vq_lengthlist__16u2_p8_0[] = {
  144879. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144880. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144881. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144882. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144883. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144884. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144885. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144886. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144887. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144888. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144889. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144890. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144891. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144892. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144893. 14,
  144894. };
  144895. static float _vq_quantthresh__16u2_p8_0[] = {
  144896. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144897. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144898. };
  144899. static long _vq_quantmap__16u2_p8_0[] = {
  144900. 13, 11, 9, 7, 5, 3, 1, 0,
  144901. 2, 4, 6, 8, 10, 12, 14,
  144902. };
  144903. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144904. _vq_quantthresh__16u2_p8_0,
  144905. _vq_quantmap__16u2_p8_0,
  144906. 15,
  144907. 15
  144908. };
  144909. static static_codebook _16u2_p8_0 = {
  144910. 2, 225,
  144911. _vq_lengthlist__16u2_p8_0,
  144912. 1, -520986624, 1620377600, 4, 0,
  144913. _vq_quantlist__16u2_p8_0,
  144914. NULL,
  144915. &_vq_auxt__16u2_p8_0,
  144916. NULL,
  144917. 0
  144918. };
  144919. static long _vq_quantlist__16u2_p8_1[] = {
  144920. 10,
  144921. 9,
  144922. 11,
  144923. 8,
  144924. 12,
  144925. 7,
  144926. 13,
  144927. 6,
  144928. 14,
  144929. 5,
  144930. 15,
  144931. 4,
  144932. 16,
  144933. 3,
  144934. 17,
  144935. 2,
  144936. 18,
  144937. 1,
  144938. 19,
  144939. 0,
  144940. 20,
  144941. };
  144942. static long _vq_lengthlist__16u2_p8_1[] = {
  144943. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144944. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144945. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144946. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144947. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144948. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144949. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144950. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144951. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144952. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144953. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144954. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144955. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144956. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144957. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144958. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144959. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144960. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144961. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144962. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144963. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144964. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144965. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144966. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144967. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144968. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144969. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144970. 11,11,10,11,11,11,10,11,11,
  144971. };
  144972. static float _vq_quantthresh__16u2_p8_1[] = {
  144973. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144974. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144975. 6.5, 7.5, 8.5, 9.5,
  144976. };
  144977. static long _vq_quantmap__16u2_p8_1[] = {
  144978. 19, 17, 15, 13, 11, 9, 7, 5,
  144979. 3, 1, 0, 2, 4, 6, 8, 10,
  144980. 12, 14, 16, 18, 20,
  144981. };
  144982. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144983. _vq_quantthresh__16u2_p8_1,
  144984. _vq_quantmap__16u2_p8_1,
  144985. 21,
  144986. 21
  144987. };
  144988. static static_codebook _16u2_p8_1 = {
  144989. 2, 441,
  144990. _vq_lengthlist__16u2_p8_1,
  144991. 1, -529268736, 1611661312, 5, 0,
  144992. _vq_quantlist__16u2_p8_1,
  144993. NULL,
  144994. &_vq_auxt__16u2_p8_1,
  144995. NULL,
  144996. 0
  144997. };
  144998. static long _vq_quantlist__16u2_p9_0[] = {
  144999. 5586,
  145000. 4655,
  145001. 6517,
  145002. 3724,
  145003. 7448,
  145004. 2793,
  145005. 8379,
  145006. 1862,
  145007. 9310,
  145008. 931,
  145009. 10241,
  145010. 0,
  145011. 11172,
  145012. 5521,
  145013. 5651,
  145014. };
  145015. static long _vq_lengthlist__16u2_p9_0[] = {
  145016. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  145017. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145018. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145019. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145020. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145021. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145022. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145023. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145024. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145025. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145026. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145027. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145028. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  145029. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  145030. 5,
  145031. };
  145032. static float _vq_quantthresh__16u2_p9_0[] = {
  145033. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  145034. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  145035. };
  145036. static long _vq_quantmap__16u2_p9_0[] = {
  145037. 11, 9, 7, 5, 3, 1, 13, 0,
  145038. 14, 2, 4, 6, 8, 10, 12,
  145039. };
  145040. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  145041. _vq_quantthresh__16u2_p9_0,
  145042. _vq_quantmap__16u2_p9_0,
  145043. 15,
  145044. 15
  145045. };
  145046. static static_codebook _16u2_p9_0 = {
  145047. 2, 225,
  145048. _vq_lengthlist__16u2_p9_0,
  145049. 1, -510275072, 1611661312, 14, 0,
  145050. _vq_quantlist__16u2_p9_0,
  145051. NULL,
  145052. &_vq_auxt__16u2_p9_0,
  145053. NULL,
  145054. 0
  145055. };
  145056. static long _vq_quantlist__16u2_p9_1[] = {
  145057. 392,
  145058. 343,
  145059. 441,
  145060. 294,
  145061. 490,
  145062. 245,
  145063. 539,
  145064. 196,
  145065. 588,
  145066. 147,
  145067. 637,
  145068. 98,
  145069. 686,
  145070. 49,
  145071. 735,
  145072. 0,
  145073. 784,
  145074. 388,
  145075. 396,
  145076. };
  145077. static long _vq_lengthlist__16u2_p9_1[] = {
  145078. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  145079. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  145080. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  145081. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  145082. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  145083. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  145084. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145085. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  145086. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  145087. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145088. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145089. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145090. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145091. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145092. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  145093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145094. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145096. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145097. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145098. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  145099. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  145100. 11,11,11,11,11,11,11, 5, 4,
  145101. };
  145102. static float _vq_quantthresh__16u2_p9_1[] = {
  145103. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  145104. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  145105. 318.5, 367.5,
  145106. };
  145107. static long _vq_quantmap__16u2_p9_1[] = {
  145108. 15, 13, 11, 9, 7, 5, 3, 1,
  145109. 17, 0, 18, 2, 4, 6, 8, 10,
  145110. 12, 14, 16,
  145111. };
  145112. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  145113. _vq_quantthresh__16u2_p9_1,
  145114. _vq_quantmap__16u2_p9_1,
  145115. 19,
  145116. 19
  145117. };
  145118. static static_codebook _16u2_p9_1 = {
  145119. 2, 361,
  145120. _vq_lengthlist__16u2_p9_1,
  145121. 1, -518488064, 1611661312, 10, 0,
  145122. _vq_quantlist__16u2_p9_1,
  145123. NULL,
  145124. &_vq_auxt__16u2_p9_1,
  145125. NULL,
  145126. 0
  145127. };
  145128. static long _vq_quantlist__16u2_p9_2[] = {
  145129. 24,
  145130. 23,
  145131. 25,
  145132. 22,
  145133. 26,
  145134. 21,
  145135. 27,
  145136. 20,
  145137. 28,
  145138. 19,
  145139. 29,
  145140. 18,
  145141. 30,
  145142. 17,
  145143. 31,
  145144. 16,
  145145. 32,
  145146. 15,
  145147. 33,
  145148. 14,
  145149. 34,
  145150. 13,
  145151. 35,
  145152. 12,
  145153. 36,
  145154. 11,
  145155. 37,
  145156. 10,
  145157. 38,
  145158. 9,
  145159. 39,
  145160. 8,
  145161. 40,
  145162. 7,
  145163. 41,
  145164. 6,
  145165. 42,
  145166. 5,
  145167. 43,
  145168. 4,
  145169. 44,
  145170. 3,
  145171. 45,
  145172. 2,
  145173. 46,
  145174. 1,
  145175. 47,
  145176. 0,
  145177. 48,
  145178. };
  145179. static long _vq_lengthlist__16u2_p9_2[] = {
  145180. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145181. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  145182. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  145183. 11,
  145184. };
  145185. static float _vq_quantthresh__16u2_p9_2[] = {
  145186. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145187. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145188. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145189. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145190. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145191. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145192. };
  145193. static long _vq_quantmap__16u2_p9_2[] = {
  145194. 47, 45, 43, 41, 39, 37, 35, 33,
  145195. 31, 29, 27, 25, 23, 21, 19, 17,
  145196. 15, 13, 11, 9, 7, 5, 3, 1,
  145197. 0, 2, 4, 6, 8, 10, 12, 14,
  145198. 16, 18, 20, 22, 24, 26, 28, 30,
  145199. 32, 34, 36, 38, 40, 42, 44, 46,
  145200. 48,
  145201. };
  145202. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145203. _vq_quantthresh__16u2_p9_2,
  145204. _vq_quantmap__16u2_p9_2,
  145205. 49,
  145206. 49
  145207. };
  145208. static static_codebook _16u2_p9_2 = {
  145209. 1, 49,
  145210. _vq_lengthlist__16u2_p9_2,
  145211. 1, -526909440, 1611661312, 6, 0,
  145212. _vq_quantlist__16u2_p9_2,
  145213. NULL,
  145214. &_vq_auxt__16u2_p9_2,
  145215. NULL,
  145216. 0
  145217. };
  145218. static long _vq_quantlist__8u0__p1_0[] = {
  145219. 1,
  145220. 0,
  145221. 2,
  145222. };
  145223. static long _vq_lengthlist__8u0__p1_0[] = {
  145224. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145225. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145226. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145227. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145228. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145229. 11,
  145230. };
  145231. static float _vq_quantthresh__8u0__p1_0[] = {
  145232. -0.5, 0.5,
  145233. };
  145234. static long _vq_quantmap__8u0__p1_0[] = {
  145235. 1, 0, 2,
  145236. };
  145237. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145238. _vq_quantthresh__8u0__p1_0,
  145239. _vq_quantmap__8u0__p1_0,
  145240. 3,
  145241. 3
  145242. };
  145243. static static_codebook _8u0__p1_0 = {
  145244. 4, 81,
  145245. _vq_lengthlist__8u0__p1_0,
  145246. 1, -535822336, 1611661312, 2, 0,
  145247. _vq_quantlist__8u0__p1_0,
  145248. NULL,
  145249. &_vq_auxt__8u0__p1_0,
  145250. NULL,
  145251. 0
  145252. };
  145253. static long _vq_quantlist__8u0__p2_0[] = {
  145254. 1,
  145255. 0,
  145256. 2,
  145257. };
  145258. static long _vq_lengthlist__8u0__p2_0[] = {
  145259. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145260. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145261. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145262. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145263. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145264. 8,
  145265. };
  145266. static float _vq_quantthresh__8u0__p2_0[] = {
  145267. -0.5, 0.5,
  145268. };
  145269. static long _vq_quantmap__8u0__p2_0[] = {
  145270. 1, 0, 2,
  145271. };
  145272. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145273. _vq_quantthresh__8u0__p2_0,
  145274. _vq_quantmap__8u0__p2_0,
  145275. 3,
  145276. 3
  145277. };
  145278. static static_codebook _8u0__p2_0 = {
  145279. 4, 81,
  145280. _vq_lengthlist__8u0__p2_0,
  145281. 1, -535822336, 1611661312, 2, 0,
  145282. _vq_quantlist__8u0__p2_0,
  145283. NULL,
  145284. &_vq_auxt__8u0__p2_0,
  145285. NULL,
  145286. 0
  145287. };
  145288. static long _vq_quantlist__8u0__p3_0[] = {
  145289. 2,
  145290. 1,
  145291. 3,
  145292. 0,
  145293. 4,
  145294. };
  145295. static long _vq_lengthlist__8u0__p3_0[] = {
  145296. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145297. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145298. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145299. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145300. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145301. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145302. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145303. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145304. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145305. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145306. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145307. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145308. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145309. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145310. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145311. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145312. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145313. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145314. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145315. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145316. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145317. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145318. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145319. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145320. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145321. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145322. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145323. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145324. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145325. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145326. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145327. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145328. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145329. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145330. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145331. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145332. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145333. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145334. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145335. 16,
  145336. };
  145337. static float _vq_quantthresh__8u0__p3_0[] = {
  145338. -1.5, -0.5, 0.5, 1.5,
  145339. };
  145340. static long _vq_quantmap__8u0__p3_0[] = {
  145341. 3, 1, 0, 2, 4,
  145342. };
  145343. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145344. _vq_quantthresh__8u0__p3_0,
  145345. _vq_quantmap__8u0__p3_0,
  145346. 5,
  145347. 5
  145348. };
  145349. static static_codebook _8u0__p3_0 = {
  145350. 4, 625,
  145351. _vq_lengthlist__8u0__p3_0,
  145352. 1, -533725184, 1611661312, 3, 0,
  145353. _vq_quantlist__8u0__p3_0,
  145354. NULL,
  145355. &_vq_auxt__8u0__p3_0,
  145356. NULL,
  145357. 0
  145358. };
  145359. static long _vq_quantlist__8u0__p4_0[] = {
  145360. 2,
  145361. 1,
  145362. 3,
  145363. 0,
  145364. 4,
  145365. };
  145366. static long _vq_lengthlist__8u0__p4_0[] = {
  145367. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145368. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145369. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145370. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145371. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145372. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145373. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145374. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145375. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145376. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145377. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145378. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145379. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145380. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145381. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145382. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145383. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145384. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145385. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145386. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145387. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145388. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145389. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145390. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145391. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145392. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145393. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145394. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145395. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145396. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145397. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145398. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145399. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145400. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145401. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145402. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145403. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145404. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145405. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145406. 12,
  145407. };
  145408. static float _vq_quantthresh__8u0__p4_0[] = {
  145409. -1.5, -0.5, 0.5, 1.5,
  145410. };
  145411. static long _vq_quantmap__8u0__p4_0[] = {
  145412. 3, 1, 0, 2, 4,
  145413. };
  145414. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145415. _vq_quantthresh__8u0__p4_0,
  145416. _vq_quantmap__8u0__p4_0,
  145417. 5,
  145418. 5
  145419. };
  145420. static static_codebook _8u0__p4_0 = {
  145421. 4, 625,
  145422. _vq_lengthlist__8u0__p4_0,
  145423. 1, -533725184, 1611661312, 3, 0,
  145424. _vq_quantlist__8u0__p4_0,
  145425. NULL,
  145426. &_vq_auxt__8u0__p4_0,
  145427. NULL,
  145428. 0
  145429. };
  145430. static long _vq_quantlist__8u0__p5_0[] = {
  145431. 4,
  145432. 3,
  145433. 5,
  145434. 2,
  145435. 6,
  145436. 1,
  145437. 7,
  145438. 0,
  145439. 8,
  145440. };
  145441. static long _vq_lengthlist__8u0__p5_0[] = {
  145442. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145443. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145444. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145445. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145446. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145447. 12,
  145448. };
  145449. static float _vq_quantthresh__8u0__p5_0[] = {
  145450. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145451. };
  145452. static long _vq_quantmap__8u0__p5_0[] = {
  145453. 7, 5, 3, 1, 0, 2, 4, 6,
  145454. 8,
  145455. };
  145456. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145457. _vq_quantthresh__8u0__p5_0,
  145458. _vq_quantmap__8u0__p5_0,
  145459. 9,
  145460. 9
  145461. };
  145462. static static_codebook _8u0__p5_0 = {
  145463. 2, 81,
  145464. _vq_lengthlist__8u0__p5_0,
  145465. 1, -531628032, 1611661312, 4, 0,
  145466. _vq_quantlist__8u0__p5_0,
  145467. NULL,
  145468. &_vq_auxt__8u0__p5_0,
  145469. NULL,
  145470. 0
  145471. };
  145472. static long _vq_quantlist__8u0__p6_0[] = {
  145473. 6,
  145474. 5,
  145475. 7,
  145476. 4,
  145477. 8,
  145478. 3,
  145479. 9,
  145480. 2,
  145481. 10,
  145482. 1,
  145483. 11,
  145484. 0,
  145485. 12,
  145486. };
  145487. static long _vq_lengthlist__8u0__p6_0[] = {
  145488. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145489. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145490. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145491. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145492. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145493. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145494. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145495. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145496. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145497. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145498. 16, 0,15, 0,17, 0, 0, 0, 0,
  145499. };
  145500. static float _vq_quantthresh__8u0__p6_0[] = {
  145501. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145502. 12.5, 17.5, 22.5, 27.5,
  145503. };
  145504. static long _vq_quantmap__8u0__p6_0[] = {
  145505. 11, 9, 7, 5, 3, 1, 0, 2,
  145506. 4, 6, 8, 10, 12,
  145507. };
  145508. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145509. _vq_quantthresh__8u0__p6_0,
  145510. _vq_quantmap__8u0__p6_0,
  145511. 13,
  145512. 13
  145513. };
  145514. static static_codebook _8u0__p6_0 = {
  145515. 2, 169,
  145516. _vq_lengthlist__8u0__p6_0,
  145517. 1, -526516224, 1616117760, 4, 0,
  145518. _vq_quantlist__8u0__p6_0,
  145519. NULL,
  145520. &_vq_auxt__8u0__p6_0,
  145521. NULL,
  145522. 0
  145523. };
  145524. static long _vq_quantlist__8u0__p6_1[] = {
  145525. 2,
  145526. 1,
  145527. 3,
  145528. 0,
  145529. 4,
  145530. };
  145531. static long _vq_lengthlist__8u0__p6_1[] = {
  145532. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145533. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145534. };
  145535. static float _vq_quantthresh__8u0__p6_1[] = {
  145536. -1.5, -0.5, 0.5, 1.5,
  145537. };
  145538. static long _vq_quantmap__8u0__p6_1[] = {
  145539. 3, 1, 0, 2, 4,
  145540. };
  145541. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145542. _vq_quantthresh__8u0__p6_1,
  145543. _vq_quantmap__8u0__p6_1,
  145544. 5,
  145545. 5
  145546. };
  145547. static static_codebook _8u0__p6_1 = {
  145548. 2, 25,
  145549. _vq_lengthlist__8u0__p6_1,
  145550. 1, -533725184, 1611661312, 3, 0,
  145551. _vq_quantlist__8u0__p6_1,
  145552. NULL,
  145553. &_vq_auxt__8u0__p6_1,
  145554. NULL,
  145555. 0
  145556. };
  145557. static long _vq_quantlist__8u0__p7_0[] = {
  145558. 1,
  145559. 0,
  145560. 2,
  145561. };
  145562. static long _vq_lengthlist__8u0__p7_0[] = {
  145563. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145564. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145565. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145566. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145567. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145568. 7,
  145569. };
  145570. static float _vq_quantthresh__8u0__p7_0[] = {
  145571. -157.5, 157.5,
  145572. };
  145573. static long _vq_quantmap__8u0__p7_0[] = {
  145574. 1, 0, 2,
  145575. };
  145576. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145577. _vq_quantthresh__8u0__p7_0,
  145578. _vq_quantmap__8u0__p7_0,
  145579. 3,
  145580. 3
  145581. };
  145582. static static_codebook _8u0__p7_0 = {
  145583. 4, 81,
  145584. _vq_lengthlist__8u0__p7_0,
  145585. 1, -518803456, 1628680192, 2, 0,
  145586. _vq_quantlist__8u0__p7_0,
  145587. NULL,
  145588. &_vq_auxt__8u0__p7_0,
  145589. NULL,
  145590. 0
  145591. };
  145592. static long _vq_quantlist__8u0__p7_1[] = {
  145593. 7,
  145594. 6,
  145595. 8,
  145596. 5,
  145597. 9,
  145598. 4,
  145599. 10,
  145600. 3,
  145601. 11,
  145602. 2,
  145603. 12,
  145604. 1,
  145605. 13,
  145606. 0,
  145607. 14,
  145608. };
  145609. static long _vq_lengthlist__8u0__p7_1[] = {
  145610. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145611. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145612. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145613. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145614. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145615. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145616. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145617. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145618. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145619. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145620. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145621. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145622. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145623. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145624. 10,
  145625. };
  145626. static float _vq_quantthresh__8u0__p7_1[] = {
  145627. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145628. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145629. };
  145630. static long _vq_quantmap__8u0__p7_1[] = {
  145631. 13, 11, 9, 7, 5, 3, 1, 0,
  145632. 2, 4, 6, 8, 10, 12, 14,
  145633. };
  145634. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145635. _vq_quantthresh__8u0__p7_1,
  145636. _vq_quantmap__8u0__p7_1,
  145637. 15,
  145638. 15
  145639. };
  145640. static static_codebook _8u0__p7_1 = {
  145641. 2, 225,
  145642. _vq_lengthlist__8u0__p7_1,
  145643. 1, -520986624, 1620377600, 4, 0,
  145644. _vq_quantlist__8u0__p7_1,
  145645. NULL,
  145646. &_vq_auxt__8u0__p7_1,
  145647. NULL,
  145648. 0
  145649. };
  145650. static long _vq_quantlist__8u0__p7_2[] = {
  145651. 10,
  145652. 9,
  145653. 11,
  145654. 8,
  145655. 12,
  145656. 7,
  145657. 13,
  145658. 6,
  145659. 14,
  145660. 5,
  145661. 15,
  145662. 4,
  145663. 16,
  145664. 3,
  145665. 17,
  145666. 2,
  145667. 18,
  145668. 1,
  145669. 19,
  145670. 0,
  145671. 20,
  145672. };
  145673. static long _vq_lengthlist__8u0__p7_2[] = {
  145674. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145675. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145676. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145677. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145678. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145679. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145680. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145681. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145682. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145683. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145684. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145685. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145686. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145687. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145688. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145689. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145690. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145691. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145692. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145693. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145694. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145695. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145696. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145697. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145698. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145699. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145700. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145701. 11,12,11,11,11,10,10,11,11,
  145702. };
  145703. static float _vq_quantthresh__8u0__p7_2[] = {
  145704. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145705. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145706. 6.5, 7.5, 8.5, 9.5,
  145707. };
  145708. static long _vq_quantmap__8u0__p7_2[] = {
  145709. 19, 17, 15, 13, 11, 9, 7, 5,
  145710. 3, 1, 0, 2, 4, 6, 8, 10,
  145711. 12, 14, 16, 18, 20,
  145712. };
  145713. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145714. _vq_quantthresh__8u0__p7_2,
  145715. _vq_quantmap__8u0__p7_2,
  145716. 21,
  145717. 21
  145718. };
  145719. static static_codebook _8u0__p7_2 = {
  145720. 2, 441,
  145721. _vq_lengthlist__8u0__p7_2,
  145722. 1, -529268736, 1611661312, 5, 0,
  145723. _vq_quantlist__8u0__p7_2,
  145724. NULL,
  145725. &_vq_auxt__8u0__p7_2,
  145726. NULL,
  145727. 0
  145728. };
  145729. static long _huff_lengthlist__8u0__single[] = {
  145730. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145731. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145732. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145733. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145734. };
  145735. static static_codebook _huff_book__8u0__single = {
  145736. 2, 64,
  145737. _huff_lengthlist__8u0__single,
  145738. 0, 0, 0, 0, 0,
  145739. NULL,
  145740. NULL,
  145741. NULL,
  145742. NULL,
  145743. 0
  145744. };
  145745. static long _vq_quantlist__8u1__p1_0[] = {
  145746. 1,
  145747. 0,
  145748. 2,
  145749. };
  145750. static long _vq_lengthlist__8u1__p1_0[] = {
  145751. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145752. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145753. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145754. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145755. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145756. 10,
  145757. };
  145758. static float _vq_quantthresh__8u1__p1_0[] = {
  145759. -0.5, 0.5,
  145760. };
  145761. static long _vq_quantmap__8u1__p1_0[] = {
  145762. 1, 0, 2,
  145763. };
  145764. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145765. _vq_quantthresh__8u1__p1_0,
  145766. _vq_quantmap__8u1__p1_0,
  145767. 3,
  145768. 3
  145769. };
  145770. static static_codebook _8u1__p1_0 = {
  145771. 4, 81,
  145772. _vq_lengthlist__8u1__p1_0,
  145773. 1, -535822336, 1611661312, 2, 0,
  145774. _vq_quantlist__8u1__p1_0,
  145775. NULL,
  145776. &_vq_auxt__8u1__p1_0,
  145777. NULL,
  145778. 0
  145779. };
  145780. static long _vq_quantlist__8u1__p2_0[] = {
  145781. 1,
  145782. 0,
  145783. 2,
  145784. };
  145785. static long _vq_lengthlist__8u1__p2_0[] = {
  145786. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145787. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145788. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145789. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145790. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145791. 7,
  145792. };
  145793. static float _vq_quantthresh__8u1__p2_0[] = {
  145794. -0.5, 0.5,
  145795. };
  145796. static long _vq_quantmap__8u1__p2_0[] = {
  145797. 1, 0, 2,
  145798. };
  145799. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145800. _vq_quantthresh__8u1__p2_0,
  145801. _vq_quantmap__8u1__p2_0,
  145802. 3,
  145803. 3
  145804. };
  145805. static static_codebook _8u1__p2_0 = {
  145806. 4, 81,
  145807. _vq_lengthlist__8u1__p2_0,
  145808. 1, -535822336, 1611661312, 2, 0,
  145809. _vq_quantlist__8u1__p2_0,
  145810. NULL,
  145811. &_vq_auxt__8u1__p2_0,
  145812. NULL,
  145813. 0
  145814. };
  145815. static long _vq_quantlist__8u1__p3_0[] = {
  145816. 2,
  145817. 1,
  145818. 3,
  145819. 0,
  145820. 4,
  145821. };
  145822. static long _vq_lengthlist__8u1__p3_0[] = {
  145823. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145824. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145825. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145826. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145827. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145828. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145829. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145830. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145831. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145832. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145833. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145834. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145835. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145836. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145837. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145838. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145839. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145840. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145841. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145842. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145843. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145844. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145845. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145846. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145847. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145848. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145849. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145850. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145851. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145852. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145853. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145854. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145855. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145856. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145857. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145858. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145859. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145860. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145861. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145862. 16,
  145863. };
  145864. static float _vq_quantthresh__8u1__p3_0[] = {
  145865. -1.5, -0.5, 0.5, 1.5,
  145866. };
  145867. static long _vq_quantmap__8u1__p3_0[] = {
  145868. 3, 1, 0, 2, 4,
  145869. };
  145870. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145871. _vq_quantthresh__8u1__p3_0,
  145872. _vq_quantmap__8u1__p3_0,
  145873. 5,
  145874. 5
  145875. };
  145876. static static_codebook _8u1__p3_0 = {
  145877. 4, 625,
  145878. _vq_lengthlist__8u1__p3_0,
  145879. 1, -533725184, 1611661312, 3, 0,
  145880. _vq_quantlist__8u1__p3_0,
  145881. NULL,
  145882. &_vq_auxt__8u1__p3_0,
  145883. NULL,
  145884. 0
  145885. };
  145886. static long _vq_quantlist__8u1__p4_0[] = {
  145887. 2,
  145888. 1,
  145889. 3,
  145890. 0,
  145891. 4,
  145892. };
  145893. static long _vq_lengthlist__8u1__p4_0[] = {
  145894. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145895. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145896. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145897. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145898. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145899. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145900. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145901. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145902. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145903. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145904. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145905. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145906. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145907. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145908. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145909. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145910. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145911. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145912. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145913. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145914. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145915. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145916. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145917. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145918. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145919. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145920. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145921. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145922. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145923. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145924. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145925. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145926. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145927. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145928. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145929. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145930. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145931. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145932. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145933. 10,
  145934. };
  145935. static float _vq_quantthresh__8u1__p4_0[] = {
  145936. -1.5, -0.5, 0.5, 1.5,
  145937. };
  145938. static long _vq_quantmap__8u1__p4_0[] = {
  145939. 3, 1, 0, 2, 4,
  145940. };
  145941. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145942. _vq_quantthresh__8u1__p4_0,
  145943. _vq_quantmap__8u1__p4_0,
  145944. 5,
  145945. 5
  145946. };
  145947. static static_codebook _8u1__p4_0 = {
  145948. 4, 625,
  145949. _vq_lengthlist__8u1__p4_0,
  145950. 1, -533725184, 1611661312, 3, 0,
  145951. _vq_quantlist__8u1__p4_0,
  145952. NULL,
  145953. &_vq_auxt__8u1__p4_0,
  145954. NULL,
  145955. 0
  145956. };
  145957. static long _vq_quantlist__8u1__p5_0[] = {
  145958. 4,
  145959. 3,
  145960. 5,
  145961. 2,
  145962. 6,
  145963. 1,
  145964. 7,
  145965. 0,
  145966. 8,
  145967. };
  145968. static long _vq_lengthlist__8u1__p5_0[] = {
  145969. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145970. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145971. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145972. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145973. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145974. 13,
  145975. };
  145976. static float _vq_quantthresh__8u1__p5_0[] = {
  145977. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145978. };
  145979. static long _vq_quantmap__8u1__p5_0[] = {
  145980. 7, 5, 3, 1, 0, 2, 4, 6,
  145981. 8,
  145982. };
  145983. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145984. _vq_quantthresh__8u1__p5_0,
  145985. _vq_quantmap__8u1__p5_0,
  145986. 9,
  145987. 9
  145988. };
  145989. static static_codebook _8u1__p5_0 = {
  145990. 2, 81,
  145991. _vq_lengthlist__8u1__p5_0,
  145992. 1, -531628032, 1611661312, 4, 0,
  145993. _vq_quantlist__8u1__p5_0,
  145994. NULL,
  145995. &_vq_auxt__8u1__p5_0,
  145996. NULL,
  145997. 0
  145998. };
  145999. static long _vq_quantlist__8u1__p6_0[] = {
  146000. 4,
  146001. 3,
  146002. 5,
  146003. 2,
  146004. 6,
  146005. 1,
  146006. 7,
  146007. 0,
  146008. 8,
  146009. };
  146010. static long _vq_lengthlist__8u1__p6_0[] = {
  146011. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  146012. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  146013. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  146014. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  146015. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146016. 10,
  146017. };
  146018. static float _vq_quantthresh__8u1__p6_0[] = {
  146019. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146020. };
  146021. static long _vq_quantmap__8u1__p6_0[] = {
  146022. 7, 5, 3, 1, 0, 2, 4, 6,
  146023. 8,
  146024. };
  146025. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  146026. _vq_quantthresh__8u1__p6_0,
  146027. _vq_quantmap__8u1__p6_0,
  146028. 9,
  146029. 9
  146030. };
  146031. static static_codebook _8u1__p6_0 = {
  146032. 2, 81,
  146033. _vq_lengthlist__8u1__p6_0,
  146034. 1, -531628032, 1611661312, 4, 0,
  146035. _vq_quantlist__8u1__p6_0,
  146036. NULL,
  146037. &_vq_auxt__8u1__p6_0,
  146038. NULL,
  146039. 0
  146040. };
  146041. static long _vq_quantlist__8u1__p7_0[] = {
  146042. 1,
  146043. 0,
  146044. 2,
  146045. };
  146046. static long _vq_lengthlist__8u1__p7_0[] = {
  146047. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  146048. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  146049. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  146050. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  146051. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  146052. 11,
  146053. };
  146054. static float _vq_quantthresh__8u1__p7_0[] = {
  146055. -5.5, 5.5,
  146056. };
  146057. static long _vq_quantmap__8u1__p7_0[] = {
  146058. 1, 0, 2,
  146059. };
  146060. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  146061. _vq_quantthresh__8u1__p7_0,
  146062. _vq_quantmap__8u1__p7_0,
  146063. 3,
  146064. 3
  146065. };
  146066. static static_codebook _8u1__p7_0 = {
  146067. 4, 81,
  146068. _vq_lengthlist__8u1__p7_0,
  146069. 1, -529137664, 1618345984, 2, 0,
  146070. _vq_quantlist__8u1__p7_0,
  146071. NULL,
  146072. &_vq_auxt__8u1__p7_0,
  146073. NULL,
  146074. 0
  146075. };
  146076. static long _vq_quantlist__8u1__p7_1[] = {
  146077. 5,
  146078. 4,
  146079. 6,
  146080. 3,
  146081. 7,
  146082. 2,
  146083. 8,
  146084. 1,
  146085. 9,
  146086. 0,
  146087. 10,
  146088. };
  146089. static long _vq_lengthlist__8u1__p7_1[] = {
  146090. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  146091. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  146092. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  146093. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146094. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  146095. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146096. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  146097. 9, 9, 9, 9, 9,10,10,10,10,
  146098. };
  146099. static float _vq_quantthresh__8u1__p7_1[] = {
  146100. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146101. 3.5, 4.5,
  146102. };
  146103. static long _vq_quantmap__8u1__p7_1[] = {
  146104. 9, 7, 5, 3, 1, 0, 2, 4,
  146105. 6, 8, 10,
  146106. };
  146107. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  146108. _vq_quantthresh__8u1__p7_1,
  146109. _vq_quantmap__8u1__p7_1,
  146110. 11,
  146111. 11
  146112. };
  146113. static static_codebook _8u1__p7_1 = {
  146114. 2, 121,
  146115. _vq_lengthlist__8u1__p7_1,
  146116. 1, -531365888, 1611661312, 4, 0,
  146117. _vq_quantlist__8u1__p7_1,
  146118. NULL,
  146119. &_vq_auxt__8u1__p7_1,
  146120. NULL,
  146121. 0
  146122. };
  146123. static long _vq_quantlist__8u1__p8_0[] = {
  146124. 5,
  146125. 4,
  146126. 6,
  146127. 3,
  146128. 7,
  146129. 2,
  146130. 8,
  146131. 1,
  146132. 9,
  146133. 0,
  146134. 10,
  146135. };
  146136. static long _vq_lengthlist__8u1__p8_0[] = {
  146137. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146138. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  146139. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  146140. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  146141. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  146142. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  146143. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  146144. 12,13,13,14,14,15,15,15,15,
  146145. };
  146146. static float _vq_quantthresh__8u1__p8_0[] = {
  146147. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146148. 38.5, 49.5,
  146149. };
  146150. static long _vq_quantmap__8u1__p8_0[] = {
  146151. 9, 7, 5, 3, 1, 0, 2, 4,
  146152. 6, 8, 10,
  146153. };
  146154. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  146155. _vq_quantthresh__8u1__p8_0,
  146156. _vq_quantmap__8u1__p8_0,
  146157. 11,
  146158. 11
  146159. };
  146160. static static_codebook _8u1__p8_0 = {
  146161. 2, 121,
  146162. _vq_lengthlist__8u1__p8_0,
  146163. 1, -524582912, 1618345984, 4, 0,
  146164. _vq_quantlist__8u1__p8_0,
  146165. NULL,
  146166. &_vq_auxt__8u1__p8_0,
  146167. NULL,
  146168. 0
  146169. };
  146170. static long _vq_quantlist__8u1__p8_1[] = {
  146171. 5,
  146172. 4,
  146173. 6,
  146174. 3,
  146175. 7,
  146176. 2,
  146177. 8,
  146178. 1,
  146179. 9,
  146180. 0,
  146181. 10,
  146182. };
  146183. static long _vq_lengthlist__8u1__p8_1[] = {
  146184. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  146185. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  146186. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146187. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146188. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146189. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  146190. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  146191. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146192. };
  146193. static float _vq_quantthresh__8u1__p8_1[] = {
  146194. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146195. 3.5, 4.5,
  146196. };
  146197. static long _vq_quantmap__8u1__p8_1[] = {
  146198. 9, 7, 5, 3, 1, 0, 2, 4,
  146199. 6, 8, 10,
  146200. };
  146201. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146202. _vq_quantthresh__8u1__p8_1,
  146203. _vq_quantmap__8u1__p8_1,
  146204. 11,
  146205. 11
  146206. };
  146207. static static_codebook _8u1__p8_1 = {
  146208. 2, 121,
  146209. _vq_lengthlist__8u1__p8_1,
  146210. 1, -531365888, 1611661312, 4, 0,
  146211. _vq_quantlist__8u1__p8_1,
  146212. NULL,
  146213. &_vq_auxt__8u1__p8_1,
  146214. NULL,
  146215. 0
  146216. };
  146217. static long _vq_quantlist__8u1__p9_0[] = {
  146218. 7,
  146219. 6,
  146220. 8,
  146221. 5,
  146222. 9,
  146223. 4,
  146224. 10,
  146225. 3,
  146226. 11,
  146227. 2,
  146228. 12,
  146229. 1,
  146230. 13,
  146231. 0,
  146232. 14,
  146233. };
  146234. static long _vq_lengthlist__8u1__p9_0[] = {
  146235. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146236. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146237. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146238. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146239. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146240. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146241. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146242. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146243. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146244. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146245. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146246. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146247. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146248. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146249. 10,
  146250. };
  146251. static float _vq_quantthresh__8u1__p9_0[] = {
  146252. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146253. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146254. };
  146255. static long _vq_quantmap__8u1__p9_0[] = {
  146256. 13, 11, 9, 7, 5, 3, 1, 0,
  146257. 2, 4, 6, 8, 10, 12, 14,
  146258. };
  146259. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146260. _vq_quantthresh__8u1__p9_0,
  146261. _vq_quantmap__8u1__p9_0,
  146262. 15,
  146263. 15
  146264. };
  146265. static static_codebook _8u1__p9_0 = {
  146266. 2, 225,
  146267. _vq_lengthlist__8u1__p9_0,
  146268. 1, -514071552, 1627381760, 4, 0,
  146269. _vq_quantlist__8u1__p9_0,
  146270. NULL,
  146271. &_vq_auxt__8u1__p9_0,
  146272. NULL,
  146273. 0
  146274. };
  146275. static long _vq_quantlist__8u1__p9_1[] = {
  146276. 7,
  146277. 6,
  146278. 8,
  146279. 5,
  146280. 9,
  146281. 4,
  146282. 10,
  146283. 3,
  146284. 11,
  146285. 2,
  146286. 12,
  146287. 1,
  146288. 13,
  146289. 0,
  146290. 14,
  146291. };
  146292. static long _vq_lengthlist__8u1__p9_1[] = {
  146293. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146294. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146295. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146296. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146297. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146298. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146299. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146300. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146301. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146302. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146303. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146304. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146305. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146306. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146307. 13,
  146308. };
  146309. static float _vq_quantthresh__8u1__p9_1[] = {
  146310. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146311. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146312. };
  146313. static long _vq_quantmap__8u1__p9_1[] = {
  146314. 13, 11, 9, 7, 5, 3, 1, 0,
  146315. 2, 4, 6, 8, 10, 12, 14,
  146316. };
  146317. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146318. _vq_quantthresh__8u1__p9_1,
  146319. _vq_quantmap__8u1__p9_1,
  146320. 15,
  146321. 15
  146322. };
  146323. static static_codebook _8u1__p9_1 = {
  146324. 2, 225,
  146325. _vq_lengthlist__8u1__p9_1,
  146326. 1, -522338304, 1620115456, 4, 0,
  146327. _vq_quantlist__8u1__p9_1,
  146328. NULL,
  146329. &_vq_auxt__8u1__p9_1,
  146330. NULL,
  146331. 0
  146332. };
  146333. static long _vq_quantlist__8u1__p9_2[] = {
  146334. 8,
  146335. 7,
  146336. 9,
  146337. 6,
  146338. 10,
  146339. 5,
  146340. 11,
  146341. 4,
  146342. 12,
  146343. 3,
  146344. 13,
  146345. 2,
  146346. 14,
  146347. 1,
  146348. 15,
  146349. 0,
  146350. 16,
  146351. };
  146352. static long _vq_lengthlist__8u1__p9_2[] = {
  146353. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146354. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146355. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146356. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146357. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146358. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146359. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146360. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146361. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146362. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146363. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146364. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146365. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146366. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146367. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146368. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146369. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146370. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146371. 10,
  146372. };
  146373. static float _vq_quantthresh__8u1__p9_2[] = {
  146374. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146375. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146376. };
  146377. static long _vq_quantmap__8u1__p9_2[] = {
  146378. 15, 13, 11, 9, 7, 5, 3, 1,
  146379. 0, 2, 4, 6, 8, 10, 12, 14,
  146380. 16,
  146381. };
  146382. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146383. _vq_quantthresh__8u1__p9_2,
  146384. _vq_quantmap__8u1__p9_2,
  146385. 17,
  146386. 17
  146387. };
  146388. static static_codebook _8u1__p9_2 = {
  146389. 2, 289,
  146390. _vq_lengthlist__8u1__p9_2,
  146391. 1, -529530880, 1611661312, 5, 0,
  146392. _vq_quantlist__8u1__p9_2,
  146393. NULL,
  146394. &_vq_auxt__8u1__p9_2,
  146395. NULL,
  146396. 0
  146397. };
  146398. static long _huff_lengthlist__8u1__single[] = {
  146399. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146400. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146401. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146402. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146403. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146404. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146405. 13, 8, 8,15,
  146406. };
  146407. static static_codebook _huff_book__8u1__single = {
  146408. 2, 100,
  146409. _huff_lengthlist__8u1__single,
  146410. 0, 0, 0, 0, 0,
  146411. NULL,
  146412. NULL,
  146413. NULL,
  146414. NULL,
  146415. 0
  146416. };
  146417. static long _huff_lengthlist__44u0__long[] = {
  146418. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146419. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146420. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146421. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146422. };
  146423. static static_codebook _huff_book__44u0__long = {
  146424. 2, 64,
  146425. _huff_lengthlist__44u0__long,
  146426. 0, 0, 0, 0, 0,
  146427. NULL,
  146428. NULL,
  146429. NULL,
  146430. NULL,
  146431. 0
  146432. };
  146433. static long _vq_quantlist__44u0__p1_0[] = {
  146434. 1,
  146435. 0,
  146436. 2,
  146437. };
  146438. static long _vq_lengthlist__44u0__p1_0[] = {
  146439. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146440. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146441. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146442. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146443. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146444. 13,
  146445. };
  146446. static float _vq_quantthresh__44u0__p1_0[] = {
  146447. -0.5, 0.5,
  146448. };
  146449. static long _vq_quantmap__44u0__p1_0[] = {
  146450. 1, 0, 2,
  146451. };
  146452. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146453. _vq_quantthresh__44u0__p1_0,
  146454. _vq_quantmap__44u0__p1_0,
  146455. 3,
  146456. 3
  146457. };
  146458. static static_codebook _44u0__p1_0 = {
  146459. 4, 81,
  146460. _vq_lengthlist__44u0__p1_0,
  146461. 1, -535822336, 1611661312, 2, 0,
  146462. _vq_quantlist__44u0__p1_0,
  146463. NULL,
  146464. &_vq_auxt__44u0__p1_0,
  146465. NULL,
  146466. 0
  146467. };
  146468. static long _vq_quantlist__44u0__p2_0[] = {
  146469. 1,
  146470. 0,
  146471. 2,
  146472. };
  146473. static long _vq_lengthlist__44u0__p2_0[] = {
  146474. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146475. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146476. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146477. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146478. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146479. 9,
  146480. };
  146481. static float _vq_quantthresh__44u0__p2_0[] = {
  146482. -0.5, 0.5,
  146483. };
  146484. static long _vq_quantmap__44u0__p2_0[] = {
  146485. 1, 0, 2,
  146486. };
  146487. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146488. _vq_quantthresh__44u0__p2_0,
  146489. _vq_quantmap__44u0__p2_0,
  146490. 3,
  146491. 3
  146492. };
  146493. static static_codebook _44u0__p2_0 = {
  146494. 4, 81,
  146495. _vq_lengthlist__44u0__p2_0,
  146496. 1, -535822336, 1611661312, 2, 0,
  146497. _vq_quantlist__44u0__p2_0,
  146498. NULL,
  146499. &_vq_auxt__44u0__p2_0,
  146500. NULL,
  146501. 0
  146502. };
  146503. static long _vq_quantlist__44u0__p3_0[] = {
  146504. 2,
  146505. 1,
  146506. 3,
  146507. 0,
  146508. 4,
  146509. };
  146510. static long _vq_lengthlist__44u0__p3_0[] = {
  146511. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146512. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146513. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146514. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146515. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146516. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146517. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146518. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146519. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146520. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146521. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146522. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146523. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146524. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146525. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146526. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146527. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146528. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146529. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146530. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146531. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146532. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146533. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146534. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146535. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146536. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146537. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146538. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146539. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146540. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146541. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146542. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146543. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146544. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146545. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146546. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146547. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146548. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146549. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146550. 19,
  146551. };
  146552. static float _vq_quantthresh__44u0__p3_0[] = {
  146553. -1.5, -0.5, 0.5, 1.5,
  146554. };
  146555. static long _vq_quantmap__44u0__p3_0[] = {
  146556. 3, 1, 0, 2, 4,
  146557. };
  146558. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146559. _vq_quantthresh__44u0__p3_0,
  146560. _vq_quantmap__44u0__p3_0,
  146561. 5,
  146562. 5
  146563. };
  146564. static static_codebook _44u0__p3_0 = {
  146565. 4, 625,
  146566. _vq_lengthlist__44u0__p3_0,
  146567. 1, -533725184, 1611661312, 3, 0,
  146568. _vq_quantlist__44u0__p3_0,
  146569. NULL,
  146570. &_vq_auxt__44u0__p3_0,
  146571. NULL,
  146572. 0
  146573. };
  146574. static long _vq_quantlist__44u0__p4_0[] = {
  146575. 2,
  146576. 1,
  146577. 3,
  146578. 0,
  146579. 4,
  146580. };
  146581. static long _vq_lengthlist__44u0__p4_0[] = {
  146582. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146583. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146584. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146585. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146586. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146587. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146588. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146589. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146590. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146591. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146592. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146593. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146594. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146595. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146596. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146597. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146598. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146599. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146600. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146601. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146602. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146603. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146604. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146605. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146606. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146607. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146608. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146609. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146610. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146611. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146612. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146613. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146614. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146615. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146616. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146617. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146618. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146619. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146620. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146621. 12,
  146622. };
  146623. static float _vq_quantthresh__44u0__p4_0[] = {
  146624. -1.5, -0.5, 0.5, 1.5,
  146625. };
  146626. static long _vq_quantmap__44u0__p4_0[] = {
  146627. 3, 1, 0, 2, 4,
  146628. };
  146629. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146630. _vq_quantthresh__44u0__p4_0,
  146631. _vq_quantmap__44u0__p4_0,
  146632. 5,
  146633. 5
  146634. };
  146635. static static_codebook _44u0__p4_0 = {
  146636. 4, 625,
  146637. _vq_lengthlist__44u0__p4_0,
  146638. 1, -533725184, 1611661312, 3, 0,
  146639. _vq_quantlist__44u0__p4_0,
  146640. NULL,
  146641. &_vq_auxt__44u0__p4_0,
  146642. NULL,
  146643. 0
  146644. };
  146645. static long _vq_quantlist__44u0__p5_0[] = {
  146646. 4,
  146647. 3,
  146648. 5,
  146649. 2,
  146650. 6,
  146651. 1,
  146652. 7,
  146653. 0,
  146654. 8,
  146655. };
  146656. static long _vq_lengthlist__44u0__p5_0[] = {
  146657. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146658. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146659. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146660. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146661. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146662. 12,
  146663. };
  146664. static float _vq_quantthresh__44u0__p5_0[] = {
  146665. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146666. };
  146667. static long _vq_quantmap__44u0__p5_0[] = {
  146668. 7, 5, 3, 1, 0, 2, 4, 6,
  146669. 8,
  146670. };
  146671. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146672. _vq_quantthresh__44u0__p5_0,
  146673. _vq_quantmap__44u0__p5_0,
  146674. 9,
  146675. 9
  146676. };
  146677. static static_codebook _44u0__p5_0 = {
  146678. 2, 81,
  146679. _vq_lengthlist__44u0__p5_0,
  146680. 1, -531628032, 1611661312, 4, 0,
  146681. _vq_quantlist__44u0__p5_0,
  146682. NULL,
  146683. &_vq_auxt__44u0__p5_0,
  146684. NULL,
  146685. 0
  146686. };
  146687. static long _vq_quantlist__44u0__p6_0[] = {
  146688. 6,
  146689. 5,
  146690. 7,
  146691. 4,
  146692. 8,
  146693. 3,
  146694. 9,
  146695. 2,
  146696. 10,
  146697. 1,
  146698. 11,
  146699. 0,
  146700. 12,
  146701. };
  146702. static long _vq_lengthlist__44u0__p6_0[] = {
  146703. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146704. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146705. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146706. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146707. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146708. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146709. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146710. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146711. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146712. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146713. 15,17,16,17,18,17,17,18, 0,
  146714. };
  146715. static float _vq_quantthresh__44u0__p6_0[] = {
  146716. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146717. 12.5, 17.5, 22.5, 27.5,
  146718. };
  146719. static long _vq_quantmap__44u0__p6_0[] = {
  146720. 11, 9, 7, 5, 3, 1, 0, 2,
  146721. 4, 6, 8, 10, 12,
  146722. };
  146723. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146724. _vq_quantthresh__44u0__p6_0,
  146725. _vq_quantmap__44u0__p6_0,
  146726. 13,
  146727. 13
  146728. };
  146729. static static_codebook _44u0__p6_0 = {
  146730. 2, 169,
  146731. _vq_lengthlist__44u0__p6_0,
  146732. 1, -526516224, 1616117760, 4, 0,
  146733. _vq_quantlist__44u0__p6_0,
  146734. NULL,
  146735. &_vq_auxt__44u0__p6_0,
  146736. NULL,
  146737. 0
  146738. };
  146739. static long _vq_quantlist__44u0__p6_1[] = {
  146740. 2,
  146741. 1,
  146742. 3,
  146743. 0,
  146744. 4,
  146745. };
  146746. static long _vq_lengthlist__44u0__p6_1[] = {
  146747. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146748. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146749. };
  146750. static float _vq_quantthresh__44u0__p6_1[] = {
  146751. -1.5, -0.5, 0.5, 1.5,
  146752. };
  146753. static long _vq_quantmap__44u0__p6_1[] = {
  146754. 3, 1, 0, 2, 4,
  146755. };
  146756. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146757. _vq_quantthresh__44u0__p6_1,
  146758. _vq_quantmap__44u0__p6_1,
  146759. 5,
  146760. 5
  146761. };
  146762. static static_codebook _44u0__p6_1 = {
  146763. 2, 25,
  146764. _vq_lengthlist__44u0__p6_1,
  146765. 1, -533725184, 1611661312, 3, 0,
  146766. _vq_quantlist__44u0__p6_1,
  146767. NULL,
  146768. &_vq_auxt__44u0__p6_1,
  146769. NULL,
  146770. 0
  146771. };
  146772. static long _vq_quantlist__44u0__p7_0[] = {
  146773. 2,
  146774. 1,
  146775. 3,
  146776. 0,
  146777. 4,
  146778. };
  146779. static long _vq_lengthlist__44u0__p7_0[] = {
  146780. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146781. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146783. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146784. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146785. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146787. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146788. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146791. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146793. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146794. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146797. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146798. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146799. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146802. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146803. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146804. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146808. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146809. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146810. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146811. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146812. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146813. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146814. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146815. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146816. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146817. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146818. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146819. 10,
  146820. };
  146821. static float _vq_quantthresh__44u0__p7_0[] = {
  146822. -253.5, -84.5, 84.5, 253.5,
  146823. };
  146824. static long _vq_quantmap__44u0__p7_0[] = {
  146825. 3, 1, 0, 2, 4,
  146826. };
  146827. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146828. _vq_quantthresh__44u0__p7_0,
  146829. _vq_quantmap__44u0__p7_0,
  146830. 5,
  146831. 5
  146832. };
  146833. static static_codebook _44u0__p7_0 = {
  146834. 4, 625,
  146835. _vq_lengthlist__44u0__p7_0,
  146836. 1, -518709248, 1626677248, 3, 0,
  146837. _vq_quantlist__44u0__p7_0,
  146838. NULL,
  146839. &_vq_auxt__44u0__p7_0,
  146840. NULL,
  146841. 0
  146842. };
  146843. static long _vq_quantlist__44u0__p7_1[] = {
  146844. 6,
  146845. 5,
  146846. 7,
  146847. 4,
  146848. 8,
  146849. 3,
  146850. 9,
  146851. 2,
  146852. 10,
  146853. 1,
  146854. 11,
  146855. 0,
  146856. 12,
  146857. };
  146858. static long _vq_lengthlist__44u0__p7_1[] = {
  146859. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146860. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146861. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146862. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146863. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146864. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146865. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146866. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146867. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146868. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146869. 15,15,15,15,15,15,15,15,15,
  146870. };
  146871. static float _vq_quantthresh__44u0__p7_1[] = {
  146872. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146873. 32.5, 45.5, 58.5, 71.5,
  146874. };
  146875. static long _vq_quantmap__44u0__p7_1[] = {
  146876. 11, 9, 7, 5, 3, 1, 0, 2,
  146877. 4, 6, 8, 10, 12,
  146878. };
  146879. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146880. _vq_quantthresh__44u0__p7_1,
  146881. _vq_quantmap__44u0__p7_1,
  146882. 13,
  146883. 13
  146884. };
  146885. static static_codebook _44u0__p7_1 = {
  146886. 2, 169,
  146887. _vq_lengthlist__44u0__p7_1,
  146888. 1, -523010048, 1618608128, 4, 0,
  146889. _vq_quantlist__44u0__p7_1,
  146890. NULL,
  146891. &_vq_auxt__44u0__p7_1,
  146892. NULL,
  146893. 0
  146894. };
  146895. static long _vq_quantlist__44u0__p7_2[] = {
  146896. 6,
  146897. 5,
  146898. 7,
  146899. 4,
  146900. 8,
  146901. 3,
  146902. 9,
  146903. 2,
  146904. 10,
  146905. 1,
  146906. 11,
  146907. 0,
  146908. 12,
  146909. };
  146910. static long _vq_lengthlist__44u0__p7_2[] = {
  146911. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146912. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146913. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146914. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146915. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146916. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146917. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146918. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146919. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146920. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146921. 9, 9, 9,10, 9, 9,10,10, 9,
  146922. };
  146923. static float _vq_quantthresh__44u0__p7_2[] = {
  146924. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146925. 2.5, 3.5, 4.5, 5.5,
  146926. };
  146927. static long _vq_quantmap__44u0__p7_2[] = {
  146928. 11, 9, 7, 5, 3, 1, 0, 2,
  146929. 4, 6, 8, 10, 12,
  146930. };
  146931. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146932. _vq_quantthresh__44u0__p7_2,
  146933. _vq_quantmap__44u0__p7_2,
  146934. 13,
  146935. 13
  146936. };
  146937. static static_codebook _44u0__p7_2 = {
  146938. 2, 169,
  146939. _vq_lengthlist__44u0__p7_2,
  146940. 1, -531103744, 1611661312, 4, 0,
  146941. _vq_quantlist__44u0__p7_2,
  146942. NULL,
  146943. &_vq_auxt__44u0__p7_2,
  146944. NULL,
  146945. 0
  146946. };
  146947. static long _huff_lengthlist__44u0__short[] = {
  146948. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146949. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146950. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146951. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146952. };
  146953. static static_codebook _huff_book__44u0__short = {
  146954. 2, 64,
  146955. _huff_lengthlist__44u0__short,
  146956. 0, 0, 0, 0, 0,
  146957. NULL,
  146958. NULL,
  146959. NULL,
  146960. NULL,
  146961. 0
  146962. };
  146963. static long _huff_lengthlist__44u1__long[] = {
  146964. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146965. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146966. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146967. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146968. };
  146969. static static_codebook _huff_book__44u1__long = {
  146970. 2, 64,
  146971. _huff_lengthlist__44u1__long,
  146972. 0, 0, 0, 0, 0,
  146973. NULL,
  146974. NULL,
  146975. NULL,
  146976. NULL,
  146977. 0
  146978. };
  146979. static long _vq_quantlist__44u1__p1_0[] = {
  146980. 1,
  146981. 0,
  146982. 2,
  146983. };
  146984. static long _vq_lengthlist__44u1__p1_0[] = {
  146985. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146986. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146987. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146988. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146989. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146990. 13,
  146991. };
  146992. static float _vq_quantthresh__44u1__p1_0[] = {
  146993. -0.5, 0.5,
  146994. };
  146995. static long _vq_quantmap__44u1__p1_0[] = {
  146996. 1, 0, 2,
  146997. };
  146998. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146999. _vq_quantthresh__44u1__p1_0,
  147000. _vq_quantmap__44u1__p1_0,
  147001. 3,
  147002. 3
  147003. };
  147004. static static_codebook _44u1__p1_0 = {
  147005. 4, 81,
  147006. _vq_lengthlist__44u1__p1_0,
  147007. 1, -535822336, 1611661312, 2, 0,
  147008. _vq_quantlist__44u1__p1_0,
  147009. NULL,
  147010. &_vq_auxt__44u1__p1_0,
  147011. NULL,
  147012. 0
  147013. };
  147014. static long _vq_quantlist__44u1__p2_0[] = {
  147015. 1,
  147016. 0,
  147017. 2,
  147018. };
  147019. static long _vq_lengthlist__44u1__p2_0[] = {
  147020. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  147021. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  147022. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147023. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  147024. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147025. 9,
  147026. };
  147027. static float _vq_quantthresh__44u1__p2_0[] = {
  147028. -0.5, 0.5,
  147029. };
  147030. static long _vq_quantmap__44u1__p2_0[] = {
  147031. 1, 0, 2,
  147032. };
  147033. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  147034. _vq_quantthresh__44u1__p2_0,
  147035. _vq_quantmap__44u1__p2_0,
  147036. 3,
  147037. 3
  147038. };
  147039. static static_codebook _44u1__p2_0 = {
  147040. 4, 81,
  147041. _vq_lengthlist__44u1__p2_0,
  147042. 1, -535822336, 1611661312, 2, 0,
  147043. _vq_quantlist__44u1__p2_0,
  147044. NULL,
  147045. &_vq_auxt__44u1__p2_0,
  147046. NULL,
  147047. 0
  147048. };
  147049. static long _vq_quantlist__44u1__p3_0[] = {
  147050. 2,
  147051. 1,
  147052. 3,
  147053. 0,
  147054. 4,
  147055. };
  147056. static long _vq_lengthlist__44u1__p3_0[] = {
  147057. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  147058. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  147059. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  147060. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  147061. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  147062. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  147063. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  147064. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  147065. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  147066. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  147067. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  147068. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  147069. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  147070. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  147071. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  147072. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  147073. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  147074. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  147075. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  147076. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  147077. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  147078. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  147079. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  147080. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  147081. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  147082. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  147083. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  147084. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  147085. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  147086. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  147087. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  147088. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  147089. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  147090. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  147091. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  147092. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  147093. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  147094. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  147095. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  147096. 19,
  147097. };
  147098. static float _vq_quantthresh__44u1__p3_0[] = {
  147099. -1.5, -0.5, 0.5, 1.5,
  147100. };
  147101. static long _vq_quantmap__44u1__p3_0[] = {
  147102. 3, 1, 0, 2, 4,
  147103. };
  147104. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  147105. _vq_quantthresh__44u1__p3_0,
  147106. _vq_quantmap__44u1__p3_0,
  147107. 5,
  147108. 5
  147109. };
  147110. static static_codebook _44u1__p3_0 = {
  147111. 4, 625,
  147112. _vq_lengthlist__44u1__p3_0,
  147113. 1, -533725184, 1611661312, 3, 0,
  147114. _vq_quantlist__44u1__p3_0,
  147115. NULL,
  147116. &_vq_auxt__44u1__p3_0,
  147117. NULL,
  147118. 0
  147119. };
  147120. static long _vq_quantlist__44u1__p4_0[] = {
  147121. 2,
  147122. 1,
  147123. 3,
  147124. 0,
  147125. 4,
  147126. };
  147127. static long _vq_lengthlist__44u1__p4_0[] = {
  147128. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  147129. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  147130. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  147131. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  147132. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  147133. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  147134. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  147135. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  147136. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  147137. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  147138. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  147139. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147140. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  147141. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  147142. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  147143. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  147144. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  147145. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  147146. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  147147. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  147148. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  147149. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  147150. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  147151. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  147152. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  147153. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  147154. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  147155. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  147156. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  147157. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  147158. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  147159. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  147160. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  147161. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  147162. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  147163. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  147164. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  147165. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  147166. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147167. 12,
  147168. };
  147169. static float _vq_quantthresh__44u1__p4_0[] = {
  147170. -1.5, -0.5, 0.5, 1.5,
  147171. };
  147172. static long _vq_quantmap__44u1__p4_0[] = {
  147173. 3, 1, 0, 2, 4,
  147174. };
  147175. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  147176. _vq_quantthresh__44u1__p4_0,
  147177. _vq_quantmap__44u1__p4_0,
  147178. 5,
  147179. 5
  147180. };
  147181. static static_codebook _44u1__p4_0 = {
  147182. 4, 625,
  147183. _vq_lengthlist__44u1__p4_0,
  147184. 1, -533725184, 1611661312, 3, 0,
  147185. _vq_quantlist__44u1__p4_0,
  147186. NULL,
  147187. &_vq_auxt__44u1__p4_0,
  147188. NULL,
  147189. 0
  147190. };
  147191. static long _vq_quantlist__44u1__p5_0[] = {
  147192. 4,
  147193. 3,
  147194. 5,
  147195. 2,
  147196. 6,
  147197. 1,
  147198. 7,
  147199. 0,
  147200. 8,
  147201. };
  147202. static long _vq_lengthlist__44u1__p5_0[] = {
  147203. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147204. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147205. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147206. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147207. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147208. 12,
  147209. };
  147210. static float _vq_quantthresh__44u1__p5_0[] = {
  147211. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147212. };
  147213. static long _vq_quantmap__44u1__p5_0[] = {
  147214. 7, 5, 3, 1, 0, 2, 4, 6,
  147215. 8,
  147216. };
  147217. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147218. _vq_quantthresh__44u1__p5_0,
  147219. _vq_quantmap__44u1__p5_0,
  147220. 9,
  147221. 9
  147222. };
  147223. static static_codebook _44u1__p5_0 = {
  147224. 2, 81,
  147225. _vq_lengthlist__44u1__p5_0,
  147226. 1, -531628032, 1611661312, 4, 0,
  147227. _vq_quantlist__44u1__p5_0,
  147228. NULL,
  147229. &_vq_auxt__44u1__p5_0,
  147230. NULL,
  147231. 0
  147232. };
  147233. static long _vq_quantlist__44u1__p6_0[] = {
  147234. 6,
  147235. 5,
  147236. 7,
  147237. 4,
  147238. 8,
  147239. 3,
  147240. 9,
  147241. 2,
  147242. 10,
  147243. 1,
  147244. 11,
  147245. 0,
  147246. 12,
  147247. };
  147248. static long _vq_lengthlist__44u1__p6_0[] = {
  147249. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147250. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147251. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147252. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147253. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147254. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147255. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147256. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147257. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147258. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147259. 15,17,16,17,18,17,17,18, 0,
  147260. };
  147261. static float _vq_quantthresh__44u1__p6_0[] = {
  147262. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147263. 12.5, 17.5, 22.5, 27.5,
  147264. };
  147265. static long _vq_quantmap__44u1__p6_0[] = {
  147266. 11, 9, 7, 5, 3, 1, 0, 2,
  147267. 4, 6, 8, 10, 12,
  147268. };
  147269. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147270. _vq_quantthresh__44u1__p6_0,
  147271. _vq_quantmap__44u1__p6_0,
  147272. 13,
  147273. 13
  147274. };
  147275. static static_codebook _44u1__p6_0 = {
  147276. 2, 169,
  147277. _vq_lengthlist__44u1__p6_0,
  147278. 1, -526516224, 1616117760, 4, 0,
  147279. _vq_quantlist__44u1__p6_0,
  147280. NULL,
  147281. &_vq_auxt__44u1__p6_0,
  147282. NULL,
  147283. 0
  147284. };
  147285. static long _vq_quantlist__44u1__p6_1[] = {
  147286. 2,
  147287. 1,
  147288. 3,
  147289. 0,
  147290. 4,
  147291. };
  147292. static long _vq_lengthlist__44u1__p6_1[] = {
  147293. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147294. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147295. };
  147296. static float _vq_quantthresh__44u1__p6_1[] = {
  147297. -1.5, -0.5, 0.5, 1.5,
  147298. };
  147299. static long _vq_quantmap__44u1__p6_1[] = {
  147300. 3, 1, 0, 2, 4,
  147301. };
  147302. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147303. _vq_quantthresh__44u1__p6_1,
  147304. _vq_quantmap__44u1__p6_1,
  147305. 5,
  147306. 5
  147307. };
  147308. static static_codebook _44u1__p6_1 = {
  147309. 2, 25,
  147310. _vq_lengthlist__44u1__p6_1,
  147311. 1, -533725184, 1611661312, 3, 0,
  147312. _vq_quantlist__44u1__p6_1,
  147313. NULL,
  147314. &_vq_auxt__44u1__p6_1,
  147315. NULL,
  147316. 0
  147317. };
  147318. static long _vq_quantlist__44u1__p7_0[] = {
  147319. 3,
  147320. 2,
  147321. 4,
  147322. 1,
  147323. 5,
  147324. 0,
  147325. 6,
  147326. };
  147327. static long _vq_lengthlist__44u1__p7_0[] = {
  147328. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147329. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147330. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147331. 8,
  147332. };
  147333. static float _vq_quantthresh__44u1__p7_0[] = {
  147334. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147335. };
  147336. static long _vq_quantmap__44u1__p7_0[] = {
  147337. 5, 3, 1, 0, 2, 4, 6,
  147338. };
  147339. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147340. _vq_quantthresh__44u1__p7_0,
  147341. _vq_quantmap__44u1__p7_0,
  147342. 7,
  147343. 7
  147344. };
  147345. static static_codebook _44u1__p7_0 = {
  147346. 2, 49,
  147347. _vq_lengthlist__44u1__p7_0,
  147348. 1, -518017024, 1626677248, 3, 0,
  147349. _vq_quantlist__44u1__p7_0,
  147350. NULL,
  147351. &_vq_auxt__44u1__p7_0,
  147352. NULL,
  147353. 0
  147354. };
  147355. static long _vq_quantlist__44u1__p7_1[] = {
  147356. 6,
  147357. 5,
  147358. 7,
  147359. 4,
  147360. 8,
  147361. 3,
  147362. 9,
  147363. 2,
  147364. 10,
  147365. 1,
  147366. 11,
  147367. 0,
  147368. 12,
  147369. };
  147370. static long _vq_lengthlist__44u1__p7_1[] = {
  147371. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147372. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147373. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147374. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147375. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147376. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147377. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147378. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147379. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147380. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147381. 15,15,15,15,15,15,15,15,15,
  147382. };
  147383. static float _vq_quantthresh__44u1__p7_1[] = {
  147384. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147385. 32.5, 45.5, 58.5, 71.5,
  147386. };
  147387. static long _vq_quantmap__44u1__p7_1[] = {
  147388. 11, 9, 7, 5, 3, 1, 0, 2,
  147389. 4, 6, 8, 10, 12,
  147390. };
  147391. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147392. _vq_quantthresh__44u1__p7_1,
  147393. _vq_quantmap__44u1__p7_1,
  147394. 13,
  147395. 13
  147396. };
  147397. static static_codebook _44u1__p7_1 = {
  147398. 2, 169,
  147399. _vq_lengthlist__44u1__p7_1,
  147400. 1, -523010048, 1618608128, 4, 0,
  147401. _vq_quantlist__44u1__p7_1,
  147402. NULL,
  147403. &_vq_auxt__44u1__p7_1,
  147404. NULL,
  147405. 0
  147406. };
  147407. static long _vq_quantlist__44u1__p7_2[] = {
  147408. 6,
  147409. 5,
  147410. 7,
  147411. 4,
  147412. 8,
  147413. 3,
  147414. 9,
  147415. 2,
  147416. 10,
  147417. 1,
  147418. 11,
  147419. 0,
  147420. 12,
  147421. };
  147422. static long _vq_lengthlist__44u1__p7_2[] = {
  147423. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147424. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147425. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147426. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147427. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147428. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147429. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147430. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147431. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147432. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147433. 9, 9, 9,10, 9, 9,10,10, 9,
  147434. };
  147435. static float _vq_quantthresh__44u1__p7_2[] = {
  147436. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147437. 2.5, 3.5, 4.5, 5.5,
  147438. };
  147439. static long _vq_quantmap__44u1__p7_2[] = {
  147440. 11, 9, 7, 5, 3, 1, 0, 2,
  147441. 4, 6, 8, 10, 12,
  147442. };
  147443. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147444. _vq_quantthresh__44u1__p7_2,
  147445. _vq_quantmap__44u1__p7_2,
  147446. 13,
  147447. 13
  147448. };
  147449. static static_codebook _44u1__p7_2 = {
  147450. 2, 169,
  147451. _vq_lengthlist__44u1__p7_2,
  147452. 1, -531103744, 1611661312, 4, 0,
  147453. _vq_quantlist__44u1__p7_2,
  147454. NULL,
  147455. &_vq_auxt__44u1__p7_2,
  147456. NULL,
  147457. 0
  147458. };
  147459. static long _huff_lengthlist__44u1__short[] = {
  147460. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147461. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147462. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147463. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147464. };
  147465. static static_codebook _huff_book__44u1__short = {
  147466. 2, 64,
  147467. _huff_lengthlist__44u1__short,
  147468. 0, 0, 0, 0, 0,
  147469. NULL,
  147470. NULL,
  147471. NULL,
  147472. NULL,
  147473. 0
  147474. };
  147475. static long _huff_lengthlist__44u2__long[] = {
  147476. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147477. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147478. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147479. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147480. };
  147481. static static_codebook _huff_book__44u2__long = {
  147482. 2, 64,
  147483. _huff_lengthlist__44u2__long,
  147484. 0, 0, 0, 0, 0,
  147485. NULL,
  147486. NULL,
  147487. NULL,
  147488. NULL,
  147489. 0
  147490. };
  147491. static long _vq_quantlist__44u2__p1_0[] = {
  147492. 1,
  147493. 0,
  147494. 2,
  147495. };
  147496. static long _vq_lengthlist__44u2__p1_0[] = {
  147497. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147498. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147499. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147500. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147501. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147502. 13,
  147503. };
  147504. static float _vq_quantthresh__44u2__p1_0[] = {
  147505. -0.5, 0.5,
  147506. };
  147507. static long _vq_quantmap__44u2__p1_0[] = {
  147508. 1, 0, 2,
  147509. };
  147510. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147511. _vq_quantthresh__44u2__p1_0,
  147512. _vq_quantmap__44u2__p1_0,
  147513. 3,
  147514. 3
  147515. };
  147516. static static_codebook _44u2__p1_0 = {
  147517. 4, 81,
  147518. _vq_lengthlist__44u2__p1_0,
  147519. 1, -535822336, 1611661312, 2, 0,
  147520. _vq_quantlist__44u2__p1_0,
  147521. NULL,
  147522. &_vq_auxt__44u2__p1_0,
  147523. NULL,
  147524. 0
  147525. };
  147526. static long _vq_quantlist__44u2__p2_0[] = {
  147527. 1,
  147528. 0,
  147529. 2,
  147530. };
  147531. static long _vq_lengthlist__44u2__p2_0[] = {
  147532. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147533. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147534. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147535. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147536. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147537. 9,
  147538. };
  147539. static float _vq_quantthresh__44u2__p2_0[] = {
  147540. -0.5, 0.5,
  147541. };
  147542. static long _vq_quantmap__44u2__p2_0[] = {
  147543. 1, 0, 2,
  147544. };
  147545. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147546. _vq_quantthresh__44u2__p2_0,
  147547. _vq_quantmap__44u2__p2_0,
  147548. 3,
  147549. 3
  147550. };
  147551. static static_codebook _44u2__p2_0 = {
  147552. 4, 81,
  147553. _vq_lengthlist__44u2__p2_0,
  147554. 1, -535822336, 1611661312, 2, 0,
  147555. _vq_quantlist__44u2__p2_0,
  147556. NULL,
  147557. &_vq_auxt__44u2__p2_0,
  147558. NULL,
  147559. 0
  147560. };
  147561. static long _vq_quantlist__44u2__p3_0[] = {
  147562. 2,
  147563. 1,
  147564. 3,
  147565. 0,
  147566. 4,
  147567. };
  147568. static long _vq_lengthlist__44u2__p3_0[] = {
  147569. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147570. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147571. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147572. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147573. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147574. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147575. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147576. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147577. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147578. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147579. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147580. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147581. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147582. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147583. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147584. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147585. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147586. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147587. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147588. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147589. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147590. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147591. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147592. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147593. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147594. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147595. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147596. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147597. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147598. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147599. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147600. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147601. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147602. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147603. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147604. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147605. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147606. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147607. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147608. 0,
  147609. };
  147610. static float _vq_quantthresh__44u2__p3_0[] = {
  147611. -1.5, -0.5, 0.5, 1.5,
  147612. };
  147613. static long _vq_quantmap__44u2__p3_0[] = {
  147614. 3, 1, 0, 2, 4,
  147615. };
  147616. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147617. _vq_quantthresh__44u2__p3_0,
  147618. _vq_quantmap__44u2__p3_0,
  147619. 5,
  147620. 5
  147621. };
  147622. static static_codebook _44u2__p3_0 = {
  147623. 4, 625,
  147624. _vq_lengthlist__44u2__p3_0,
  147625. 1, -533725184, 1611661312, 3, 0,
  147626. _vq_quantlist__44u2__p3_0,
  147627. NULL,
  147628. &_vq_auxt__44u2__p3_0,
  147629. NULL,
  147630. 0
  147631. };
  147632. static long _vq_quantlist__44u2__p4_0[] = {
  147633. 2,
  147634. 1,
  147635. 3,
  147636. 0,
  147637. 4,
  147638. };
  147639. static long _vq_lengthlist__44u2__p4_0[] = {
  147640. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147641. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147642. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147643. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147644. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147645. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147646. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147647. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147648. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147649. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147650. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147651. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147652. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147653. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147654. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147655. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147656. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147657. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147658. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147659. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147660. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147661. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147662. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147663. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147664. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147665. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147666. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147667. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147668. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147669. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147670. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147671. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147672. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147673. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147674. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147675. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147676. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147677. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147678. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147679. 13,
  147680. };
  147681. static float _vq_quantthresh__44u2__p4_0[] = {
  147682. -1.5, -0.5, 0.5, 1.5,
  147683. };
  147684. static long _vq_quantmap__44u2__p4_0[] = {
  147685. 3, 1, 0, 2, 4,
  147686. };
  147687. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147688. _vq_quantthresh__44u2__p4_0,
  147689. _vq_quantmap__44u2__p4_0,
  147690. 5,
  147691. 5
  147692. };
  147693. static static_codebook _44u2__p4_0 = {
  147694. 4, 625,
  147695. _vq_lengthlist__44u2__p4_0,
  147696. 1, -533725184, 1611661312, 3, 0,
  147697. _vq_quantlist__44u2__p4_0,
  147698. NULL,
  147699. &_vq_auxt__44u2__p4_0,
  147700. NULL,
  147701. 0
  147702. };
  147703. static long _vq_quantlist__44u2__p5_0[] = {
  147704. 4,
  147705. 3,
  147706. 5,
  147707. 2,
  147708. 6,
  147709. 1,
  147710. 7,
  147711. 0,
  147712. 8,
  147713. };
  147714. static long _vq_lengthlist__44u2__p5_0[] = {
  147715. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147716. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147717. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147718. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147719. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147720. 13,
  147721. };
  147722. static float _vq_quantthresh__44u2__p5_0[] = {
  147723. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147724. };
  147725. static long _vq_quantmap__44u2__p5_0[] = {
  147726. 7, 5, 3, 1, 0, 2, 4, 6,
  147727. 8,
  147728. };
  147729. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147730. _vq_quantthresh__44u2__p5_0,
  147731. _vq_quantmap__44u2__p5_0,
  147732. 9,
  147733. 9
  147734. };
  147735. static static_codebook _44u2__p5_0 = {
  147736. 2, 81,
  147737. _vq_lengthlist__44u2__p5_0,
  147738. 1, -531628032, 1611661312, 4, 0,
  147739. _vq_quantlist__44u2__p5_0,
  147740. NULL,
  147741. &_vq_auxt__44u2__p5_0,
  147742. NULL,
  147743. 0
  147744. };
  147745. static long _vq_quantlist__44u2__p6_0[] = {
  147746. 6,
  147747. 5,
  147748. 7,
  147749. 4,
  147750. 8,
  147751. 3,
  147752. 9,
  147753. 2,
  147754. 10,
  147755. 1,
  147756. 11,
  147757. 0,
  147758. 12,
  147759. };
  147760. static long _vq_lengthlist__44u2__p6_0[] = {
  147761. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147762. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147763. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147764. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147765. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147766. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147767. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147768. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147769. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147770. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147771. 15,17,17,16,18,17,18, 0, 0,
  147772. };
  147773. static float _vq_quantthresh__44u2__p6_0[] = {
  147774. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147775. 12.5, 17.5, 22.5, 27.5,
  147776. };
  147777. static long _vq_quantmap__44u2__p6_0[] = {
  147778. 11, 9, 7, 5, 3, 1, 0, 2,
  147779. 4, 6, 8, 10, 12,
  147780. };
  147781. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147782. _vq_quantthresh__44u2__p6_0,
  147783. _vq_quantmap__44u2__p6_0,
  147784. 13,
  147785. 13
  147786. };
  147787. static static_codebook _44u2__p6_0 = {
  147788. 2, 169,
  147789. _vq_lengthlist__44u2__p6_0,
  147790. 1, -526516224, 1616117760, 4, 0,
  147791. _vq_quantlist__44u2__p6_0,
  147792. NULL,
  147793. &_vq_auxt__44u2__p6_0,
  147794. NULL,
  147795. 0
  147796. };
  147797. static long _vq_quantlist__44u2__p6_1[] = {
  147798. 2,
  147799. 1,
  147800. 3,
  147801. 0,
  147802. 4,
  147803. };
  147804. static long _vq_lengthlist__44u2__p6_1[] = {
  147805. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147806. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147807. };
  147808. static float _vq_quantthresh__44u2__p6_1[] = {
  147809. -1.5, -0.5, 0.5, 1.5,
  147810. };
  147811. static long _vq_quantmap__44u2__p6_1[] = {
  147812. 3, 1, 0, 2, 4,
  147813. };
  147814. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147815. _vq_quantthresh__44u2__p6_1,
  147816. _vq_quantmap__44u2__p6_1,
  147817. 5,
  147818. 5
  147819. };
  147820. static static_codebook _44u2__p6_1 = {
  147821. 2, 25,
  147822. _vq_lengthlist__44u2__p6_1,
  147823. 1, -533725184, 1611661312, 3, 0,
  147824. _vq_quantlist__44u2__p6_1,
  147825. NULL,
  147826. &_vq_auxt__44u2__p6_1,
  147827. NULL,
  147828. 0
  147829. };
  147830. static long _vq_quantlist__44u2__p7_0[] = {
  147831. 4,
  147832. 3,
  147833. 5,
  147834. 2,
  147835. 6,
  147836. 1,
  147837. 7,
  147838. 0,
  147839. 8,
  147840. };
  147841. static long _vq_lengthlist__44u2__p7_0[] = {
  147842. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147843. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147845. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147846. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147847. 11,
  147848. };
  147849. static float _vq_quantthresh__44u2__p7_0[] = {
  147850. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147851. };
  147852. static long _vq_quantmap__44u2__p7_0[] = {
  147853. 7, 5, 3, 1, 0, 2, 4, 6,
  147854. 8,
  147855. };
  147856. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147857. _vq_quantthresh__44u2__p7_0,
  147858. _vq_quantmap__44u2__p7_0,
  147859. 9,
  147860. 9
  147861. };
  147862. static static_codebook _44u2__p7_0 = {
  147863. 2, 81,
  147864. _vq_lengthlist__44u2__p7_0,
  147865. 1, -516612096, 1626677248, 4, 0,
  147866. _vq_quantlist__44u2__p7_0,
  147867. NULL,
  147868. &_vq_auxt__44u2__p7_0,
  147869. NULL,
  147870. 0
  147871. };
  147872. static long _vq_quantlist__44u2__p7_1[] = {
  147873. 6,
  147874. 5,
  147875. 7,
  147876. 4,
  147877. 8,
  147878. 3,
  147879. 9,
  147880. 2,
  147881. 10,
  147882. 1,
  147883. 11,
  147884. 0,
  147885. 12,
  147886. };
  147887. static long _vq_lengthlist__44u2__p7_1[] = {
  147888. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147889. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147890. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147891. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147892. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147893. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147894. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147895. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147896. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147897. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147898. 14,14,14,17,15,17,17,17,17,
  147899. };
  147900. static float _vq_quantthresh__44u2__p7_1[] = {
  147901. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147902. 32.5, 45.5, 58.5, 71.5,
  147903. };
  147904. static long _vq_quantmap__44u2__p7_1[] = {
  147905. 11, 9, 7, 5, 3, 1, 0, 2,
  147906. 4, 6, 8, 10, 12,
  147907. };
  147908. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147909. _vq_quantthresh__44u2__p7_1,
  147910. _vq_quantmap__44u2__p7_1,
  147911. 13,
  147912. 13
  147913. };
  147914. static static_codebook _44u2__p7_1 = {
  147915. 2, 169,
  147916. _vq_lengthlist__44u2__p7_1,
  147917. 1, -523010048, 1618608128, 4, 0,
  147918. _vq_quantlist__44u2__p7_1,
  147919. NULL,
  147920. &_vq_auxt__44u2__p7_1,
  147921. NULL,
  147922. 0
  147923. };
  147924. static long _vq_quantlist__44u2__p7_2[] = {
  147925. 6,
  147926. 5,
  147927. 7,
  147928. 4,
  147929. 8,
  147930. 3,
  147931. 9,
  147932. 2,
  147933. 10,
  147934. 1,
  147935. 11,
  147936. 0,
  147937. 12,
  147938. };
  147939. static long _vq_lengthlist__44u2__p7_2[] = {
  147940. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147941. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147942. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147943. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147944. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147945. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147946. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147947. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147948. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147949. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147950. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147951. };
  147952. static float _vq_quantthresh__44u2__p7_2[] = {
  147953. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147954. 2.5, 3.5, 4.5, 5.5,
  147955. };
  147956. static long _vq_quantmap__44u2__p7_2[] = {
  147957. 11, 9, 7, 5, 3, 1, 0, 2,
  147958. 4, 6, 8, 10, 12,
  147959. };
  147960. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147961. _vq_quantthresh__44u2__p7_2,
  147962. _vq_quantmap__44u2__p7_2,
  147963. 13,
  147964. 13
  147965. };
  147966. static static_codebook _44u2__p7_2 = {
  147967. 2, 169,
  147968. _vq_lengthlist__44u2__p7_2,
  147969. 1, -531103744, 1611661312, 4, 0,
  147970. _vq_quantlist__44u2__p7_2,
  147971. NULL,
  147972. &_vq_auxt__44u2__p7_2,
  147973. NULL,
  147974. 0
  147975. };
  147976. static long _huff_lengthlist__44u2__short[] = {
  147977. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147978. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147979. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147980. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147981. };
  147982. static static_codebook _huff_book__44u2__short = {
  147983. 2, 64,
  147984. _huff_lengthlist__44u2__short,
  147985. 0, 0, 0, 0, 0,
  147986. NULL,
  147987. NULL,
  147988. NULL,
  147989. NULL,
  147990. 0
  147991. };
  147992. static long _huff_lengthlist__44u3__long[] = {
  147993. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147994. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147995. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147996. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147997. };
  147998. static static_codebook _huff_book__44u3__long = {
  147999. 2, 64,
  148000. _huff_lengthlist__44u3__long,
  148001. 0, 0, 0, 0, 0,
  148002. NULL,
  148003. NULL,
  148004. NULL,
  148005. NULL,
  148006. 0
  148007. };
  148008. static long _vq_quantlist__44u3__p1_0[] = {
  148009. 1,
  148010. 0,
  148011. 2,
  148012. };
  148013. static long _vq_lengthlist__44u3__p1_0[] = {
  148014. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148015. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148016. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  148017. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148018. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  148019. 13,
  148020. };
  148021. static float _vq_quantthresh__44u3__p1_0[] = {
  148022. -0.5, 0.5,
  148023. };
  148024. static long _vq_quantmap__44u3__p1_0[] = {
  148025. 1, 0, 2,
  148026. };
  148027. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  148028. _vq_quantthresh__44u3__p1_0,
  148029. _vq_quantmap__44u3__p1_0,
  148030. 3,
  148031. 3
  148032. };
  148033. static static_codebook _44u3__p1_0 = {
  148034. 4, 81,
  148035. _vq_lengthlist__44u3__p1_0,
  148036. 1, -535822336, 1611661312, 2, 0,
  148037. _vq_quantlist__44u3__p1_0,
  148038. NULL,
  148039. &_vq_auxt__44u3__p1_0,
  148040. NULL,
  148041. 0
  148042. };
  148043. static long _vq_quantlist__44u3__p2_0[] = {
  148044. 1,
  148045. 0,
  148046. 2,
  148047. };
  148048. static long _vq_lengthlist__44u3__p2_0[] = {
  148049. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148050. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  148051. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148052. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  148053. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  148054. 9,
  148055. };
  148056. static float _vq_quantthresh__44u3__p2_0[] = {
  148057. -0.5, 0.5,
  148058. };
  148059. static long _vq_quantmap__44u3__p2_0[] = {
  148060. 1, 0, 2,
  148061. };
  148062. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  148063. _vq_quantthresh__44u3__p2_0,
  148064. _vq_quantmap__44u3__p2_0,
  148065. 3,
  148066. 3
  148067. };
  148068. static static_codebook _44u3__p2_0 = {
  148069. 4, 81,
  148070. _vq_lengthlist__44u3__p2_0,
  148071. 1, -535822336, 1611661312, 2, 0,
  148072. _vq_quantlist__44u3__p2_0,
  148073. NULL,
  148074. &_vq_auxt__44u3__p2_0,
  148075. NULL,
  148076. 0
  148077. };
  148078. static long _vq_quantlist__44u3__p3_0[] = {
  148079. 2,
  148080. 1,
  148081. 3,
  148082. 0,
  148083. 4,
  148084. };
  148085. static long _vq_lengthlist__44u3__p3_0[] = {
  148086. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148087. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  148088. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  148089. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  148090. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  148091. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  148092. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  148093. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  148094. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  148095. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  148096. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  148097. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  148098. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  148099. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  148100. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  148101. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  148102. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  148103. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  148104. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  148105. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  148106. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  148107. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  148108. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  148109. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  148110. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  148111. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  148112. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  148113. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  148114. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  148115. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  148116. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  148117. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  148118. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  148119. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  148120. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  148121. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  148122. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  148123. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  148124. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  148125. 0,
  148126. };
  148127. static float _vq_quantthresh__44u3__p3_0[] = {
  148128. -1.5, -0.5, 0.5, 1.5,
  148129. };
  148130. static long _vq_quantmap__44u3__p3_0[] = {
  148131. 3, 1, 0, 2, 4,
  148132. };
  148133. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  148134. _vq_quantthresh__44u3__p3_0,
  148135. _vq_quantmap__44u3__p3_0,
  148136. 5,
  148137. 5
  148138. };
  148139. static static_codebook _44u3__p3_0 = {
  148140. 4, 625,
  148141. _vq_lengthlist__44u3__p3_0,
  148142. 1, -533725184, 1611661312, 3, 0,
  148143. _vq_quantlist__44u3__p3_0,
  148144. NULL,
  148145. &_vq_auxt__44u3__p3_0,
  148146. NULL,
  148147. 0
  148148. };
  148149. static long _vq_quantlist__44u3__p4_0[] = {
  148150. 2,
  148151. 1,
  148152. 3,
  148153. 0,
  148154. 4,
  148155. };
  148156. static long _vq_lengthlist__44u3__p4_0[] = {
  148157. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148158. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148159. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148160. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148161. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148162. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  148163. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  148164. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  148165. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148166. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148167. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148168. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148169. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148170. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  148171. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148172. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148173. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148174. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148175. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148176. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148177. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148178. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148179. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148180. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148181. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  148182. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  148183. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  148184. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  148185. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148186. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  148187. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  148188. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148189. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148190. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148191. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  148192. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148193. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148194. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148195. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148196. 13,
  148197. };
  148198. static float _vq_quantthresh__44u3__p4_0[] = {
  148199. -1.5, -0.5, 0.5, 1.5,
  148200. };
  148201. static long _vq_quantmap__44u3__p4_0[] = {
  148202. 3, 1, 0, 2, 4,
  148203. };
  148204. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148205. _vq_quantthresh__44u3__p4_0,
  148206. _vq_quantmap__44u3__p4_0,
  148207. 5,
  148208. 5
  148209. };
  148210. static static_codebook _44u3__p4_0 = {
  148211. 4, 625,
  148212. _vq_lengthlist__44u3__p4_0,
  148213. 1, -533725184, 1611661312, 3, 0,
  148214. _vq_quantlist__44u3__p4_0,
  148215. NULL,
  148216. &_vq_auxt__44u3__p4_0,
  148217. NULL,
  148218. 0
  148219. };
  148220. static long _vq_quantlist__44u3__p5_0[] = {
  148221. 4,
  148222. 3,
  148223. 5,
  148224. 2,
  148225. 6,
  148226. 1,
  148227. 7,
  148228. 0,
  148229. 8,
  148230. };
  148231. static long _vq_lengthlist__44u3__p5_0[] = {
  148232. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148233. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148234. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148235. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148236. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148237. 12,
  148238. };
  148239. static float _vq_quantthresh__44u3__p5_0[] = {
  148240. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148241. };
  148242. static long _vq_quantmap__44u3__p5_0[] = {
  148243. 7, 5, 3, 1, 0, 2, 4, 6,
  148244. 8,
  148245. };
  148246. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148247. _vq_quantthresh__44u3__p5_0,
  148248. _vq_quantmap__44u3__p5_0,
  148249. 9,
  148250. 9
  148251. };
  148252. static static_codebook _44u3__p5_0 = {
  148253. 2, 81,
  148254. _vq_lengthlist__44u3__p5_0,
  148255. 1, -531628032, 1611661312, 4, 0,
  148256. _vq_quantlist__44u3__p5_0,
  148257. NULL,
  148258. &_vq_auxt__44u3__p5_0,
  148259. NULL,
  148260. 0
  148261. };
  148262. static long _vq_quantlist__44u3__p6_0[] = {
  148263. 6,
  148264. 5,
  148265. 7,
  148266. 4,
  148267. 8,
  148268. 3,
  148269. 9,
  148270. 2,
  148271. 10,
  148272. 1,
  148273. 11,
  148274. 0,
  148275. 12,
  148276. };
  148277. static long _vq_lengthlist__44u3__p6_0[] = {
  148278. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148279. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148280. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148281. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148282. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148283. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148284. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148285. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148286. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148287. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148288. 15,16,16,16,17,18,16,20,18,
  148289. };
  148290. static float _vq_quantthresh__44u3__p6_0[] = {
  148291. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148292. 12.5, 17.5, 22.5, 27.5,
  148293. };
  148294. static long _vq_quantmap__44u3__p6_0[] = {
  148295. 11, 9, 7, 5, 3, 1, 0, 2,
  148296. 4, 6, 8, 10, 12,
  148297. };
  148298. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148299. _vq_quantthresh__44u3__p6_0,
  148300. _vq_quantmap__44u3__p6_0,
  148301. 13,
  148302. 13
  148303. };
  148304. static static_codebook _44u3__p6_0 = {
  148305. 2, 169,
  148306. _vq_lengthlist__44u3__p6_0,
  148307. 1, -526516224, 1616117760, 4, 0,
  148308. _vq_quantlist__44u3__p6_0,
  148309. NULL,
  148310. &_vq_auxt__44u3__p6_0,
  148311. NULL,
  148312. 0
  148313. };
  148314. static long _vq_quantlist__44u3__p6_1[] = {
  148315. 2,
  148316. 1,
  148317. 3,
  148318. 0,
  148319. 4,
  148320. };
  148321. static long _vq_lengthlist__44u3__p6_1[] = {
  148322. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148323. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148324. };
  148325. static float _vq_quantthresh__44u3__p6_1[] = {
  148326. -1.5, -0.5, 0.5, 1.5,
  148327. };
  148328. static long _vq_quantmap__44u3__p6_1[] = {
  148329. 3, 1, 0, 2, 4,
  148330. };
  148331. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148332. _vq_quantthresh__44u3__p6_1,
  148333. _vq_quantmap__44u3__p6_1,
  148334. 5,
  148335. 5
  148336. };
  148337. static static_codebook _44u3__p6_1 = {
  148338. 2, 25,
  148339. _vq_lengthlist__44u3__p6_1,
  148340. 1, -533725184, 1611661312, 3, 0,
  148341. _vq_quantlist__44u3__p6_1,
  148342. NULL,
  148343. &_vq_auxt__44u3__p6_1,
  148344. NULL,
  148345. 0
  148346. };
  148347. static long _vq_quantlist__44u3__p7_0[] = {
  148348. 4,
  148349. 3,
  148350. 5,
  148351. 2,
  148352. 6,
  148353. 1,
  148354. 7,
  148355. 0,
  148356. 8,
  148357. };
  148358. static long _vq_lengthlist__44u3__p7_0[] = {
  148359. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148360. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148361. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148362. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148363. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148364. 9,
  148365. };
  148366. static float _vq_quantthresh__44u3__p7_0[] = {
  148367. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148368. };
  148369. static long _vq_quantmap__44u3__p7_0[] = {
  148370. 7, 5, 3, 1, 0, 2, 4, 6,
  148371. 8,
  148372. };
  148373. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148374. _vq_quantthresh__44u3__p7_0,
  148375. _vq_quantmap__44u3__p7_0,
  148376. 9,
  148377. 9
  148378. };
  148379. static static_codebook _44u3__p7_0 = {
  148380. 2, 81,
  148381. _vq_lengthlist__44u3__p7_0,
  148382. 1, -515907584, 1627381760, 4, 0,
  148383. _vq_quantlist__44u3__p7_0,
  148384. NULL,
  148385. &_vq_auxt__44u3__p7_0,
  148386. NULL,
  148387. 0
  148388. };
  148389. static long _vq_quantlist__44u3__p7_1[] = {
  148390. 7,
  148391. 6,
  148392. 8,
  148393. 5,
  148394. 9,
  148395. 4,
  148396. 10,
  148397. 3,
  148398. 11,
  148399. 2,
  148400. 12,
  148401. 1,
  148402. 13,
  148403. 0,
  148404. 14,
  148405. };
  148406. static long _vq_lengthlist__44u3__p7_1[] = {
  148407. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148408. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148409. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148410. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148411. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148412. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148413. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148414. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148415. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148416. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148417. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148418. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148419. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148420. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148421. 17,
  148422. };
  148423. static float _vq_quantthresh__44u3__p7_1[] = {
  148424. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148425. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148426. };
  148427. static long _vq_quantmap__44u3__p7_1[] = {
  148428. 13, 11, 9, 7, 5, 3, 1, 0,
  148429. 2, 4, 6, 8, 10, 12, 14,
  148430. };
  148431. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148432. _vq_quantthresh__44u3__p7_1,
  148433. _vq_quantmap__44u3__p7_1,
  148434. 15,
  148435. 15
  148436. };
  148437. static static_codebook _44u3__p7_1 = {
  148438. 2, 225,
  148439. _vq_lengthlist__44u3__p7_1,
  148440. 1, -522338304, 1620115456, 4, 0,
  148441. _vq_quantlist__44u3__p7_1,
  148442. NULL,
  148443. &_vq_auxt__44u3__p7_1,
  148444. NULL,
  148445. 0
  148446. };
  148447. static long _vq_quantlist__44u3__p7_2[] = {
  148448. 8,
  148449. 7,
  148450. 9,
  148451. 6,
  148452. 10,
  148453. 5,
  148454. 11,
  148455. 4,
  148456. 12,
  148457. 3,
  148458. 13,
  148459. 2,
  148460. 14,
  148461. 1,
  148462. 15,
  148463. 0,
  148464. 16,
  148465. };
  148466. static long _vq_lengthlist__44u3__p7_2[] = {
  148467. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148468. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148469. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148470. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148471. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148472. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148473. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148474. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148475. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148476. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148477. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148478. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148479. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148480. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148481. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148482. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148483. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148484. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148485. 11,
  148486. };
  148487. static float _vq_quantthresh__44u3__p7_2[] = {
  148488. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148489. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148490. };
  148491. static long _vq_quantmap__44u3__p7_2[] = {
  148492. 15, 13, 11, 9, 7, 5, 3, 1,
  148493. 0, 2, 4, 6, 8, 10, 12, 14,
  148494. 16,
  148495. };
  148496. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148497. _vq_quantthresh__44u3__p7_2,
  148498. _vq_quantmap__44u3__p7_2,
  148499. 17,
  148500. 17
  148501. };
  148502. static static_codebook _44u3__p7_2 = {
  148503. 2, 289,
  148504. _vq_lengthlist__44u3__p7_2,
  148505. 1, -529530880, 1611661312, 5, 0,
  148506. _vq_quantlist__44u3__p7_2,
  148507. NULL,
  148508. &_vq_auxt__44u3__p7_2,
  148509. NULL,
  148510. 0
  148511. };
  148512. static long _huff_lengthlist__44u3__short[] = {
  148513. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148514. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148515. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148516. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148517. };
  148518. static static_codebook _huff_book__44u3__short = {
  148519. 2, 64,
  148520. _huff_lengthlist__44u3__short,
  148521. 0, 0, 0, 0, 0,
  148522. NULL,
  148523. NULL,
  148524. NULL,
  148525. NULL,
  148526. 0
  148527. };
  148528. static long _huff_lengthlist__44u4__long[] = {
  148529. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148530. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148531. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148532. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148533. };
  148534. static static_codebook _huff_book__44u4__long = {
  148535. 2, 64,
  148536. _huff_lengthlist__44u4__long,
  148537. 0, 0, 0, 0, 0,
  148538. NULL,
  148539. NULL,
  148540. NULL,
  148541. NULL,
  148542. 0
  148543. };
  148544. static long _vq_quantlist__44u4__p1_0[] = {
  148545. 1,
  148546. 0,
  148547. 2,
  148548. };
  148549. static long _vq_lengthlist__44u4__p1_0[] = {
  148550. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148551. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148552. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148553. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148554. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148555. 13,
  148556. };
  148557. static float _vq_quantthresh__44u4__p1_0[] = {
  148558. -0.5, 0.5,
  148559. };
  148560. static long _vq_quantmap__44u4__p1_0[] = {
  148561. 1, 0, 2,
  148562. };
  148563. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148564. _vq_quantthresh__44u4__p1_0,
  148565. _vq_quantmap__44u4__p1_0,
  148566. 3,
  148567. 3
  148568. };
  148569. static static_codebook _44u4__p1_0 = {
  148570. 4, 81,
  148571. _vq_lengthlist__44u4__p1_0,
  148572. 1, -535822336, 1611661312, 2, 0,
  148573. _vq_quantlist__44u4__p1_0,
  148574. NULL,
  148575. &_vq_auxt__44u4__p1_0,
  148576. NULL,
  148577. 0
  148578. };
  148579. static long _vq_quantlist__44u4__p2_0[] = {
  148580. 1,
  148581. 0,
  148582. 2,
  148583. };
  148584. static long _vq_lengthlist__44u4__p2_0[] = {
  148585. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148586. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148587. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148588. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148589. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148590. 9,
  148591. };
  148592. static float _vq_quantthresh__44u4__p2_0[] = {
  148593. -0.5, 0.5,
  148594. };
  148595. static long _vq_quantmap__44u4__p2_0[] = {
  148596. 1, 0, 2,
  148597. };
  148598. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148599. _vq_quantthresh__44u4__p2_0,
  148600. _vq_quantmap__44u4__p2_0,
  148601. 3,
  148602. 3
  148603. };
  148604. static static_codebook _44u4__p2_0 = {
  148605. 4, 81,
  148606. _vq_lengthlist__44u4__p2_0,
  148607. 1, -535822336, 1611661312, 2, 0,
  148608. _vq_quantlist__44u4__p2_0,
  148609. NULL,
  148610. &_vq_auxt__44u4__p2_0,
  148611. NULL,
  148612. 0
  148613. };
  148614. static long _vq_quantlist__44u4__p3_0[] = {
  148615. 2,
  148616. 1,
  148617. 3,
  148618. 0,
  148619. 4,
  148620. };
  148621. static long _vq_lengthlist__44u4__p3_0[] = {
  148622. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148623. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148624. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148625. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148626. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148627. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148628. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148629. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148630. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148631. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148632. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148633. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148634. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148635. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148636. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148637. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148638. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148639. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148640. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148641. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148642. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148643. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148644. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148645. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148646. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148647. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148648. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148649. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148650. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148651. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148652. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148653. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148654. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148655. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148656. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148657. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148658. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148659. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148660. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148661. 0,
  148662. };
  148663. static float _vq_quantthresh__44u4__p3_0[] = {
  148664. -1.5, -0.5, 0.5, 1.5,
  148665. };
  148666. static long _vq_quantmap__44u4__p3_0[] = {
  148667. 3, 1, 0, 2, 4,
  148668. };
  148669. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148670. _vq_quantthresh__44u4__p3_0,
  148671. _vq_quantmap__44u4__p3_0,
  148672. 5,
  148673. 5
  148674. };
  148675. static static_codebook _44u4__p3_0 = {
  148676. 4, 625,
  148677. _vq_lengthlist__44u4__p3_0,
  148678. 1, -533725184, 1611661312, 3, 0,
  148679. _vq_quantlist__44u4__p3_0,
  148680. NULL,
  148681. &_vq_auxt__44u4__p3_0,
  148682. NULL,
  148683. 0
  148684. };
  148685. static long _vq_quantlist__44u4__p4_0[] = {
  148686. 2,
  148687. 1,
  148688. 3,
  148689. 0,
  148690. 4,
  148691. };
  148692. static long _vq_lengthlist__44u4__p4_0[] = {
  148693. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148694. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148695. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148696. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148697. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148698. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148699. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148700. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148701. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148702. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148703. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148704. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148705. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148706. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148707. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148708. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148709. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148710. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148711. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148712. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148713. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148714. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148715. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148716. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148717. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148718. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148719. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148720. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148721. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148722. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148723. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148724. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148725. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148726. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148727. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148728. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148729. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148730. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148731. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148732. 13,
  148733. };
  148734. static float _vq_quantthresh__44u4__p4_0[] = {
  148735. -1.5, -0.5, 0.5, 1.5,
  148736. };
  148737. static long _vq_quantmap__44u4__p4_0[] = {
  148738. 3, 1, 0, 2, 4,
  148739. };
  148740. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148741. _vq_quantthresh__44u4__p4_0,
  148742. _vq_quantmap__44u4__p4_0,
  148743. 5,
  148744. 5
  148745. };
  148746. static static_codebook _44u4__p4_0 = {
  148747. 4, 625,
  148748. _vq_lengthlist__44u4__p4_0,
  148749. 1, -533725184, 1611661312, 3, 0,
  148750. _vq_quantlist__44u4__p4_0,
  148751. NULL,
  148752. &_vq_auxt__44u4__p4_0,
  148753. NULL,
  148754. 0
  148755. };
  148756. static long _vq_quantlist__44u4__p5_0[] = {
  148757. 4,
  148758. 3,
  148759. 5,
  148760. 2,
  148761. 6,
  148762. 1,
  148763. 7,
  148764. 0,
  148765. 8,
  148766. };
  148767. static long _vq_lengthlist__44u4__p5_0[] = {
  148768. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148769. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148770. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148771. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148772. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148773. 12,
  148774. };
  148775. static float _vq_quantthresh__44u4__p5_0[] = {
  148776. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148777. };
  148778. static long _vq_quantmap__44u4__p5_0[] = {
  148779. 7, 5, 3, 1, 0, 2, 4, 6,
  148780. 8,
  148781. };
  148782. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148783. _vq_quantthresh__44u4__p5_0,
  148784. _vq_quantmap__44u4__p5_0,
  148785. 9,
  148786. 9
  148787. };
  148788. static static_codebook _44u4__p5_0 = {
  148789. 2, 81,
  148790. _vq_lengthlist__44u4__p5_0,
  148791. 1, -531628032, 1611661312, 4, 0,
  148792. _vq_quantlist__44u4__p5_0,
  148793. NULL,
  148794. &_vq_auxt__44u4__p5_0,
  148795. NULL,
  148796. 0
  148797. };
  148798. static long _vq_quantlist__44u4__p6_0[] = {
  148799. 6,
  148800. 5,
  148801. 7,
  148802. 4,
  148803. 8,
  148804. 3,
  148805. 9,
  148806. 2,
  148807. 10,
  148808. 1,
  148809. 11,
  148810. 0,
  148811. 12,
  148812. };
  148813. static long _vq_lengthlist__44u4__p6_0[] = {
  148814. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148815. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148816. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148817. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148818. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148819. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148820. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148821. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148822. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148823. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148824. 16,16,16,17,17,18,17,20,21,
  148825. };
  148826. static float _vq_quantthresh__44u4__p6_0[] = {
  148827. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148828. 12.5, 17.5, 22.5, 27.5,
  148829. };
  148830. static long _vq_quantmap__44u4__p6_0[] = {
  148831. 11, 9, 7, 5, 3, 1, 0, 2,
  148832. 4, 6, 8, 10, 12,
  148833. };
  148834. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148835. _vq_quantthresh__44u4__p6_0,
  148836. _vq_quantmap__44u4__p6_0,
  148837. 13,
  148838. 13
  148839. };
  148840. static static_codebook _44u4__p6_0 = {
  148841. 2, 169,
  148842. _vq_lengthlist__44u4__p6_0,
  148843. 1, -526516224, 1616117760, 4, 0,
  148844. _vq_quantlist__44u4__p6_0,
  148845. NULL,
  148846. &_vq_auxt__44u4__p6_0,
  148847. NULL,
  148848. 0
  148849. };
  148850. static long _vq_quantlist__44u4__p6_1[] = {
  148851. 2,
  148852. 1,
  148853. 3,
  148854. 0,
  148855. 4,
  148856. };
  148857. static long _vq_lengthlist__44u4__p6_1[] = {
  148858. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148859. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148860. };
  148861. static float _vq_quantthresh__44u4__p6_1[] = {
  148862. -1.5, -0.5, 0.5, 1.5,
  148863. };
  148864. static long _vq_quantmap__44u4__p6_1[] = {
  148865. 3, 1, 0, 2, 4,
  148866. };
  148867. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148868. _vq_quantthresh__44u4__p6_1,
  148869. _vq_quantmap__44u4__p6_1,
  148870. 5,
  148871. 5
  148872. };
  148873. static static_codebook _44u4__p6_1 = {
  148874. 2, 25,
  148875. _vq_lengthlist__44u4__p6_1,
  148876. 1, -533725184, 1611661312, 3, 0,
  148877. _vq_quantlist__44u4__p6_1,
  148878. NULL,
  148879. &_vq_auxt__44u4__p6_1,
  148880. NULL,
  148881. 0
  148882. };
  148883. static long _vq_quantlist__44u4__p7_0[] = {
  148884. 6,
  148885. 5,
  148886. 7,
  148887. 4,
  148888. 8,
  148889. 3,
  148890. 9,
  148891. 2,
  148892. 10,
  148893. 1,
  148894. 11,
  148895. 0,
  148896. 12,
  148897. };
  148898. static long _vq_lengthlist__44u4__p7_0[] = {
  148899. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148900. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148901. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148902. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148903. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148904. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148905. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148906. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148907. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148908. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148909. 11,11,11,11,11,11,11,11,11,
  148910. };
  148911. static float _vq_quantthresh__44u4__p7_0[] = {
  148912. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148913. 637.5, 892.5, 1147.5, 1402.5,
  148914. };
  148915. static long _vq_quantmap__44u4__p7_0[] = {
  148916. 11, 9, 7, 5, 3, 1, 0, 2,
  148917. 4, 6, 8, 10, 12,
  148918. };
  148919. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148920. _vq_quantthresh__44u4__p7_0,
  148921. _vq_quantmap__44u4__p7_0,
  148922. 13,
  148923. 13
  148924. };
  148925. static static_codebook _44u4__p7_0 = {
  148926. 2, 169,
  148927. _vq_lengthlist__44u4__p7_0,
  148928. 1, -514332672, 1627381760, 4, 0,
  148929. _vq_quantlist__44u4__p7_0,
  148930. NULL,
  148931. &_vq_auxt__44u4__p7_0,
  148932. NULL,
  148933. 0
  148934. };
  148935. static long _vq_quantlist__44u4__p7_1[] = {
  148936. 7,
  148937. 6,
  148938. 8,
  148939. 5,
  148940. 9,
  148941. 4,
  148942. 10,
  148943. 3,
  148944. 11,
  148945. 2,
  148946. 12,
  148947. 1,
  148948. 13,
  148949. 0,
  148950. 14,
  148951. };
  148952. static long _vq_lengthlist__44u4__p7_1[] = {
  148953. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148954. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148955. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148956. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148957. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148958. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148959. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148960. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148961. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148962. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148963. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148964. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148965. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148966. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148967. 16,
  148968. };
  148969. static float _vq_quantthresh__44u4__p7_1[] = {
  148970. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148971. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148972. };
  148973. static long _vq_quantmap__44u4__p7_1[] = {
  148974. 13, 11, 9, 7, 5, 3, 1, 0,
  148975. 2, 4, 6, 8, 10, 12, 14,
  148976. };
  148977. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148978. _vq_quantthresh__44u4__p7_1,
  148979. _vq_quantmap__44u4__p7_1,
  148980. 15,
  148981. 15
  148982. };
  148983. static static_codebook _44u4__p7_1 = {
  148984. 2, 225,
  148985. _vq_lengthlist__44u4__p7_1,
  148986. 1, -522338304, 1620115456, 4, 0,
  148987. _vq_quantlist__44u4__p7_1,
  148988. NULL,
  148989. &_vq_auxt__44u4__p7_1,
  148990. NULL,
  148991. 0
  148992. };
  148993. static long _vq_quantlist__44u4__p7_2[] = {
  148994. 8,
  148995. 7,
  148996. 9,
  148997. 6,
  148998. 10,
  148999. 5,
  149000. 11,
  149001. 4,
  149002. 12,
  149003. 3,
  149004. 13,
  149005. 2,
  149006. 14,
  149007. 1,
  149008. 15,
  149009. 0,
  149010. 16,
  149011. };
  149012. static long _vq_lengthlist__44u4__p7_2[] = {
  149013. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149014. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149015. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149016. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149017. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  149018. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149019. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149020. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149021. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  149022. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  149023. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  149024. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  149025. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149026. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  149027. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149028. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149029. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149030. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  149031. 10,
  149032. };
  149033. static float _vq_quantthresh__44u4__p7_2[] = {
  149034. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149035. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149036. };
  149037. static long _vq_quantmap__44u4__p7_2[] = {
  149038. 15, 13, 11, 9, 7, 5, 3, 1,
  149039. 0, 2, 4, 6, 8, 10, 12, 14,
  149040. 16,
  149041. };
  149042. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  149043. _vq_quantthresh__44u4__p7_2,
  149044. _vq_quantmap__44u4__p7_2,
  149045. 17,
  149046. 17
  149047. };
  149048. static static_codebook _44u4__p7_2 = {
  149049. 2, 289,
  149050. _vq_lengthlist__44u4__p7_2,
  149051. 1, -529530880, 1611661312, 5, 0,
  149052. _vq_quantlist__44u4__p7_2,
  149053. NULL,
  149054. &_vq_auxt__44u4__p7_2,
  149055. NULL,
  149056. 0
  149057. };
  149058. static long _huff_lengthlist__44u4__short[] = {
  149059. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  149060. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  149061. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  149062. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  149063. };
  149064. static static_codebook _huff_book__44u4__short = {
  149065. 2, 64,
  149066. _huff_lengthlist__44u4__short,
  149067. 0, 0, 0, 0, 0,
  149068. NULL,
  149069. NULL,
  149070. NULL,
  149071. NULL,
  149072. 0
  149073. };
  149074. static long _huff_lengthlist__44u5__long[] = {
  149075. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  149076. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  149077. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  149078. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  149079. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  149080. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  149081. 14, 8, 7, 8,
  149082. };
  149083. static static_codebook _huff_book__44u5__long = {
  149084. 2, 100,
  149085. _huff_lengthlist__44u5__long,
  149086. 0, 0, 0, 0, 0,
  149087. NULL,
  149088. NULL,
  149089. NULL,
  149090. NULL,
  149091. 0
  149092. };
  149093. static long _vq_quantlist__44u5__p1_0[] = {
  149094. 1,
  149095. 0,
  149096. 2,
  149097. };
  149098. static long _vq_lengthlist__44u5__p1_0[] = {
  149099. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149100. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149101. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149102. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  149103. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149104. 12,
  149105. };
  149106. static float _vq_quantthresh__44u5__p1_0[] = {
  149107. -0.5, 0.5,
  149108. };
  149109. static long _vq_quantmap__44u5__p1_0[] = {
  149110. 1, 0, 2,
  149111. };
  149112. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  149113. _vq_quantthresh__44u5__p1_0,
  149114. _vq_quantmap__44u5__p1_0,
  149115. 3,
  149116. 3
  149117. };
  149118. static static_codebook _44u5__p1_0 = {
  149119. 4, 81,
  149120. _vq_lengthlist__44u5__p1_0,
  149121. 1, -535822336, 1611661312, 2, 0,
  149122. _vq_quantlist__44u5__p1_0,
  149123. NULL,
  149124. &_vq_auxt__44u5__p1_0,
  149125. NULL,
  149126. 0
  149127. };
  149128. static long _vq_quantlist__44u5__p2_0[] = {
  149129. 1,
  149130. 0,
  149131. 2,
  149132. };
  149133. static long _vq_lengthlist__44u5__p2_0[] = {
  149134. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149135. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149136. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149137. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149138. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149139. 9,
  149140. };
  149141. static float _vq_quantthresh__44u5__p2_0[] = {
  149142. -0.5, 0.5,
  149143. };
  149144. static long _vq_quantmap__44u5__p2_0[] = {
  149145. 1, 0, 2,
  149146. };
  149147. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  149148. _vq_quantthresh__44u5__p2_0,
  149149. _vq_quantmap__44u5__p2_0,
  149150. 3,
  149151. 3
  149152. };
  149153. static static_codebook _44u5__p2_0 = {
  149154. 4, 81,
  149155. _vq_lengthlist__44u5__p2_0,
  149156. 1, -535822336, 1611661312, 2, 0,
  149157. _vq_quantlist__44u5__p2_0,
  149158. NULL,
  149159. &_vq_auxt__44u5__p2_0,
  149160. NULL,
  149161. 0
  149162. };
  149163. static long _vq_quantlist__44u5__p3_0[] = {
  149164. 2,
  149165. 1,
  149166. 3,
  149167. 0,
  149168. 4,
  149169. };
  149170. static long _vq_lengthlist__44u5__p3_0[] = {
  149171. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149172. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149173. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149174. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  149175. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  149176. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  149177. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149178. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  149179. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  149180. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149181. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  149182. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149183. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  149184. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  149185. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  149186. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  149187. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149188. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  149189. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  149190. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  149191. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  149192. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149193. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149194. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149195. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149196. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149197. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149198. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149199. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149200. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149201. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149202. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149203. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149204. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149205. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149206. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149207. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149208. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149209. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149210. 0,
  149211. };
  149212. static float _vq_quantthresh__44u5__p3_0[] = {
  149213. -1.5, -0.5, 0.5, 1.5,
  149214. };
  149215. static long _vq_quantmap__44u5__p3_0[] = {
  149216. 3, 1, 0, 2, 4,
  149217. };
  149218. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149219. _vq_quantthresh__44u5__p3_0,
  149220. _vq_quantmap__44u5__p3_0,
  149221. 5,
  149222. 5
  149223. };
  149224. static static_codebook _44u5__p3_0 = {
  149225. 4, 625,
  149226. _vq_lengthlist__44u5__p3_0,
  149227. 1, -533725184, 1611661312, 3, 0,
  149228. _vq_quantlist__44u5__p3_0,
  149229. NULL,
  149230. &_vq_auxt__44u5__p3_0,
  149231. NULL,
  149232. 0
  149233. };
  149234. static long _vq_quantlist__44u5__p4_0[] = {
  149235. 2,
  149236. 1,
  149237. 3,
  149238. 0,
  149239. 4,
  149240. };
  149241. static long _vq_lengthlist__44u5__p4_0[] = {
  149242. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149243. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149244. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149245. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149246. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149247. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149248. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149249. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149250. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149251. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149252. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149253. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149254. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149255. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149256. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149257. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149258. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149259. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149260. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149261. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149262. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149263. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149264. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149265. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149266. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149267. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149268. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149269. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149270. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149271. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149272. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149273. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149274. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149275. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149276. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149277. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149278. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149279. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149280. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149281. 12,
  149282. };
  149283. static float _vq_quantthresh__44u5__p4_0[] = {
  149284. -1.5, -0.5, 0.5, 1.5,
  149285. };
  149286. static long _vq_quantmap__44u5__p4_0[] = {
  149287. 3, 1, 0, 2, 4,
  149288. };
  149289. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149290. _vq_quantthresh__44u5__p4_0,
  149291. _vq_quantmap__44u5__p4_0,
  149292. 5,
  149293. 5
  149294. };
  149295. static static_codebook _44u5__p4_0 = {
  149296. 4, 625,
  149297. _vq_lengthlist__44u5__p4_0,
  149298. 1, -533725184, 1611661312, 3, 0,
  149299. _vq_quantlist__44u5__p4_0,
  149300. NULL,
  149301. &_vq_auxt__44u5__p4_0,
  149302. NULL,
  149303. 0
  149304. };
  149305. static long _vq_quantlist__44u5__p5_0[] = {
  149306. 4,
  149307. 3,
  149308. 5,
  149309. 2,
  149310. 6,
  149311. 1,
  149312. 7,
  149313. 0,
  149314. 8,
  149315. };
  149316. static long _vq_lengthlist__44u5__p5_0[] = {
  149317. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149318. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149319. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149320. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149321. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149322. 14,
  149323. };
  149324. static float _vq_quantthresh__44u5__p5_0[] = {
  149325. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149326. };
  149327. static long _vq_quantmap__44u5__p5_0[] = {
  149328. 7, 5, 3, 1, 0, 2, 4, 6,
  149329. 8,
  149330. };
  149331. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149332. _vq_quantthresh__44u5__p5_0,
  149333. _vq_quantmap__44u5__p5_0,
  149334. 9,
  149335. 9
  149336. };
  149337. static static_codebook _44u5__p5_0 = {
  149338. 2, 81,
  149339. _vq_lengthlist__44u5__p5_0,
  149340. 1, -531628032, 1611661312, 4, 0,
  149341. _vq_quantlist__44u5__p5_0,
  149342. NULL,
  149343. &_vq_auxt__44u5__p5_0,
  149344. NULL,
  149345. 0
  149346. };
  149347. static long _vq_quantlist__44u5__p6_0[] = {
  149348. 4,
  149349. 3,
  149350. 5,
  149351. 2,
  149352. 6,
  149353. 1,
  149354. 7,
  149355. 0,
  149356. 8,
  149357. };
  149358. static long _vq_lengthlist__44u5__p6_0[] = {
  149359. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149360. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149361. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149362. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149363. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149364. 11,
  149365. };
  149366. static float _vq_quantthresh__44u5__p6_0[] = {
  149367. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149368. };
  149369. static long _vq_quantmap__44u5__p6_0[] = {
  149370. 7, 5, 3, 1, 0, 2, 4, 6,
  149371. 8,
  149372. };
  149373. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149374. _vq_quantthresh__44u5__p6_0,
  149375. _vq_quantmap__44u5__p6_0,
  149376. 9,
  149377. 9
  149378. };
  149379. static static_codebook _44u5__p6_0 = {
  149380. 2, 81,
  149381. _vq_lengthlist__44u5__p6_0,
  149382. 1, -531628032, 1611661312, 4, 0,
  149383. _vq_quantlist__44u5__p6_0,
  149384. NULL,
  149385. &_vq_auxt__44u5__p6_0,
  149386. NULL,
  149387. 0
  149388. };
  149389. static long _vq_quantlist__44u5__p7_0[] = {
  149390. 1,
  149391. 0,
  149392. 2,
  149393. };
  149394. static long _vq_lengthlist__44u5__p7_0[] = {
  149395. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149396. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149397. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149398. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149399. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149400. 12,
  149401. };
  149402. static float _vq_quantthresh__44u5__p7_0[] = {
  149403. -5.5, 5.5,
  149404. };
  149405. static long _vq_quantmap__44u5__p7_0[] = {
  149406. 1, 0, 2,
  149407. };
  149408. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149409. _vq_quantthresh__44u5__p7_0,
  149410. _vq_quantmap__44u5__p7_0,
  149411. 3,
  149412. 3
  149413. };
  149414. static static_codebook _44u5__p7_0 = {
  149415. 4, 81,
  149416. _vq_lengthlist__44u5__p7_0,
  149417. 1, -529137664, 1618345984, 2, 0,
  149418. _vq_quantlist__44u5__p7_0,
  149419. NULL,
  149420. &_vq_auxt__44u5__p7_0,
  149421. NULL,
  149422. 0
  149423. };
  149424. static long _vq_quantlist__44u5__p7_1[] = {
  149425. 5,
  149426. 4,
  149427. 6,
  149428. 3,
  149429. 7,
  149430. 2,
  149431. 8,
  149432. 1,
  149433. 9,
  149434. 0,
  149435. 10,
  149436. };
  149437. static long _vq_lengthlist__44u5__p7_1[] = {
  149438. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149439. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149440. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149441. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149442. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149443. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149444. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149445. 9, 9, 9, 9, 9,10,10,10,10,
  149446. };
  149447. static float _vq_quantthresh__44u5__p7_1[] = {
  149448. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149449. 3.5, 4.5,
  149450. };
  149451. static long _vq_quantmap__44u5__p7_1[] = {
  149452. 9, 7, 5, 3, 1, 0, 2, 4,
  149453. 6, 8, 10,
  149454. };
  149455. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149456. _vq_quantthresh__44u5__p7_1,
  149457. _vq_quantmap__44u5__p7_1,
  149458. 11,
  149459. 11
  149460. };
  149461. static static_codebook _44u5__p7_1 = {
  149462. 2, 121,
  149463. _vq_lengthlist__44u5__p7_1,
  149464. 1, -531365888, 1611661312, 4, 0,
  149465. _vq_quantlist__44u5__p7_1,
  149466. NULL,
  149467. &_vq_auxt__44u5__p7_1,
  149468. NULL,
  149469. 0
  149470. };
  149471. static long _vq_quantlist__44u5__p8_0[] = {
  149472. 5,
  149473. 4,
  149474. 6,
  149475. 3,
  149476. 7,
  149477. 2,
  149478. 8,
  149479. 1,
  149480. 9,
  149481. 0,
  149482. 10,
  149483. };
  149484. static long _vq_lengthlist__44u5__p8_0[] = {
  149485. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149486. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149487. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149488. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149489. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149490. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149491. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149492. 12,13,13,14,14,14,14,15,15,
  149493. };
  149494. static float _vq_quantthresh__44u5__p8_0[] = {
  149495. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149496. 38.5, 49.5,
  149497. };
  149498. static long _vq_quantmap__44u5__p8_0[] = {
  149499. 9, 7, 5, 3, 1, 0, 2, 4,
  149500. 6, 8, 10,
  149501. };
  149502. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149503. _vq_quantthresh__44u5__p8_0,
  149504. _vq_quantmap__44u5__p8_0,
  149505. 11,
  149506. 11
  149507. };
  149508. static static_codebook _44u5__p8_0 = {
  149509. 2, 121,
  149510. _vq_lengthlist__44u5__p8_0,
  149511. 1, -524582912, 1618345984, 4, 0,
  149512. _vq_quantlist__44u5__p8_0,
  149513. NULL,
  149514. &_vq_auxt__44u5__p8_0,
  149515. NULL,
  149516. 0
  149517. };
  149518. static long _vq_quantlist__44u5__p8_1[] = {
  149519. 5,
  149520. 4,
  149521. 6,
  149522. 3,
  149523. 7,
  149524. 2,
  149525. 8,
  149526. 1,
  149527. 9,
  149528. 0,
  149529. 10,
  149530. };
  149531. static long _vq_lengthlist__44u5__p8_1[] = {
  149532. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149533. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149534. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149535. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149536. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149537. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149538. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149539. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149540. };
  149541. static float _vq_quantthresh__44u5__p8_1[] = {
  149542. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149543. 3.5, 4.5,
  149544. };
  149545. static long _vq_quantmap__44u5__p8_1[] = {
  149546. 9, 7, 5, 3, 1, 0, 2, 4,
  149547. 6, 8, 10,
  149548. };
  149549. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149550. _vq_quantthresh__44u5__p8_1,
  149551. _vq_quantmap__44u5__p8_1,
  149552. 11,
  149553. 11
  149554. };
  149555. static static_codebook _44u5__p8_1 = {
  149556. 2, 121,
  149557. _vq_lengthlist__44u5__p8_1,
  149558. 1, -531365888, 1611661312, 4, 0,
  149559. _vq_quantlist__44u5__p8_1,
  149560. NULL,
  149561. &_vq_auxt__44u5__p8_1,
  149562. NULL,
  149563. 0
  149564. };
  149565. static long _vq_quantlist__44u5__p9_0[] = {
  149566. 6,
  149567. 5,
  149568. 7,
  149569. 4,
  149570. 8,
  149571. 3,
  149572. 9,
  149573. 2,
  149574. 10,
  149575. 1,
  149576. 11,
  149577. 0,
  149578. 12,
  149579. };
  149580. static long _vq_lengthlist__44u5__p9_0[] = {
  149581. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149582. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149583. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149584. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149585. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149586. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149587. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149588. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149589. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149590. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149591. 12,12,12,12,12,12,12,12,12,
  149592. };
  149593. static float _vq_quantthresh__44u5__p9_0[] = {
  149594. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149595. 637.5, 892.5, 1147.5, 1402.5,
  149596. };
  149597. static long _vq_quantmap__44u5__p9_0[] = {
  149598. 11, 9, 7, 5, 3, 1, 0, 2,
  149599. 4, 6, 8, 10, 12,
  149600. };
  149601. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149602. _vq_quantthresh__44u5__p9_0,
  149603. _vq_quantmap__44u5__p9_0,
  149604. 13,
  149605. 13
  149606. };
  149607. static static_codebook _44u5__p9_0 = {
  149608. 2, 169,
  149609. _vq_lengthlist__44u5__p9_0,
  149610. 1, -514332672, 1627381760, 4, 0,
  149611. _vq_quantlist__44u5__p9_0,
  149612. NULL,
  149613. &_vq_auxt__44u5__p9_0,
  149614. NULL,
  149615. 0
  149616. };
  149617. static long _vq_quantlist__44u5__p9_1[] = {
  149618. 7,
  149619. 6,
  149620. 8,
  149621. 5,
  149622. 9,
  149623. 4,
  149624. 10,
  149625. 3,
  149626. 11,
  149627. 2,
  149628. 12,
  149629. 1,
  149630. 13,
  149631. 0,
  149632. 14,
  149633. };
  149634. static long _vq_lengthlist__44u5__p9_1[] = {
  149635. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149636. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149637. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149638. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149639. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149640. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149641. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149642. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149643. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149644. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149645. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149646. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149647. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149648. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149649. 14,
  149650. };
  149651. static float _vq_quantthresh__44u5__p9_1[] = {
  149652. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149653. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149654. };
  149655. static long _vq_quantmap__44u5__p9_1[] = {
  149656. 13, 11, 9, 7, 5, 3, 1, 0,
  149657. 2, 4, 6, 8, 10, 12, 14,
  149658. };
  149659. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149660. _vq_quantthresh__44u5__p9_1,
  149661. _vq_quantmap__44u5__p9_1,
  149662. 15,
  149663. 15
  149664. };
  149665. static static_codebook _44u5__p9_1 = {
  149666. 2, 225,
  149667. _vq_lengthlist__44u5__p9_1,
  149668. 1, -522338304, 1620115456, 4, 0,
  149669. _vq_quantlist__44u5__p9_1,
  149670. NULL,
  149671. &_vq_auxt__44u5__p9_1,
  149672. NULL,
  149673. 0
  149674. };
  149675. static long _vq_quantlist__44u5__p9_2[] = {
  149676. 8,
  149677. 7,
  149678. 9,
  149679. 6,
  149680. 10,
  149681. 5,
  149682. 11,
  149683. 4,
  149684. 12,
  149685. 3,
  149686. 13,
  149687. 2,
  149688. 14,
  149689. 1,
  149690. 15,
  149691. 0,
  149692. 16,
  149693. };
  149694. static long _vq_lengthlist__44u5__p9_2[] = {
  149695. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149696. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149697. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149698. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149699. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149700. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149701. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149702. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149703. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149704. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149705. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149706. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149707. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149708. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149709. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149710. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149711. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149712. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149713. 10,
  149714. };
  149715. static float _vq_quantthresh__44u5__p9_2[] = {
  149716. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149717. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149718. };
  149719. static long _vq_quantmap__44u5__p9_2[] = {
  149720. 15, 13, 11, 9, 7, 5, 3, 1,
  149721. 0, 2, 4, 6, 8, 10, 12, 14,
  149722. 16,
  149723. };
  149724. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149725. _vq_quantthresh__44u5__p9_2,
  149726. _vq_quantmap__44u5__p9_2,
  149727. 17,
  149728. 17
  149729. };
  149730. static static_codebook _44u5__p9_2 = {
  149731. 2, 289,
  149732. _vq_lengthlist__44u5__p9_2,
  149733. 1, -529530880, 1611661312, 5, 0,
  149734. _vq_quantlist__44u5__p9_2,
  149735. NULL,
  149736. &_vq_auxt__44u5__p9_2,
  149737. NULL,
  149738. 0
  149739. };
  149740. static long _huff_lengthlist__44u5__short[] = {
  149741. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149742. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149743. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149744. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149745. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149746. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149747. 6, 8,15,17,
  149748. };
  149749. static static_codebook _huff_book__44u5__short = {
  149750. 2, 100,
  149751. _huff_lengthlist__44u5__short,
  149752. 0, 0, 0, 0, 0,
  149753. NULL,
  149754. NULL,
  149755. NULL,
  149756. NULL,
  149757. 0
  149758. };
  149759. static long _huff_lengthlist__44u6__long[] = {
  149760. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149761. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149762. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149763. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149764. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149765. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149766. 13, 8, 7, 7,
  149767. };
  149768. static static_codebook _huff_book__44u6__long = {
  149769. 2, 100,
  149770. _huff_lengthlist__44u6__long,
  149771. 0, 0, 0, 0, 0,
  149772. NULL,
  149773. NULL,
  149774. NULL,
  149775. NULL,
  149776. 0
  149777. };
  149778. static long _vq_quantlist__44u6__p1_0[] = {
  149779. 1,
  149780. 0,
  149781. 2,
  149782. };
  149783. static long _vq_lengthlist__44u6__p1_0[] = {
  149784. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149785. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149786. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149787. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149788. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149789. 12,
  149790. };
  149791. static float _vq_quantthresh__44u6__p1_0[] = {
  149792. -0.5, 0.5,
  149793. };
  149794. static long _vq_quantmap__44u6__p1_0[] = {
  149795. 1, 0, 2,
  149796. };
  149797. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149798. _vq_quantthresh__44u6__p1_0,
  149799. _vq_quantmap__44u6__p1_0,
  149800. 3,
  149801. 3
  149802. };
  149803. static static_codebook _44u6__p1_0 = {
  149804. 4, 81,
  149805. _vq_lengthlist__44u6__p1_0,
  149806. 1, -535822336, 1611661312, 2, 0,
  149807. _vq_quantlist__44u6__p1_0,
  149808. NULL,
  149809. &_vq_auxt__44u6__p1_0,
  149810. NULL,
  149811. 0
  149812. };
  149813. static long _vq_quantlist__44u6__p2_0[] = {
  149814. 1,
  149815. 0,
  149816. 2,
  149817. };
  149818. static long _vq_lengthlist__44u6__p2_0[] = {
  149819. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149820. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149821. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149822. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149823. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149824. 9,
  149825. };
  149826. static float _vq_quantthresh__44u6__p2_0[] = {
  149827. -0.5, 0.5,
  149828. };
  149829. static long _vq_quantmap__44u6__p2_0[] = {
  149830. 1, 0, 2,
  149831. };
  149832. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149833. _vq_quantthresh__44u6__p2_0,
  149834. _vq_quantmap__44u6__p2_0,
  149835. 3,
  149836. 3
  149837. };
  149838. static static_codebook _44u6__p2_0 = {
  149839. 4, 81,
  149840. _vq_lengthlist__44u6__p2_0,
  149841. 1, -535822336, 1611661312, 2, 0,
  149842. _vq_quantlist__44u6__p2_0,
  149843. NULL,
  149844. &_vq_auxt__44u6__p2_0,
  149845. NULL,
  149846. 0
  149847. };
  149848. static long _vq_quantlist__44u6__p3_0[] = {
  149849. 2,
  149850. 1,
  149851. 3,
  149852. 0,
  149853. 4,
  149854. };
  149855. static long _vq_lengthlist__44u6__p3_0[] = {
  149856. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149857. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149858. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149859. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149860. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149861. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149862. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149863. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149864. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149865. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149866. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149867. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149868. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149869. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149870. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149871. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149872. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149873. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149874. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149875. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149876. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149877. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149878. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149879. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149880. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149881. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149882. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149883. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149884. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149885. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149886. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149887. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149888. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149889. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149890. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149891. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149892. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149893. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149894. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149895. 19,
  149896. };
  149897. static float _vq_quantthresh__44u6__p3_0[] = {
  149898. -1.5, -0.5, 0.5, 1.5,
  149899. };
  149900. static long _vq_quantmap__44u6__p3_0[] = {
  149901. 3, 1, 0, 2, 4,
  149902. };
  149903. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149904. _vq_quantthresh__44u6__p3_0,
  149905. _vq_quantmap__44u6__p3_0,
  149906. 5,
  149907. 5
  149908. };
  149909. static static_codebook _44u6__p3_0 = {
  149910. 4, 625,
  149911. _vq_lengthlist__44u6__p3_0,
  149912. 1, -533725184, 1611661312, 3, 0,
  149913. _vq_quantlist__44u6__p3_0,
  149914. NULL,
  149915. &_vq_auxt__44u6__p3_0,
  149916. NULL,
  149917. 0
  149918. };
  149919. static long _vq_quantlist__44u6__p4_0[] = {
  149920. 2,
  149921. 1,
  149922. 3,
  149923. 0,
  149924. 4,
  149925. };
  149926. static long _vq_lengthlist__44u6__p4_0[] = {
  149927. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149928. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149929. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149930. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149931. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149932. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149933. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149934. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149935. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149936. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149937. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149938. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149939. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149940. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149941. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149942. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149943. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149944. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149945. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149946. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149947. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149948. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149949. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149950. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149951. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149952. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149953. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149954. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149955. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149956. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149957. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149958. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149959. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149960. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149961. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149962. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149963. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149964. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149965. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149966. 13,
  149967. };
  149968. static float _vq_quantthresh__44u6__p4_0[] = {
  149969. -1.5, -0.5, 0.5, 1.5,
  149970. };
  149971. static long _vq_quantmap__44u6__p4_0[] = {
  149972. 3, 1, 0, 2, 4,
  149973. };
  149974. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149975. _vq_quantthresh__44u6__p4_0,
  149976. _vq_quantmap__44u6__p4_0,
  149977. 5,
  149978. 5
  149979. };
  149980. static static_codebook _44u6__p4_0 = {
  149981. 4, 625,
  149982. _vq_lengthlist__44u6__p4_0,
  149983. 1, -533725184, 1611661312, 3, 0,
  149984. _vq_quantlist__44u6__p4_0,
  149985. NULL,
  149986. &_vq_auxt__44u6__p4_0,
  149987. NULL,
  149988. 0
  149989. };
  149990. static long _vq_quantlist__44u6__p5_0[] = {
  149991. 4,
  149992. 3,
  149993. 5,
  149994. 2,
  149995. 6,
  149996. 1,
  149997. 7,
  149998. 0,
  149999. 8,
  150000. };
  150001. static long _vq_lengthlist__44u6__p5_0[] = {
  150002. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150003. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  150004. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  150005. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  150006. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  150007. 14,
  150008. };
  150009. static float _vq_quantthresh__44u6__p5_0[] = {
  150010. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150011. };
  150012. static long _vq_quantmap__44u6__p5_0[] = {
  150013. 7, 5, 3, 1, 0, 2, 4, 6,
  150014. 8,
  150015. };
  150016. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  150017. _vq_quantthresh__44u6__p5_0,
  150018. _vq_quantmap__44u6__p5_0,
  150019. 9,
  150020. 9
  150021. };
  150022. static static_codebook _44u6__p5_0 = {
  150023. 2, 81,
  150024. _vq_lengthlist__44u6__p5_0,
  150025. 1, -531628032, 1611661312, 4, 0,
  150026. _vq_quantlist__44u6__p5_0,
  150027. NULL,
  150028. &_vq_auxt__44u6__p5_0,
  150029. NULL,
  150030. 0
  150031. };
  150032. static long _vq_quantlist__44u6__p6_0[] = {
  150033. 4,
  150034. 3,
  150035. 5,
  150036. 2,
  150037. 6,
  150038. 1,
  150039. 7,
  150040. 0,
  150041. 8,
  150042. };
  150043. static long _vq_lengthlist__44u6__p6_0[] = {
  150044. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150045. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  150046. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150047. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  150048. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  150049. 12,
  150050. };
  150051. static float _vq_quantthresh__44u6__p6_0[] = {
  150052. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150053. };
  150054. static long _vq_quantmap__44u6__p6_0[] = {
  150055. 7, 5, 3, 1, 0, 2, 4, 6,
  150056. 8,
  150057. };
  150058. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  150059. _vq_quantthresh__44u6__p6_0,
  150060. _vq_quantmap__44u6__p6_0,
  150061. 9,
  150062. 9
  150063. };
  150064. static static_codebook _44u6__p6_0 = {
  150065. 2, 81,
  150066. _vq_lengthlist__44u6__p6_0,
  150067. 1, -531628032, 1611661312, 4, 0,
  150068. _vq_quantlist__44u6__p6_0,
  150069. NULL,
  150070. &_vq_auxt__44u6__p6_0,
  150071. NULL,
  150072. 0
  150073. };
  150074. static long _vq_quantlist__44u6__p7_0[] = {
  150075. 1,
  150076. 0,
  150077. 2,
  150078. };
  150079. static long _vq_lengthlist__44u6__p7_0[] = {
  150080. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  150081. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  150082. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  150083. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  150084. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  150085. 10,
  150086. };
  150087. static float _vq_quantthresh__44u6__p7_0[] = {
  150088. -5.5, 5.5,
  150089. };
  150090. static long _vq_quantmap__44u6__p7_0[] = {
  150091. 1, 0, 2,
  150092. };
  150093. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  150094. _vq_quantthresh__44u6__p7_0,
  150095. _vq_quantmap__44u6__p7_0,
  150096. 3,
  150097. 3
  150098. };
  150099. static static_codebook _44u6__p7_0 = {
  150100. 4, 81,
  150101. _vq_lengthlist__44u6__p7_0,
  150102. 1, -529137664, 1618345984, 2, 0,
  150103. _vq_quantlist__44u6__p7_0,
  150104. NULL,
  150105. &_vq_auxt__44u6__p7_0,
  150106. NULL,
  150107. 0
  150108. };
  150109. static long _vq_quantlist__44u6__p7_1[] = {
  150110. 5,
  150111. 4,
  150112. 6,
  150113. 3,
  150114. 7,
  150115. 2,
  150116. 8,
  150117. 1,
  150118. 9,
  150119. 0,
  150120. 10,
  150121. };
  150122. static long _vq_lengthlist__44u6__p7_1[] = {
  150123. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  150124. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  150125. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  150126. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  150127. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  150128. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  150129. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  150130. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150131. };
  150132. static float _vq_quantthresh__44u6__p7_1[] = {
  150133. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150134. 3.5, 4.5,
  150135. };
  150136. static long _vq_quantmap__44u6__p7_1[] = {
  150137. 9, 7, 5, 3, 1, 0, 2, 4,
  150138. 6, 8, 10,
  150139. };
  150140. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  150141. _vq_quantthresh__44u6__p7_1,
  150142. _vq_quantmap__44u6__p7_1,
  150143. 11,
  150144. 11
  150145. };
  150146. static static_codebook _44u6__p7_1 = {
  150147. 2, 121,
  150148. _vq_lengthlist__44u6__p7_1,
  150149. 1, -531365888, 1611661312, 4, 0,
  150150. _vq_quantlist__44u6__p7_1,
  150151. NULL,
  150152. &_vq_auxt__44u6__p7_1,
  150153. NULL,
  150154. 0
  150155. };
  150156. static long _vq_quantlist__44u6__p8_0[] = {
  150157. 5,
  150158. 4,
  150159. 6,
  150160. 3,
  150161. 7,
  150162. 2,
  150163. 8,
  150164. 1,
  150165. 9,
  150166. 0,
  150167. 10,
  150168. };
  150169. static long _vq_lengthlist__44u6__p8_0[] = {
  150170. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  150171. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  150172. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  150173. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  150174. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  150175. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  150176. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  150177. 12,13,13,14,14,14,15,15,15,
  150178. };
  150179. static float _vq_quantthresh__44u6__p8_0[] = {
  150180. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150181. 38.5, 49.5,
  150182. };
  150183. static long _vq_quantmap__44u6__p8_0[] = {
  150184. 9, 7, 5, 3, 1, 0, 2, 4,
  150185. 6, 8, 10,
  150186. };
  150187. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  150188. _vq_quantthresh__44u6__p8_0,
  150189. _vq_quantmap__44u6__p8_0,
  150190. 11,
  150191. 11
  150192. };
  150193. static static_codebook _44u6__p8_0 = {
  150194. 2, 121,
  150195. _vq_lengthlist__44u6__p8_0,
  150196. 1, -524582912, 1618345984, 4, 0,
  150197. _vq_quantlist__44u6__p8_0,
  150198. NULL,
  150199. &_vq_auxt__44u6__p8_0,
  150200. NULL,
  150201. 0
  150202. };
  150203. static long _vq_quantlist__44u6__p8_1[] = {
  150204. 5,
  150205. 4,
  150206. 6,
  150207. 3,
  150208. 7,
  150209. 2,
  150210. 8,
  150211. 1,
  150212. 9,
  150213. 0,
  150214. 10,
  150215. };
  150216. static long _vq_lengthlist__44u6__p8_1[] = {
  150217. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150218. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150219. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150220. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150221. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150222. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150223. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150224. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150225. };
  150226. static float _vq_quantthresh__44u6__p8_1[] = {
  150227. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150228. 3.5, 4.5,
  150229. };
  150230. static long _vq_quantmap__44u6__p8_1[] = {
  150231. 9, 7, 5, 3, 1, 0, 2, 4,
  150232. 6, 8, 10,
  150233. };
  150234. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150235. _vq_quantthresh__44u6__p8_1,
  150236. _vq_quantmap__44u6__p8_1,
  150237. 11,
  150238. 11
  150239. };
  150240. static static_codebook _44u6__p8_1 = {
  150241. 2, 121,
  150242. _vq_lengthlist__44u6__p8_1,
  150243. 1, -531365888, 1611661312, 4, 0,
  150244. _vq_quantlist__44u6__p8_1,
  150245. NULL,
  150246. &_vq_auxt__44u6__p8_1,
  150247. NULL,
  150248. 0
  150249. };
  150250. static long _vq_quantlist__44u6__p9_0[] = {
  150251. 7,
  150252. 6,
  150253. 8,
  150254. 5,
  150255. 9,
  150256. 4,
  150257. 10,
  150258. 3,
  150259. 11,
  150260. 2,
  150261. 12,
  150262. 1,
  150263. 13,
  150264. 0,
  150265. 14,
  150266. };
  150267. static long _vq_lengthlist__44u6__p9_0[] = {
  150268. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150269. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150270. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150271. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150272. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150273. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150274. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150275. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150276. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150277. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150278. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150279. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150280. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150281. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150282. 14,
  150283. };
  150284. static float _vq_quantthresh__44u6__p9_0[] = {
  150285. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150286. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150287. };
  150288. static long _vq_quantmap__44u6__p9_0[] = {
  150289. 13, 11, 9, 7, 5, 3, 1, 0,
  150290. 2, 4, 6, 8, 10, 12, 14,
  150291. };
  150292. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150293. _vq_quantthresh__44u6__p9_0,
  150294. _vq_quantmap__44u6__p9_0,
  150295. 15,
  150296. 15
  150297. };
  150298. static static_codebook _44u6__p9_0 = {
  150299. 2, 225,
  150300. _vq_lengthlist__44u6__p9_0,
  150301. 1, -514071552, 1627381760, 4, 0,
  150302. _vq_quantlist__44u6__p9_0,
  150303. NULL,
  150304. &_vq_auxt__44u6__p9_0,
  150305. NULL,
  150306. 0
  150307. };
  150308. static long _vq_quantlist__44u6__p9_1[] = {
  150309. 7,
  150310. 6,
  150311. 8,
  150312. 5,
  150313. 9,
  150314. 4,
  150315. 10,
  150316. 3,
  150317. 11,
  150318. 2,
  150319. 12,
  150320. 1,
  150321. 13,
  150322. 0,
  150323. 14,
  150324. };
  150325. static long _vq_lengthlist__44u6__p9_1[] = {
  150326. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150327. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150328. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150329. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150330. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150331. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150332. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150333. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150334. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150335. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150336. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150337. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150338. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150339. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150340. 13,
  150341. };
  150342. static float _vq_quantthresh__44u6__p9_1[] = {
  150343. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150344. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150345. };
  150346. static long _vq_quantmap__44u6__p9_1[] = {
  150347. 13, 11, 9, 7, 5, 3, 1, 0,
  150348. 2, 4, 6, 8, 10, 12, 14,
  150349. };
  150350. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150351. _vq_quantthresh__44u6__p9_1,
  150352. _vq_quantmap__44u6__p9_1,
  150353. 15,
  150354. 15
  150355. };
  150356. static static_codebook _44u6__p9_1 = {
  150357. 2, 225,
  150358. _vq_lengthlist__44u6__p9_1,
  150359. 1, -522338304, 1620115456, 4, 0,
  150360. _vq_quantlist__44u6__p9_1,
  150361. NULL,
  150362. &_vq_auxt__44u6__p9_1,
  150363. NULL,
  150364. 0
  150365. };
  150366. static long _vq_quantlist__44u6__p9_2[] = {
  150367. 8,
  150368. 7,
  150369. 9,
  150370. 6,
  150371. 10,
  150372. 5,
  150373. 11,
  150374. 4,
  150375. 12,
  150376. 3,
  150377. 13,
  150378. 2,
  150379. 14,
  150380. 1,
  150381. 15,
  150382. 0,
  150383. 16,
  150384. };
  150385. static long _vq_lengthlist__44u6__p9_2[] = {
  150386. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150387. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150388. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150389. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150390. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150391. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150392. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150393. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150394. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150395. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150396. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150397. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150398. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150399. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150400. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150401. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150402. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150403. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150404. 10,
  150405. };
  150406. static float _vq_quantthresh__44u6__p9_2[] = {
  150407. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150408. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150409. };
  150410. static long _vq_quantmap__44u6__p9_2[] = {
  150411. 15, 13, 11, 9, 7, 5, 3, 1,
  150412. 0, 2, 4, 6, 8, 10, 12, 14,
  150413. 16,
  150414. };
  150415. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150416. _vq_quantthresh__44u6__p9_2,
  150417. _vq_quantmap__44u6__p9_2,
  150418. 17,
  150419. 17
  150420. };
  150421. static static_codebook _44u6__p9_2 = {
  150422. 2, 289,
  150423. _vq_lengthlist__44u6__p9_2,
  150424. 1, -529530880, 1611661312, 5, 0,
  150425. _vq_quantlist__44u6__p9_2,
  150426. NULL,
  150427. &_vq_auxt__44u6__p9_2,
  150428. NULL,
  150429. 0
  150430. };
  150431. static long _huff_lengthlist__44u6__short[] = {
  150432. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150433. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150434. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150435. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150436. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150437. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150438. 7, 6, 9,16,
  150439. };
  150440. static static_codebook _huff_book__44u6__short = {
  150441. 2, 100,
  150442. _huff_lengthlist__44u6__short,
  150443. 0, 0, 0, 0, 0,
  150444. NULL,
  150445. NULL,
  150446. NULL,
  150447. NULL,
  150448. 0
  150449. };
  150450. static long _huff_lengthlist__44u7__long[] = {
  150451. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150452. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150453. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150454. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150455. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150456. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150457. 12, 8, 6, 7,
  150458. };
  150459. static static_codebook _huff_book__44u7__long = {
  150460. 2, 100,
  150461. _huff_lengthlist__44u7__long,
  150462. 0, 0, 0, 0, 0,
  150463. NULL,
  150464. NULL,
  150465. NULL,
  150466. NULL,
  150467. 0
  150468. };
  150469. static long _vq_quantlist__44u7__p1_0[] = {
  150470. 1,
  150471. 0,
  150472. 2,
  150473. };
  150474. static long _vq_lengthlist__44u7__p1_0[] = {
  150475. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150476. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150477. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150478. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150479. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150480. 12,
  150481. };
  150482. static float _vq_quantthresh__44u7__p1_0[] = {
  150483. -0.5, 0.5,
  150484. };
  150485. static long _vq_quantmap__44u7__p1_0[] = {
  150486. 1, 0, 2,
  150487. };
  150488. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150489. _vq_quantthresh__44u7__p1_0,
  150490. _vq_quantmap__44u7__p1_0,
  150491. 3,
  150492. 3
  150493. };
  150494. static static_codebook _44u7__p1_0 = {
  150495. 4, 81,
  150496. _vq_lengthlist__44u7__p1_0,
  150497. 1, -535822336, 1611661312, 2, 0,
  150498. _vq_quantlist__44u7__p1_0,
  150499. NULL,
  150500. &_vq_auxt__44u7__p1_0,
  150501. NULL,
  150502. 0
  150503. };
  150504. static long _vq_quantlist__44u7__p2_0[] = {
  150505. 1,
  150506. 0,
  150507. 2,
  150508. };
  150509. static long _vq_lengthlist__44u7__p2_0[] = {
  150510. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150511. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150512. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150513. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150514. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150515. 9,
  150516. };
  150517. static float _vq_quantthresh__44u7__p2_0[] = {
  150518. -0.5, 0.5,
  150519. };
  150520. static long _vq_quantmap__44u7__p2_0[] = {
  150521. 1, 0, 2,
  150522. };
  150523. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150524. _vq_quantthresh__44u7__p2_0,
  150525. _vq_quantmap__44u7__p2_0,
  150526. 3,
  150527. 3
  150528. };
  150529. static static_codebook _44u7__p2_0 = {
  150530. 4, 81,
  150531. _vq_lengthlist__44u7__p2_0,
  150532. 1, -535822336, 1611661312, 2, 0,
  150533. _vq_quantlist__44u7__p2_0,
  150534. NULL,
  150535. &_vq_auxt__44u7__p2_0,
  150536. NULL,
  150537. 0
  150538. };
  150539. static long _vq_quantlist__44u7__p3_0[] = {
  150540. 2,
  150541. 1,
  150542. 3,
  150543. 0,
  150544. 4,
  150545. };
  150546. static long _vq_lengthlist__44u7__p3_0[] = {
  150547. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150548. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150549. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150550. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150551. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150552. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150553. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150554. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150555. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150556. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150557. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150558. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150559. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150560. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150561. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150562. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150563. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150564. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150565. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150566. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150567. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150568. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150569. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150570. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150571. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150572. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150573. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150574. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150575. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150576. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150577. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150578. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150579. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150580. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150581. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150582. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150583. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150584. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150585. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150586. 0,
  150587. };
  150588. static float _vq_quantthresh__44u7__p3_0[] = {
  150589. -1.5, -0.5, 0.5, 1.5,
  150590. };
  150591. static long _vq_quantmap__44u7__p3_0[] = {
  150592. 3, 1, 0, 2, 4,
  150593. };
  150594. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150595. _vq_quantthresh__44u7__p3_0,
  150596. _vq_quantmap__44u7__p3_0,
  150597. 5,
  150598. 5
  150599. };
  150600. static static_codebook _44u7__p3_0 = {
  150601. 4, 625,
  150602. _vq_lengthlist__44u7__p3_0,
  150603. 1, -533725184, 1611661312, 3, 0,
  150604. _vq_quantlist__44u7__p3_0,
  150605. NULL,
  150606. &_vq_auxt__44u7__p3_0,
  150607. NULL,
  150608. 0
  150609. };
  150610. static long _vq_quantlist__44u7__p4_0[] = {
  150611. 2,
  150612. 1,
  150613. 3,
  150614. 0,
  150615. 4,
  150616. };
  150617. static long _vq_lengthlist__44u7__p4_0[] = {
  150618. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150619. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150620. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150621. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150622. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150623. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150624. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150625. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150626. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150627. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150628. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150629. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150630. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150631. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150632. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150633. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150634. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150635. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150636. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150637. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150638. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150639. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150640. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150641. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150642. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150643. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150644. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150645. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150646. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150647. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150648. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150649. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150650. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150651. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150652. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150653. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150654. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150655. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150656. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150657. 14,
  150658. };
  150659. static float _vq_quantthresh__44u7__p4_0[] = {
  150660. -1.5, -0.5, 0.5, 1.5,
  150661. };
  150662. static long _vq_quantmap__44u7__p4_0[] = {
  150663. 3, 1, 0, 2, 4,
  150664. };
  150665. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150666. _vq_quantthresh__44u7__p4_0,
  150667. _vq_quantmap__44u7__p4_0,
  150668. 5,
  150669. 5
  150670. };
  150671. static static_codebook _44u7__p4_0 = {
  150672. 4, 625,
  150673. _vq_lengthlist__44u7__p4_0,
  150674. 1, -533725184, 1611661312, 3, 0,
  150675. _vq_quantlist__44u7__p4_0,
  150676. NULL,
  150677. &_vq_auxt__44u7__p4_0,
  150678. NULL,
  150679. 0
  150680. };
  150681. static long _vq_quantlist__44u7__p5_0[] = {
  150682. 4,
  150683. 3,
  150684. 5,
  150685. 2,
  150686. 6,
  150687. 1,
  150688. 7,
  150689. 0,
  150690. 8,
  150691. };
  150692. static long _vq_lengthlist__44u7__p5_0[] = {
  150693. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150694. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150695. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150696. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150697. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150698. 14,
  150699. };
  150700. static float _vq_quantthresh__44u7__p5_0[] = {
  150701. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150702. };
  150703. static long _vq_quantmap__44u7__p5_0[] = {
  150704. 7, 5, 3, 1, 0, 2, 4, 6,
  150705. 8,
  150706. };
  150707. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150708. _vq_quantthresh__44u7__p5_0,
  150709. _vq_quantmap__44u7__p5_0,
  150710. 9,
  150711. 9
  150712. };
  150713. static static_codebook _44u7__p5_0 = {
  150714. 2, 81,
  150715. _vq_lengthlist__44u7__p5_0,
  150716. 1, -531628032, 1611661312, 4, 0,
  150717. _vq_quantlist__44u7__p5_0,
  150718. NULL,
  150719. &_vq_auxt__44u7__p5_0,
  150720. NULL,
  150721. 0
  150722. };
  150723. static long _vq_quantlist__44u7__p6_0[] = {
  150724. 4,
  150725. 3,
  150726. 5,
  150727. 2,
  150728. 6,
  150729. 1,
  150730. 7,
  150731. 0,
  150732. 8,
  150733. };
  150734. static long _vq_lengthlist__44u7__p6_0[] = {
  150735. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150736. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150737. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150738. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150739. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150740. 12,
  150741. };
  150742. static float _vq_quantthresh__44u7__p6_0[] = {
  150743. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150744. };
  150745. static long _vq_quantmap__44u7__p6_0[] = {
  150746. 7, 5, 3, 1, 0, 2, 4, 6,
  150747. 8,
  150748. };
  150749. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150750. _vq_quantthresh__44u7__p6_0,
  150751. _vq_quantmap__44u7__p6_0,
  150752. 9,
  150753. 9
  150754. };
  150755. static static_codebook _44u7__p6_0 = {
  150756. 2, 81,
  150757. _vq_lengthlist__44u7__p6_0,
  150758. 1, -531628032, 1611661312, 4, 0,
  150759. _vq_quantlist__44u7__p6_0,
  150760. NULL,
  150761. &_vq_auxt__44u7__p6_0,
  150762. NULL,
  150763. 0
  150764. };
  150765. static long _vq_quantlist__44u7__p7_0[] = {
  150766. 1,
  150767. 0,
  150768. 2,
  150769. };
  150770. static long _vq_lengthlist__44u7__p7_0[] = {
  150771. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150772. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150773. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150774. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150775. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150776. 10,
  150777. };
  150778. static float _vq_quantthresh__44u7__p7_0[] = {
  150779. -5.5, 5.5,
  150780. };
  150781. static long _vq_quantmap__44u7__p7_0[] = {
  150782. 1, 0, 2,
  150783. };
  150784. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150785. _vq_quantthresh__44u7__p7_0,
  150786. _vq_quantmap__44u7__p7_0,
  150787. 3,
  150788. 3
  150789. };
  150790. static static_codebook _44u7__p7_0 = {
  150791. 4, 81,
  150792. _vq_lengthlist__44u7__p7_0,
  150793. 1, -529137664, 1618345984, 2, 0,
  150794. _vq_quantlist__44u7__p7_0,
  150795. NULL,
  150796. &_vq_auxt__44u7__p7_0,
  150797. NULL,
  150798. 0
  150799. };
  150800. static long _vq_quantlist__44u7__p7_1[] = {
  150801. 5,
  150802. 4,
  150803. 6,
  150804. 3,
  150805. 7,
  150806. 2,
  150807. 8,
  150808. 1,
  150809. 9,
  150810. 0,
  150811. 10,
  150812. };
  150813. static long _vq_lengthlist__44u7__p7_1[] = {
  150814. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150815. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150816. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150817. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150818. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150819. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150820. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150821. 8, 9, 9, 9, 9, 9,10,10,10,
  150822. };
  150823. static float _vq_quantthresh__44u7__p7_1[] = {
  150824. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150825. 3.5, 4.5,
  150826. };
  150827. static long _vq_quantmap__44u7__p7_1[] = {
  150828. 9, 7, 5, 3, 1, 0, 2, 4,
  150829. 6, 8, 10,
  150830. };
  150831. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150832. _vq_quantthresh__44u7__p7_1,
  150833. _vq_quantmap__44u7__p7_1,
  150834. 11,
  150835. 11
  150836. };
  150837. static static_codebook _44u7__p7_1 = {
  150838. 2, 121,
  150839. _vq_lengthlist__44u7__p7_1,
  150840. 1, -531365888, 1611661312, 4, 0,
  150841. _vq_quantlist__44u7__p7_1,
  150842. NULL,
  150843. &_vq_auxt__44u7__p7_1,
  150844. NULL,
  150845. 0
  150846. };
  150847. static long _vq_quantlist__44u7__p8_0[] = {
  150848. 5,
  150849. 4,
  150850. 6,
  150851. 3,
  150852. 7,
  150853. 2,
  150854. 8,
  150855. 1,
  150856. 9,
  150857. 0,
  150858. 10,
  150859. };
  150860. static long _vq_lengthlist__44u7__p8_0[] = {
  150861. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150862. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150863. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150864. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150865. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150866. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150867. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150868. 12,13,13,14,14,15,15,15,16,
  150869. };
  150870. static float _vq_quantthresh__44u7__p8_0[] = {
  150871. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150872. 38.5, 49.5,
  150873. };
  150874. static long _vq_quantmap__44u7__p8_0[] = {
  150875. 9, 7, 5, 3, 1, 0, 2, 4,
  150876. 6, 8, 10,
  150877. };
  150878. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150879. _vq_quantthresh__44u7__p8_0,
  150880. _vq_quantmap__44u7__p8_0,
  150881. 11,
  150882. 11
  150883. };
  150884. static static_codebook _44u7__p8_0 = {
  150885. 2, 121,
  150886. _vq_lengthlist__44u7__p8_0,
  150887. 1, -524582912, 1618345984, 4, 0,
  150888. _vq_quantlist__44u7__p8_0,
  150889. NULL,
  150890. &_vq_auxt__44u7__p8_0,
  150891. NULL,
  150892. 0
  150893. };
  150894. static long _vq_quantlist__44u7__p8_1[] = {
  150895. 5,
  150896. 4,
  150897. 6,
  150898. 3,
  150899. 7,
  150900. 2,
  150901. 8,
  150902. 1,
  150903. 9,
  150904. 0,
  150905. 10,
  150906. };
  150907. static long _vq_lengthlist__44u7__p8_1[] = {
  150908. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150909. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150910. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150911. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150912. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150913. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150914. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150915. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150916. };
  150917. static float _vq_quantthresh__44u7__p8_1[] = {
  150918. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150919. 3.5, 4.5,
  150920. };
  150921. static long _vq_quantmap__44u7__p8_1[] = {
  150922. 9, 7, 5, 3, 1, 0, 2, 4,
  150923. 6, 8, 10,
  150924. };
  150925. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150926. _vq_quantthresh__44u7__p8_1,
  150927. _vq_quantmap__44u7__p8_1,
  150928. 11,
  150929. 11
  150930. };
  150931. static static_codebook _44u7__p8_1 = {
  150932. 2, 121,
  150933. _vq_lengthlist__44u7__p8_1,
  150934. 1, -531365888, 1611661312, 4, 0,
  150935. _vq_quantlist__44u7__p8_1,
  150936. NULL,
  150937. &_vq_auxt__44u7__p8_1,
  150938. NULL,
  150939. 0
  150940. };
  150941. static long _vq_quantlist__44u7__p9_0[] = {
  150942. 5,
  150943. 4,
  150944. 6,
  150945. 3,
  150946. 7,
  150947. 2,
  150948. 8,
  150949. 1,
  150950. 9,
  150951. 0,
  150952. 10,
  150953. };
  150954. static long _vq_lengthlist__44u7__p9_0[] = {
  150955. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150956. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150957. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150958. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150959. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150960. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150961. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150962. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150963. };
  150964. static float _vq_quantthresh__44u7__p9_0[] = {
  150965. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150966. 2229.5, 2866.5,
  150967. };
  150968. static long _vq_quantmap__44u7__p9_0[] = {
  150969. 9, 7, 5, 3, 1, 0, 2, 4,
  150970. 6, 8, 10,
  150971. };
  150972. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150973. _vq_quantthresh__44u7__p9_0,
  150974. _vq_quantmap__44u7__p9_0,
  150975. 11,
  150976. 11
  150977. };
  150978. static static_codebook _44u7__p9_0 = {
  150979. 2, 121,
  150980. _vq_lengthlist__44u7__p9_0,
  150981. 1, -512171520, 1630791680, 4, 0,
  150982. _vq_quantlist__44u7__p9_0,
  150983. NULL,
  150984. &_vq_auxt__44u7__p9_0,
  150985. NULL,
  150986. 0
  150987. };
  150988. static long _vq_quantlist__44u7__p9_1[] = {
  150989. 6,
  150990. 5,
  150991. 7,
  150992. 4,
  150993. 8,
  150994. 3,
  150995. 9,
  150996. 2,
  150997. 10,
  150998. 1,
  150999. 11,
  151000. 0,
  151001. 12,
  151002. };
  151003. static long _vq_lengthlist__44u7__p9_1[] = {
  151004. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  151005. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  151006. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  151007. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  151008. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  151009. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  151010. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  151011. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  151012. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  151013. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  151014. 15,15,15,15,17,17,16,17,16,
  151015. };
  151016. static float _vq_quantthresh__44u7__p9_1[] = {
  151017. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  151018. 122.5, 171.5, 220.5, 269.5,
  151019. };
  151020. static long _vq_quantmap__44u7__p9_1[] = {
  151021. 11, 9, 7, 5, 3, 1, 0, 2,
  151022. 4, 6, 8, 10, 12,
  151023. };
  151024. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  151025. _vq_quantthresh__44u7__p9_1,
  151026. _vq_quantmap__44u7__p9_1,
  151027. 13,
  151028. 13
  151029. };
  151030. static static_codebook _44u7__p9_1 = {
  151031. 2, 169,
  151032. _vq_lengthlist__44u7__p9_1,
  151033. 1, -518889472, 1622704128, 4, 0,
  151034. _vq_quantlist__44u7__p9_1,
  151035. NULL,
  151036. &_vq_auxt__44u7__p9_1,
  151037. NULL,
  151038. 0
  151039. };
  151040. static long _vq_quantlist__44u7__p9_2[] = {
  151041. 24,
  151042. 23,
  151043. 25,
  151044. 22,
  151045. 26,
  151046. 21,
  151047. 27,
  151048. 20,
  151049. 28,
  151050. 19,
  151051. 29,
  151052. 18,
  151053. 30,
  151054. 17,
  151055. 31,
  151056. 16,
  151057. 32,
  151058. 15,
  151059. 33,
  151060. 14,
  151061. 34,
  151062. 13,
  151063. 35,
  151064. 12,
  151065. 36,
  151066. 11,
  151067. 37,
  151068. 10,
  151069. 38,
  151070. 9,
  151071. 39,
  151072. 8,
  151073. 40,
  151074. 7,
  151075. 41,
  151076. 6,
  151077. 42,
  151078. 5,
  151079. 43,
  151080. 4,
  151081. 44,
  151082. 3,
  151083. 45,
  151084. 2,
  151085. 46,
  151086. 1,
  151087. 47,
  151088. 0,
  151089. 48,
  151090. };
  151091. static long _vq_lengthlist__44u7__p9_2[] = {
  151092. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151093. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151094. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  151095. 8,
  151096. };
  151097. static float _vq_quantthresh__44u7__p9_2[] = {
  151098. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151099. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151100. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151101. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151102. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151103. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151104. };
  151105. static long _vq_quantmap__44u7__p9_2[] = {
  151106. 47, 45, 43, 41, 39, 37, 35, 33,
  151107. 31, 29, 27, 25, 23, 21, 19, 17,
  151108. 15, 13, 11, 9, 7, 5, 3, 1,
  151109. 0, 2, 4, 6, 8, 10, 12, 14,
  151110. 16, 18, 20, 22, 24, 26, 28, 30,
  151111. 32, 34, 36, 38, 40, 42, 44, 46,
  151112. 48,
  151113. };
  151114. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  151115. _vq_quantthresh__44u7__p9_2,
  151116. _vq_quantmap__44u7__p9_2,
  151117. 49,
  151118. 49
  151119. };
  151120. static static_codebook _44u7__p9_2 = {
  151121. 1, 49,
  151122. _vq_lengthlist__44u7__p9_2,
  151123. 1, -526909440, 1611661312, 6, 0,
  151124. _vq_quantlist__44u7__p9_2,
  151125. NULL,
  151126. &_vq_auxt__44u7__p9_2,
  151127. NULL,
  151128. 0
  151129. };
  151130. static long _huff_lengthlist__44u7__short[] = {
  151131. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  151132. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  151133. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  151134. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  151135. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  151136. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  151137. 6, 8, 5, 9,
  151138. };
  151139. static static_codebook _huff_book__44u7__short = {
  151140. 2, 100,
  151141. _huff_lengthlist__44u7__short,
  151142. 0, 0, 0, 0, 0,
  151143. NULL,
  151144. NULL,
  151145. NULL,
  151146. NULL,
  151147. 0
  151148. };
  151149. static long _huff_lengthlist__44u8__long[] = {
  151150. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  151151. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  151152. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  151153. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  151154. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  151155. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  151156. 10, 8, 8, 9,
  151157. };
  151158. static static_codebook _huff_book__44u8__long = {
  151159. 2, 100,
  151160. _huff_lengthlist__44u8__long,
  151161. 0, 0, 0, 0, 0,
  151162. NULL,
  151163. NULL,
  151164. NULL,
  151165. NULL,
  151166. 0
  151167. };
  151168. static long _huff_lengthlist__44u8__short[] = {
  151169. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  151170. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  151171. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  151172. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  151173. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  151174. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  151175. 10,10,15,17,
  151176. };
  151177. static static_codebook _huff_book__44u8__short = {
  151178. 2, 100,
  151179. _huff_lengthlist__44u8__short,
  151180. 0, 0, 0, 0, 0,
  151181. NULL,
  151182. NULL,
  151183. NULL,
  151184. NULL,
  151185. 0
  151186. };
  151187. static long _vq_quantlist__44u8_p1_0[] = {
  151188. 1,
  151189. 0,
  151190. 2,
  151191. };
  151192. static long _vq_lengthlist__44u8_p1_0[] = {
  151193. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151194. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151195. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151196. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151197. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151198. 10,
  151199. };
  151200. static float _vq_quantthresh__44u8_p1_0[] = {
  151201. -0.5, 0.5,
  151202. };
  151203. static long _vq_quantmap__44u8_p1_0[] = {
  151204. 1, 0, 2,
  151205. };
  151206. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151207. _vq_quantthresh__44u8_p1_0,
  151208. _vq_quantmap__44u8_p1_0,
  151209. 3,
  151210. 3
  151211. };
  151212. static static_codebook _44u8_p1_0 = {
  151213. 4, 81,
  151214. _vq_lengthlist__44u8_p1_0,
  151215. 1, -535822336, 1611661312, 2, 0,
  151216. _vq_quantlist__44u8_p1_0,
  151217. NULL,
  151218. &_vq_auxt__44u8_p1_0,
  151219. NULL,
  151220. 0
  151221. };
  151222. static long _vq_quantlist__44u8_p2_0[] = {
  151223. 2,
  151224. 1,
  151225. 3,
  151226. 0,
  151227. 4,
  151228. };
  151229. static long _vq_lengthlist__44u8_p2_0[] = {
  151230. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151231. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151232. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151233. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151234. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151235. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151236. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151237. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151238. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151239. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151240. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151241. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151242. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151243. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151244. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151245. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151246. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151247. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151248. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151249. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151250. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151251. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151252. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151253. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151254. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151255. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151256. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151257. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151258. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151259. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151260. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151261. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151262. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151263. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151264. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151265. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151266. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151267. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151268. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151269. 14,
  151270. };
  151271. static float _vq_quantthresh__44u8_p2_0[] = {
  151272. -1.5, -0.5, 0.5, 1.5,
  151273. };
  151274. static long _vq_quantmap__44u8_p2_0[] = {
  151275. 3, 1, 0, 2, 4,
  151276. };
  151277. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151278. _vq_quantthresh__44u8_p2_0,
  151279. _vq_quantmap__44u8_p2_0,
  151280. 5,
  151281. 5
  151282. };
  151283. static static_codebook _44u8_p2_0 = {
  151284. 4, 625,
  151285. _vq_lengthlist__44u8_p2_0,
  151286. 1, -533725184, 1611661312, 3, 0,
  151287. _vq_quantlist__44u8_p2_0,
  151288. NULL,
  151289. &_vq_auxt__44u8_p2_0,
  151290. NULL,
  151291. 0
  151292. };
  151293. static long _vq_quantlist__44u8_p3_0[] = {
  151294. 4,
  151295. 3,
  151296. 5,
  151297. 2,
  151298. 6,
  151299. 1,
  151300. 7,
  151301. 0,
  151302. 8,
  151303. };
  151304. static long _vq_lengthlist__44u8_p3_0[] = {
  151305. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151306. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151307. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151308. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151309. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151310. 12,
  151311. };
  151312. static float _vq_quantthresh__44u8_p3_0[] = {
  151313. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151314. };
  151315. static long _vq_quantmap__44u8_p3_0[] = {
  151316. 7, 5, 3, 1, 0, 2, 4, 6,
  151317. 8,
  151318. };
  151319. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151320. _vq_quantthresh__44u8_p3_0,
  151321. _vq_quantmap__44u8_p3_0,
  151322. 9,
  151323. 9
  151324. };
  151325. static static_codebook _44u8_p3_0 = {
  151326. 2, 81,
  151327. _vq_lengthlist__44u8_p3_0,
  151328. 1, -531628032, 1611661312, 4, 0,
  151329. _vq_quantlist__44u8_p3_0,
  151330. NULL,
  151331. &_vq_auxt__44u8_p3_0,
  151332. NULL,
  151333. 0
  151334. };
  151335. static long _vq_quantlist__44u8_p4_0[] = {
  151336. 8,
  151337. 7,
  151338. 9,
  151339. 6,
  151340. 10,
  151341. 5,
  151342. 11,
  151343. 4,
  151344. 12,
  151345. 3,
  151346. 13,
  151347. 2,
  151348. 14,
  151349. 1,
  151350. 15,
  151351. 0,
  151352. 16,
  151353. };
  151354. static long _vq_lengthlist__44u8_p4_0[] = {
  151355. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151356. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151357. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151358. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151359. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151360. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151361. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151362. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151363. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151364. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151365. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151366. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151367. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151368. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151369. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151370. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151371. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151372. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151373. 14,
  151374. };
  151375. static float _vq_quantthresh__44u8_p4_0[] = {
  151376. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151377. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151378. };
  151379. static long _vq_quantmap__44u8_p4_0[] = {
  151380. 15, 13, 11, 9, 7, 5, 3, 1,
  151381. 0, 2, 4, 6, 8, 10, 12, 14,
  151382. 16,
  151383. };
  151384. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151385. _vq_quantthresh__44u8_p4_0,
  151386. _vq_quantmap__44u8_p4_0,
  151387. 17,
  151388. 17
  151389. };
  151390. static static_codebook _44u8_p4_0 = {
  151391. 2, 289,
  151392. _vq_lengthlist__44u8_p4_0,
  151393. 1, -529530880, 1611661312, 5, 0,
  151394. _vq_quantlist__44u8_p4_0,
  151395. NULL,
  151396. &_vq_auxt__44u8_p4_0,
  151397. NULL,
  151398. 0
  151399. };
  151400. static long _vq_quantlist__44u8_p5_0[] = {
  151401. 1,
  151402. 0,
  151403. 2,
  151404. };
  151405. static long _vq_lengthlist__44u8_p5_0[] = {
  151406. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151407. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151408. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151409. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151410. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151411. 10,
  151412. };
  151413. static float _vq_quantthresh__44u8_p5_0[] = {
  151414. -5.5, 5.5,
  151415. };
  151416. static long _vq_quantmap__44u8_p5_0[] = {
  151417. 1, 0, 2,
  151418. };
  151419. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151420. _vq_quantthresh__44u8_p5_0,
  151421. _vq_quantmap__44u8_p5_0,
  151422. 3,
  151423. 3
  151424. };
  151425. static static_codebook _44u8_p5_0 = {
  151426. 4, 81,
  151427. _vq_lengthlist__44u8_p5_0,
  151428. 1, -529137664, 1618345984, 2, 0,
  151429. _vq_quantlist__44u8_p5_0,
  151430. NULL,
  151431. &_vq_auxt__44u8_p5_0,
  151432. NULL,
  151433. 0
  151434. };
  151435. static long _vq_quantlist__44u8_p5_1[] = {
  151436. 5,
  151437. 4,
  151438. 6,
  151439. 3,
  151440. 7,
  151441. 2,
  151442. 8,
  151443. 1,
  151444. 9,
  151445. 0,
  151446. 10,
  151447. };
  151448. static long _vq_lengthlist__44u8_p5_1[] = {
  151449. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151450. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151451. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151452. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151453. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151454. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151455. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151456. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151457. };
  151458. static float _vq_quantthresh__44u8_p5_1[] = {
  151459. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151460. 3.5, 4.5,
  151461. };
  151462. static long _vq_quantmap__44u8_p5_1[] = {
  151463. 9, 7, 5, 3, 1, 0, 2, 4,
  151464. 6, 8, 10,
  151465. };
  151466. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151467. _vq_quantthresh__44u8_p5_1,
  151468. _vq_quantmap__44u8_p5_1,
  151469. 11,
  151470. 11
  151471. };
  151472. static static_codebook _44u8_p5_1 = {
  151473. 2, 121,
  151474. _vq_lengthlist__44u8_p5_1,
  151475. 1, -531365888, 1611661312, 4, 0,
  151476. _vq_quantlist__44u8_p5_1,
  151477. NULL,
  151478. &_vq_auxt__44u8_p5_1,
  151479. NULL,
  151480. 0
  151481. };
  151482. static long _vq_quantlist__44u8_p6_0[] = {
  151483. 6,
  151484. 5,
  151485. 7,
  151486. 4,
  151487. 8,
  151488. 3,
  151489. 9,
  151490. 2,
  151491. 10,
  151492. 1,
  151493. 11,
  151494. 0,
  151495. 12,
  151496. };
  151497. static long _vq_lengthlist__44u8_p6_0[] = {
  151498. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151499. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151500. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151501. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151502. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151503. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151504. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151505. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151506. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151507. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151508. 11,11,11,11,11,12,11,12,12,
  151509. };
  151510. static float _vq_quantthresh__44u8_p6_0[] = {
  151511. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151512. 12.5, 17.5, 22.5, 27.5,
  151513. };
  151514. static long _vq_quantmap__44u8_p6_0[] = {
  151515. 11, 9, 7, 5, 3, 1, 0, 2,
  151516. 4, 6, 8, 10, 12,
  151517. };
  151518. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151519. _vq_quantthresh__44u8_p6_0,
  151520. _vq_quantmap__44u8_p6_0,
  151521. 13,
  151522. 13
  151523. };
  151524. static static_codebook _44u8_p6_0 = {
  151525. 2, 169,
  151526. _vq_lengthlist__44u8_p6_0,
  151527. 1, -526516224, 1616117760, 4, 0,
  151528. _vq_quantlist__44u8_p6_0,
  151529. NULL,
  151530. &_vq_auxt__44u8_p6_0,
  151531. NULL,
  151532. 0
  151533. };
  151534. static long _vq_quantlist__44u8_p6_1[] = {
  151535. 2,
  151536. 1,
  151537. 3,
  151538. 0,
  151539. 4,
  151540. };
  151541. static long _vq_lengthlist__44u8_p6_1[] = {
  151542. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151543. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151544. };
  151545. static float _vq_quantthresh__44u8_p6_1[] = {
  151546. -1.5, -0.5, 0.5, 1.5,
  151547. };
  151548. static long _vq_quantmap__44u8_p6_1[] = {
  151549. 3, 1, 0, 2, 4,
  151550. };
  151551. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151552. _vq_quantthresh__44u8_p6_1,
  151553. _vq_quantmap__44u8_p6_1,
  151554. 5,
  151555. 5
  151556. };
  151557. static static_codebook _44u8_p6_1 = {
  151558. 2, 25,
  151559. _vq_lengthlist__44u8_p6_1,
  151560. 1, -533725184, 1611661312, 3, 0,
  151561. _vq_quantlist__44u8_p6_1,
  151562. NULL,
  151563. &_vq_auxt__44u8_p6_1,
  151564. NULL,
  151565. 0
  151566. };
  151567. static long _vq_quantlist__44u8_p7_0[] = {
  151568. 6,
  151569. 5,
  151570. 7,
  151571. 4,
  151572. 8,
  151573. 3,
  151574. 9,
  151575. 2,
  151576. 10,
  151577. 1,
  151578. 11,
  151579. 0,
  151580. 12,
  151581. };
  151582. static long _vq_lengthlist__44u8_p7_0[] = {
  151583. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151584. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151585. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151586. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151587. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151588. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151589. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151590. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151591. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151592. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151593. 13,13,14,14,14,15,15,15,16,
  151594. };
  151595. static float _vq_quantthresh__44u8_p7_0[] = {
  151596. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151597. 27.5, 38.5, 49.5, 60.5,
  151598. };
  151599. static long _vq_quantmap__44u8_p7_0[] = {
  151600. 11, 9, 7, 5, 3, 1, 0, 2,
  151601. 4, 6, 8, 10, 12,
  151602. };
  151603. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151604. _vq_quantthresh__44u8_p7_0,
  151605. _vq_quantmap__44u8_p7_0,
  151606. 13,
  151607. 13
  151608. };
  151609. static static_codebook _44u8_p7_0 = {
  151610. 2, 169,
  151611. _vq_lengthlist__44u8_p7_0,
  151612. 1, -523206656, 1618345984, 4, 0,
  151613. _vq_quantlist__44u8_p7_0,
  151614. NULL,
  151615. &_vq_auxt__44u8_p7_0,
  151616. NULL,
  151617. 0
  151618. };
  151619. static long _vq_quantlist__44u8_p7_1[] = {
  151620. 5,
  151621. 4,
  151622. 6,
  151623. 3,
  151624. 7,
  151625. 2,
  151626. 8,
  151627. 1,
  151628. 9,
  151629. 0,
  151630. 10,
  151631. };
  151632. static long _vq_lengthlist__44u8_p7_1[] = {
  151633. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151634. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151635. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151636. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151637. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151638. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151639. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151640. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151641. };
  151642. static float _vq_quantthresh__44u8_p7_1[] = {
  151643. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151644. 3.5, 4.5,
  151645. };
  151646. static long _vq_quantmap__44u8_p7_1[] = {
  151647. 9, 7, 5, 3, 1, 0, 2, 4,
  151648. 6, 8, 10,
  151649. };
  151650. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151651. _vq_quantthresh__44u8_p7_1,
  151652. _vq_quantmap__44u8_p7_1,
  151653. 11,
  151654. 11
  151655. };
  151656. static static_codebook _44u8_p7_1 = {
  151657. 2, 121,
  151658. _vq_lengthlist__44u8_p7_1,
  151659. 1, -531365888, 1611661312, 4, 0,
  151660. _vq_quantlist__44u8_p7_1,
  151661. NULL,
  151662. &_vq_auxt__44u8_p7_1,
  151663. NULL,
  151664. 0
  151665. };
  151666. static long _vq_quantlist__44u8_p8_0[] = {
  151667. 7,
  151668. 6,
  151669. 8,
  151670. 5,
  151671. 9,
  151672. 4,
  151673. 10,
  151674. 3,
  151675. 11,
  151676. 2,
  151677. 12,
  151678. 1,
  151679. 13,
  151680. 0,
  151681. 14,
  151682. };
  151683. static long _vq_lengthlist__44u8_p8_0[] = {
  151684. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151685. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151686. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151687. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151688. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151689. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151690. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151691. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151692. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151693. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151694. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151695. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151696. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151697. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151698. 17,
  151699. };
  151700. static float _vq_quantthresh__44u8_p8_0[] = {
  151701. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151702. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151703. };
  151704. static long _vq_quantmap__44u8_p8_0[] = {
  151705. 13, 11, 9, 7, 5, 3, 1, 0,
  151706. 2, 4, 6, 8, 10, 12, 14,
  151707. };
  151708. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151709. _vq_quantthresh__44u8_p8_0,
  151710. _vq_quantmap__44u8_p8_0,
  151711. 15,
  151712. 15
  151713. };
  151714. static static_codebook _44u8_p8_0 = {
  151715. 2, 225,
  151716. _vq_lengthlist__44u8_p8_0,
  151717. 1, -520986624, 1620377600, 4, 0,
  151718. _vq_quantlist__44u8_p8_0,
  151719. NULL,
  151720. &_vq_auxt__44u8_p8_0,
  151721. NULL,
  151722. 0
  151723. };
  151724. static long _vq_quantlist__44u8_p8_1[] = {
  151725. 10,
  151726. 9,
  151727. 11,
  151728. 8,
  151729. 12,
  151730. 7,
  151731. 13,
  151732. 6,
  151733. 14,
  151734. 5,
  151735. 15,
  151736. 4,
  151737. 16,
  151738. 3,
  151739. 17,
  151740. 2,
  151741. 18,
  151742. 1,
  151743. 19,
  151744. 0,
  151745. 20,
  151746. };
  151747. static long _vq_lengthlist__44u8_p8_1[] = {
  151748. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151749. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151750. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151751. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151752. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151753. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151754. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151755. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151756. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151757. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151758. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151759. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151760. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151761. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151762. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151763. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151764. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151765. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151766. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151767. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151768. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151769. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151770. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151771. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151772. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151773. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151774. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151775. 10,10,10,10,10,10,10,10,10,
  151776. };
  151777. static float _vq_quantthresh__44u8_p8_1[] = {
  151778. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151779. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151780. 6.5, 7.5, 8.5, 9.5,
  151781. };
  151782. static long _vq_quantmap__44u8_p8_1[] = {
  151783. 19, 17, 15, 13, 11, 9, 7, 5,
  151784. 3, 1, 0, 2, 4, 6, 8, 10,
  151785. 12, 14, 16, 18, 20,
  151786. };
  151787. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151788. _vq_quantthresh__44u8_p8_1,
  151789. _vq_quantmap__44u8_p8_1,
  151790. 21,
  151791. 21
  151792. };
  151793. static static_codebook _44u8_p8_1 = {
  151794. 2, 441,
  151795. _vq_lengthlist__44u8_p8_1,
  151796. 1, -529268736, 1611661312, 5, 0,
  151797. _vq_quantlist__44u8_p8_1,
  151798. NULL,
  151799. &_vq_auxt__44u8_p8_1,
  151800. NULL,
  151801. 0
  151802. };
  151803. static long _vq_quantlist__44u8_p9_0[] = {
  151804. 4,
  151805. 3,
  151806. 5,
  151807. 2,
  151808. 6,
  151809. 1,
  151810. 7,
  151811. 0,
  151812. 8,
  151813. };
  151814. static long _vq_lengthlist__44u8_p9_0[] = {
  151815. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151816. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151817. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151818. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151819. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151820. 8,
  151821. };
  151822. static float _vq_quantthresh__44u8_p9_0[] = {
  151823. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151824. };
  151825. static long _vq_quantmap__44u8_p9_0[] = {
  151826. 7, 5, 3, 1, 0, 2, 4, 6,
  151827. 8,
  151828. };
  151829. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151830. _vq_quantthresh__44u8_p9_0,
  151831. _vq_quantmap__44u8_p9_0,
  151832. 9,
  151833. 9
  151834. };
  151835. static static_codebook _44u8_p9_0 = {
  151836. 2, 81,
  151837. _vq_lengthlist__44u8_p9_0,
  151838. 1, -511895552, 1631393792, 4, 0,
  151839. _vq_quantlist__44u8_p9_0,
  151840. NULL,
  151841. &_vq_auxt__44u8_p9_0,
  151842. NULL,
  151843. 0
  151844. };
  151845. static long _vq_quantlist__44u8_p9_1[] = {
  151846. 9,
  151847. 8,
  151848. 10,
  151849. 7,
  151850. 11,
  151851. 6,
  151852. 12,
  151853. 5,
  151854. 13,
  151855. 4,
  151856. 14,
  151857. 3,
  151858. 15,
  151859. 2,
  151860. 16,
  151861. 1,
  151862. 17,
  151863. 0,
  151864. 18,
  151865. };
  151866. static long _vq_lengthlist__44u8_p9_1[] = {
  151867. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151868. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151869. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151870. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151871. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151872. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151873. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151874. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151875. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151876. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151877. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151878. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151879. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151880. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151881. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151882. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151883. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151884. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151885. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151886. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151887. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151888. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151889. 16,15,16,16,16,16,16,16,16,
  151890. };
  151891. static float _vq_quantthresh__44u8_p9_1[] = {
  151892. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151893. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151894. 367.5, 416.5,
  151895. };
  151896. static long _vq_quantmap__44u8_p9_1[] = {
  151897. 17, 15, 13, 11, 9, 7, 5, 3,
  151898. 1, 0, 2, 4, 6, 8, 10, 12,
  151899. 14, 16, 18,
  151900. };
  151901. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151902. _vq_quantthresh__44u8_p9_1,
  151903. _vq_quantmap__44u8_p9_1,
  151904. 19,
  151905. 19
  151906. };
  151907. static static_codebook _44u8_p9_1 = {
  151908. 2, 361,
  151909. _vq_lengthlist__44u8_p9_1,
  151910. 1, -518287360, 1622704128, 5, 0,
  151911. _vq_quantlist__44u8_p9_1,
  151912. NULL,
  151913. &_vq_auxt__44u8_p9_1,
  151914. NULL,
  151915. 0
  151916. };
  151917. static long _vq_quantlist__44u8_p9_2[] = {
  151918. 24,
  151919. 23,
  151920. 25,
  151921. 22,
  151922. 26,
  151923. 21,
  151924. 27,
  151925. 20,
  151926. 28,
  151927. 19,
  151928. 29,
  151929. 18,
  151930. 30,
  151931. 17,
  151932. 31,
  151933. 16,
  151934. 32,
  151935. 15,
  151936. 33,
  151937. 14,
  151938. 34,
  151939. 13,
  151940. 35,
  151941. 12,
  151942. 36,
  151943. 11,
  151944. 37,
  151945. 10,
  151946. 38,
  151947. 9,
  151948. 39,
  151949. 8,
  151950. 40,
  151951. 7,
  151952. 41,
  151953. 6,
  151954. 42,
  151955. 5,
  151956. 43,
  151957. 4,
  151958. 44,
  151959. 3,
  151960. 45,
  151961. 2,
  151962. 46,
  151963. 1,
  151964. 47,
  151965. 0,
  151966. 48,
  151967. };
  151968. static long _vq_lengthlist__44u8_p9_2[] = {
  151969. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151970. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151971. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151972. 7,
  151973. };
  151974. static float _vq_quantthresh__44u8_p9_2[] = {
  151975. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151976. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151977. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151978. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151979. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151980. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151981. };
  151982. static long _vq_quantmap__44u8_p9_2[] = {
  151983. 47, 45, 43, 41, 39, 37, 35, 33,
  151984. 31, 29, 27, 25, 23, 21, 19, 17,
  151985. 15, 13, 11, 9, 7, 5, 3, 1,
  151986. 0, 2, 4, 6, 8, 10, 12, 14,
  151987. 16, 18, 20, 22, 24, 26, 28, 30,
  151988. 32, 34, 36, 38, 40, 42, 44, 46,
  151989. 48,
  151990. };
  151991. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151992. _vq_quantthresh__44u8_p9_2,
  151993. _vq_quantmap__44u8_p9_2,
  151994. 49,
  151995. 49
  151996. };
  151997. static static_codebook _44u8_p9_2 = {
  151998. 1, 49,
  151999. _vq_lengthlist__44u8_p9_2,
  152000. 1, -526909440, 1611661312, 6, 0,
  152001. _vq_quantlist__44u8_p9_2,
  152002. NULL,
  152003. &_vq_auxt__44u8_p9_2,
  152004. NULL,
  152005. 0
  152006. };
  152007. static long _huff_lengthlist__44u9__long[] = {
  152008. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  152009. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  152010. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  152011. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  152012. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  152013. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  152014. 10, 8, 8, 9,
  152015. };
  152016. static static_codebook _huff_book__44u9__long = {
  152017. 2, 100,
  152018. _huff_lengthlist__44u9__long,
  152019. 0, 0, 0, 0, 0,
  152020. NULL,
  152021. NULL,
  152022. NULL,
  152023. NULL,
  152024. 0
  152025. };
  152026. static long _huff_lengthlist__44u9__short[] = {
  152027. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  152028. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  152029. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  152030. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  152031. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  152032. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  152033. 9, 9,12,15,
  152034. };
  152035. static static_codebook _huff_book__44u9__short = {
  152036. 2, 100,
  152037. _huff_lengthlist__44u9__short,
  152038. 0, 0, 0, 0, 0,
  152039. NULL,
  152040. NULL,
  152041. NULL,
  152042. NULL,
  152043. 0
  152044. };
  152045. static long _vq_quantlist__44u9_p1_0[] = {
  152046. 1,
  152047. 0,
  152048. 2,
  152049. };
  152050. static long _vq_lengthlist__44u9_p1_0[] = {
  152051. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  152052. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  152053. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  152054. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  152055. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  152056. 10,
  152057. };
  152058. static float _vq_quantthresh__44u9_p1_0[] = {
  152059. -0.5, 0.5,
  152060. };
  152061. static long _vq_quantmap__44u9_p1_0[] = {
  152062. 1, 0, 2,
  152063. };
  152064. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  152065. _vq_quantthresh__44u9_p1_0,
  152066. _vq_quantmap__44u9_p1_0,
  152067. 3,
  152068. 3
  152069. };
  152070. static static_codebook _44u9_p1_0 = {
  152071. 4, 81,
  152072. _vq_lengthlist__44u9_p1_0,
  152073. 1, -535822336, 1611661312, 2, 0,
  152074. _vq_quantlist__44u9_p1_0,
  152075. NULL,
  152076. &_vq_auxt__44u9_p1_0,
  152077. NULL,
  152078. 0
  152079. };
  152080. static long _vq_quantlist__44u9_p2_0[] = {
  152081. 2,
  152082. 1,
  152083. 3,
  152084. 0,
  152085. 4,
  152086. };
  152087. static long _vq_lengthlist__44u9_p2_0[] = {
  152088. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  152089. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  152090. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  152091. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  152092. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  152093. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  152094. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  152095. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  152096. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  152097. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  152098. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  152099. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  152100. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  152101. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  152102. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  152103. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  152104. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  152105. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  152106. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  152107. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  152108. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  152109. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  152110. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  152111. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  152112. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  152113. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  152114. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  152115. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  152116. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  152117. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  152118. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  152119. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  152120. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  152121. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  152122. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  152123. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  152124. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  152125. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  152126. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  152127. 14,
  152128. };
  152129. static float _vq_quantthresh__44u9_p2_0[] = {
  152130. -1.5, -0.5, 0.5, 1.5,
  152131. };
  152132. static long _vq_quantmap__44u9_p2_0[] = {
  152133. 3, 1, 0, 2, 4,
  152134. };
  152135. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  152136. _vq_quantthresh__44u9_p2_0,
  152137. _vq_quantmap__44u9_p2_0,
  152138. 5,
  152139. 5
  152140. };
  152141. static static_codebook _44u9_p2_0 = {
  152142. 4, 625,
  152143. _vq_lengthlist__44u9_p2_0,
  152144. 1, -533725184, 1611661312, 3, 0,
  152145. _vq_quantlist__44u9_p2_0,
  152146. NULL,
  152147. &_vq_auxt__44u9_p2_0,
  152148. NULL,
  152149. 0
  152150. };
  152151. static long _vq_quantlist__44u9_p3_0[] = {
  152152. 4,
  152153. 3,
  152154. 5,
  152155. 2,
  152156. 6,
  152157. 1,
  152158. 7,
  152159. 0,
  152160. 8,
  152161. };
  152162. static long _vq_lengthlist__44u9_p3_0[] = {
  152163. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  152164. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  152165. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  152166. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  152167. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  152168. 11,
  152169. };
  152170. static float _vq_quantthresh__44u9_p3_0[] = {
  152171. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152172. };
  152173. static long _vq_quantmap__44u9_p3_0[] = {
  152174. 7, 5, 3, 1, 0, 2, 4, 6,
  152175. 8,
  152176. };
  152177. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  152178. _vq_quantthresh__44u9_p3_0,
  152179. _vq_quantmap__44u9_p3_0,
  152180. 9,
  152181. 9
  152182. };
  152183. static static_codebook _44u9_p3_0 = {
  152184. 2, 81,
  152185. _vq_lengthlist__44u9_p3_0,
  152186. 1, -531628032, 1611661312, 4, 0,
  152187. _vq_quantlist__44u9_p3_0,
  152188. NULL,
  152189. &_vq_auxt__44u9_p3_0,
  152190. NULL,
  152191. 0
  152192. };
  152193. static long _vq_quantlist__44u9_p4_0[] = {
  152194. 8,
  152195. 7,
  152196. 9,
  152197. 6,
  152198. 10,
  152199. 5,
  152200. 11,
  152201. 4,
  152202. 12,
  152203. 3,
  152204. 13,
  152205. 2,
  152206. 14,
  152207. 1,
  152208. 15,
  152209. 0,
  152210. 16,
  152211. };
  152212. static long _vq_lengthlist__44u9_p4_0[] = {
  152213. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152214. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152215. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152216. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152217. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152218. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152219. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152220. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152221. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152222. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152223. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152224. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152225. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152226. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152227. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152228. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152229. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152230. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152231. 14,
  152232. };
  152233. static float _vq_quantthresh__44u9_p4_0[] = {
  152234. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152235. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152236. };
  152237. static long _vq_quantmap__44u9_p4_0[] = {
  152238. 15, 13, 11, 9, 7, 5, 3, 1,
  152239. 0, 2, 4, 6, 8, 10, 12, 14,
  152240. 16,
  152241. };
  152242. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152243. _vq_quantthresh__44u9_p4_0,
  152244. _vq_quantmap__44u9_p4_0,
  152245. 17,
  152246. 17
  152247. };
  152248. static static_codebook _44u9_p4_0 = {
  152249. 2, 289,
  152250. _vq_lengthlist__44u9_p4_0,
  152251. 1, -529530880, 1611661312, 5, 0,
  152252. _vq_quantlist__44u9_p4_0,
  152253. NULL,
  152254. &_vq_auxt__44u9_p4_0,
  152255. NULL,
  152256. 0
  152257. };
  152258. static long _vq_quantlist__44u9_p5_0[] = {
  152259. 1,
  152260. 0,
  152261. 2,
  152262. };
  152263. static long _vq_lengthlist__44u9_p5_0[] = {
  152264. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152265. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152266. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152267. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152268. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152269. 10,
  152270. };
  152271. static float _vq_quantthresh__44u9_p5_0[] = {
  152272. -5.5, 5.5,
  152273. };
  152274. static long _vq_quantmap__44u9_p5_0[] = {
  152275. 1, 0, 2,
  152276. };
  152277. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152278. _vq_quantthresh__44u9_p5_0,
  152279. _vq_quantmap__44u9_p5_0,
  152280. 3,
  152281. 3
  152282. };
  152283. static static_codebook _44u9_p5_0 = {
  152284. 4, 81,
  152285. _vq_lengthlist__44u9_p5_0,
  152286. 1, -529137664, 1618345984, 2, 0,
  152287. _vq_quantlist__44u9_p5_0,
  152288. NULL,
  152289. &_vq_auxt__44u9_p5_0,
  152290. NULL,
  152291. 0
  152292. };
  152293. static long _vq_quantlist__44u9_p5_1[] = {
  152294. 5,
  152295. 4,
  152296. 6,
  152297. 3,
  152298. 7,
  152299. 2,
  152300. 8,
  152301. 1,
  152302. 9,
  152303. 0,
  152304. 10,
  152305. };
  152306. static long _vq_lengthlist__44u9_p5_1[] = {
  152307. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152308. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152309. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152310. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152311. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152312. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152313. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152314. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152315. };
  152316. static float _vq_quantthresh__44u9_p5_1[] = {
  152317. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152318. 3.5, 4.5,
  152319. };
  152320. static long _vq_quantmap__44u9_p5_1[] = {
  152321. 9, 7, 5, 3, 1, 0, 2, 4,
  152322. 6, 8, 10,
  152323. };
  152324. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152325. _vq_quantthresh__44u9_p5_1,
  152326. _vq_quantmap__44u9_p5_1,
  152327. 11,
  152328. 11
  152329. };
  152330. static static_codebook _44u9_p5_1 = {
  152331. 2, 121,
  152332. _vq_lengthlist__44u9_p5_1,
  152333. 1, -531365888, 1611661312, 4, 0,
  152334. _vq_quantlist__44u9_p5_1,
  152335. NULL,
  152336. &_vq_auxt__44u9_p5_1,
  152337. NULL,
  152338. 0
  152339. };
  152340. static long _vq_quantlist__44u9_p6_0[] = {
  152341. 6,
  152342. 5,
  152343. 7,
  152344. 4,
  152345. 8,
  152346. 3,
  152347. 9,
  152348. 2,
  152349. 10,
  152350. 1,
  152351. 11,
  152352. 0,
  152353. 12,
  152354. };
  152355. static long _vq_lengthlist__44u9_p6_0[] = {
  152356. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152357. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152358. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152359. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152360. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152361. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152362. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152363. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152364. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152365. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152366. 10,11,11,11,11,12,11,12,12,
  152367. };
  152368. static float _vq_quantthresh__44u9_p6_0[] = {
  152369. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152370. 12.5, 17.5, 22.5, 27.5,
  152371. };
  152372. static long _vq_quantmap__44u9_p6_0[] = {
  152373. 11, 9, 7, 5, 3, 1, 0, 2,
  152374. 4, 6, 8, 10, 12,
  152375. };
  152376. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152377. _vq_quantthresh__44u9_p6_0,
  152378. _vq_quantmap__44u9_p6_0,
  152379. 13,
  152380. 13
  152381. };
  152382. static static_codebook _44u9_p6_0 = {
  152383. 2, 169,
  152384. _vq_lengthlist__44u9_p6_0,
  152385. 1, -526516224, 1616117760, 4, 0,
  152386. _vq_quantlist__44u9_p6_0,
  152387. NULL,
  152388. &_vq_auxt__44u9_p6_0,
  152389. NULL,
  152390. 0
  152391. };
  152392. static long _vq_quantlist__44u9_p6_1[] = {
  152393. 2,
  152394. 1,
  152395. 3,
  152396. 0,
  152397. 4,
  152398. };
  152399. static long _vq_lengthlist__44u9_p6_1[] = {
  152400. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152401. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152402. };
  152403. static float _vq_quantthresh__44u9_p6_1[] = {
  152404. -1.5, -0.5, 0.5, 1.5,
  152405. };
  152406. static long _vq_quantmap__44u9_p6_1[] = {
  152407. 3, 1, 0, 2, 4,
  152408. };
  152409. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152410. _vq_quantthresh__44u9_p6_1,
  152411. _vq_quantmap__44u9_p6_1,
  152412. 5,
  152413. 5
  152414. };
  152415. static static_codebook _44u9_p6_1 = {
  152416. 2, 25,
  152417. _vq_lengthlist__44u9_p6_1,
  152418. 1, -533725184, 1611661312, 3, 0,
  152419. _vq_quantlist__44u9_p6_1,
  152420. NULL,
  152421. &_vq_auxt__44u9_p6_1,
  152422. NULL,
  152423. 0
  152424. };
  152425. static long _vq_quantlist__44u9_p7_0[] = {
  152426. 6,
  152427. 5,
  152428. 7,
  152429. 4,
  152430. 8,
  152431. 3,
  152432. 9,
  152433. 2,
  152434. 10,
  152435. 1,
  152436. 11,
  152437. 0,
  152438. 12,
  152439. };
  152440. static long _vq_lengthlist__44u9_p7_0[] = {
  152441. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152442. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152443. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152444. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152445. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152446. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152447. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152448. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152449. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152450. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152451. 12,13,13,14,14,14,15,15,15,
  152452. };
  152453. static float _vq_quantthresh__44u9_p7_0[] = {
  152454. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152455. 27.5, 38.5, 49.5, 60.5,
  152456. };
  152457. static long _vq_quantmap__44u9_p7_0[] = {
  152458. 11, 9, 7, 5, 3, 1, 0, 2,
  152459. 4, 6, 8, 10, 12,
  152460. };
  152461. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152462. _vq_quantthresh__44u9_p7_0,
  152463. _vq_quantmap__44u9_p7_0,
  152464. 13,
  152465. 13
  152466. };
  152467. static static_codebook _44u9_p7_0 = {
  152468. 2, 169,
  152469. _vq_lengthlist__44u9_p7_0,
  152470. 1, -523206656, 1618345984, 4, 0,
  152471. _vq_quantlist__44u9_p7_0,
  152472. NULL,
  152473. &_vq_auxt__44u9_p7_0,
  152474. NULL,
  152475. 0
  152476. };
  152477. static long _vq_quantlist__44u9_p7_1[] = {
  152478. 5,
  152479. 4,
  152480. 6,
  152481. 3,
  152482. 7,
  152483. 2,
  152484. 8,
  152485. 1,
  152486. 9,
  152487. 0,
  152488. 10,
  152489. };
  152490. static long _vq_lengthlist__44u9_p7_1[] = {
  152491. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152492. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152493. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152494. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152495. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152496. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152497. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152498. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152499. };
  152500. static float _vq_quantthresh__44u9_p7_1[] = {
  152501. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152502. 3.5, 4.5,
  152503. };
  152504. static long _vq_quantmap__44u9_p7_1[] = {
  152505. 9, 7, 5, 3, 1, 0, 2, 4,
  152506. 6, 8, 10,
  152507. };
  152508. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152509. _vq_quantthresh__44u9_p7_1,
  152510. _vq_quantmap__44u9_p7_1,
  152511. 11,
  152512. 11
  152513. };
  152514. static static_codebook _44u9_p7_1 = {
  152515. 2, 121,
  152516. _vq_lengthlist__44u9_p7_1,
  152517. 1, -531365888, 1611661312, 4, 0,
  152518. _vq_quantlist__44u9_p7_1,
  152519. NULL,
  152520. &_vq_auxt__44u9_p7_1,
  152521. NULL,
  152522. 0
  152523. };
  152524. static long _vq_quantlist__44u9_p8_0[] = {
  152525. 7,
  152526. 6,
  152527. 8,
  152528. 5,
  152529. 9,
  152530. 4,
  152531. 10,
  152532. 3,
  152533. 11,
  152534. 2,
  152535. 12,
  152536. 1,
  152537. 13,
  152538. 0,
  152539. 14,
  152540. };
  152541. static long _vq_lengthlist__44u9_p8_0[] = {
  152542. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152543. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152544. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152545. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152546. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152547. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152548. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152549. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152550. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152551. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152552. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152553. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152554. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152555. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152556. 15,
  152557. };
  152558. static float _vq_quantthresh__44u9_p8_0[] = {
  152559. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152560. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152561. };
  152562. static long _vq_quantmap__44u9_p8_0[] = {
  152563. 13, 11, 9, 7, 5, 3, 1, 0,
  152564. 2, 4, 6, 8, 10, 12, 14,
  152565. };
  152566. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152567. _vq_quantthresh__44u9_p8_0,
  152568. _vq_quantmap__44u9_p8_0,
  152569. 15,
  152570. 15
  152571. };
  152572. static static_codebook _44u9_p8_0 = {
  152573. 2, 225,
  152574. _vq_lengthlist__44u9_p8_0,
  152575. 1, -520986624, 1620377600, 4, 0,
  152576. _vq_quantlist__44u9_p8_0,
  152577. NULL,
  152578. &_vq_auxt__44u9_p8_0,
  152579. NULL,
  152580. 0
  152581. };
  152582. static long _vq_quantlist__44u9_p8_1[] = {
  152583. 10,
  152584. 9,
  152585. 11,
  152586. 8,
  152587. 12,
  152588. 7,
  152589. 13,
  152590. 6,
  152591. 14,
  152592. 5,
  152593. 15,
  152594. 4,
  152595. 16,
  152596. 3,
  152597. 17,
  152598. 2,
  152599. 18,
  152600. 1,
  152601. 19,
  152602. 0,
  152603. 20,
  152604. };
  152605. static long _vq_lengthlist__44u9_p8_1[] = {
  152606. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152607. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152608. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152609. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152610. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152611. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152612. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152613. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152614. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152615. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152616. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152617. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152618. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152619. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152620. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152621. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152622. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152623. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152624. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152625. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152626. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152627. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152628. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152629. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152630. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152631. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152632. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152633. 10,10,10,10,10,10,10,10,10,
  152634. };
  152635. static float _vq_quantthresh__44u9_p8_1[] = {
  152636. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152637. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152638. 6.5, 7.5, 8.5, 9.5,
  152639. };
  152640. static long _vq_quantmap__44u9_p8_1[] = {
  152641. 19, 17, 15, 13, 11, 9, 7, 5,
  152642. 3, 1, 0, 2, 4, 6, 8, 10,
  152643. 12, 14, 16, 18, 20,
  152644. };
  152645. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152646. _vq_quantthresh__44u9_p8_1,
  152647. _vq_quantmap__44u9_p8_1,
  152648. 21,
  152649. 21
  152650. };
  152651. static static_codebook _44u9_p8_1 = {
  152652. 2, 441,
  152653. _vq_lengthlist__44u9_p8_1,
  152654. 1, -529268736, 1611661312, 5, 0,
  152655. _vq_quantlist__44u9_p8_1,
  152656. NULL,
  152657. &_vq_auxt__44u9_p8_1,
  152658. NULL,
  152659. 0
  152660. };
  152661. static long _vq_quantlist__44u9_p9_0[] = {
  152662. 7,
  152663. 6,
  152664. 8,
  152665. 5,
  152666. 9,
  152667. 4,
  152668. 10,
  152669. 3,
  152670. 11,
  152671. 2,
  152672. 12,
  152673. 1,
  152674. 13,
  152675. 0,
  152676. 14,
  152677. };
  152678. static long _vq_lengthlist__44u9_p9_0[] = {
  152679. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152680. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152681. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152682. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152683. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152684. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152685. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152686. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152687. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152688. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152689. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152690. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152691. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152692. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152693. 10,
  152694. };
  152695. static float _vq_quantthresh__44u9_p9_0[] = {
  152696. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152697. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152698. };
  152699. static long _vq_quantmap__44u9_p9_0[] = {
  152700. 13, 11, 9, 7, 5, 3, 1, 0,
  152701. 2, 4, 6, 8, 10, 12, 14,
  152702. };
  152703. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152704. _vq_quantthresh__44u9_p9_0,
  152705. _vq_quantmap__44u9_p9_0,
  152706. 15,
  152707. 15
  152708. };
  152709. static static_codebook _44u9_p9_0 = {
  152710. 2, 225,
  152711. _vq_lengthlist__44u9_p9_0,
  152712. 1, -510036736, 1631393792, 4, 0,
  152713. _vq_quantlist__44u9_p9_0,
  152714. NULL,
  152715. &_vq_auxt__44u9_p9_0,
  152716. NULL,
  152717. 0
  152718. };
  152719. static long _vq_quantlist__44u9_p9_1[] = {
  152720. 9,
  152721. 8,
  152722. 10,
  152723. 7,
  152724. 11,
  152725. 6,
  152726. 12,
  152727. 5,
  152728. 13,
  152729. 4,
  152730. 14,
  152731. 3,
  152732. 15,
  152733. 2,
  152734. 16,
  152735. 1,
  152736. 17,
  152737. 0,
  152738. 18,
  152739. };
  152740. static long _vq_lengthlist__44u9_p9_1[] = {
  152741. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152742. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152743. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152744. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152745. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152746. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152747. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152748. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152749. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152750. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152751. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152752. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152753. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152754. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152755. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152756. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152757. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152758. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152759. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152760. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152761. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152762. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152763. 17,17,15,17,15,17,16,16,17,
  152764. };
  152765. static float _vq_quantthresh__44u9_p9_1[] = {
  152766. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152767. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152768. 367.5, 416.5,
  152769. };
  152770. static long _vq_quantmap__44u9_p9_1[] = {
  152771. 17, 15, 13, 11, 9, 7, 5, 3,
  152772. 1, 0, 2, 4, 6, 8, 10, 12,
  152773. 14, 16, 18,
  152774. };
  152775. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152776. _vq_quantthresh__44u9_p9_1,
  152777. _vq_quantmap__44u9_p9_1,
  152778. 19,
  152779. 19
  152780. };
  152781. static static_codebook _44u9_p9_1 = {
  152782. 2, 361,
  152783. _vq_lengthlist__44u9_p9_1,
  152784. 1, -518287360, 1622704128, 5, 0,
  152785. _vq_quantlist__44u9_p9_1,
  152786. NULL,
  152787. &_vq_auxt__44u9_p9_1,
  152788. NULL,
  152789. 0
  152790. };
  152791. static long _vq_quantlist__44u9_p9_2[] = {
  152792. 24,
  152793. 23,
  152794. 25,
  152795. 22,
  152796. 26,
  152797. 21,
  152798. 27,
  152799. 20,
  152800. 28,
  152801. 19,
  152802. 29,
  152803. 18,
  152804. 30,
  152805. 17,
  152806. 31,
  152807. 16,
  152808. 32,
  152809. 15,
  152810. 33,
  152811. 14,
  152812. 34,
  152813. 13,
  152814. 35,
  152815. 12,
  152816. 36,
  152817. 11,
  152818. 37,
  152819. 10,
  152820. 38,
  152821. 9,
  152822. 39,
  152823. 8,
  152824. 40,
  152825. 7,
  152826. 41,
  152827. 6,
  152828. 42,
  152829. 5,
  152830. 43,
  152831. 4,
  152832. 44,
  152833. 3,
  152834. 45,
  152835. 2,
  152836. 46,
  152837. 1,
  152838. 47,
  152839. 0,
  152840. 48,
  152841. };
  152842. static long _vq_lengthlist__44u9_p9_2[] = {
  152843. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152844. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152845. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152846. 7,
  152847. };
  152848. static float _vq_quantthresh__44u9_p9_2[] = {
  152849. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152850. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152851. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152852. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152853. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152854. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152855. };
  152856. static long _vq_quantmap__44u9_p9_2[] = {
  152857. 47, 45, 43, 41, 39, 37, 35, 33,
  152858. 31, 29, 27, 25, 23, 21, 19, 17,
  152859. 15, 13, 11, 9, 7, 5, 3, 1,
  152860. 0, 2, 4, 6, 8, 10, 12, 14,
  152861. 16, 18, 20, 22, 24, 26, 28, 30,
  152862. 32, 34, 36, 38, 40, 42, 44, 46,
  152863. 48,
  152864. };
  152865. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152866. _vq_quantthresh__44u9_p9_2,
  152867. _vq_quantmap__44u9_p9_2,
  152868. 49,
  152869. 49
  152870. };
  152871. static static_codebook _44u9_p9_2 = {
  152872. 1, 49,
  152873. _vq_lengthlist__44u9_p9_2,
  152874. 1, -526909440, 1611661312, 6, 0,
  152875. _vq_quantlist__44u9_p9_2,
  152876. NULL,
  152877. &_vq_auxt__44u9_p9_2,
  152878. NULL,
  152879. 0
  152880. };
  152881. static long _huff_lengthlist__44un1__long[] = {
  152882. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152883. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152884. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152885. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152886. };
  152887. static static_codebook _huff_book__44un1__long = {
  152888. 2, 64,
  152889. _huff_lengthlist__44un1__long,
  152890. 0, 0, 0, 0, 0,
  152891. NULL,
  152892. NULL,
  152893. NULL,
  152894. NULL,
  152895. 0
  152896. };
  152897. static long _vq_quantlist__44un1__p1_0[] = {
  152898. 1,
  152899. 0,
  152900. 2,
  152901. };
  152902. static long _vq_lengthlist__44un1__p1_0[] = {
  152903. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152904. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152905. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152906. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152907. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152908. 12,
  152909. };
  152910. static float _vq_quantthresh__44un1__p1_0[] = {
  152911. -0.5, 0.5,
  152912. };
  152913. static long _vq_quantmap__44un1__p1_0[] = {
  152914. 1, 0, 2,
  152915. };
  152916. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152917. _vq_quantthresh__44un1__p1_0,
  152918. _vq_quantmap__44un1__p1_0,
  152919. 3,
  152920. 3
  152921. };
  152922. static static_codebook _44un1__p1_0 = {
  152923. 4, 81,
  152924. _vq_lengthlist__44un1__p1_0,
  152925. 1, -535822336, 1611661312, 2, 0,
  152926. _vq_quantlist__44un1__p1_0,
  152927. NULL,
  152928. &_vq_auxt__44un1__p1_0,
  152929. NULL,
  152930. 0
  152931. };
  152932. static long _vq_quantlist__44un1__p2_0[] = {
  152933. 1,
  152934. 0,
  152935. 2,
  152936. };
  152937. static long _vq_lengthlist__44un1__p2_0[] = {
  152938. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152939. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152940. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152941. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152942. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152943. 8,
  152944. };
  152945. static float _vq_quantthresh__44un1__p2_0[] = {
  152946. -0.5, 0.5,
  152947. };
  152948. static long _vq_quantmap__44un1__p2_0[] = {
  152949. 1, 0, 2,
  152950. };
  152951. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152952. _vq_quantthresh__44un1__p2_0,
  152953. _vq_quantmap__44un1__p2_0,
  152954. 3,
  152955. 3
  152956. };
  152957. static static_codebook _44un1__p2_0 = {
  152958. 4, 81,
  152959. _vq_lengthlist__44un1__p2_0,
  152960. 1, -535822336, 1611661312, 2, 0,
  152961. _vq_quantlist__44un1__p2_0,
  152962. NULL,
  152963. &_vq_auxt__44un1__p2_0,
  152964. NULL,
  152965. 0
  152966. };
  152967. static long _vq_quantlist__44un1__p3_0[] = {
  152968. 2,
  152969. 1,
  152970. 3,
  152971. 0,
  152972. 4,
  152973. };
  152974. static long _vq_lengthlist__44un1__p3_0[] = {
  152975. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152976. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152977. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152978. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152979. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152980. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152981. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152982. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152983. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152984. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152985. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152986. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152987. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152988. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152989. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152990. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152991. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152992. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152993. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152994. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152995. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152996. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152997. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152998. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152999. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  153000. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  153001. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  153002. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  153003. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  153004. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  153005. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  153006. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  153007. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  153008. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  153009. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  153010. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  153011. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  153012. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  153013. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  153014. 17,
  153015. };
  153016. static float _vq_quantthresh__44un1__p3_0[] = {
  153017. -1.5, -0.5, 0.5, 1.5,
  153018. };
  153019. static long _vq_quantmap__44un1__p3_0[] = {
  153020. 3, 1, 0, 2, 4,
  153021. };
  153022. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  153023. _vq_quantthresh__44un1__p3_0,
  153024. _vq_quantmap__44un1__p3_0,
  153025. 5,
  153026. 5
  153027. };
  153028. static static_codebook _44un1__p3_0 = {
  153029. 4, 625,
  153030. _vq_lengthlist__44un1__p3_0,
  153031. 1, -533725184, 1611661312, 3, 0,
  153032. _vq_quantlist__44un1__p3_0,
  153033. NULL,
  153034. &_vq_auxt__44un1__p3_0,
  153035. NULL,
  153036. 0
  153037. };
  153038. static long _vq_quantlist__44un1__p4_0[] = {
  153039. 2,
  153040. 1,
  153041. 3,
  153042. 0,
  153043. 4,
  153044. };
  153045. static long _vq_lengthlist__44un1__p4_0[] = {
  153046. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  153047. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  153048. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  153049. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  153050. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  153051. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  153052. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  153053. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  153054. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  153055. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  153056. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  153057. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  153058. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  153059. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  153060. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  153061. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  153062. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  153063. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  153064. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  153065. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  153066. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  153067. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  153068. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  153069. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  153070. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  153071. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  153072. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  153073. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  153074. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  153075. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  153076. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  153077. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  153078. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  153079. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  153080. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  153081. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  153082. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  153083. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  153084. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  153085. 12,
  153086. };
  153087. static float _vq_quantthresh__44un1__p4_0[] = {
  153088. -1.5, -0.5, 0.5, 1.5,
  153089. };
  153090. static long _vq_quantmap__44un1__p4_0[] = {
  153091. 3, 1, 0, 2, 4,
  153092. };
  153093. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  153094. _vq_quantthresh__44un1__p4_0,
  153095. _vq_quantmap__44un1__p4_0,
  153096. 5,
  153097. 5
  153098. };
  153099. static static_codebook _44un1__p4_0 = {
  153100. 4, 625,
  153101. _vq_lengthlist__44un1__p4_0,
  153102. 1, -533725184, 1611661312, 3, 0,
  153103. _vq_quantlist__44un1__p4_0,
  153104. NULL,
  153105. &_vq_auxt__44un1__p4_0,
  153106. NULL,
  153107. 0
  153108. };
  153109. static long _vq_quantlist__44un1__p5_0[] = {
  153110. 4,
  153111. 3,
  153112. 5,
  153113. 2,
  153114. 6,
  153115. 1,
  153116. 7,
  153117. 0,
  153118. 8,
  153119. };
  153120. static long _vq_lengthlist__44un1__p5_0[] = {
  153121. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  153122. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  153123. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  153124. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  153125. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  153126. 12,
  153127. };
  153128. static float _vq_quantthresh__44un1__p5_0[] = {
  153129. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  153130. };
  153131. static long _vq_quantmap__44un1__p5_0[] = {
  153132. 7, 5, 3, 1, 0, 2, 4, 6,
  153133. 8,
  153134. };
  153135. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  153136. _vq_quantthresh__44un1__p5_0,
  153137. _vq_quantmap__44un1__p5_0,
  153138. 9,
  153139. 9
  153140. };
  153141. static static_codebook _44un1__p5_0 = {
  153142. 2, 81,
  153143. _vq_lengthlist__44un1__p5_0,
  153144. 1, -531628032, 1611661312, 4, 0,
  153145. _vq_quantlist__44un1__p5_0,
  153146. NULL,
  153147. &_vq_auxt__44un1__p5_0,
  153148. NULL,
  153149. 0
  153150. };
  153151. static long _vq_quantlist__44un1__p6_0[] = {
  153152. 6,
  153153. 5,
  153154. 7,
  153155. 4,
  153156. 8,
  153157. 3,
  153158. 9,
  153159. 2,
  153160. 10,
  153161. 1,
  153162. 11,
  153163. 0,
  153164. 12,
  153165. };
  153166. static long _vq_lengthlist__44un1__p6_0[] = {
  153167. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  153168. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  153169. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  153170. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  153171. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  153172. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  153173. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  153174. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  153175. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  153176. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  153177. 16, 0,15,18,18, 0,16, 0, 0,
  153178. };
  153179. static float _vq_quantthresh__44un1__p6_0[] = {
  153180. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  153181. 12.5, 17.5, 22.5, 27.5,
  153182. };
  153183. static long _vq_quantmap__44un1__p6_0[] = {
  153184. 11, 9, 7, 5, 3, 1, 0, 2,
  153185. 4, 6, 8, 10, 12,
  153186. };
  153187. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  153188. _vq_quantthresh__44un1__p6_0,
  153189. _vq_quantmap__44un1__p6_0,
  153190. 13,
  153191. 13
  153192. };
  153193. static static_codebook _44un1__p6_0 = {
  153194. 2, 169,
  153195. _vq_lengthlist__44un1__p6_0,
  153196. 1, -526516224, 1616117760, 4, 0,
  153197. _vq_quantlist__44un1__p6_0,
  153198. NULL,
  153199. &_vq_auxt__44un1__p6_0,
  153200. NULL,
  153201. 0
  153202. };
  153203. static long _vq_quantlist__44un1__p6_1[] = {
  153204. 2,
  153205. 1,
  153206. 3,
  153207. 0,
  153208. 4,
  153209. };
  153210. static long _vq_lengthlist__44un1__p6_1[] = {
  153211. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153212. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153213. };
  153214. static float _vq_quantthresh__44un1__p6_1[] = {
  153215. -1.5, -0.5, 0.5, 1.5,
  153216. };
  153217. static long _vq_quantmap__44un1__p6_1[] = {
  153218. 3, 1, 0, 2, 4,
  153219. };
  153220. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153221. _vq_quantthresh__44un1__p6_1,
  153222. _vq_quantmap__44un1__p6_1,
  153223. 5,
  153224. 5
  153225. };
  153226. static static_codebook _44un1__p6_1 = {
  153227. 2, 25,
  153228. _vq_lengthlist__44un1__p6_1,
  153229. 1, -533725184, 1611661312, 3, 0,
  153230. _vq_quantlist__44un1__p6_1,
  153231. NULL,
  153232. &_vq_auxt__44un1__p6_1,
  153233. NULL,
  153234. 0
  153235. };
  153236. static long _vq_quantlist__44un1__p7_0[] = {
  153237. 2,
  153238. 1,
  153239. 3,
  153240. 0,
  153241. 4,
  153242. };
  153243. static long _vq_lengthlist__44un1__p7_0[] = {
  153244. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153245. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153246. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153247. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153248. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153249. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153250. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153251. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153254. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153255. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153256. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153257. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153258. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153259. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153261. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153270. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153271. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153273. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153274. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153276. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153277. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153278. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153279. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153280. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153281. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153282. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153283. 10,
  153284. };
  153285. static float _vq_quantthresh__44un1__p7_0[] = {
  153286. -253.5, -84.5, 84.5, 253.5,
  153287. };
  153288. static long _vq_quantmap__44un1__p7_0[] = {
  153289. 3, 1, 0, 2, 4,
  153290. };
  153291. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153292. _vq_quantthresh__44un1__p7_0,
  153293. _vq_quantmap__44un1__p7_0,
  153294. 5,
  153295. 5
  153296. };
  153297. static static_codebook _44un1__p7_0 = {
  153298. 4, 625,
  153299. _vq_lengthlist__44un1__p7_0,
  153300. 1, -518709248, 1626677248, 3, 0,
  153301. _vq_quantlist__44un1__p7_0,
  153302. NULL,
  153303. &_vq_auxt__44un1__p7_0,
  153304. NULL,
  153305. 0
  153306. };
  153307. static long _vq_quantlist__44un1__p7_1[] = {
  153308. 6,
  153309. 5,
  153310. 7,
  153311. 4,
  153312. 8,
  153313. 3,
  153314. 9,
  153315. 2,
  153316. 10,
  153317. 1,
  153318. 11,
  153319. 0,
  153320. 12,
  153321. };
  153322. static long _vq_lengthlist__44un1__p7_1[] = {
  153323. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153324. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153325. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153326. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153327. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153328. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153329. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153330. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153331. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153332. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153333. 12,13,13,12,13,13,14,14,14,
  153334. };
  153335. static float _vq_quantthresh__44un1__p7_1[] = {
  153336. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153337. 32.5, 45.5, 58.5, 71.5,
  153338. };
  153339. static long _vq_quantmap__44un1__p7_1[] = {
  153340. 11, 9, 7, 5, 3, 1, 0, 2,
  153341. 4, 6, 8, 10, 12,
  153342. };
  153343. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153344. _vq_quantthresh__44un1__p7_1,
  153345. _vq_quantmap__44un1__p7_1,
  153346. 13,
  153347. 13
  153348. };
  153349. static static_codebook _44un1__p7_1 = {
  153350. 2, 169,
  153351. _vq_lengthlist__44un1__p7_1,
  153352. 1, -523010048, 1618608128, 4, 0,
  153353. _vq_quantlist__44un1__p7_1,
  153354. NULL,
  153355. &_vq_auxt__44un1__p7_1,
  153356. NULL,
  153357. 0
  153358. };
  153359. static long _vq_quantlist__44un1__p7_2[] = {
  153360. 6,
  153361. 5,
  153362. 7,
  153363. 4,
  153364. 8,
  153365. 3,
  153366. 9,
  153367. 2,
  153368. 10,
  153369. 1,
  153370. 11,
  153371. 0,
  153372. 12,
  153373. };
  153374. static long _vq_lengthlist__44un1__p7_2[] = {
  153375. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153376. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153377. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153378. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153379. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153380. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153381. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153382. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153383. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153384. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153385. 9, 9, 9,10,10,10,10,10,10,
  153386. };
  153387. static float _vq_quantthresh__44un1__p7_2[] = {
  153388. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153389. 2.5, 3.5, 4.5, 5.5,
  153390. };
  153391. static long _vq_quantmap__44un1__p7_2[] = {
  153392. 11, 9, 7, 5, 3, 1, 0, 2,
  153393. 4, 6, 8, 10, 12,
  153394. };
  153395. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153396. _vq_quantthresh__44un1__p7_2,
  153397. _vq_quantmap__44un1__p7_2,
  153398. 13,
  153399. 13
  153400. };
  153401. static static_codebook _44un1__p7_2 = {
  153402. 2, 169,
  153403. _vq_lengthlist__44un1__p7_2,
  153404. 1, -531103744, 1611661312, 4, 0,
  153405. _vq_quantlist__44un1__p7_2,
  153406. NULL,
  153407. &_vq_auxt__44un1__p7_2,
  153408. NULL,
  153409. 0
  153410. };
  153411. static long _huff_lengthlist__44un1__short[] = {
  153412. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153413. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153414. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153415. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153416. };
  153417. static static_codebook _huff_book__44un1__short = {
  153418. 2, 64,
  153419. _huff_lengthlist__44un1__short,
  153420. 0, 0, 0, 0, 0,
  153421. NULL,
  153422. NULL,
  153423. NULL,
  153424. NULL,
  153425. 0
  153426. };
  153427. /*** End of inlined file: res_books_uncoupled.h ***/
  153428. /***** residue backends *********************************************/
  153429. static vorbis_info_residue0 _residue_44_low_un={
  153430. 0,-1, -1, 8,-1,
  153431. {0},
  153432. {-1},
  153433. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153434. { -1, 25, -1, 45, -1, -1, -1}
  153435. };
  153436. static vorbis_info_residue0 _residue_44_mid_un={
  153437. 0,-1, -1, 10,-1,
  153438. /* 0 1 2 3 4 5 6 7 8 9 */
  153439. {0},
  153440. {-1},
  153441. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153442. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153443. };
  153444. static vorbis_info_residue0 _residue_44_hi_un={
  153445. 0,-1, -1, 10,-1,
  153446. /* 0 1 2 3 4 5 6 7 8 9 */
  153447. {0},
  153448. {-1},
  153449. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153450. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153451. };
  153452. /* mapping conventions:
  153453. only one submap (this would change for efficient 5.1 support for example)*/
  153454. /* Four psychoacoustic profiles are used, one for each blocktype */
  153455. static vorbis_info_mapping0 _map_nominal_u[2]={
  153456. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153457. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153458. };
  153459. static static_bookblock _resbook_44u_n1={
  153460. {
  153461. {0},
  153462. {0,0,&_44un1__p1_0},
  153463. {0,0,&_44un1__p2_0},
  153464. {0,0,&_44un1__p3_0},
  153465. {0,0,&_44un1__p4_0},
  153466. {0,0,&_44un1__p5_0},
  153467. {&_44un1__p6_0,&_44un1__p6_1},
  153468. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153469. }
  153470. };
  153471. static static_bookblock _resbook_44u_0={
  153472. {
  153473. {0},
  153474. {0,0,&_44u0__p1_0},
  153475. {0,0,&_44u0__p2_0},
  153476. {0,0,&_44u0__p3_0},
  153477. {0,0,&_44u0__p4_0},
  153478. {0,0,&_44u0__p5_0},
  153479. {&_44u0__p6_0,&_44u0__p6_1},
  153480. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153481. }
  153482. };
  153483. static static_bookblock _resbook_44u_1={
  153484. {
  153485. {0},
  153486. {0,0,&_44u1__p1_0},
  153487. {0,0,&_44u1__p2_0},
  153488. {0,0,&_44u1__p3_0},
  153489. {0,0,&_44u1__p4_0},
  153490. {0,0,&_44u1__p5_0},
  153491. {&_44u1__p6_0,&_44u1__p6_1},
  153492. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153493. }
  153494. };
  153495. static static_bookblock _resbook_44u_2={
  153496. {
  153497. {0},
  153498. {0,0,&_44u2__p1_0},
  153499. {0,0,&_44u2__p2_0},
  153500. {0,0,&_44u2__p3_0},
  153501. {0,0,&_44u2__p4_0},
  153502. {0,0,&_44u2__p5_0},
  153503. {&_44u2__p6_0,&_44u2__p6_1},
  153504. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153505. }
  153506. };
  153507. static static_bookblock _resbook_44u_3={
  153508. {
  153509. {0},
  153510. {0,0,&_44u3__p1_0},
  153511. {0,0,&_44u3__p2_0},
  153512. {0,0,&_44u3__p3_0},
  153513. {0,0,&_44u3__p4_0},
  153514. {0,0,&_44u3__p5_0},
  153515. {&_44u3__p6_0,&_44u3__p6_1},
  153516. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153517. }
  153518. };
  153519. static static_bookblock _resbook_44u_4={
  153520. {
  153521. {0},
  153522. {0,0,&_44u4__p1_0},
  153523. {0,0,&_44u4__p2_0},
  153524. {0,0,&_44u4__p3_0},
  153525. {0,0,&_44u4__p4_0},
  153526. {0,0,&_44u4__p5_0},
  153527. {&_44u4__p6_0,&_44u4__p6_1},
  153528. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153529. }
  153530. };
  153531. static static_bookblock _resbook_44u_5={
  153532. {
  153533. {0},
  153534. {0,0,&_44u5__p1_0},
  153535. {0,0,&_44u5__p2_0},
  153536. {0,0,&_44u5__p3_0},
  153537. {0,0,&_44u5__p4_0},
  153538. {0,0,&_44u5__p5_0},
  153539. {0,0,&_44u5__p6_0},
  153540. {&_44u5__p7_0,&_44u5__p7_1},
  153541. {&_44u5__p8_0,&_44u5__p8_1},
  153542. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153543. }
  153544. };
  153545. static static_bookblock _resbook_44u_6={
  153546. {
  153547. {0},
  153548. {0,0,&_44u6__p1_0},
  153549. {0,0,&_44u6__p2_0},
  153550. {0,0,&_44u6__p3_0},
  153551. {0,0,&_44u6__p4_0},
  153552. {0,0,&_44u6__p5_0},
  153553. {0,0,&_44u6__p6_0},
  153554. {&_44u6__p7_0,&_44u6__p7_1},
  153555. {&_44u6__p8_0,&_44u6__p8_1},
  153556. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153557. }
  153558. };
  153559. static static_bookblock _resbook_44u_7={
  153560. {
  153561. {0},
  153562. {0,0,&_44u7__p1_0},
  153563. {0,0,&_44u7__p2_0},
  153564. {0,0,&_44u7__p3_0},
  153565. {0,0,&_44u7__p4_0},
  153566. {0,0,&_44u7__p5_0},
  153567. {0,0,&_44u7__p6_0},
  153568. {&_44u7__p7_0,&_44u7__p7_1},
  153569. {&_44u7__p8_0,&_44u7__p8_1},
  153570. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153571. }
  153572. };
  153573. static static_bookblock _resbook_44u_8={
  153574. {
  153575. {0},
  153576. {0,0,&_44u8_p1_0},
  153577. {0,0,&_44u8_p2_0},
  153578. {0,0,&_44u8_p3_0},
  153579. {0,0,&_44u8_p4_0},
  153580. {&_44u8_p5_0,&_44u8_p5_1},
  153581. {&_44u8_p6_0,&_44u8_p6_1},
  153582. {&_44u8_p7_0,&_44u8_p7_1},
  153583. {&_44u8_p8_0,&_44u8_p8_1},
  153584. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153585. }
  153586. };
  153587. static static_bookblock _resbook_44u_9={
  153588. {
  153589. {0},
  153590. {0,0,&_44u9_p1_0},
  153591. {0,0,&_44u9_p2_0},
  153592. {0,0,&_44u9_p3_0},
  153593. {0,0,&_44u9_p4_0},
  153594. {&_44u9_p5_0,&_44u9_p5_1},
  153595. {&_44u9_p6_0,&_44u9_p6_1},
  153596. {&_44u9_p7_0,&_44u9_p7_1},
  153597. {&_44u9_p8_0,&_44u9_p8_1},
  153598. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153599. }
  153600. };
  153601. static vorbis_residue_template _res_44u_n1[]={
  153602. {1,0, &_residue_44_low_un,
  153603. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153604. &_resbook_44u_n1,&_resbook_44u_n1},
  153605. {1,0, &_residue_44_low_un,
  153606. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153607. &_resbook_44u_n1,&_resbook_44u_n1}
  153608. };
  153609. static vorbis_residue_template _res_44u_0[]={
  153610. {1,0, &_residue_44_low_un,
  153611. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153612. &_resbook_44u_0,&_resbook_44u_0},
  153613. {1,0, &_residue_44_low_un,
  153614. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153615. &_resbook_44u_0,&_resbook_44u_0}
  153616. };
  153617. static vorbis_residue_template _res_44u_1[]={
  153618. {1,0, &_residue_44_low_un,
  153619. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153620. &_resbook_44u_1,&_resbook_44u_1},
  153621. {1,0, &_residue_44_low_un,
  153622. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153623. &_resbook_44u_1,&_resbook_44u_1}
  153624. };
  153625. static vorbis_residue_template _res_44u_2[]={
  153626. {1,0, &_residue_44_low_un,
  153627. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153628. &_resbook_44u_2,&_resbook_44u_2},
  153629. {1,0, &_residue_44_low_un,
  153630. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153631. &_resbook_44u_2,&_resbook_44u_2}
  153632. };
  153633. static vorbis_residue_template _res_44u_3[]={
  153634. {1,0, &_residue_44_low_un,
  153635. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153636. &_resbook_44u_3,&_resbook_44u_3},
  153637. {1,0, &_residue_44_low_un,
  153638. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153639. &_resbook_44u_3,&_resbook_44u_3}
  153640. };
  153641. static vorbis_residue_template _res_44u_4[]={
  153642. {1,0, &_residue_44_low_un,
  153643. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153644. &_resbook_44u_4,&_resbook_44u_4},
  153645. {1,0, &_residue_44_low_un,
  153646. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153647. &_resbook_44u_4,&_resbook_44u_4}
  153648. };
  153649. static vorbis_residue_template _res_44u_5[]={
  153650. {1,0, &_residue_44_mid_un,
  153651. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153652. &_resbook_44u_5,&_resbook_44u_5},
  153653. {1,0, &_residue_44_mid_un,
  153654. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153655. &_resbook_44u_5,&_resbook_44u_5}
  153656. };
  153657. static vorbis_residue_template _res_44u_6[]={
  153658. {1,0, &_residue_44_mid_un,
  153659. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153660. &_resbook_44u_6,&_resbook_44u_6},
  153661. {1,0, &_residue_44_mid_un,
  153662. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153663. &_resbook_44u_6,&_resbook_44u_6}
  153664. };
  153665. static vorbis_residue_template _res_44u_7[]={
  153666. {1,0, &_residue_44_mid_un,
  153667. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153668. &_resbook_44u_7,&_resbook_44u_7},
  153669. {1,0, &_residue_44_mid_un,
  153670. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153671. &_resbook_44u_7,&_resbook_44u_7}
  153672. };
  153673. static vorbis_residue_template _res_44u_8[]={
  153674. {1,0, &_residue_44_hi_un,
  153675. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153676. &_resbook_44u_8,&_resbook_44u_8},
  153677. {1,0, &_residue_44_hi_un,
  153678. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153679. &_resbook_44u_8,&_resbook_44u_8}
  153680. };
  153681. static vorbis_residue_template _res_44u_9[]={
  153682. {1,0, &_residue_44_hi_un,
  153683. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153684. &_resbook_44u_9,&_resbook_44u_9},
  153685. {1,0, &_residue_44_hi_un,
  153686. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153687. &_resbook_44u_9,&_resbook_44u_9}
  153688. };
  153689. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153690. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153691. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153692. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153693. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153694. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153695. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153696. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153697. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153698. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153699. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153700. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153701. };
  153702. /*** End of inlined file: residue_44u.h ***/
  153703. static double rate_mapping_44_un[12]={
  153704. 32000.,48000.,60000.,70000.,80000.,86000.,
  153705. 96000.,110000.,120000.,140000.,160000.,240001.
  153706. };
  153707. ve_setup_data_template ve_setup_44_uncoupled={
  153708. 11,
  153709. rate_mapping_44_un,
  153710. quality_mapping_44,
  153711. -1,
  153712. 40000,
  153713. 50000,
  153714. blocksize_short_44,
  153715. blocksize_long_44,
  153716. _psy_tone_masteratt_44,
  153717. _psy_tone_0dB,
  153718. _psy_tone_suppress,
  153719. _vp_tonemask_adj_otherblock,
  153720. _vp_tonemask_adj_longblock,
  153721. _vp_tonemask_adj_otherblock,
  153722. _psy_noiseguards_44,
  153723. _psy_noisebias_impulse,
  153724. _psy_noisebias_padding,
  153725. _psy_noisebias_trans,
  153726. _psy_noisebias_long,
  153727. _psy_noise_suppress,
  153728. _psy_compand_44,
  153729. _psy_compand_short_mapping,
  153730. _psy_compand_long_mapping,
  153731. {_noise_start_short_44,_noise_start_long_44},
  153732. {_noise_part_short_44,_noise_part_long_44},
  153733. _noise_thresh_44,
  153734. _psy_ath_floater,
  153735. _psy_ath_abs,
  153736. _psy_lowpass_44,
  153737. _psy_global_44,
  153738. _global_mapping_44,
  153739. NULL,
  153740. _floor_books,
  153741. _floor,
  153742. _floor_short_mapping_44,
  153743. _floor_long_mapping_44,
  153744. _mapres_template_44_uncoupled
  153745. };
  153746. /*** End of inlined file: setup_44u.h ***/
  153747. /*** Start of inlined file: setup_32.h ***/
  153748. static double rate_mapping_32[12]={
  153749. 18000.,28000.,35000.,45000.,56000.,60000.,
  153750. 75000.,90000.,100000.,115000.,150000.,190000.,
  153751. };
  153752. static double rate_mapping_32_un[12]={
  153753. 30000.,42000.,52000.,64000.,72000.,78000.,
  153754. 86000.,92000.,110000.,120000.,140000.,190000.,
  153755. };
  153756. static double _psy_lowpass_32[12]={
  153757. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153758. };
  153759. ve_setup_data_template ve_setup_32_stereo={
  153760. 11,
  153761. rate_mapping_32,
  153762. quality_mapping_44,
  153763. 2,
  153764. 26000,
  153765. 40000,
  153766. blocksize_short_44,
  153767. blocksize_long_44,
  153768. _psy_tone_masteratt_44,
  153769. _psy_tone_0dB,
  153770. _psy_tone_suppress,
  153771. _vp_tonemask_adj_otherblock,
  153772. _vp_tonemask_adj_longblock,
  153773. _vp_tonemask_adj_otherblock,
  153774. _psy_noiseguards_44,
  153775. _psy_noisebias_impulse,
  153776. _psy_noisebias_padding,
  153777. _psy_noisebias_trans,
  153778. _psy_noisebias_long,
  153779. _psy_noise_suppress,
  153780. _psy_compand_44,
  153781. _psy_compand_short_mapping,
  153782. _psy_compand_long_mapping,
  153783. {_noise_start_short_44,_noise_start_long_44},
  153784. {_noise_part_short_44,_noise_part_long_44},
  153785. _noise_thresh_44,
  153786. _psy_ath_floater,
  153787. _psy_ath_abs,
  153788. _psy_lowpass_32,
  153789. _psy_global_44,
  153790. _global_mapping_44,
  153791. _psy_stereo_modes_44,
  153792. _floor_books,
  153793. _floor,
  153794. _floor_short_mapping_44,
  153795. _floor_long_mapping_44,
  153796. _mapres_template_44_stereo
  153797. };
  153798. ve_setup_data_template ve_setup_32_uncoupled={
  153799. 11,
  153800. rate_mapping_32_un,
  153801. quality_mapping_44,
  153802. -1,
  153803. 26000,
  153804. 40000,
  153805. blocksize_short_44,
  153806. blocksize_long_44,
  153807. _psy_tone_masteratt_44,
  153808. _psy_tone_0dB,
  153809. _psy_tone_suppress,
  153810. _vp_tonemask_adj_otherblock,
  153811. _vp_tonemask_adj_longblock,
  153812. _vp_tonemask_adj_otherblock,
  153813. _psy_noiseguards_44,
  153814. _psy_noisebias_impulse,
  153815. _psy_noisebias_padding,
  153816. _psy_noisebias_trans,
  153817. _psy_noisebias_long,
  153818. _psy_noise_suppress,
  153819. _psy_compand_44,
  153820. _psy_compand_short_mapping,
  153821. _psy_compand_long_mapping,
  153822. {_noise_start_short_44,_noise_start_long_44},
  153823. {_noise_part_short_44,_noise_part_long_44},
  153824. _noise_thresh_44,
  153825. _psy_ath_floater,
  153826. _psy_ath_abs,
  153827. _psy_lowpass_32,
  153828. _psy_global_44,
  153829. _global_mapping_44,
  153830. NULL,
  153831. _floor_books,
  153832. _floor,
  153833. _floor_short_mapping_44,
  153834. _floor_long_mapping_44,
  153835. _mapres_template_44_uncoupled
  153836. };
  153837. /*** End of inlined file: setup_32.h ***/
  153838. /*** Start of inlined file: setup_8.h ***/
  153839. /*** Start of inlined file: psych_8.h ***/
  153840. static att3 _psy_tone_masteratt_8[3]={
  153841. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153842. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153843. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153844. };
  153845. static vp_adjblock _vp_tonemask_adj_8[3]={
  153846. /* adjust for mode zero */
  153847. /* 63 125 250 500 1 2 4 8 16 */
  153848. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153849. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153850. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153851. };
  153852. static noise3 _psy_noisebias_8[3]={
  153853. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153854. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153855. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153856. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153857. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153858. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153859. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153860. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153861. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153862. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153863. };
  153864. /* stereo mode by base quality level */
  153865. static adj_stereo _psy_stereo_modes_8[3]={
  153866. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153867. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153868. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153869. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153870. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153871. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153872. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153873. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153874. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153875. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153876. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153877. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153878. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153879. };
  153880. static noiseguard _psy_noiseguards_8[2]={
  153881. {10,10,-1},
  153882. {10,10,-1},
  153883. };
  153884. static compandblock _psy_compand_8[2]={
  153885. {{
  153886. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153887. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153888. 12,12,13,13,14,14,15, 15, /* 23dB */
  153889. 16,16,17,17,17,18,18, 19, /* 31dB */
  153890. 19,19,20,21,22,23,24, 25, /* 39dB */
  153891. }},
  153892. {{
  153893. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153894. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153895. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153896. 9,10,11,12,13,14,15, 16, /* 31dB */
  153897. 17,18,19,20,21,22,23, 24, /* 39dB */
  153898. }},
  153899. };
  153900. static double _psy_lowpass_8[3]={3.,4.,4.};
  153901. static int _noise_start_8[2]={
  153902. 64,64,
  153903. };
  153904. static int _noise_part_8[2]={
  153905. 8,8,
  153906. };
  153907. static int _psy_ath_floater_8[3]={
  153908. -100,-100,-105,
  153909. };
  153910. static int _psy_ath_abs_8[3]={
  153911. -130,-130,-140,
  153912. };
  153913. /*** End of inlined file: psych_8.h ***/
  153914. /*** Start of inlined file: residue_8.h ***/
  153915. /***** residue backends *********************************************/
  153916. static static_bookblock _resbook_8s_0={
  153917. {
  153918. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153919. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153920. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153921. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153922. }
  153923. };
  153924. static static_bookblock _resbook_8s_1={
  153925. {
  153926. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153927. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153928. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153929. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153930. }
  153931. };
  153932. static vorbis_residue_template _res_8s_0[]={
  153933. {2,0, &_residue_44_mid,
  153934. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153935. &_resbook_8s_0,&_resbook_8s_0},
  153936. };
  153937. static vorbis_residue_template _res_8s_1[]={
  153938. {2,0, &_residue_44_mid,
  153939. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153940. &_resbook_8s_1,&_resbook_8s_1},
  153941. };
  153942. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153943. { _map_nominal, _res_8s_0 }, /* 0 */
  153944. { _map_nominal, _res_8s_1 }, /* 1 */
  153945. };
  153946. static static_bookblock _resbook_8u_0={
  153947. {
  153948. {0},
  153949. {0,0,&_8u0__p1_0},
  153950. {0,0,&_8u0__p2_0},
  153951. {0,0,&_8u0__p3_0},
  153952. {0,0,&_8u0__p4_0},
  153953. {0,0,&_8u0__p5_0},
  153954. {&_8u0__p6_0,&_8u0__p6_1},
  153955. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153956. }
  153957. };
  153958. static static_bookblock _resbook_8u_1={
  153959. {
  153960. {0},
  153961. {0,0,&_8u1__p1_0},
  153962. {0,0,&_8u1__p2_0},
  153963. {0,0,&_8u1__p3_0},
  153964. {0,0,&_8u1__p4_0},
  153965. {0,0,&_8u1__p5_0},
  153966. {0,0,&_8u1__p6_0},
  153967. {&_8u1__p7_0,&_8u1__p7_1},
  153968. {&_8u1__p8_0,&_8u1__p8_1},
  153969. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153970. }
  153971. };
  153972. static vorbis_residue_template _res_8u_0[]={
  153973. {1,0, &_residue_44_low_un,
  153974. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153975. &_resbook_8u_0,&_resbook_8u_0},
  153976. };
  153977. static vorbis_residue_template _res_8u_1[]={
  153978. {1,0, &_residue_44_mid_un,
  153979. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153980. &_resbook_8u_1,&_resbook_8u_1},
  153981. };
  153982. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153983. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153984. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153985. };
  153986. /*** End of inlined file: residue_8.h ***/
  153987. static int blocksize_8[2]={
  153988. 512,512
  153989. };
  153990. static int _floor_mapping_8[2]={
  153991. 6,6,
  153992. };
  153993. static double rate_mapping_8[3]={
  153994. 6000.,9000.,32000.,
  153995. };
  153996. static double rate_mapping_8_uncoupled[3]={
  153997. 8000.,14000.,42000.,
  153998. };
  153999. static double quality_mapping_8[3]={
  154000. -.1,.0,1.
  154001. };
  154002. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  154003. static double _global_mapping_8[3]={ 1., 2., 3. };
  154004. ve_setup_data_template ve_setup_8_stereo={
  154005. 2,
  154006. rate_mapping_8,
  154007. quality_mapping_8,
  154008. 2,
  154009. 8000,
  154010. 9000,
  154011. blocksize_8,
  154012. blocksize_8,
  154013. _psy_tone_masteratt_8,
  154014. _psy_tone_0dB,
  154015. _psy_tone_suppress,
  154016. _vp_tonemask_adj_8,
  154017. NULL,
  154018. _vp_tonemask_adj_8,
  154019. _psy_noiseguards_8,
  154020. _psy_noisebias_8,
  154021. _psy_noisebias_8,
  154022. NULL,
  154023. NULL,
  154024. _psy_noise_suppress,
  154025. _psy_compand_8,
  154026. _psy_compand_8_mapping,
  154027. NULL,
  154028. {_noise_start_8,_noise_start_8},
  154029. {_noise_part_8,_noise_part_8},
  154030. _noise_thresh_5only,
  154031. _psy_ath_floater_8,
  154032. _psy_ath_abs_8,
  154033. _psy_lowpass_8,
  154034. _psy_global_44,
  154035. _global_mapping_8,
  154036. _psy_stereo_modes_8,
  154037. _floor_books,
  154038. _floor,
  154039. _floor_mapping_8,
  154040. NULL,
  154041. _mapres_template_8_stereo
  154042. };
  154043. ve_setup_data_template ve_setup_8_uncoupled={
  154044. 2,
  154045. rate_mapping_8_uncoupled,
  154046. quality_mapping_8,
  154047. -1,
  154048. 8000,
  154049. 9000,
  154050. blocksize_8,
  154051. blocksize_8,
  154052. _psy_tone_masteratt_8,
  154053. _psy_tone_0dB,
  154054. _psy_tone_suppress,
  154055. _vp_tonemask_adj_8,
  154056. NULL,
  154057. _vp_tonemask_adj_8,
  154058. _psy_noiseguards_8,
  154059. _psy_noisebias_8,
  154060. _psy_noisebias_8,
  154061. NULL,
  154062. NULL,
  154063. _psy_noise_suppress,
  154064. _psy_compand_8,
  154065. _psy_compand_8_mapping,
  154066. NULL,
  154067. {_noise_start_8,_noise_start_8},
  154068. {_noise_part_8,_noise_part_8},
  154069. _noise_thresh_5only,
  154070. _psy_ath_floater_8,
  154071. _psy_ath_abs_8,
  154072. _psy_lowpass_8,
  154073. _psy_global_44,
  154074. _global_mapping_8,
  154075. _psy_stereo_modes_8,
  154076. _floor_books,
  154077. _floor,
  154078. _floor_mapping_8,
  154079. NULL,
  154080. _mapres_template_8_uncoupled
  154081. };
  154082. /*** End of inlined file: setup_8.h ***/
  154083. /*** Start of inlined file: setup_11.h ***/
  154084. /*** Start of inlined file: psych_11.h ***/
  154085. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  154086. static att3 _psy_tone_masteratt_11[3]={
  154087. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154088. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154089. {{ 20, 0, -14}, 0, 0}, /* 0 */
  154090. };
  154091. static vp_adjblock _vp_tonemask_adj_11[3]={
  154092. /* adjust for mode zero */
  154093. /* 63 125 250 500 1 2 4 8 16 */
  154094. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  154095. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  154096. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  154097. };
  154098. static noise3 _psy_noisebias_11[3]={
  154099. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154100. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154101. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  154102. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154103. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154104. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  154105. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154106. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  154107. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  154108. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  154109. };
  154110. static double _noise_thresh_11[3]={ .3,.5,.5 };
  154111. /*** End of inlined file: psych_11.h ***/
  154112. static int blocksize_11[2]={
  154113. 512,512
  154114. };
  154115. static int _floor_mapping_11[2]={
  154116. 6,6,
  154117. };
  154118. static double rate_mapping_11[3]={
  154119. 8000.,13000.,44000.,
  154120. };
  154121. static double rate_mapping_11_uncoupled[3]={
  154122. 12000.,20000.,50000.,
  154123. };
  154124. static double quality_mapping_11[3]={
  154125. -.1,.0,1.
  154126. };
  154127. ve_setup_data_template ve_setup_11_stereo={
  154128. 2,
  154129. rate_mapping_11,
  154130. quality_mapping_11,
  154131. 2,
  154132. 9000,
  154133. 15000,
  154134. blocksize_11,
  154135. blocksize_11,
  154136. _psy_tone_masteratt_11,
  154137. _psy_tone_0dB,
  154138. _psy_tone_suppress,
  154139. _vp_tonemask_adj_11,
  154140. NULL,
  154141. _vp_tonemask_adj_11,
  154142. _psy_noiseguards_8,
  154143. _psy_noisebias_11,
  154144. _psy_noisebias_11,
  154145. NULL,
  154146. NULL,
  154147. _psy_noise_suppress,
  154148. _psy_compand_8,
  154149. _psy_compand_8_mapping,
  154150. NULL,
  154151. {_noise_start_8,_noise_start_8},
  154152. {_noise_part_8,_noise_part_8},
  154153. _noise_thresh_11,
  154154. _psy_ath_floater_8,
  154155. _psy_ath_abs_8,
  154156. _psy_lowpass_11,
  154157. _psy_global_44,
  154158. _global_mapping_8,
  154159. _psy_stereo_modes_8,
  154160. _floor_books,
  154161. _floor,
  154162. _floor_mapping_11,
  154163. NULL,
  154164. _mapres_template_8_stereo
  154165. };
  154166. ve_setup_data_template ve_setup_11_uncoupled={
  154167. 2,
  154168. rate_mapping_11_uncoupled,
  154169. quality_mapping_11,
  154170. -1,
  154171. 9000,
  154172. 15000,
  154173. blocksize_11,
  154174. blocksize_11,
  154175. _psy_tone_masteratt_11,
  154176. _psy_tone_0dB,
  154177. _psy_tone_suppress,
  154178. _vp_tonemask_adj_11,
  154179. NULL,
  154180. _vp_tonemask_adj_11,
  154181. _psy_noiseguards_8,
  154182. _psy_noisebias_11,
  154183. _psy_noisebias_11,
  154184. NULL,
  154185. NULL,
  154186. _psy_noise_suppress,
  154187. _psy_compand_8,
  154188. _psy_compand_8_mapping,
  154189. NULL,
  154190. {_noise_start_8,_noise_start_8},
  154191. {_noise_part_8,_noise_part_8},
  154192. _noise_thresh_11,
  154193. _psy_ath_floater_8,
  154194. _psy_ath_abs_8,
  154195. _psy_lowpass_11,
  154196. _psy_global_44,
  154197. _global_mapping_8,
  154198. _psy_stereo_modes_8,
  154199. _floor_books,
  154200. _floor,
  154201. _floor_mapping_11,
  154202. NULL,
  154203. _mapres_template_8_uncoupled
  154204. };
  154205. /*** End of inlined file: setup_11.h ***/
  154206. /*** Start of inlined file: setup_16.h ***/
  154207. /*** Start of inlined file: psych_16.h ***/
  154208. /* stereo mode by base quality level */
  154209. static adj_stereo _psy_stereo_modes_16[4]={
  154210. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154211. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154212. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154213. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154214. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154215. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154216. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154217. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154218. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154219. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154220. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154221. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154222. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154223. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154224. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154225. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154226. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154227. };
  154228. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154229. static att3 _psy_tone_masteratt_16[4]={
  154230. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154231. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154232. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154233. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154234. };
  154235. static vp_adjblock _vp_tonemask_adj_16[4]={
  154236. /* adjust for mode zero */
  154237. /* 63 125 250 500 1 2 4 8 16 */
  154238. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154239. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154240. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154241. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154242. };
  154243. static noise3 _psy_noisebias_16_short[4]={
  154244. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154245. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154246. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154247. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154248. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154249. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154250. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154251. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154252. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154253. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154254. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154255. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154256. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154257. };
  154258. static noise3 _psy_noisebias_16_impulse[4]={
  154259. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154260. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154261. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154262. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154263. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154264. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154265. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154266. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154267. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154268. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154269. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154270. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154271. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154272. };
  154273. static noise3 _psy_noisebias_16[4]={
  154274. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154275. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154276. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154277. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154278. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154279. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154280. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154281. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154282. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154283. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154284. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154285. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154286. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154287. };
  154288. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154289. static int _noise_start_16[3]={ 256,256,9999 };
  154290. static int _noise_part_16[4]={ 8,8,8,8 };
  154291. static int _psy_ath_floater_16[4]={
  154292. -100,-100,-100,-105,
  154293. };
  154294. static int _psy_ath_abs_16[4]={
  154295. -130,-130,-130,-140,
  154296. };
  154297. /*** End of inlined file: psych_16.h ***/
  154298. /*** Start of inlined file: residue_16.h ***/
  154299. /***** residue backends *********************************************/
  154300. static static_bookblock _resbook_16s_0={
  154301. {
  154302. {0},
  154303. {0,0,&_16c0_s_p1_0},
  154304. {0,0,&_16c0_s_p2_0},
  154305. {0,0,&_16c0_s_p3_0},
  154306. {0,0,&_16c0_s_p4_0},
  154307. {0,0,&_16c0_s_p5_0},
  154308. {0,0,&_16c0_s_p6_0},
  154309. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154310. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154311. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154312. }
  154313. };
  154314. static static_bookblock _resbook_16s_1={
  154315. {
  154316. {0},
  154317. {0,0,&_16c1_s_p1_0},
  154318. {0,0,&_16c1_s_p2_0},
  154319. {0,0,&_16c1_s_p3_0},
  154320. {0,0,&_16c1_s_p4_0},
  154321. {0,0,&_16c1_s_p5_0},
  154322. {0,0,&_16c1_s_p6_0},
  154323. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154324. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154325. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154326. }
  154327. };
  154328. static static_bookblock _resbook_16s_2={
  154329. {
  154330. {0},
  154331. {0,0,&_16c2_s_p1_0},
  154332. {0,0,&_16c2_s_p2_0},
  154333. {0,0,&_16c2_s_p3_0},
  154334. {0,0,&_16c2_s_p4_0},
  154335. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154336. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154337. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154338. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154339. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154340. }
  154341. };
  154342. static vorbis_residue_template _res_16s_0[]={
  154343. {2,0, &_residue_44_mid,
  154344. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154345. &_resbook_16s_0,&_resbook_16s_0},
  154346. };
  154347. static vorbis_residue_template _res_16s_1[]={
  154348. {2,0, &_residue_44_mid,
  154349. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154350. &_resbook_16s_1,&_resbook_16s_1},
  154351. {2,0, &_residue_44_mid,
  154352. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154353. &_resbook_16s_1,&_resbook_16s_1}
  154354. };
  154355. static vorbis_residue_template _res_16s_2[]={
  154356. {2,0, &_residue_44_high,
  154357. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154358. &_resbook_16s_2,&_resbook_16s_2},
  154359. {2,0, &_residue_44_high,
  154360. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154361. &_resbook_16s_2,&_resbook_16s_2}
  154362. };
  154363. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154364. { _map_nominal, _res_16s_0 }, /* 0 */
  154365. { _map_nominal, _res_16s_1 }, /* 1 */
  154366. { _map_nominal, _res_16s_2 }, /* 2 */
  154367. };
  154368. static static_bookblock _resbook_16u_0={
  154369. {
  154370. {0},
  154371. {0,0,&_16u0__p1_0},
  154372. {0,0,&_16u0__p2_0},
  154373. {0,0,&_16u0__p3_0},
  154374. {0,0,&_16u0__p4_0},
  154375. {0,0,&_16u0__p5_0},
  154376. {&_16u0__p6_0,&_16u0__p6_1},
  154377. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154378. }
  154379. };
  154380. static static_bookblock _resbook_16u_1={
  154381. {
  154382. {0},
  154383. {0,0,&_16u1__p1_0},
  154384. {0,0,&_16u1__p2_0},
  154385. {0,0,&_16u1__p3_0},
  154386. {0,0,&_16u1__p4_0},
  154387. {0,0,&_16u1__p5_0},
  154388. {0,0,&_16u1__p6_0},
  154389. {&_16u1__p7_0,&_16u1__p7_1},
  154390. {&_16u1__p8_0,&_16u1__p8_1},
  154391. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154392. }
  154393. };
  154394. static static_bookblock _resbook_16u_2={
  154395. {
  154396. {0},
  154397. {0,0,&_16u2_p1_0},
  154398. {0,0,&_16u2_p2_0},
  154399. {0,0,&_16u2_p3_0},
  154400. {0,0,&_16u2_p4_0},
  154401. {&_16u2_p5_0,&_16u2_p5_1},
  154402. {&_16u2_p6_0,&_16u2_p6_1},
  154403. {&_16u2_p7_0,&_16u2_p7_1},
  154404. {&_16u2_p8_0,&_16u2_p8_1},
  154405. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154406. }
  154407. };
  154408. static vorbis_residue_template _res_16u_0[]={
  154409. {1,0, &_residue_44_low_un,
  154410. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154411. &_resbook_16u_0,&_resbook_16u_0},
  154412. };
  154413. static vorbis_residue_template _res_16u_1[]={
  154414. {1,0, &_residue_44_mid_un,
  154415. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154416. &_resbook_16u_1,&_resbook_16u_1},
  154417. {1,0, &_residue_44_mid_un,
  154418. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154419. &_resbook_16u_1,&_resbook_16u_1}
  154420. };
  154421. static vorbis_residue_template _res_16u_2[]={
  154422. {1,0, &_residue_44_hi_un,
  154423. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154424. &_resbook_16u_2,&_resbook_16u_2},
  154425. {1,0, &_residue_44_hi_un,
  154426. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154427. &_resbook_16u_2,&_resbook_16u_2}
  154428. };
  154429. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154430. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154431. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154432. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154433. };
  154434. /*** End of inlined file: residue_16.h ***/
  154435. static int blocksize_16_short[3]={
  154436. 1024,512,512
  154437. };
  154438. static int blocksize_16_long[3]={
  154439. 1024,1024,1024
  154440. };
  154441. static int _floor_mapping_16_short[3]={
  154442. 9,3,3
  154443. };
  154444. static int _floor_mapping_16[3]={
  154445. 9,9,9
  154446. };
  154447. static double rate_mapping_16[4]={
  154448. 12000.,20000.,44000.,86000.
  154449. };
  154450. static double rate_mapping_16_uncoupled[4]={
  154451. 16000.,28000.,64000.,100000.
  154452. };
  154453. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154454. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154455. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154456. ve_setup_data_template ve_setup_16_stereo={
  154457. 3,
  154458. rate_mapping_16,
  154459. quality_mapping_16,
  154460. 2,
  154461. 15000,
  154462. 19000,
  154463. blocksize_16_short,
  154464. blocksize_16_long,
  154465. _psy_tone_masteratt_16,
  154466. _psy_tone_0dB,
  154467. _psy_tone_suppress,
  154468. _vp_tonemask_adj_16,
  154469. _vp_tonemask_adj_16,
  154470. _vp_tonemask_adj_16,
  154471. _psy_noiseguards_8,
  154472. _psy_noisebias_16_impulse,
  154473. _psy_noisebias_16_short,
  154474. _psy_noisebias_16_short,
  154475. _psy_noisebias_16,
  154476. _psy_noise_suppress,
  154477. _psy_compand_8,
  154478. _psy_compand_16_mapping,
  154479. _psy_compand_16_mapping,
  154480. {_noise_start_16,_noise_start_16},
  154481. { _noise_part_16, _noise_part_16},
  154482. _noise_thresh_16,
  154483. _psy_ath_floater_16,
  154484. _psy_ath_abs_16,
  154485. _psy_lowpass_16,
  154486. _psy_global_44,
  154487. _global_mapping_16,
  154488. _psy_stereo_modes_16,
  154489. _floor_books,
  154490. _floor,
  154491. _floor_mapping_16_short,
  154492. _floor_mapping_16,
  154493. _mapres_template_16_stereo
  154494. };
  154495. ve_setup_data_template ve_setup_16_uncoupled={
  154496. 3,
  154497. rate_mapping_16_uncoupled,
  154498. quality_mapping_16,
  154499. -1,
  154500. 15000,
  154501. 19000,
  154502. blocksize_16_short,
  154503. blocksize_16_long,
  154504. _psy_tone_masteratt_16,
  154505. _psy_tone_0dB,
  154506. _psy_tone_suppress,
  154507. _vp_tonemask_adj_16,
  154508. _vp_tonemask_adj_16,
  154509. _vp_tonemask_adj_16,
  154510. _psy_noiseguards_8,
  154511. _psy_noisebias_16_impulse,
  154512. _psy_noisebias_16_short,
  154513. _psy_noisebias_16_short,
  154514. _psy_noisebias_16,
  154515. _psy_noise_suppress,
  154516. _psy_compand_8,
  154517. _psy_compand_16_mapping,
  154518. _psy_compand_16_mapping,
  154519. {_noise_start_16,_noise_start_16},
  154520. { _noise_part_16, _noise_part_16},
  154521. _noise_thresh_16,
  154522. _psy_ath_floater_16,
  154523. _psy_ath_abs_16,
  154524. _psy_lowpass_16,
  154525. _psy_global_44,
  154526. _global_mapping_16,
  154527. _psy_stereo_modes_16,
  154528. _floor_books,
  154529. _floor,
  154530. _floor_mapping_16_short,
  154531. _floor_mapping_16,
  154532. _mapres_template_16_uncoupled
  154533. };
  154534. /*** End of inlined file: setup_16.h ***/
  154535. /*** Start of inlined file: setup_22.h ***/
  154536. static double rate_mapping_22[4]={
  154537. 15000.,20000.,44000.,86000.
  154538. };
  154539. static double rate_mapping_22_uncoupled[4]={
  154540. 16000.,28000.,50000.,90000.
  154541. };
  154542. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154543. ve_setup_data_template ve_setup_22_stereo={
  154544. 3,
  154545. rate_mapping_22,
  154546. quality_mapping_16,
  154547. 2,
  154548. 19000,
  154549. 26000,
  154550. blocksize_16_short,
  154551. blocksize_16_long,
  154552. _psy_tone_masteratt_16,
  154553. _psy_tone_0dB,
  154554. _psy_tone_suppress,
  154555. _vp_tonemask_adj_16,
  154556. _vp_tonemask_adj_16,
  154557. _vp_tonemask_adj_16,
  154558. _psy_noiseguards_8,
  154559. _psy_noisebias_16_impulse,
  154560. _psy_noisebias_16_short,
  154561. _psy_noisebias_16_short,
  154562. _psy_noisebias_16,
  154563. _psy_noise_suppress,
  154564. _psy_compand_8,
  154565. _psy_compand_8_mapping,
  154566. _psy_compand_8_mapping,
  154567. {_noise_start_16,_noise_start_16},
  154568. { _noise_part_16, _noise_part_16},
  154569. _noise_thresh_16,
  154570. _psy_ath_floater_16,
  154571. _psy_ath_abs_16,
  154572. _psy_lowpass_22,
  154573. _psy_global_44,
  154574. _global_mapping_16,
  154575. _psy_stereo_modes_16,
  154576. _floor_books,
  154577. _floor,
  154578. _floor_mapping_16_short,
  154579. _floor_mapping_16,
  154580. _mapres_template_16_stereo
  154581. };
  154582. ve_setup_data_template ve_setup_22_uncoupled={
  154583. 3,
  154584. rate_mapping_22_uncoupled,
  154585. quality_mapping_16,
  154586. -1,
  154587. 19000,
  154588. 26000,
  154589. blocksize_16_short,
  154590. blocksize_16_long,
  154591. _psy_tone_masteratt_16,
  154592. _psy_tone_0dB,
  154593. _psy_tone_suppress,
  154594. _vp_tonemask_adj_16,
  154595. _vp_tonemask_adj_16,
  154596. _vp_tonemask_adj_16,
  154597. _psy_noiseguards_8,
  154598. _psy_noisebias_16_impulse,
  154599. _psy_noisebias_16_short,
  154600. _psy_noisebias_16_short,
  154601. _psy_noisebias_16,
  154602. _psy_noise_suppress,
  154603. _psy_compand_8,
  154604. _psy_compand_8_mapping,
  154605. _psy_compand_8_mapping,
  154606. {_noise_start_16,_noise_start_16},
  154607. { _noise_part_16, _noise_part_16},
  154608. _noise_thresh_16,
  154609. _psy_ath_floater_16,
  154610. _psy_ath_abs_16,
  154611. _psy_lowpass_22,
  154612. _psy_global_44,
  154613. _global_mapping_16,
  154614. _psy_stereo_modes_16,
  154615. _floor_books,
  154616. _floor,
  154617. _floor_mapping_16_short,
  154618. _floor_mapping_16,
  154619. _mapres_template_16_uncoupled
  154620. };
  154621. /*** End of inlined file: setup_22.h ***/
  154622. /*** Start of inlined file: setup_X.h ***/
  154623. static double rate_mapping_X[12]={
  154624. -1.,-1.,-1.,-1.,-1.,-1.,
  154625. -1.,-1.,-1.,-1.,-1.,-1.
  154626. };
  154627. ve_setup_data_template ve_setup_X_stereo={
  154628. 11,
  154629. rate_mapping_X,
  154630. quality_mapping_44,
  154631. 2,
  154632. 50000,
  154633. 200000,
  154634. blocksize_short_44,
  154635. blocksize_long_44,
  154636. _psy_tone_masteratt_44,
  154637. _psy_tone_0dB,
  154638. _psy_tone_suppress,
  154639. _vp_tonemask_adj_otherblock,
  154640. _vp_tonemask_adj_longblock,
  154641. _vp_tonemask_adj_otherblock,
  154642. _psy_noiseguards_44,
  154643. _psy_noisebias_impulse,
  154644. _psy_noisebias_padding,
  154645. _psy_noisebias_trans,
  154646. _psy_noisebias_long,
  154647. _psy_noise_suppress,
  154648. _psy_compand_44,
  154649. _psy_compand_short_mapping,
  154650. _psy_compand_long_mapping,
  154651. {_noise_start_short_44,_noise_start_long_44},
  154652. {_noise_part_short_44,_noise_part_long_44},
  154653. _noise_thresh_44,
  154654. _psy_ath_floater,
  154655. _psy_ath_abs,
  154656. _psy_lowpass_44,
  154657. _psy_global_44,
  154658. _global_mapping_44,
  154659. _psy_stereo_modes_44,
  154660. _floor_books,
  154661. _floor,
  154662. _floor_short_mapping_44,
  154663. _floor_long_mapping_44,
  154664. _mapres_template_44_stereo
  154665. };
  154666. ve_setup_data_template ve_setup_X_uncoupled={
  154667. 11,
  154668. rate_mapping_X,
  154669. quality_mapping_44,
  154670. -1,
  154671. 50000,
  154672. 200000,
  154673. blocksize_short_44,
  154674. blocksize_long_44,
  154675. _psy_tone_masteratt_44,
  154676. _psy_tone_0dB,
  154677. _psy_tone_suppress,
  154678. _vp_tonemask_adj_otherblock,
  154679. _vp_tonemask_adj_longblock,
  154680. _vp_tonemask_adj_otherblock,
  154681. _psy_noiseguards_44,
  154682. _psy_noisebias_impulse,
  154683. _psy_noisebias_padding,
  154684. _psy_noisebias_trans,
  154685. _psy_noisebias_long,
  154686. _psy_noise_suppress,
  154687. _psy_compand_44,
  154688. _psy_compand_short_mapping,
  154689. _psy_compand_long_mapping,
  154690. {_noise_start_short_44,_noise_start_long_44},
  154691. {_noise_part_short_44,_noise_part_long_44},
  154692. _noise_thresh_44,
  154693. _psy_ath_floater,
  154694. _psy_ath_abs,
  154695. _psy_lowpass_44,
  154696. _psy_global_44,
  154697. _global_mapping_44,
  154698. NULL,
  154699. _floor_books,
  154700. _floor,
  154701. _floor_short_mapping_44,
  154702. _floor_long_mapping_44,
  154703. _mapres_template_44_uncoupled
  154704. };
  154705. ve_setup_data_template ve_setup_XX_stereo={
  154706. 2,
  154707. rate_mapping_X,
  154708. quality_mapping_8,
  154709. 2,
  154710. 0,
  154711. 8000,
  154712. blocksize_8,
  154713. blocksize_8,
  154714. _psy_tone_masteratt_8,
  154715. _psy_tone_0dB,
  154716. _psy_tone_suppress,
  154717. _vp_tonemask_adj_8,
  154718. NULL,
  154719. _vp_tonemask_adj_8,
  154720. _psy_noiseguards_8,
  154721. _psy_noisebias_8,
  154722. _psy_noisebias_8,
  154723. NULL,
  154724. NULL,
  154725. _psy_noise_suppress,
  154726. _psy_compand_8,
  154727. _psy_compand_8_mapping,
  154728. NULL,
  154729. {_noise_start_8,_noise_start_8},
  154730. {_noise_part_8,_noise_part_8},
  154731. _noise_thresh_5only,
  154732. _psy_ath_floater_8,
  154733. _psy_ath_abs_8,
  154734. _psy_lowpass_8,
  154735. _psy_global_44,
  154736. _global_mapping_8,
  154737. _psy_stereo_modes_8,
  154738. _floor_books,
  154739. _floor,
  154740. _floor_mapping_8,
  154741. NULL,
  154742. _mapres_template_8_stereo
  154743. };
  154744. ve_setup_data_template ve_setup_XX_uncoupled={
  154745. 2,
  154746. rate_mapping_X,
  154747. quality_mapping_8,
  154748. -1,
  154749. 0,
  154750. 8000,
  154751. blocksize_8,
  154752. blocksize_8,
  154753. _psy_tone_masteratt_8,
  154754. _psy_tone_0dB,
  154755. _psy_tone_suppress,
  154756. _vp_tonemask_adj_8,
  154757. NULL,
  154758. _vp_tonemask_adj_8,
  154759. _psy_noiseguards_8,
  154760. _psy_noisebias_8,
  154761. _psy_noisebias_8,
  154762. NULL,
  154763. NULL,
  154764. _psy_noise_suppress,
  154765. _psy_compand_8,
  154766. _psy_compand_8_mapping,
  154767. NULL,
  154768. {_noise_start_8,_noise_start_8},
  154769. {_noise_part_8,_noise_part_8},
  154770. _noise_thresh_5only,
  154771. _psy_ath_floater_8,
  154772. _psy_ath_abs_8,
  154773. _psy_lowpass_8,
  154774. _psy_global_44,
  154775. _global_mapping_8,
  154776. _psy_stereo_modes_8,
  154777. _floor_books,
  154778. _floor,
  154779. _floor_mapping_8,
  154780. NULL,
  154781. _mapres_template_8_uncoupled
  154782. };
  154783. /*** End of inlined file: setup_X.h ***/
  154784. static ve_setup_data_template *setup_list[]={
  154785. &ve_setup_44_stereo,
  154786. &ve_setup_44_uncoupled,
  154787. &ve_setup_32_stereo,
  154788. &ve_setup_32_uncoupled,
  154789. &ve_setup_22_stereo,
  154790. &ve_setup_22_uncoupled,
  154791. &ve_setup_16_stereo,
  154792. &ve_setup_16_uncoupled,
  154793. &ve_setup_11_stereo,
  154794. &ve_setup_11_uncoupled,
  154795. &ve_setup_8_stereo,
  154796. &ve_setup_8_uncoupled,
  154797. &ve_setup_X_stereo,
  154798. &ve_setup_X_uncoupled,
  154799. &ve_setup_XX_stereo,
  154800. &ve_setup_XX_uncoupled,
  154801. 0
  154802. };
  154803. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154804. if(vi && vi->codec_setup){
  154805. vi->version=0;
  154806. vi->channels=ch;
  154807. vi->rate=rate;
  154808. return(0);
  154809. }
  154810. return(OV_EINVAL);
  154811. }
  154812. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154813. static_codebook ***books,
  154814. vorbis_info_floor1 *in,
  154815. int *x){
  154816. int i,k,is=s;
  154817. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154818. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154819. memcpy(f,in+x[is],sizeof(*f));
  154820. /* fill in the lowpass field, even if it's temporary */
  154821. f->n=ci->blocksizes[block]>>1;
  154822. /* books */
  154823. {
  154824. int partitions=f->partitions;
  154825. int maxclass=-1;
  154826. int maxbook=-1;
  154827. for(i=0;i<partitions;i++)
  154828. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154829. for(i=0;i<=maxclass;i++){
  154830. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154831. f->class_book[i]+=ci->books;
  154832. for(k=0;k<(1<<f->class_subs[i]);k++){
  154833. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154834. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154835. }
  154836. }
  154837. for(i=0;i<=maxbook;i++)
  154838. ci->book_param[ci->books++]=books[x[is]][i];
  154839. }
  154840. /* for now, we're only using floor 1 */
  154841. ci->floor_type[ci->floors]=1;
  154842. ci->floor_param[ci->floors]=f;
  154843. ci->floors++;
  154844. return;
  154845. }
  154846. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154847. vorbis_info_psy_global *in,
  154848. double *x){
  154849. int i,is=s;
  154850. double ds=s-is;
  154851. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154852. vorbis_info_psy_global *g=&ci->psy_g_param;
  154853. memcpy(g,in+(int)x[is],sizeof(*g));
  154854. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154855. is=(int)ds;
  154856. ds-=is;
  154857. if(ds==0 && is>0){
  154858. is--;
  154859. ds=1.;
  154860. }
  154861. /* interpolate the trigger threshholds */
  154862. for(i=0;i<4;i++){
  154863. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154864. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154865. }
  154866. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154867. return;
  154868. }
  154869. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154870. highlevel_encode_setup *hi,
  154871. adj_stereo *p){
  154872. float s=hi->stereo_point_setting;
  154873. int i,is=s;
  154874. double ds=s-is;
  154875. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154876. vorbis_info_psy_global *g=&ci->psy_g_param;
  154877. if(p){
  154878. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154879. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154880. if(hi->managed){
  154881. /* interpolate the kHz threshholds */
  154882. for(i=0;i<PACKETBLOBS;i++){
  154883. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154884. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154885. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154886. g->coupling_pkHz[i]=kHz;
  154887. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154888. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154889. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154890. }
  154891. }else{
  154892. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154893. for(i=0;i<PACKETBLOBS;i++){
  154894. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154895. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154896. g->coupling_pkHz[i]=kHz;
  154897. }
  154898. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154899. for(i=0;i<PACKETBLOBS;i++){
  154900. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154901. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154902. }
  154903. }
  154904. }else{
  154905. for(i=0;i<PACKETBLOBS;i++){
  154906. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154907. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154908. }
  154909. }
  154910. return;
  154911. }
  154912. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154913. int *nn_start,
  154914. int *nn_partition,
  154915. double *nn_thresh,
  154916. int block){
  154917. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154918. vorbis_info_psy *p=ci->psy_param[block];
  154919. highlevel_encode_setup *hi=&ci->hi;
  154920. int is=s;
  154921. if(block>=ci->psys)
  154922. ci->psys=block+1;
  154923. if(!p){
  154924. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154925. ci->psy_param[block]=p;
  154926. }
  154927. memcpy(p,&_psy_info_template,sizeof(*p));
  154928. p->blockflag=block>>1;
  154929. if(hi->noise_normalize_p){
  154930. p->normal_channel_p=1;
  154931. p->normal_point_p=1;
  154932. p->normal_start=nn_start[is];
  154933. p->normal_partition=nn_partition[is];
  154934. p->normal_thresh=nn_thresh[is];
  154935. }
  154936. return;
  154937. }
  154938. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154939. att3 *att,
  154940. int *max,
  154941. vp_adjblock *in){
  154942. int i,is=s;
  154943. double ds=s-is;
  154944. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154945. vorbis_info_psy *p=ci->psy_param[block];
  154946. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154947. filling the values in here */
  154948. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154949. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154950. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154951. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154952. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154953. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154954. for(i=0;i<P_BANDS;i++)
  154955. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154956. return;
  154957. }
  154958. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154959. compandblock *in, double *x){
  154960. int i,is=s;
  154961. double ds=s-is;
  154962. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154963. vorbis_info_psy *p=ci->psy_param[block];
  154964. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154965. is=(int)ds;
  154966. ds-=is;
  154967. if(ds==0 && is>0){
  154968. is--;
  154969. ds=1.;
  154970. }
  154971. /* interpolate the compander settings */
  154972. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154973. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154974. return;
  154975. }
  154976. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154977. int *suppress){
  154978. int is=s;
  154979. double ds=s-is;
  154980. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154981. vorbis_info_psy *p=ci->psy_param[block];
  154982. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154983. return;
  154984. }
  154985. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154986. int *suppress,
  154987. noise3 *in,
  154988. noiseguard *guard,
  154989. double userbias){
  154990. int i,is=s,j;
  154991. double ds=s-is;
  154992. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154993. vorbis_info_psy *p=ci->psy_param[block];
  154994. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154995. p->noisewindowlomin=guard[block].lo;
  154996. p->noisewindowhimin=guard[block].hi;
  154997. p->noisewindowfixed=guard[block].fixed;
  154998. for(j=0;j<P_NOISECURVES;j++)
  154999. for(i=0;i<P_BANDS;i++)
  155000. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  155001. /* impulse blocks may take a user specified bias to boost the
  155002. nominal/high noise encoding depth */
  155003. for(j=0;j<P_NOISECURVES;j++){
  155004. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  155005. for(i=0;i<P_BANDS;i++){
  155006. p->noiseoff[j][i]+=userbias;
  155007. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  155008. }
  155009. }
  155010. return;
  155011. }
  155012. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  155013. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155014. vorbis_info_psy *p=ci->psy_param[block];
  155015. p->ath_adjatt=ci->hi.ath_floating_dB;
  155016. p->ath_maxatt=ci->hi.ath_absolute_dB;
  155017. return;
  155018. }
  155019. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  155020. int i;
  155021. for(i=0;i<ci->books;i++)
  155022. if(ci->book_param[i]==book)return(i);
  155023. return(ci->books++);
  155024. }
  155025. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  155026. int *shortb,int *longb){
  155027. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155028. int is=s;
  155029. int blockshort=shortb[is];
  155030. int blocklong=longb[is];
  155031. ci->blocksizes[0]=blockshort;
  155032. ci->blocksizes[1]=blocklong;
  155033. }
  155034. static void vorbis_encode_residue_setup(vorbis_info *vi,
  155035. int number, int block,
  155036. vorbis_residue_template *res){
  155037. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155038. int i,n;
  155039. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  155040. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  155041. memcpy(r,res->res,sizeof(*r));
  155042. if(ci->residues<=number)ci->residues=number+1;
  155043. switch(ci->blocksizes[block]){
  155044. case 64:case 128:case 256:
  155045. r->grouping=16;
  155046. break;
  155047. default:
  155048. r->grouping=32;
  155049. break;
  155050. }
  155051. ci->residue_type[number]=res->res_type;
  155052. /* to be adjusted by lowpass/pointlimit later */
  155053. n=r->end=ci->blocksizes[block]>>1;
  155054. if(res->res_type==2)
  155055. n=r->end*=vi->channels;
  155056. /* fill in all the books */
  155057. {
  155058. int booklist=0,k;
  155059. if(ci->hi.managed){
  155060. for(i=0;i<r->partitions;i++)
  155061. for(k=0;k<3;k++)
  155062. if(res->books_base_managed->books[i][k])
  155063. r->secondstages[i]|=(1<<k);
  155064. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  155065. ci->book_param[r->groupbook]=res->book_aux_managed;
  155066. for(i=0;i<r->partitions;i++){
  155067. for(k=0;k<3;k++){
  155068. if(res->books_base_managed->books[i][k]){
  155069. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  155070. r->booklist[booklist++]=bookid;
  155071. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  155072. }
  155073. }
  155074. }
  155075. }else{
  155076. for(i=0;i<r->partitions;i++)
  155077. for(k=0;k<3;k++)
  155078. if(res->books_base->books[i][k])
  155079. r->secondstages[i]|=(1<<k);
  155080. r->groupbook=book_dup_or_new(ci,res->book_aux);
  155081. ci->book_param[r->groupbook]=res->book_aux;
  155082. for(i=0;i<r->partitions;i++){
  155083. for(k=0;k<3;k++){
  155084. if(res->books_base->books[i][k]){
  155085. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  155086. r->booklist[booklist++]=bookid;
  155087. ci->book_param[bookid]=res->books_base->books[i][k];
  155088. }
  155089. }
  155090. }
  155091. }
  155092. }
  155093. /* lowpass setup/pointlimit */
  155094. {
  155095. double freq=ci->hi.lowpass_kHz*1000.;
  155096. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  155097. double nyq=vi->rate/2.;
  155098. long blocksize=ci->blocksizes[block]>>1;
  155099. /* lowpass needs to be set in the floor and the residue. */
  155100. if(freq>nyq)freq=nyq;
  155101. /* in the floor, the granularity can be very fine; it doesn't alter
  155102. the encoding structure, only the samples used to fit the floor
  155103. approximation */
  155104. f->n=freq/nyq*blocksize;
  155105. /* this res may by limited by the maximum pointlimit of the mode,
  155106. not the lowpass. the floor is always lowpass limited. */
  155107. if(res->limit_type){
  155108. if(ci->hi.managed)
  155109. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  155110. else
  155111. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  155112. if(freq>nyq)freq=nyq;
  155113. }
  155114. /* in the residue, we're constrained, physically, by partition
  155115. boundaries. We still lowpass 'wherever', but we have to round up
  155116. here to next boundary, or the vorbis spec will round it *down* to
  155117. previous boundary in encode/decode */
  155118. if(ci->residue_type[block]==2)
  155119. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  155120. r->grouping;
  155121. else
  155122. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  155123. r->grouping;
  155124. }
  155125. }
  155126. /* we assume two maps in this encoder */
  155127. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  155128. vorbis_mapping_template *maps){
  155129. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155130. int i,j,is=s,modes=2;
  155131. vorbis_info_mapping0 *map=maps[is].map;
  155132. vorbis_info_mode *mode=_mode_template;
  155133. vorbis_residue_template *res=maps[is].res;
  155134. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  155135. for(i=0;i<modes;i++){
  155136. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  155137. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  155138. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  155139. if(i>=ci->modes)ci->modes=i+1;
  155140. ci->map_type[i]=0;
  155141. memcpy(ci->map_param[i],map+i,sizeof(*map));
  155142. if(i>=ci->maps)ci->maps=i+1;
  155143. for(j=0;j<map[i].submaps;j++)
  155144. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  155145. ,res+map[i].residuesubmap[j]);
  155146. }
  155147. }
  155148. static double setting_to_approx_bitrate(vorbis_info *vi){
  155149. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155150. highlevel_encode_setup *hi=&ci->hi;
  155151. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  155152. int is=hi->base_setting;
  155153. double ds=hi->base_setting-is;
  155154. int ch=vi->channels;
  155155. double *r=setup->rate_mapping;
  155156. if(r==NULL)
  155157. return(-1);
  155158. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  155159. }
  155160. static void get_setup_template(vorbis_info *vi,
  155161. long ch,long srate,
  155162. double req,int q_or_bitrate){
  155163. int i=0,j;
  155164. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155165. highlevel_encode_setup *hi=&ci->hi;
  155166. if(q_or_bitrate)req/=ch;
  155167. while(setup_list[i]){
  155168. if(setup_list[i]->coupling_restriction==-1 ||
  155169. setup_list[i]->coupling_restriction==ch){
  155170. if(srate>=setup_list[i]->samplerate_min_restriction &&
  155171. srate<=setup_list[i]->samplerate_max_restriction){
  155172. int mappings=setup_list[i]->mappings;
  155173. double *map=(q_or_bitrate?
  155174. setup_list[i]->rate_mapping:
  155175. setup_list[i]->quality_mapping);
  155176. /* the template matches. Does the requested quality mode
  155177. fall within this template's modes? */
  155178. if(req<map[0]){++i;continue;}
  155179. if(req>map[setup_list[i]->mappings]){++i;continue;}
  155180. for(j=0;j<mappings;j++)
  155181. if(req>=map[j] && req<map[j+1])break;
  155182. /* an all-points match */
  155183. hi->setup=setup_list[i];
  155184. if(j==mappings)
  155185. hi->base_setting=j-.001;
  155186. else{
  155187. float low=map[j];
  155188. float high=map[j+1];
  155189. float del=(req-low)/(high-low);
  155190. hi->base_setting=j+del;
  155191. }
  155192. return;
  155193. }
  155194. }
  155195. i++;
  155196. }
  155197. hi->setup=NULL;
  155198. }
  155199. /* encoders will need to use vorbis_info_init beforehand and call
  155200. vorbis_info clear when all done */
  155201. /* two interfaces; this, more detailed one, and later a convenience
  155202. layer on top */
  155203. /* the final setup call */
  155204. int vorbis_encode_setup_init(vorbis_info *vi){
  155205. int i0=0,singleblock=0;
  155206. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155207. ve_setup_data_template *setup=NULL;
  155208. highlevel_encode_setup *hi=&ci->hi;
  155209. if(ci==NULL)return(OV_EINVAL);
  155210. if(!hi->impulse_block_p)i0=1;
  155211. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155212. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155213. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155214. /* again, bound this to avoid the app shooting itself int he foot
  155215. too badly */
  155216. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155217. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155218. /* get the appropriate setup template; matches the fetch in previous
  155219. stages */
  155220. setup=(ve_setup_data_template *)hi->setup;
  155221. if(setup==NULL)return(OV_EINVAL);
  155222. hi->set_in_stone=1;
  155223. /* choose block sizes from configured sizes as well as paying
  155224. attention to long_block_p and short_block_p. If the configured
  155225. short and long blocks are the same length, we set long_block_p
  155226. and unset short_block_p */
  155227. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155228. setup->blocksize_short,
  155229. setup->blocksize_long);
  155230. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155231. /* floor setup; choose proper floor params. Allocated on the floor
  155232. stack in order; if we alloc only long floor, it's 0 */
  155233. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155234. setup->floor_books,
  155235. setup->floor_params,
  155236. setup->floor_short_mapping);
  155237. if(!singleblock)
  155238. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155239. setup->floor_books,
  155240. setup->floor_params,
  155241. setup->floor_long_mapping);
  155242. /* setup of [mostly] short block detection and stereo*/
  155243. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155244. setup->global_params,
  155245. setup->global_mapping);
  155246. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155247. /* basic psych setup and noise normalization */
  155248. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155249. setup->psy_noise_normal_start[0],
  155250. setup->psy_noise_normal_partition[0],
  155251. setup->psy_noise_normal_thresh,
  155252. 0);
  155253. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155254. setup->psy_noise_normal_start[0],
  155255. setup->psy_noise_normal_partition[0],
  155256. setup->psy_noise_normal_thresh,
  155257. 1);
  155258. if(!singleblock){
  155259. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155260. setup->psy_noise_normal_start[1],
  155261. setup->psy_noise_normal_partition[1],
  155262. setup->psy_noise_normal_thresh,
  155263. 2);
  155264. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155265. setup->psy_noise_normal_start[1],
  155266. setup->psy_noise_normal_partition[1],
  155267. setup->psy_noise_normal_thresh,
  155268. 3);
  155269. }
  155270. /* tone masking setup */
  155271. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155272. setup->psy_tone_masteratt,
  155273. setup->psy_tone_0dB,
  155274. setup->psy_tone_adj_impulse);
  155275. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155276. setup->psy_tone_masteratt,
  155277. setup->psy_tone_0dB,
  155278. setup->psy_tone_adj_other);
  155279. if(!singleblock){
  155280. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155281. setup->psy_tone_masteratt,
  155282. setup->psy_tone_0dB,
  155283. setup->psy_tone_adj_other);
  155284. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155285. setup->psy_tone_masteratt,
  155286. setup->psy_tone_0dB,
  155287. setup->psy_tone_adj_long);
  155288. }
  155289. /* noise companding setup */
  155290. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155291. setup->psy_noise_compand,
  155292. setup->psy_noise_compand_short_mapping);
  155293. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155294. setup->psy_noise_compand,
  155295. setup->psy_noise_compand_short_mapping);
  155296. if(!singleblock){
  155297. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155298. setup->psy_noise_compand,
  155299. setup->psy_noise_compand_long_mapping);
  155300. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155301. setup->psy_noise_compand,
  155302. setup->psy_noise_compand_long_mapping);
  155303. }
  155304. /* peak guarding setup */
  155305. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155306. setup->psy_tone_dBsuppress);
  155307. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155308. setup->psy_tone_dBsuppress);
  155309. if(!singleblock){
  155310. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155311. setup->psy_tone_dBsuppress);
  155312. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155313. setup->psy_tone_dBsuppress);
  155314. }
  155315. /* noise bias setup */
  155316. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155317. setup->psy_noise_dBsuppress,
  155318. setup->psy_noise_bias_impulse,
  155319. setup->psy_noiseguards,
  155320. (i0==0?hi->impulse_noisetune:0.));
  155321. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155322. setup->psy_noise_dBsuppress,
  155323. setup->psy_noise_bias_padding,
  155324. setup->psy_noiseguards,0.);
  155325. if(!singleblock){
  155326. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155327. setup->psy_noise_dBsuppress,
  155328. setup->psy_noise_bias_trans,
  155329. setup->psy_noiseguards,0.);
  155330. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155331. setup->psy_noise_dBsuppress,
  155332. setup->psy_noise_bias_long,
  155333. setup->psy_noiseguards,0.);
  155334. }
  155335. vorbis_encode_ath_setup(vi,0);
  155336. vorbis_encode_ath_setup(vi,1);
  155337. if(!singleblock){
  155338. vorbis_encode_ath_setup(vi,2);
  155339. vorbis_encode_ath_setup(vi,3);
  155340. }
  155341. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155342. /* set bitrate readonlies and management */
  155343. if(hi->bitrate_av>0)
  155344. vi->bitrate_nominal=hi->bitrate_av;
  155345. else{
  155346. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155347. }
  155348. vi->bitrate_lower=hi->bitrate_min;
  155349. vi->bitrate_upper=hi->bitrate_max;
  155350. if(hi->bitrate_av)
  155351. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155352. else
  155353. vi->bitrate_window=0.;
  155354. if(hi->managed){
  155355. ci->bi.avg_rate=hi->bitrate_av;
  155356. ci->bi.min_rate=hi->bitrate_min;
  155357. ci->bi.max_rate=hi->bitrate_max;
  155358. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155359. ci->bi.reservoir_bias=
  155360. hi->bitrate_reservoir_bias;
  155361. ci->bi.slew_damp=hi->bitrate_av_damp;
  155362. }
  155363. return(0);
  155364. }
  155365. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155366. long channels,
  155367. long rate){
  155368. int ret=0,i,is;
  155369. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155370. highlevel_encode_setup *hi=&ci->hi;
  155371. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155372. double ds;
  155373. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155374. if(ret)return(ret);
  155375. is=hi->base_setting;
  155376. ds=hi->base_setting-is;
  155377. hi->short_setting=hi->base_setting;
  155378. hi->long_setting=hi->base_setting;
  155379. hi->managed=0;
  155380. hi->impulse_block_p=1;
  155381. hi->noise_normalize_p=1;
  155382. hi->stereo_point_setting=hi->base_setting;
  155383. hi->lowpass_kHz=
  155384. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155385. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155386. setup->psy_ath_float[is+1]*ds;
  155387. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155388. setup->psy_ath_abs[is+1]*ds;
  155389. hi->amplitude_track_dBpersec=-6.;
  155390. hi->trigger_setting=hi->base_setting;
  155391. for(i=0;i<4;i++){
  155392. hi->block[i].tone_mask_setting=hi->base_setting;
  155393. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155394. hi->block[i].noise_bias_setting=hi->base_setting;
  155395. hi->block[i].noise_compand_setting=hi->base_setting;
  155396. }
  155397. return(ret);
  155398. }
  155399. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155400. long channels,
  155401. long rate,
  155402. float quality){
  155403. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155404. highlevel_encode_setup *hi=&ci->hi;
  155405. quality+=.0000001;
  155406. if(quality>=1.)quality=.9999;
  155407. get_setup_template(vi,channels,rate,quality,0);
  155408. if(!hi->setup)return OV_EIMPL;
  155409. return vorbis_encode_setup_setting(vi,channels,rate);
  155410. }
  155411. int vorbis_encode_init_vbr(vorbis_info *vi,
  155412. long channels,
  155413. long rate,
  155414. float base_quality /* 0. to 1. */
  155415. ){
  155416. int ret=0;
  155417. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155418. if(ret){
  155419. vorbis_info_clear(vi);
  155420. return ret;
  155421. }
  155422. ret=vorbis_encode_setup_init(vi);
  155423. if(ret)
  155424. vorbis_info_clear(vi);
  155425. return(ret);
  155426. }
  155427. int vorbis_encode_setup_managed(vorbis_info *vi,
  155428. long channels,
  155429. long rate,
  155430. long max_bitrate,
  155431. long nominal_bitrate,
  155432. long min_bitrate){
  155433. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155434. highlevel_encode_setup *hi=&ci->hi;
  155435. double tnominal=nominal_bitrate;
  155436. int ret=0;
  155437. if(nominal_bitrate<=0.){
  155438. if(max_bitrate>0.){
  155439. if(min_bitrate>0.)
  155440. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155441. else
  155442. nominal_bitrate=max_bitrate*.875;
  155443. }else{
  155444. if(min_bitrate>0.){
  155445. nominal_bitrate=min_bitrate;
  155446. }else{
  155447. return(OV_EINVAL);
  155448. }
  155449. }
  155450. }
  155451. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155452. if(!hi->setup)return OV_EIMPL;
  155453. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155454. if(ret){
  155455. vorbis_info_clear(vi);
  155456. return ret;
  155457. }
  155458. /* initialize management with sane defaults */
  155459. hi->managed=1;
  155460. hi->bitrate_min=min_bitrate;
  155461. hi->bitrate_max=max_bitrate;
  155462. hi->bitrate_av=tnominal;
  155463. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155464. hi->bitrate_reservoir=nominal_bitrate*2;
  155465. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155466. return(ret);
  155467. }
  155468. int vorbis_encode_init(vorbis_info *vi,
  155469. long channels,
  155470. long rate,
  155471. long max_bitrate,
  155472. long nominal_bitrate,
  155473. long min_bitrate){
  155474. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155475. max_bitrate,
  155476. nominal_bitrate,
  155477. min_bitrate);
  155478. if(ret){
  155479. vorbis_info_clear(vi);
  155480. return(ret);
  155481. }
  155482. ret=vorbis_encode_setup_init(vi);
  155483. if(ret)
  155484. vorbis_info_clear(vi);
  155485. return(ret);
  155486. }
  155487. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155488. if(vi){
  155489. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155490. highlevel_encode_setup *hi=&ci->hi;
  155491. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155492. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155493. switch(number){
  155494. /* now deprecated *****************/
  155495. case OV_ECTL_RATEMANAGE_GET:
  155496. {
  155497. struct ovectl_ratemanage_arg *ai=
  155498. (struct ovectl_ratemanage_arg *)arg;
  155499. ai->management_active=hi->managed;
  155500. ai->bitrate_hard_window=ai->bitrate_av_window=
  155501. (double)hi->bitrate_reservoir/vi->rate;
  155502. ai->bitrate_av_window_center=1.;
  155503. ai->bitrate_hard_min=hi->bitrate_min;
  155504. ai->bitrate_hard_max=hi->bitrate_max;
  155505. ai->bitrate_av_lo=hi->bitrate_av;
  155506. ai->bitrate_av_hi=hi->bitrate_av;
  155507. }
  155508. return(0);
  155509. /* now deprecated *****************/
  155510. case OV_ECTL_RATEMANAGE_SET:
  155511. {
  155512. struct ovectl_ratemanage_arg *ai=
  155513. (struct ovectl_ratemanage_arg *)arg;
  155514. if(ai==NULL){
  155515. hi->managed=0;
  155516. }else{
  155517. hi->managed=ai->management_active;
  155518. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155519. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155520. }
  155521. }
  155522. return 0;
  155523. /* now deprecated *****************/
  155524. case OV_ECTL_RATEMANAGE_AVG:
  155525. {
  155526. struct ovectl_ratemanage_arg *ai=
  155527. (struct ovectl_ratemanage_arg *)arg;
  155528. if(ai==NULL){
  155529. hi->bitrate_av=0;
  155530. }else{
  155531. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155532. }
  155533. }
  155534. return(0);
  155535. /* now deprecated *****************/
  155536. case OV_ECTL_RATEMANAGE_HARD:
  155537. {
  155538. struct ovectl_ratemanage_arg *ai=
  155539. (struct ovectl_ratemanage_arg *)arg;
  155540. if(ai==NULL){
  155541. hi->bitrate_min=0;
  155542. hi->bitrate_max=0;
  155543. }else{
  155544. hi->bitrate_min=ai->bitrate_hard_min;
  155545. hi->bitrate_max=ai->bitrate_hard_max;
  155546. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155547. (hi->bitrate_max+hi->bitrate_min)*.5;
  155548. }
  155549. if(hi->bitrate_reservoir<128.)
  155550. hi->bitrate_reservoir=128.;
  155551. }
  155552. return(0);
  155553. /* replacement ratemanage interface */
  155554. case OV_ECTL_RATEMANAGE2_GET:
  155555. {
  155556. struct ovectl_ratemanage2_arg *ai=
  155557. (struct ovectl_ratemanage2_arg *)arg;
  155558. if(ai==NULL)return OV_EINVAL;
  155559. ai->management_active=hi->managed;
  155560. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155561. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155562. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155563. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155564. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155565. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155566. }
  155567. return (0);
  155568. case OV_ECTL_RATEMANAGE2_SET:
  155569. {
  155570. struct ovectl_ratemanage2_arg *ai=
  155571. (struct ovectl_ratemanage2_arg *)arg;
  155572. if(ai==NULL){
  155573. hi->managed=0;
  155574. }else{
  155575. /* sanity check; only catch invariant violations */
  155576. if(ai->bitrate_limit_min_kbps>0 &&
  155577. ai->bitrate_average_kbps>0 &&
  155578. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155579. return OV_EINVAL;
  155580. if(ai->bitrate_limit_max_kbps>0 &&
  155581. ai->bitrate_average_kbps>0 &&
  155582. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155583. return OV_EINVAL;
  155584. if(ai->bitrate_limit_min_kbps>0 &&
  155585. ai->bitrate_limit_max_kbps>0 &&
  155586. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155587. return OV_EINVAL;
  155588. if(ai->bitrate_average_damping <= 0.)
  155589. return OV_EINVAL;
  155590. if(ai->bitrate_limit_reservoir_bits < 0)
  155591. return OV_EINVAL;
  155592. if(ai->bitrate_limit_reservoir_bias < 0.)
  155593. return OV_EINVAL;
  155594. if(ai->bitrate_limit_reservoir_bias > 1.)
  155595. return OV_EINVAL;
  155596. hi->managed=ai->management_active;
  155597. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155598. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155599. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155600. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155601. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155602. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155603. }
  155604. }
  155605. return 0;
  155606. case OV_ECTL_LOWPASS_GET:
  155607. {
  155608. double *farg=(double *)arg;
  155609. *farg=hi->lowpass_kHz;
  155610. }
  155611. return(0);
  155612. case OV_ECTL_LOWPASS_SET:
  155613. {
  155614. double *farg=(double *)arg;
  155615. hi->lowpass_kHz=*farg;
  155616. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155617. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155618. }
  155619. return(0);
  155620. case OV_ECTL_IBLOCK_GET:
  155621. {
  155622. double *farg=(double *)arg;
  155623. *farg=hi->impulse_noisetune;
  155624. }
  155625. return(0);
  155626. case OV_ECTL_IBLOCK_SET:
  155627. {
  155628. double *farg=(double *)arg;
  155629. hi->impulse_noisetune=*farg;
  155630. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155631. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155632. }
  155633. return(0);
  155634. }
  155635. return(OV_EIMPL);
  155636. }
  155637. return(OV_EINVAL);
  155638. }
  155639. #endif
  155640. /*** End of inlined file: vorbisenc.c ***/
  155641. /*** Start of inlined file: vorbisfile.c ***/
  155642. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155643. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155644. // tasks..
  155645. #if JUCE_MSVC
  155646. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155647. #endif
  155648. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155649. #if JUCE_USE_OGGVORBIS
  155650. #include <stdlib.h>
  155651. #include <stdio.h>
  155652. #include <errno.h>
  155653. #include <string.h>
  155654. #include <math.h>
  155655. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155656. one logical bitstream arranged end to end (the only form of Ogg
  155657. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155658. multiplexing] is not allowed in Vorbis) */
  155659. /* A Vorbis file can be played beginning to end (streamed) without
  155660. worrying ahead of time about chaining (see decoder_example.c). If
  155661. we have the whole file, however, and want random access
  155662. (seeking/scrubbing) or desire to know the total length/time of a
  155663. file, we need to account for the possibility of chaining. */
  155664. /* We can handle things a number of ways; we can determine the entire
  155665. bitstream structure right off the bat, or find pieces on demand.
  155666. This example determines and caches structure for the entire
  155667. bitstream, but builds a virtual decoder on the fly when moving
  155668. between links in the chain. */
  155669. /* There are also different ways to implement seeking. Enough
  155670. information exists in an Ogg bitstream to seek to
  155671. sample-granularity positions in the output. Or, one can seek by
  155672. picking some portion of the stream roughly in the desired area if
  155673. we only want coarse navigation through the stream. */
  155674. /*************************************************************************
  155675. * Many, many internal helpers. The intention is not to be confusing;
  155676. * rampant duplication and monolithic function implementation would be
  155677. * harder to understand anyway. The high level functions are last. Begin
  155678. * grokking near the end of the file */
  155679. /* read a little more data from the file/pipe into the ogg_sync framer
  155680. */
  155681. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155682. over 8k gets what they deserve */
  155683. static long _get_data(OggVorbis_File *vf){
  155684. errno=0;
  155685. if(vf->datasource){
  155686. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155687. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155688. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155689. if(bytes==0 && errno)return(-1);
  155690. return(bytes);
  155691. }else
  155692. return(0);
  155693. }
  155694. /* save a tiny smidge of verbosity to make the code more readable */
  155695. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155696. if(vf->datasource){
  155697. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155698. vf->offset=offset;
  155699. ogg_sync_reset(&vf->oy);
  155700. }else{
  155701. /* shouldn't happen unless someone writes a broken callback */
  155702. return;
  155703. }
  155704. }
  155705. /* The read/seek functions track absolute position within the stream */
  155706. /* from the head of the stream, get the next page. boundary specifies
  155707. if the function is allowed to fetch more data from the stream (and
  155708. how much) or only use internally buffered data.
  155709. boundary: -1) unbounded search
  155710. 0) read no additional data; use cached only
  155711. n) search for a new page beginning for n bytes
  155712. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155713. n) found a page at absolute offset n */
  155714. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155715. ogg_int64_t boundary){
  155716. if(boundary>0)boundary+=vf->offset;
  155717. while(1){
  155718. long more;
  155719. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155720. more=ogg_sync_pageseek(&vf->oy,og);
  155721. if(more<0){
  155722. /* skipped n bytes */
  155723. vf->offset-=more;
  155724. }else{
  155725. if(more==0){
  155726. /* send more paramedics */
  155727. if(!boundary)return(OV_FALSE);
  155728. {
  155729. long ret=_get_data(vf);
  155730. if(ret==0)return(OV_EOF);
  155731. if(ret<0)return(OV_EREAD);
  155732. }
  155733. }else{
  155734. /* got a page. Return the offset at the page beginning,
  155735. advance the internal offset past the page end */
  155736. ogg_int64_t ret=vf->offset;
  155737. vf->offset+=more;
  155738. return(ret);
  155739. }
  155740. }
  155741. }
  155742. }
  155743. /* find the latest page beginning before the current stream cursor
  155744. position. Much dirtier than the above as Ogg doesn't have any
  155745. backward search linkage. no 'readp' as it will certainly have to
  155746. read. */
  155747. /* returns offset or OV_EREAD, OV_FAULT */
  155748. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155749. ogg_int64_t begin=vf->offset;
  155750. ogg_int64_t end=begin;
  155751. ogg_int64_t ret;
  155752. ogg_int64_t offset=-1;
  155753. while(offset==-1){
  155754. begin-=CHUNKSIZE;
  155755. if(begin<0)
  155756. begin=0;
  155757. _seek_helper(vf,begin);
  155758. while(vf->offset<end){
  155759. ret=_get_next_page(vf,og,end-vf->offset);
  155760. if(ret==OV_EREAD)return(OV_EREAD);
  155761. if(ret<0){
  155762. break;
  155763. }else{
  155764. offset=ret;
  155765. }
  155766. }
  155767. }
  155768. /* we have the offset. Actually snork and hold the page now */
  155769. _seek_helper(vf,offset);
  155770. ret=_get_next_page(vf,og,CHUNKSIZE);
  155771. if(ret<0)
  155772. /* this shouldn't be possible */
  155773. return(OV_EFAULT);
  155774. return(offset);
  155775. }
  155776. /* finds each bitstream link one at a time using a bisection search
  155777. (has to begin by knowing the offset of the lb's initial page).
  155778. Recurses for each link so it can alloc the link storage after
  155779. finding them all, then unroll and fill the cache at the same time */
  155780. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155781. ogg_int64_t begin,
  155782. ogg_int64_t searched,
  155783. ogg_int64_t end,
  155784. long currentno,
  155785. long m){
  155786. ogg_int64_t endsearched=end;
  155787. ogg_int64_t next=end;
  155788. ogg_page og;
  155789. ogg_int64_t ret;
  155790. /* the below guards against garbage seperating the last and
  155791. first pages of two links. */
  155792. while(searched<endsearched){
  155793. ogg_int64_t bisect;
  155794. if(endsearched-searched<CHUNKSIZE){
  155795. bisect=searched;
  155796. }else{
  155797. bisect=(searched+endsearched)/2;
  155798. }
  155799. _seek_helper(vf,bisect);
  155800. ret=_get_next_page(vf,&og,-1);
  155801. if(ret==OV_EREAD)return(OV_EREAD);
  155802. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155803. endsearched=bisect;
  155804. if(ret>=0)next=ret;
  155805. }else{
  155806. searched=ret+og.header_len+og.body_len;
  155807. }
  155808. }
  155809. _seek_helper(vf,next);
  155810. ret=_get_next_page(vf,&og,-1);
  155811. if(ret==OV_EREAD)return(OV_EREAD);
  155812. if(searched>=end || ret<0){
  155813. vf->links=m+1;
  155814. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155815. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155816. vf->offsets[m+1]=searched;
  155817. }else{
  155818. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155819. end,ogg_page_serialno(&og),m+1);
  155820. if(ret==OV_EREAD)return(OV_EREAD);
  155821. }
  155822. vf->offsets[m]=begin;
  155823. vf->serialnos[m]=currentno;
  155824. return(0);
  155825. }
  155826. /* uses the local ogg_stream storage in vf; this is important for
  155827. non-streaming input sources */
  155828. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155829. long *serialno,ogg_page *og_ptr){
  155830. ogg_page og;
  155831. ogg_packet op;
  155832. int i,ret;
  155833. if(!og_ptr){
  155834. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155835. if(llret==OV_EREAD)return(OV_EREAD);
  155836. if(llret<0)return OV_ENOTVORBIS;
  155837. og_ptr=&og;
  155838. }
  155839. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155840. if(serialno)*serialno=vf->os.serialno;
  155841. vf->ready_state=STREAMSET;
  155842. /* extract the initial header from the first page and verify that the
  155843. Ogg bitstream is in fact Vorbis data */
  155844. vorbis_info_init(vi);
  155845. vorbis_comment_init(vc);
  155846. i=0;
  155847. while(i<3){
  155848. ogg_stream_pagein(&vf->os,og_ptr);
  155849. while(i<3){
  155850. int result=ogg_stream_packetout(&vf->os,&op);
  155851. if(result==0)break;
  155852. if(result==-1){
  155853. ret=OV_EBADHEADER;
  155854. goto bail_header;
  155855. }
  155856. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155857. goto bail_header;
  155858. }
  155859. i++;
  155860. }
  155861. if(i<3)
  155862. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155863. ret=OV_EBADHEADER;
  155864. goto bail_header;
  155865. }
  155866. }
  155867. return 0;
  155868. bail_header:
  155869. vorbis_info_clear(vi);
  155870. vorbis_comment_clear(vc);
  155871. vf->ready_state=OPENED;
  155872. return ret;
  155873. }
  155874. /* last step of the OggVorbis_File initialization; get all the
  155875. vorbis_info structs and PCM positions. Only called by the seekable
  155876. initialization (local stream storage is hacked slightly; pay
  155877. attention to how that's done) */
  155878. /* this is void and does not propogate errors up because we want to be
  155879. able to open and use damaged bitstreams as well as we can. Just
  155880. watch out for missing information for links in the OggVorbis_File
  155881. struct */
  155882. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155883. ogg_page og;
  155884. int i;
  155885. ogg_int64_t ret;
  155886. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155887. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155888. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155889. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155890. for(i=0;i<vf->links;i++){
  155891. if(i==0){
  155892. /* we already grabbed the initial header earlier. Just set the offset */
  155893. vf->dataoffsets[i]=dataoffset;
  155894. _seek_helper(vf,dataoffset);
  155895. }else{
  155896. /* seek to the location of the initial header */
  155897. _seek_helper(vf,vf->offsets[i]);
  155898. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155899. vf->dataoffsets[i]=-1;
  155900. }else{
  155901. vf->dataoffsets[i]=vf->offset;
  155902. }
  155903. }
  155904. /* fetch beginning PCM offset */
  155905. if(vf->dataoffsets[i]!=-1){
  155906. ogg_int64_t accumulated=0;
  155907. long lastblock=-1;
  155908. int result;
  155909. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155910. while(1){
  155911. ogg_packet op;
  155912. ret=_get_next_page(vf,&og,-1);
  155913. if(ret<0)
  155914. /* this should not be possible unless the file is
  155915. truncated/mangled */
  155916. break;
  155917. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155918. break;
  155919. /* count blocksizes of all frames in the page */
  155920. ogg_stream_pagein(&vf->os,&og);
  155921. while((result=ogg_stream_packetout(&vf->os,&op))){
  155922. if(result>0){ /* ignore holes */
  155923. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155924. if(lastblock!=-1)
  155925. accumulated+=(lastblock+thisblock)>>2;
  155926. lastblock=thisblock;
  155927. }
  155928. }
  155929. if(ogg_page_granulepos(&og)!=-1){
  155930. /* pcm offset of last packet on the first audio page */
  155931. accumulated= ogg_page_granulepos(&og)-accumulated;
  155932. break;
  155933. }
  155934. }
  155935. /* less than zero? This is a stream with samples trimmed off
  155936. the beginning, a normal occurrence; set the offset to zero */
  155937. if(accumulated<0)accumulated=0;
  155938. vf->pcmlengths[i*2]=accumulated;
  155939. }
  155940. /* get the PCM length of this link. To do this,
  155941. get the last page of the stream */
  155942. {
  155943. ogg_int64_t end=vf->offsets[i+1];
  155944. _seek_helper(vf,end);
  155945. while(1){
  155946. ret=_get_prev_page(vf,&og);
  155947. if(ret<0){
  155948. /* this should not be possible */
  155949. vorbis_info_clear(vf->vi+i);
  155950. vorbis_comment_clear(vf->vc+i);
  155951. break;
  155952. }
  155953. if(ogg_page_granulepos(&og)!=-1){
  155954. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155955. break;
  155956. }
  155957. vf->offset=ret;
  155958. }
  155959. }
  155960. }
  155961. }
  155962. static int _make_decode_ready(OggVorbis_File *vf){
  155963. if(vf->ready_state>STREAMSET)return 0;
  155964. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155965. if(vf->seekable){
  155966. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155967. return OV_EBADLINK;
  155968. }else{
  155969. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155970. return OV_EBADLINK;
  155971. }
  155972. vorbis_block_init(&vf->vd,&vf->vb);
  155973. vf->ready_state=INITSET;
  155974. vf->bittrack=0.f;
  155975. vf->samptrack=0.f;
  155976. return 0;
  155977. }
  155978. static int _open_seekable2(OggVorbis_File *vf){
  155979. long serialno=vf->current_serialno;
  155980. ogg_int64_t dataoffset=vf->offset, end;
  155981. ogg_page og;
  155982. /* we're partially open and have a first link header state in
  155983. storage in vf */
  155984. /* we can seek, so set out learning all about this file */
  155985. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155986. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155987. /* We get the offset for the last page of the physical bitstream.
  155988. Most OggVorbis files will contain a single logical bitstream */
  155989. end=_get_prev_page(vf,&og);
  155990. if(end<0)return(end);
  155991. /* more than one logical bitstream? */
  155992. if(ogg_page_serialno(&og)!=serialno){
  155993. /* Chained bitstream. Bisect-search each logical bitstream
  155994. section. Do so based on serial number only */
  155995. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155996. }else{
  155997. /* Only one logical bitstream */
  155998. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155999. }
  156000. /* the initial header memory is referenced by vf after; don't free it */
  156001. _prefetch_all_headers(vf,dataoffset);
  156002. return(ov_raw_seek(vf,0));
  156003. }
  156004. /* clear out the current logical bitstream decoder */
  156005. static void _decode_clear(OggVorbis_File *vf){
  156006. vorbis_dsp_clear(&vf->vd);
  156007. vorbis_block_clear(&vf->vb);
  156008. vf->ready_state=OPENED;
  156009. }
  156010. /* fetch and process a packet. Handles the case where we're at a
  156011. bitstream boundary and dumps the decoding machine. If the decoding
  156012. machine is unloaded, it loads it. It also keeps pcm_offset up to
  156013. date (seek and read both use this. seek uses a special hack with
  156014. readp).
  156015. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  156016. 0) need more data (only if readp==0)
  156017. 1) got a packet
  156018. */
  156019. static int _fetch_and_process_packet(OggVorbis_File *vf,
  156020. ogg_packet *op_in,
  156021. int readp,
  156022. int spanp){
  156023. ogg_page og;
  156024. /* handle one packet. Try to fetch it from current stream state */
  156025. /* extract packets from page */
  156026. while(1){
  156027. /* process a packet if we can. If the machine isn't loaded,
  156028. neither is a page */
  156029. if(vf->ready_state==INITSET){
  156030. while(1) {
  156031. ogg_packet op;
  156032. ogg_packet *op_ptr=(op_in?op_in:&op);
  156033. int result=ogg_stream_packetout(&vf->os,op_ptr);
  156034. ogg_int64_t granulepos;
  156035. op_in=NULL;
  156036. if(result==-1)return(OV_HOLE); /* hole in the data. */
  156037. if(result>0){
  156038. /* got a packet. process it */
  156039. granulepos=op_ptr->granulepos;
  156040. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  156041. header handling. The
  156042. header packets aren't
  156043. audio, so if/when we
  156044. submit them,
  156045. vorbis_synthesis will
  156046. reject them */
  156047. /* suck in the synthesis data and track bitrate */
  156048. {
  156049. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156050. /* for proper use of libvorbis within libvorbisfile,
  156051. oldsamples will always be zero. */
  156052. if(oldsamples)return(OV_EFAULT);
  156053. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156054. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  156055. vf->bittrack+=op_ptr->bytes*8;
  156056. }
  156057. /* update the pcm offset. */
  156058. if(granulepos!=-1 && !op_ptr->e_o_s){
  156059. int link=(vf->seekable?vf->current_link:0);
  156060. int i,samples;
  156061. /* this packet has a pcm_offset on it (the last packet
  156062. completed on a page carries the offset) After processing
  156063. (above), we know the pcm position of the *last* sample
  156064. ready to be returned. Find the offset of the *first*
  156065. As an aside, this trick is inaccurate if we begin
  156066. reading anew right at the last page; the end-of-stream
  156067. granulepos declares the last frame in the stream, and the
  156068. last packet of the last page may be a partial frame.
  156069. So, we need a previous granulepos from an in-sequence page
  156070. to have a reference point. Thus the !op_ptr->e_o_s clause
  156071. above */
  156072. if(vf->seekable && link>0)
  156073. granulepos-=vf->pcmlengths[link*2];
  156074. if(granulepos<0)granulepos=0; /* actually, this
  156075. shouldn't be possible
  156076. here unless the stream
  156077. is very broken */
  156078. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156079. granulepos-=samples;
  156080. for(i=0;i<link;i++)
  156081. granulepos+=vf->pcmlengths[i*2+1];
  156082. vf->pcm_offset=granulepos;
  156083. }
  156084. return(1);
  156085. }
  156086. }
  156087. else
  156088. break;
  156089. }
  156090. }
  156091. if(vf->ready_state>=OPENED){
  156092. ogg_int64_t ret;
  156093. if(!readp)return(0);
  156094. if((ret=_get_next_page(vf,&og,-1))<0){
  156095. return(OV_EOF); /* eof.
  156096. leave unitialized */
  156097. }
  156098. /* bitrate tracking; add the header's bytes here, the body bytes
  156099. are done by packet above */
  156100. vf->bittrack+=og.header_len*8;
  156101. /* has our decoding just traversed a bitstream boundary? */
  156102. if(vf->ready_state==INITSET){
  156103. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156104. if(!spanp)
  156105. return(OV_EOF);
  156106. _decode_clear(vf);
  156107. if(!vf->seekable){
  156108. vorbis_info_clear(vf->vi);
  156109. vorbis_comment_clear(vf->vc);
  156110. }
  156111. }
  156112. }
  156113. }
  156114. /* Do we need to load a new machine before submitting the page? */
  156115. /* This is different in the seekable and non-seekable cases.
  156116. In the seekable case, we already have all the header
  156117. information loaded and cached; we just initialize the machine
  156118. with it and continue on our merry way.
  156119. In the non-seekable (streaming) case, we'll only be at a
  156120. boundary if we just left the previous logical bitstream and
  156121. we're now nominally at the header of the next bitstream
  156122. */
  156123. if(vf->ready_state!=INITSET){
  156124. int link;
  156125. if(vf->ready_state<STREAMSET){
  156126. if(vf->seekable){
  156127. vf->current_serialno=ogg_page_serialno(&og);
  156128. /* match the serialno to bitstream section. We use this rather than
  156129. offset positions to avoid problems near logical bitstream
  156130. boundaries */
  156131. for(link=0;link<vf->links;link++)
  156132. if(vf->serialnos[link]==vf->current_serialno)break;
  156133. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  156134. stream. error out,
  156135. leave machine
  156136. uninitialized */
  156137. vf->current_link=link;
  156138. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156139. vf->ready_state=STREAMSET;
  156140. }else{
  156141. /* we're streaming */
  156142. /* fetch the three header packets, build the info struct */
  156143. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  156144. if(ret)return(ret);
  156145. vf->current_link++;
  156146. link=0;
  156147. }
  156148. }
  156149. {
  156150. int ret=_make_decode_ready(vf);
  156151. if(ret<0)return ret;
  156152. }
  156153. }
  156154. ogg_stream_pagein(&vf->os,&og);
  156155. }
  156156. }
  156157. /* if, eg, 64 bit stdio is configured by default, this will build with
  156158. fseek64 */
  156159. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  156160. if(f==NULL)return(-1);
  156161. return fseek(f,off,whence);
  156162. }
  156163. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  156164. long ibytes, ov_callbacks callbacks){
  156165. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  156166. int ret;
  156167. memset(vf,0,sizeof(*vf));
  156168. vf->datasource=f;
  156169. vf->callbacks = callbacks;
  156170. /* init the framing state */
  156171. ogg_sync_init(&vf->oy);
  156172. /* perhaps some data was previously read into a buffer for testing
  156173. against other stream types. Allow initialization from this
  156174. previously read data (as we may be reading from a non-seekable
  156175. stream) */
  156176. if(initial){
  156177. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  156178. memcpy(buffer,initial,ibytes);
  156179. ogg_sync_wrote(&vf->oy,ibytes);
  156180. }
  156181. /* can we seek? Stevens suggests the seek test was portable */
  156182. if(offsettest!=-1)vf->seekable=1;
  156183. /* No seeking yet; Set up a 'single' (current) logical bitstream
  156184. entry for partial open */
  156185. vf->links=1;
  156186. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  156187. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  156188. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  156189. /* Try to fetch the headers, maintaining all the storage */
  156190. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  156191. vf->datasource=NULL;
  156192. ov_clear(vf);
  156193. }else
  156194. vf->ready_state=PARTOPEN;
  156195. return(ret);
  156196. }
  156197. static int _ov_open2(OggVorbis_File *vf){
  156198. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156199. vf->ready_state=OPENED;
  156200. if(vf->seekable){
  156201. int ret=_open_seekable2(vf);
  156202. if(ret){
  156203. vf->datasource=NULL;
  156204. ov_clear(vf);
  156205. }
  156206. return(ret);
  156207. }else
  156208. vf->ready_state=STREAMSET;
  156209. return 0;
  156210. }
  156211. /* clear out the OggVorbis_File struct */
  156212. int ov_clear(OggVorbis_File *vf){
  156213. if(vf){
  156214. vorbis_block_clear(&vf->vb);
  156215. vorbis_dsp_clear(&vf->vd);
  156216. ogg_stream_clear(&vf->os);
  156217. if(vf->vi && vf->links){
  156218. int i;
  156219. for(i=0;i<vf->links;i++){
  156220. vorbis_info_clear(vf->vi+i);
  156221. vorbis_comment_clear(vf->vc+i);
  156222. }
  156223. _ogg_free(vf->vi);
  156224. _ogg_free(vf->vc);
  156225. }
  156226. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156227. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156228. if(vf->serialnos)_ogg_free(vf->serialnos);
  156229. if(vf->offsets)_ogg_free(vf->offsets);
  156230. ogg_sync_clear(&vf->oy);
  156231. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156232. memset(vf,0,sizeof(*vf));
  156233. }
  156234. #ifdef DEBUG_LEAKS
  156235. _VDBG_dump();
  156236. #endif
  156237. return(0);
  156238. }
  156239. /* inspects the OggVorbis file and finds/documents all the logical
  156240. bitstreams contained in it. Tries to be tolerant of logical
  156241. bitstream sections that are truncated/woogie.
  156242. return: -1) error
  156243. 0) OK
  156244. */
  156245. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156246. ov_callbacks callbacks){
  156247. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156248. if(ret)return ret;
  156249. return _ov_open2(vf);
  156250. }
  156251. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156252. ov_callbacks callbacks = {
  156253. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156254. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156255. (int (*)(void *)) fclose,
  156256. (long (*)(void *)) ftell
  156257. };
  156258. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156259. }
  156260. /* cheap hack for game usage where downsampling is desirable; there's
  156261. no need for SRC as we can just do it cheaply in libvorbis. */
  156262. int ov_halfrate(OggVorbis_File *vf,int flag){
  156263. int i;
  156264. if(vf->vi==NULL)return OV_EINVAL;
  156265. if(!vf->seekable)return OV_EINVAL;
  156266. if(vf->ready_state>=STREAMSET)
  156267. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156268. will be able to swap this on the fly, but
  156269. for now dumping the decode machine is needed
  156270. to reinit the MDCT lookups. 1.1 libvorbis
  156271. is planned to be able to switch on the fly */
  156272. for(i=0;i<vf->links;i++){
  156273. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156274. ov_halfrate(vf,0);
  156275. return OV_EINVAL;
  156276. }
  156277. }
  156278. return 0;
  156279. }
  156280. int ov_halfrate_p(OggVorbis_File *vf){
  156281. if(vf->vi==NULL)return OV_EINVAL;
  156282. return vorbis_synthesis_halfrate_p(vf->vi);
  156283. }
  156284. /* Only partially open the vorbis file; test for Vorbisness, and load
  156285. the headers for the first chain. Do not seek (although test for
  156286. seekability). Use ov_test_open to finish opening the file, else
  156287. ov_clear to close/free it. Same return codes as open. */
  156288. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156289. ov_callbacks callbacks)
  156290. {
  156291. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156292. }
  156293. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156294. ov_callbacks callbacks = {
  156295. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156296. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156297. (int (*)(void *)) fclose,
  156298. (long (*)(void *)) ftell
  156299. };
  156300. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156301. }
  156302. int ov_test_open(OggVorbis_File *vf){
  156303. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156304. return _ov_open2(vf);
  156305. }
  156306. /* How many logical bitstreams in this physical bitstream? */
  156307. long ov_streams(OggVorbis_File *vf){
  156308. return vf->links;
  156309. }
  156310. /* Is the FILE * associated with vf seekable? */
  156311. long ov_seekable(OggVorbis_File *vf){
  156312. return vf->seekable;
  156313. }
  156314. /* returns the bitrate for a given logical bitstream or the entire
  156315. physical bitstream. If the file is open for random access, it will
  156316. find the *actual* average bitrate. If the file is streaming, it
  156317. returns the nominal bitrate (if set) else the average of the
  156318. upper/lower bounds (if set) else -1 (unset).
  156319. If you want the actual bitrate field settings, get them from the
  156320. vorbis_info structs */
  156321. long ov_bitrate(OggVorbis_File *vf,int i){
  156322. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156323. if(i>=vf->links)return(OV_EINVAL);
  156324. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156325. if(i<0){
  156326. ogg_int64_t bits=0;
  156327. int i;
  156328. float br;
  156329. for(i=0;i<vf->links;i++)
  156330. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156331. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156332. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156333. * so this is slightly transformed to make it work.
  156334. */
  156335. br = bits/ov_time_total(vf,-1);
  156336. return(rint(br));
  156337. }else{
  156338. if(vf->seekable){
  156339. /* return the actual bitrate */
  156340. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156341. }else{
  156342. /* return nominal if set */
  156343. if(vf->vi[i].bitrate_nominal>0){
  156344. return vf->vi[i].bitrate_nominal;
  156345. }else{
  156346. if(vf->vi[i].bitrate_upper>0){
  156347. if(vf->vi[i].bitrate_lower>0){
  156348. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156349. }else{
  156350. return vf->vi[i].bitrate_upper;
  156351. }
  156352. }
  156353. return(OV_FALSE);
  156354. }
  156355. }
  156356. }
  156357. }
  156358. /* returns the actual bitrate since last call. returns -1 if no
  156359. additional data to offer since last call (or at beginning of stream),
  156360. EINVAL if stream is only partially open
  156361. */
  156362. long ov_bitrate_instant(OggVorbis_File *vf){
  156363. int link=(vf->seekable?vf->current_link:0);
  156364. long ret;
  156365. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156366. if(vf->samptrack==0)return(OV_FALSE);
  156367. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156368. vf->bittrack=0.f;
  156369. vf->samptrack=0.f;
  156370. return(ret);
  156371. }
  156372. /* Guess */
  156373. long ov_serialnumber(OggVorbis_File *vf,int i){
  156374. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156375. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156376. if(i<0){
  156377. return(vf->current_serialno);
  156378. }else{
  156379. return(vf->serialnos[i]);
  156380. }
  156381. }
  156382. /* returns: total raw (compressed) length of content if i==-1
  156383. raw (compressed) length of that logical bitstream for i==0 to n
  156384. OV_EINVAL if the stream is not seekable (we can't know the length)
  156385. or if stream is only partially open
  156386. */
  156387. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156388. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156389. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156390. if(i<0){
  156391. ogg_int64_t acc=0;
  156392. int i;
  156393. for(i=0;i<vf->links;i++)
  156394. acc+=ov_raw_total(vf,i);
  156395. return(acc);
  156396. }else{
  156397. return(vf->offsets[i+1]-vf->offsets[i]);
  156398. }
  156399. }
  156400. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156401. (samples) of that logical bitstream for i==0 to n
  156402. OV_EINVAL if the stream is not seekable (we can't know the
  156403. length) or only partially open
  156404. */
  156405. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156406. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156407. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156408. if(i<0){
  156409. ogg_int64_t acc=0;
  156410. int i;
  156411. for(i=0;i<vf->links;i++)
  156412. acc+=ov_pcm_total(vf,i);
  156413. return(acc);
  156414. }else{
  156415. return(vf->pcmlengths[i*2+1]);
  156416. }
  156417. }
  156418. /* returns: total seconds of content if i==-1
  156419. seconds in that logical bitstream for i==0 to n
  156420. OV_EINVAL if the stream is not seekable (we can't know the
  156421. length) or only partially open
  156422. */
  156423. double ov_time_total(OggVorbis_File *vf,int i){
  156424. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156425. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156426. if(i<0){
  156427. double acc=0;
  156428. int i;
  156429. for(i=0;i<vf->links;i++)
  156430. acc+=ov_time_total(vf,i);
  156431. return(acc);
  156432. }else{
  156433. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156434. }
  156435. }
  156436. /* seek to an offset relative to the *compressed* data. This also
  156437. scans packets to update the PCM cursor. It will cross a logical
  156438. bitstream boundary, but only if it can't get any packets out of the
  156439. tail of the bitstream we seek to (so no surprises).
  156440. returns zero on success, nonzero on failure */
  156441. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156442. ogg_stream_state work_os;
  156443. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156444. if(!vf->seekable)
  156445. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156446. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156447. /* don't yet clear out decoding machine (if it's initialized), in
  156448. the case we're in the same link. Restart the decode lapping, and
  156449. let _fetch_and_process_packet deal with a potential bitstream
  156450. boundary */
  156451. vf->pcm_offset=-1;
  156452. ogg_stream_reset_serialno(&vf->os,
  156453. vf->current_serialno); /* must set serialno */
  156454. vorbis_synthesis_restart(&vf->vd);
  156455. _seek_helper(vf,pos);
  156456. /* we need to make sure the pcm_offset is set, but we don't want to
  156457. advance the raw cursor past good packets just to get to the first
  156458. with a granulepos. That's not equivalent behavior to beginning
  156459. decoding as immediately after the seek position as possible.
  156460. So, a hack. We use two stream states; a local scratch state and
  156461. the shared vf->os stream state. We use the local state to
  156462. scan, and the shared state as a buffer for later decode.
  156463. Unfortuantely, on the last page we still advance to last packet
  156464. because the granulepos on the last page is not necessarily on a
  156465. packet boundary, and we need to make sure the granpos is
  156466. correct.
  156467. */
  156468. {
  156469. ogg_page og;
  156470. ogg_packet op;
  156471. int lastblock=0;
  156472. int accblock=0;
  156473. int thisblock;
  156474. int eosflag;
  156475. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156476. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156477. return from not necessarily
  156478. starting from the beginning */
  156479. while(1){
  156480. if(vf->ready_state>=STREAMSET){
  156481. /* snarf/scan a packet if we can */
  156482. int result=ogg_stream_packetout(&work_os,&op);
  156483. if(result>0){
  156484. if(vf->vi[vf->current_link].codec_setup){
  156485. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156486. if(thisblock<0){
  156487. ogg_stream_packetout(&vf->os,NULL);
  156488. thisblock=0;
  156489. }else{
  156490. if(eosflag)
  156491. ogg_stream_packetout(&vf->os,NULL);
  156492. else
  156493. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156494. }
  156495. if(op.granulepos!=-1){
  156496. int i,link=vf->current_link;
  156497. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156498. if(granulepos<0)granulepos=0;
  156499. for(i=0;i<link;i++)
  156500. granulepos+=vf->pcmlengths[i*2+1];
  156501. vf->pcm_offset=granulepos-accblock;
  156502. break;
  156503. }
  156504. lastblock=thisblock;
  156505. continue;
  156506. }else
  156507. ogg_stream_packetout(&vf->os,NULL);
  156508. }
  156509. }
  156510. if(!lastblock){
  156511. if(_get_next_page(vf,&og,-1)<0){
  156512. vf->pcm_offset=ov_pcm_total(vf,-1);
  156513. break;
  156514. }
  156515. }else{
  156516. /* huh? Bogus stream with packets but no granulepos */
  156517. vf->pcm_offset=-1;
  156518. break;
  156519. }
  156520. /* has our decoding just traversed a bitstream boundary? */
  156521. if(vf->ready_state>=STREAMSET)
  156522. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156523. _decode_clear(vf); /* clear out stream state */
  156524. ogg_stream_clear(&work_os);
  156525. }
  156526. if(vf->ready_state<STREAMSET){
  156527. int link;
  156528. vf->current_serialno=ogg_page_serialno(&og);
  156529. for(link=0;link<vf->links;link++)
  156530. if(vf->serialnos[link]==vf->current_serialno)break;
  156531. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156532. error out, leave
  156533. machine uninitialized */
  156534. vf->current_link=link;
  156535. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156536. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156537. vf->ready_state=STREAMSET;
  156538. }
  156539. ogg_stream_pagein(&vf->os,&og);
  156540. ogg_stream_pagein(&work_os,&og);
  156541. eosflag=ogg_page_eos(&og);
  156542. }
  156543. }
  156544. ogg_stream_clear(&work_os);
  156545. vf->bittrack=0.f;
  156546. vf->samptrack=0.f;
  156547. return(0);
  156548. seek_error:
  156549. /* dump the machine so we're in a known state */
  156550. vf->pcm_offset=-1;
  156551. ogg_stream_clear(&work_os);
  156552. _decode_clear(vf);
  156553. return OV_EBADLINK;
  156554. }
  156555. /* Page granularity seek (faster than sample granularity because we
  156556. don't do the last bit of decode to find a specific sample).
  156557. Seek to the last [granule marked] page preceeding the specified pos
  156558. location, such that decoding past the returned point will quickly
  156559. arrive at the requested position. */
  156560. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156561. int link=-1;
  156562. ogg_int64_t result=0;
  156563. ogg_int64_t total=ov_pcm_total(vf,-1);
  156564. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156565. if(!vf->seekable)return(OV_ENOSEEK);
  156566. if(pos<0 || pos>total)return(OV_EINVAL);
  156567. /* which bitstream section does this pcm offset occur in? */
  156568. for(link=vf->links-1;link>=0;link--){
  156569. total-=vf->pcmlengths[link*2+1];
  156570. if(pos>=total)break;
  156571. }
  156572. /* search within the logical bitstream for the page with the highest
  156573. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156574. missing pages or incorrect frame number information in the
  156575. bitstream could make our task impossible. Account for that (it
  156576. would be an error condition) */
  156577. /* new search algorithm by HB (Nicholas Vinen) */
  156578. {
  156579. ogg_int64_t end=vf->offsets[link+1];
  156580. ogg_int64_t begin=vf->offsets[link];
  156581. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156582. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156583. ogg_int64_t target=pos-total+begintime;
  156584. ogg_int64_t best=begin;
  156585. ogg_page og;
  156586. while(begin<end){
  156587. ogg_int64_t bisect;
  156588. if(end-begin<CHUNKSIZE){
  156589. bisect=begin;
  156590. }else{
  156591. /* take a (pretty decent) guess. */
  156592. bisect=begin +
  156593. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156594. if(bisect<=begin)
  156595. bisect=begin+1;
  156596. }
  156597. _seek_helper(vf,bisect);
  156598. while(begin<end){
  156599. result=_get_next_page(vf,&og,end-vf->offset);
  156600. if(result==OV_EREAD) goto seek_error;
  156601. if(result<0){
  156602. if(bisect<=begin+1)
  156603. end=begin; /* found it */
  156604. else{
  156605. if(bisect==0) goto seek_error;
  156606. bisect-=CHUNKSIZE;
  156607. if(bisect<=begin)bisect=begin+1;
  156608. _seek_helper(vf,bisect);
  156609. }
  156610. }else{
  156611. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156612. if(granulepos==-1)continue;
  156613. if(granulepos<target){
  156614. best=result; /* raw offset of packet with granulepos */
  156615. begin=vf->offset; /* raw offset of next page */
  156616. begintime=granulepos;
  156617. if(target-begintime>44100)break;
  156618. bisect=begin; /* *not* begin + 1 */
  156619. }else{
  156620. if(bisect<=begin+1)
  156621. end=begin; /* found it */
  156622. else{
  156623. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156624. end=result;
  156625. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156626. if(bisect<=begin)bisect=begin+1;
  156627. _seek_helper(vf,bisect);
  156628. }else{
  156629. end=result;
  156630. endtime=granulepos;
  156631. break;
  156632. }
  156633. }
  156634. }
  156635. }
  156636. }
  156637. }
  156638. /* found our page. seek to it, update pcm offset. Easier case than
  156639. raw_seek, don't keep packets preceeding granulepos. */
  156640. {
  156641. ogg_page og;
  156642. ogg_packet op;
  156643. /* seek */
  156644. _seek_helper(vf,best);
  156645. vf->pcm_offset=-1;
  156646. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156647. if(link!=vf->current_link){
  156648. /* Different link; dump entire decode machine */
  156649. _decode_clear(vf);
  156650. vf->current_link=link;
  156651. vf->current_serialno=ogg_page_serialno(&og);
  156652. vf->ready_state=STREAMSET;
  156653. }else{
  156654. vorbis_synthesis_restart(&vf->vd);
  156655. }
  156656. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156657. ogg_stream_pagein(&vf->os,&og);
  156658. /* pull out all but last packet; the one with granulepos */
  156659. while(1){
  156660. result=ogg_stream_packetpeek(&vf->os,&op);
  156661. if(result==0){
  156662. /* !!! the packet finishing this page originated on a
  156663. preceeding page. Keep fetching previous pages until we
  156664. get one with a granulepos or without the 'continued' flag
  156665. set. Then just use raw_seek for simplicity. */
  156666. _seek_helper(vf,best);
  156667. while(1){
  156668. result=_get_prev_page(vf,&og);
  156669. if(result<0) goto seek_error;
  156670. if(ogg_page_granulepos(&og)>-1 ||
  156671. !ogg_page_continued(&og)){
  156672. return ov_raw_seek(vf,result);
  156673. }
  156674. vf->offset=result;
  156675. }
  156676. }
  156677. if(result<0){
  156678. result = OV_EBADPACKET;
  156679. goto seek_error;
  156680. }
  156681. if(op.granulepos!=-1){
  156682. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156683. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156684. vf->pcm_offset+=total;
  156685. break;
  156686. }else
  156687. result=ogg_stream_packetout(&vf->os,NULL);
  156688. }
  156689. }
  156690. }
  156691. /* verify result */
  156692. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156693. result=OV_EFAULT;
  156694. goto seek_error;
  156695. }
  156696. vf->bittrack=0.f;
  156697. vf->samptrack=0.f;
  156698. return(0);
  156699. seek_error:
  156700. /* dump machine so we're in a known state */
  156701. vf->pcm_offset=-1;
  156702. _decode_clear(vf);
  156703. return (int)result;
  156704. }
  156705. /* seek to a sample offset relative to the decompressed pcm stream
  156706. returns zero on success, nonzero on failure */
  156707. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156708. int thisblock,lastblock=0;
  156709. int ret=ov_pcm_seek_page(vf,pos);
  156710. if(ret<0)return(ret);
  156711. if((ret=_make_decode_ready(vf)))return ret;
  156712. /* discard leading packets we don't need for the lapping of the
  156713. position we want; don't decode them */
  156714. while(1){
  156715. ogg_packet op;
  156716. ogg_page og;
  156717. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156718. if(ret>0){
  156719. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156720. if(thisblock<0){
  156721. ogg_stream_packetout(&vf->os,NULL);
  156722. continue; /* non audio packet */
  156723. }
  156724. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156725. if(vf->pcm_offset+((thisblock+
  156726. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156727. /* remove the packet from packet queue and track its granulepos */
  156728. ogg_stream_packetout(&vf->os,NULL);
  156729. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156730. only tracking, no
  156731. pcm_decode */
  156732. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156733. /* end of logical stream case is hard, especially with exact
  156734. length positioning. */
  156735. if(op.granulepos>-1){
  156736. int i;
  156737. /* always believe the stream markers */
  156738. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156739. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156740. for(i=0;i<vf->current_link;i++)
  156741. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156742. }
  156743. lastblock=thisblock;
  156744. }else{
  156745. if(ret<0 && ret!=OV_HOLE)break;
  156746. /* suck in a new page */
  156747. if(_get_next_page(vf,&og,-1)<0)break;
  156748. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156749. if(vf->ready_state<STREAMSET){
  156750. int link;
  156751. vf->current_serialno=ogg_page_serialno(&og);
  156752. for(link=0;link<vf->links;link++)
  156753. if(vf->serialnos[link]==vf->current_serialno)break;
  156754. if(link==vf->links)return(OV_EBADLINK);
  156755. vf->current_link=link;
  156756. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156757. vf->ready_state=STREAMSET;
  156758. ret=_make_decode_ready(vf);
  156759. if(ret)return ret;
  156760. lastblock=0;
  156761. }
  156762. ogg_stream_pagein(&vf->os,&og);
  156763. }
  156764. }
  156765. vf->bittrack=0.f;
  156766. vf->samptrack=0.f;
  156767. /* discard samples until we reach the desired position. Crossing a
  156768. logical bitstream boundary with abandon is OK. */
  156769. while(vf->pcm_offset<pos){
  156770. ogg_int64_t target=pos-vf->pcm_offset;
  156771. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156772. if(samples>target)samples=target;
  156773. vorbis_synthesis_read(&vf->vd,samples);
  156774. vf->pcm_offset+=samples;
  156775. if(samples<target)
  156776. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156777. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156778. }
  156779. return 0;
  156780. }
  156781. /* seek to a playback time relative to the decompressed pcm stream
  156782. returns zero on success, nonzero on failure */
  156783. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156784. /* translate time to PCM position and call ov_pcm_seek */
  156785. int link=-1;
  156786. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156787. double time_total=ov_time_total(vf,-1);
  156788. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156789. if(!vf->seekable)return(OV_ENOSEEK);
  156790. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156791. /* which bitstream section does this time offset occur in? */
  156792. for(link=vf->links-1;link>=0;link--){
  156793. pcm_total-=vf->pcmlengths[link*2+1];
  156794. time_total-=ov_time_total(vf,link);
  156795. if(seconds>=time_total)break;
  156796. }
  156797. /* enough information to convert time offset to pcm offset */
  156798. {
  156799. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156800. return(ov_pcm_seek(vf,target));
  156801. }
  156802. }
  156803. /* page-granularity version of ov_time_seek
  156804. returns zero on success, nonzero on failure */
  156805. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156806. /* translate time to PCM position and call ov_pcm_seek */
  156807. int link=-1;
  156808. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156809. double time_total=ov_time_total(vf,-1);
  156810. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156811. if(!vf->seekable)return(OV_ENOSEEK);
  156812. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156813. /* which bitstream section does this time offset occur in? */
  156814. for(link=vf->links-1;link>=0;link--){
  156815. pcm_total-=vf->pcmlengths[link*2+1];
  156816. time_total-=ov_time_total(vf,link);
  156817. if(seconds>=time_total)break;
  156818. }
  156819. /* enough information to convert time offset to pcm offset */
  156820. {
  156821. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156822. return(ov_pcm_seek_page(vf,target));
  156823. }
  156824. }
  156825. /* tell the current stream offset cursor. Note that seek followed by
  156826. tell will likely not give the set offset due to caching */
  156827. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156828. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156829. return(vf->offset);
  156830. }
  156831. /* return PCM offset (sample) of next PCM sample to be read */
  156832. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156833. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156834. return(vf->pcm_offset);
  156835. }
  156836. /* return time offset (seconds) of next PCM sample to be read */
  156837. double ov_time_tell(OggVorbis_File *vf){
  156838. int link=0;
  156839. ogg_int64_t pcm_total=0;
  156840. double time_total=0.f;
  156841. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156842. if(vf->seekable){
  156843. pcm_total=ov_pcm_total(vf,-1);
  156844. time_total=ov_time_total(vf,-1);
  156845. /* which bitstream section does this time offset occur in? */
  156846. for(link=vf->links-1;link>=0;link--){
  156847. pcm_total-=vf->pcmlengths[link*2+1];
  156848. time_total-=ov_time_total(vf,link);
  156849. if(vf->pcm_offset>=pcm_total)break;
  156850. }
  156851. }
  156852. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156853. }
  156854. /* link: -1) return the vorbis_info struct for the bitstream section
  156855. currently being decoded
  156856. 0-n) to request information for a specific bitstream section
  156857. In the case of a non-seekable bitstream, any call returns the
  156858. current bitstream. NULL in the case that the machine is not
  156859. initialized */
  156860. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156861. if(vf->seekable){
  156862. if(link<0)
  156863. if(vf->ready_state>=STREAMSET)
  156864. return vf->vi+vf->current_link;
  156865. else
  156866. return vf->vi;
  156867. else
  156868. if(link>=vf->links)
  156869. return NULL;
  156870. else
  156871. return vf->vi+link;
  156872. }else{
  156873. return vf->vi;
  156874. }
  156875. }
  156876. /* grr, strong typing, grr, no templates/inheritence, grr */
  156877. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156878. if(vf->seekable){
  156879. if(link<0)
  156880. if(vf->ready_state>=STREAMSET)
  156881. return vf->vc+vf->current_link;
  156882. else
  156883. return vf->vc;
  156884. else
  156885. if(link>=vf->links)
  156886. return NULL;
  156887. else
  156888. return vf->vc+link;
  156889. }else{
  156890. return vf->vc;
  156891. }
  156892. }
  156893. static int host_is_big_endian() {
  156894. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156895. unsigned char *bytewise = (unsigned char *)&pattern;
  156896. if (bytewise[0] == 0xfe) return 1;
  156897. return 0;
  156898. }
  156899. /* up to this point, everything could more or less hide the multiple
  156900. logical bitstream nature of chaining from the toplevel application
  156901. if the toplevel application didn't particularly care. However, at
  156902. the point that we actually read audio back, the multiple-section
  156903. nature must surface: Multiple bitstream sections do not necessarily
  156904. have to have the same number of channels or sampling rate.
  156905. ov_read returns the sequential logical bitstream number currently
  156906. being decoded along with the PCM data in order that the toplevel
  156907. application can take action on channel/sample rate changes. This
  156908. number will be incremented even for streamed (non-seekable) streams
  156909. (for seekable streams, it represents the actual logical bitstream
  156910. index within the physical bitstream. Note that the accessor
  156911. functions above are aware of this dichotomy).
  156912. input values: buffer) a buffer to hold packed PCM data for return
  156913. length) the byte length requested to be placed into buffer
  156914. bigendianp) should the data be packed LSB first (0) or
  156915. MSB first (1)
  156916. word) word size for output. currently 1 (byte) or
  156917. 2 (16 bit short)
  156918. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156919. 0) EOF
  156920. n) number of bytes of PCM actually returned. The
  156921. below works on a packet-by-packet basis, so the
  156922. return length is not related to the 'length' passed
  156923. in, just guaranteed to fit.
  156924. *section) set to the logical bitstream number */
  156925. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156926. int bigendianp,int word,int sgned,int *bitstream){
  156927. int i,j;
  156928. int host_endian = host_is_big_endian();
  156929. float **pcm;
  156930. long samples;
  156931. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156932. while(1){
  156933. if(vf->ready_state==INITSET){
  156934. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156935. if(samples)break;
  156936. }
  156937. /* suck in another packet */
  156938. {
  156939. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156940. if(ret==OV_EOF)
  156941. return(0);
  156942. if(ret<=0)
  156943. return(ret);
  156944. }
  156945. }
  156946. if(samples>0){
  156947. /* yay! proceed to pack data into the byte buffer */
  156948. long channels=ov_info(vf,-1)->channels;
  156949. long bytespersample=word * channels;
  156950. vorbis_fpu_control fpu;
  156951. (void) fpu; // (to avoid a warning about it being unused)
  156952. if(samples>length/bytespersample)samples=length/bytespersample;
  156953. if(samples <= 0)
  156954. return OV_EINVAL;
  156955. /* a tight loop to pack each size */
  156956. {
  156957. int val;
  156958. if(word==1){
  156959. int off=(sgned?0:128);
  156960. vorbis_fpu_setround(&fpu);
  156961. for(j=0;j<samples;j++)
  156962. for(i=0;i<channels;i++){
  156963. val=vorbis_ftoi(pcm[i][j]*128.f);
  156964. if(val>127)val=127;
  156965. else if(val<-128)val=-128;
  156966. *buffer++=val+off;
  156967. }
  156968. vorbis_fpu_restore(fpu);
  156969. }else{
  156970. int off=(sgned?0:32768);
  156971. if(host_endian==bigendianp){
  156972. if(sgned){
  156973. vorbis_fpu_setround(&fpu);
  156974. for(i=0;i<channels;i++) { /* It's faster in this order */
  156975. float *src=pcm[i];
  156976. short *dest=((short *)buffer)+i;
  156977. for(j=0;j<samples;j++) {
  156978. val=vorbis_ftoi(src[j]*32768.f);
  156979. if(val>32767)val=32767;
  156980. else if(val<-32768)val=-32768;
  156981. *dest=val;
  156982. dest+=channels;
  156983. }
  156984. }
  156985. vorbis_fpu_restore(fpu);
  156986. }else{
  156987. vorbis_fpu_setround(&fpu);
  156988. for(i=0;i<channels;i++) {
  156989. float *src=pcm[i];
  156990. short *dest=((short *)buffer)+i;
  156991. for(j=0;j<samples;j++) {
  156992. val=vorbis_ftoi(src[j]*32768.f);
  156993. if(val>32767)val=32767;
  156994. else if(val<-32768)val=-32768;
  156995. *dest=val+off;
  156996. dest+=channels;
  156997. }
  156998. }
  156999. vorbis_fpu_restore(fpu);
  157000. }
  157001. }else if(bigendianp){
  157002. vorbis_fpu_setround(&fpu);
  157003. for(j=0;j<samples;j++)
  157004. for(i=0;i<channels;i++){
  157005. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157006. if(val>32767)val=32767;
  157007. else if(val<-32768)val=-32768;
  157008. val+=off;
  157009. *buffer++=(val>>8);
  157010. *buffer++=(val&0xff);
  157011. }
  157012. vorbis_fpu_restore(fpu);
  157013. }else{
  157014. int val;
  157015. vorbis_fpu_setround(&fpu);
  157016. for(j=0;j<samples;j++)
  157017. for(i=0;i<channels;i++){
  157018. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157019. if(val>32767)val=32767;
  157020. else if(val<-32768)val=-32768;
  157021. val+=off;
  157022. *buffer++=(val&0xff);
  157023. *buffer++=(val>>8);
  157024. }
  157025. vorbis_fpu_restore(fpu);
  157026. }
  157027. }
  157028. }
  157029. vorbis_synthesis_read(&vf->vd,samples);
  157030. vf->pcm_offset+=samples;
  157031. if(bitstream)*bitstream=vf->current_link;
  157032. return(samples*bytespersample);
  157033. }else{
  157034. return(samples);
  157035. }
  157036. }
  157037. /* input values: pcm_channels) a float vector per channel of output
  157038. length) the sample length being read by the app
  157039. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  157040. 0) EOF
  157041. n) number of samples of PCM actually returned. The
  157042. below works on a packet-by-packet basis, so the
  157043. return length is not related to the 'length' passed
  157044. in, just guaranteed to fit.
  157045. *section) set to the logical bitstream number */
  157046. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  157047. int *bitstream){
  157048. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157049. while(1){
  157050. if(vf->ready_state==INITSET){
  157051. float **pcm;
  157052. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  157053. if(samples){
  157054. if(pcm_channels)*pcm_channels=pcm;
  157055. if(samples>length)samples=length;
  157056. vorbis_synthesis_read(&vf->vd,samples);
  157057. vf->pcm_offset+=samples;
  157058. if(bitstream)*bitstream=vf->current_link;
  157059. return samples;
  157060. }
  157061. }
  157062. /* suck in another packet */
  157063. {
  157064. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  157065. if(ret==OV_EOF)return(0);
  157066. if(ret<=0)return(ret);
  157067. }
  157068. }
  157069. }
  157070. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  157071. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  157072. ogg_int64_t off);
  157073. static void _ov_splice(float **pcm,float **lappcm,
  157074. int n1, int n2,
  157075. int ch1, int ch2,
  157076. float *w1, float *w2){
  157077. int i,j;
  157078. float *w=w1;
  157079. int n=n1;
  157080. if(n1>n2){
  157081. n=n2;
  157082. w=w2;
  157083. }
  157084. /* splice */
  157085. for(j=0;j<ch1 && j<ch2;j++){
  157086. float *s=lappcm[j];
  157087. float *d=pcm[j];
  157088. for(i=0;i<n;i++){
  157089. float wd=w[i]*w[i];
  157090. float ws=1.-wd;
  157091. d[i]=d[i]*wd + s[i]*ws;
  157092. }
  157093. }
  157094. /* window from zero */
  157095. for(;j<ch2;j++){
  157096. float *d=pcm[j];
  157097. for(i=0;i<n;i++){
  157098. float wd=w[i]*w[i];
  157099. d[i]=d[i]*wd;
  157100. }
  157101. }
  157102. }
  157103. /* make sure vf is INITSET */
  157104. static int _ov_initset(OggVorbis_File *vf){
  157105. while(1){
  157106. if(vf->ready_state==INITSET)break;
  157107. /* suck in another packet */
  157108. {
  157109. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157110. if(ret<0 && ret!=OV_HOLE)return(ret);
  157111. }
  157112. }
  157113. return 0;
  157114. }
  157115. /* make sure vf is INITSET and that we have a primed buffer; if
  157116. we're crosslapping at a stream section boundary, this also makes
  157117. sure we're sanity checking against the right stream information */
  157118. static int _ov_initprime(OggVorbis_File *vf){
  157119. vorbis_dsp_state *vd=&vf->vd;
  157120. while(1){
  157121. if(vf->ready_state==INITSET)
  157122. if(vorbis_synthesis_pcmout(vd,NULL))break;
  157123. /* suck in another packet */
  157124. {
  157125. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157126. if(ret<0 && ret!=OV_HOLE)return(ret);
  157127. }
  157128. }
  157129. return 0;
  157130. }
  157131. /* grab enough data for lapping from vf; this may be in the form of
  157132. unreturned, already-decoded pcm, remaining PCM we will need to
  157133. decode, or synthetic postextrapolation from last packets. */
  157134. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  157135. float **lappcm,int lapsize){
  157136. int lapcount=0,i;
  157137. float **pcm;
  157138. /* try first to decode the lapping data */
  157139. while(lapcount<lapsize){
  157140. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  157141. if(samples){
  157142. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157143. for(i=0;i<vi->channels;i++)
  157144. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157145. lapcount+=samples;
  157146. vorbis_synthesis_read(vd,samples);
  157147. }else{
  157148. /* suck in another packet */
  157149. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  157150. if(ret==OV_EOF)break;
  157151. }
  157152. }
  157153. if(lapcount<lapsize){
  157154. /* failed to get lapping data from normal decode; pry it from the
  157155. postextrapolation buffering, or the second half of the MDCT
  157156. from the last packet */
  157157. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  157158. if(samples==0){
  157159. for(i=0;i<vi->channels;i++)
  157160. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  157161. lapcount=lapsize;
  157162. }else{
  157163. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157164. for(i=0;i<vi->channels;i++)
  157165. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157166. lapcount+=samples;
  157167. }
  157168. }
  157169. }
  157170. /* this sets up crosslapping of a sample by using trailing data from
  157171. sample 1 and lapping it into the windowing buffer of sample 2 */
  157172. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  157173. vorbis_info *vi1,*vi2;
  157174. float **lappcm;
  157175. float **pcm;
  157176. float *w1,*w2;
  157177. int n1,n2,i,ret,hs1,hs2;
  157178. if(vf1==vf2)return(0); /* degenerate case */
  157179. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  157180. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  157181. /* the relevant overlap buffers must be pre-checked and pre-primed
  157182. before looking at settings in the event that priming would cross
  157183. a bitstream boundary. So, do it now */
  157184. ret=_ov_initset(vf1);
  157185. if(ret)return(ret);
  157186. ret=_ov_initprime(vf2);
  157187. if(ret)return(ret);
  157188. vi1=ov_info(vf1,-1);
  157189. vi2=ov_info(vf2,-1);
  157190. hs1=ov_halfrate_p(vf1);
  157191. hs2=ov_halfrate_p(vf2);
  157192. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157193. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157194. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157195. w1=vorbis_window(&vf1->vd,0);
  157196. w2=vorbis_window(&vf2->vd,0);
  157197. for(i=0;i<vi1->channels;i++)
  157198. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157199. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157200. /* have a lapping buffer from vf1; now to splice it into the lapping
  157201. buffer of vf2 */
  157202. /* consolidate and expose the buffer. */
  157203. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157204. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157205. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157206. /* splice */
  157207. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157208. /* done */
  157209. return(0);
  157210. }
  157211. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157212. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157213. vorbis_info *vi;
  157214. float **lappcm;
  157215. float **pcm;
  157216. float *w1,*w2;
  157217. int n1,n2,ch1,ch2,hs;
  157218. int i,ret;
  157219. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157220. ret=_ov_initset(vf);
  157221. if(ret)return(ret);
  157222. vi=ov_info(vf,-1);
  157223. hs=ov_halfrate_p(vf);
  157224. ch1=vi->channels;
  157225. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157226. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157227. persistent; even if the decode state
  157228. from this link gets dumped, this
  157229. window array continues to exist */
  157230. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157231. for(i=0;i<ch1;i++)
  157232. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157233. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157234. /* have lapping data; seek and prime the buffer */
  157235. ret=localseek(vf,pos);
  157236. if(ret)return ret;
  157237. ret=_ov_initprime(vf);
  157238. if(ret)return(ret);
  157239. /* Guard against cross-link changes; they're perfectly legal */
  157240. vi=ov_info(vf,-1);
  157241. ch2=vi->channels;
  157242. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157243. w2=vorbis_window(&vf->vd,0);
  157244. /* consolidate and expose the buffer. */
  157245. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157246. /* splice */
  157247. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157248. /* done */
  157249. return(0);
  157250. }
  157251. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157252. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157253. }
  157254. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157255. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157256. }
  157257. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157258. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157259. }
  157260. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157261. int (*localseek)(OggVorbis_File *,double)){
  157262. vorbis_info *vi;
  157263. float **lappcm;
  157264. float **pcm;
  157265. float *w1,*w2;
  157266. int n1,n2,ch1,ch2,hs;
  157267. int i,ret;
  157268. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157269. ret=_ov_initset(vf);
  157270. if(ret)return(ret);
  157271. vi=ov_info(vf,-1);
  157272. hs=ov_halfrate_p(vf);
  157273. ch1=vi->channels;
  157274. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157275. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157276. persistent; even if the decode state
  157277. from this link gets dumped, this
  157278. window array continues to exist */
  157279. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157280. for(i=0;i<ch1;i++)
  157281. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157282. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157283. /* have lapping data; seek and prime the buffer */
  157284. ret=localseek(vf,pos);
  157285. if(ret)return ret;
  157286. ret=_ov_initprime(vf);
  157287. if(ret)return(ret);
  157288. /* Guard against cross-link changes; they're perfectly legal */
  157289. vi=ov_info(vf,-1);
  157290. ch2=vi->channels;
  157291. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157292. w2=vorbis_window(&vf->vd,0);
  157293. /* consolidate and expose the buffer. */
  157294. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157295. /* splice */
  157296. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157297. /* done */
  157298. return(0);
  157299. }
  157300. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157301. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157302. }
  157303. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157304. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157305. }
  157306. #endif
  157307. /*** End of inlined file: vorbisfile.c ***/
  157308. /*** Start of inlined file: window.c ***/
  157309. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157310. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157311. // tasks..
  157312. #if JUCE_MSVC
  157313. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157314. #endif
  157315. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157316. #if JUCE_USE_OGGVORBIS
  157317. #include <stdlib.h>
  157318. #include <math.h>
  157319. static float vwin64[32] = {
  157320. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157321. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157322. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157323. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157324. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157325. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157326. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157327. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157328. };
  157329. static float vwin128[64] = {
  157330. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157331. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157332. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157333. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157334. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157335. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157336. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157337. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157338. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157339. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157340. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157341. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157342. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157343. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157344. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157345. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157346. };
  157347. static float vwin256[128] = {
  157348. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157349. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157350. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157351. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157352. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157353. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157354. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157355. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157356. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157357. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157358. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157359. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157360. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157361. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157362. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157363. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157364. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157365. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157366. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157367. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157368. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157369. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157370. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157371. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157372. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157373. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157374. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157375. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157376. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157377. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157378. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157379. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157380. };
  157381. static float vwin512[256] = {
  157382. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157383. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157384. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157385. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157386. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157387. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157388. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157389. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157390. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157391. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157392. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157393. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157394. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157395. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157396. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157397. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157398. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157399. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157400. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157401. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157402. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157403. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157404. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157405. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157406. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157407. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157408. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157409. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157410. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157411. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157412. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157413. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157414. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157415. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157416. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157417. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157418. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157419. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157420. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157421. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157422. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157423. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157424. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157425. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157426. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157427. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157428. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157429. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157430. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157431. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157432. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157433. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157434. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157435. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157436. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157437. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157438. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157439. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157440. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157441. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157442. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157443. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157444. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157445. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157446. };
  157447. static float vwin1024[512] = {
  157448. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157449. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157450. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157451. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157452. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157453. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157454. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157455. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157456. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157457. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157458. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157459. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157460. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157461. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157462. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157463. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157464. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157465. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157466. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157467. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157468. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157469. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157470. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157471. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157472. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157473. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157474. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157475. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157476. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157477. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157478. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157479. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157480. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157481. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157482. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157483. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157484. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157485. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157486. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157487. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157488. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157489. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157490. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157491. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157492. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157493. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157494. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157495. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157496. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157497. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157498. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157499. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157500. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157501. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157502. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157503. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157504. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157505. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157506. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157507. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157508. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157509. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157510. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157511. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157512. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157513. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157514. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157515. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157516. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157517. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157518. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157519. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157520. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157521. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157522. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157523. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157524. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157525. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157526. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157527. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157528. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157529. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157530. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157531. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157532. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157533. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157534. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157535. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157536. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157537. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157538. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157539. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157540. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157541. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157542. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157543. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157544. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157545. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157546. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157547. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157548. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157549. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157550. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157551. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157552. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157553. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157554. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157555. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157556. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157557. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157558. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157559. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157560. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157561. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157562. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157563. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157564. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157565. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157566. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157567. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157568. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157569. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157570. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157571. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157572. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157573. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157574. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157575. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157576. };
  157577. static float vwin2048[1024] = {
  157578. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157579. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157580. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157581. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157582. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157583. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157584. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157585. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157586. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157587. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157588. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157589. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157590. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157591. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157592. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157593. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157594. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157595. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157596. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157597. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157598. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157599. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157600. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157601. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157602. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157603. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157604. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157605. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157606. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157607. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157608. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157609. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157610. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157611. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157612. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157613. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157614. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157615. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157616. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157617. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157618. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157619. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157620. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157621. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157622. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157623. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157624. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157625. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157626. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157627. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157628. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157629. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157630. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157631. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157632. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157633. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157634. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157635. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157636. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157637. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157638. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157639. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157640. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157641. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157642. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157643. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157644. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157645. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157646. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157647. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157648. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157649. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157650. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157651. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157652. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157653. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157654. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157655. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157656. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157657. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157658. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157659. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157660. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157661. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157662. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157663. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157664. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157665. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157666. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157667. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157668. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157669. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157670. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157671. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157672. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157673. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157674. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157675. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157676. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157677. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157678. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157679. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157680. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157681. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157682. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157683. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157684. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157685. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157686. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157687. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157688. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157689. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157690. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157691. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157692. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157693. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157694. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157695. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157696. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157697. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157698. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157699. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157700. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157701. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157702. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157703. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157704. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157705. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157706. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157707. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157708. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157709. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157710. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157711. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157712. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157713. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157714. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157715. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157716. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157717. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157718. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157719. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157720. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157721. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157722. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157723. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157724. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157725. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157726. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157727. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157728. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157729. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157730. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157731. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157732. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157733. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157734. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157735. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157736. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157737. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157738. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157739. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157740. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157741. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157742. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157743. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157744. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157745. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157746. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157747. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157748. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157749. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157750. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157751. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157752. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157753. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157754. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157755. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157756. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157757. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157758. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157759. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157760. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157761. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157762. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157763. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157764. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157765. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157766. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157767. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157768. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157769. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157770. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157771. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157772. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157773. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157774. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157775. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157776. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157777. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157778. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157779. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157780. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157781. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157782. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157783. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157784. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157785. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157786. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157787. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157788. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157789. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157790. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157791. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157792. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157793. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157794. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157795. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157796. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157797. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157798. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157799. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157800. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157801. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157802. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157803. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157804. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157805. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157806. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157807. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157808. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157809. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157810. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157811. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157812. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157813. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157814. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157815. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157816. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157817. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157818. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157819. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157820. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157821. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157822. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157823. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157824. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157825. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157826. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157827. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157828. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157829. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157830. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157831. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157832. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157833. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157834. };
  157835. static float vwin4096[2048] = {
  157836. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157837. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157838. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157839. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157840. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157841. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157842. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157843. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157844. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157845. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157846. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157847. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157848. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157849. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157850. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157851. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157852. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157853. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157854. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157855. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157856. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157857. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157858. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157859. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157860. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157861. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157862. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157863. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157864. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157865. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157866. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157867. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157868. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157869. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157870. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157871. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157872. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157873. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157874. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157875. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157876. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157877. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157878. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157879. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157880. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157881. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157882. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157883. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157884. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157885. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157886. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157887. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157888. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157889. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157890. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157891. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157892. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157893. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157894. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157895. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157896. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157897. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157898. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157899. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157900. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157901. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157902. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157903. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157904. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157905. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157906. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157907. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157908. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157909. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157910. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157911. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157912. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157913. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157914. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157915. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157916. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157917. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157918. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157919. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157920. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157921. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157922. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157923. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157924. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157925. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157926. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157927. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157928. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157929. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157930. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157931. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157932. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157933. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157934. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157935. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157936. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157937. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157938. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157939. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157940. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157941. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157942. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157943. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157944. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157945. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157946. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157947. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157948. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157949. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157950. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157951. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157952. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157953. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157954. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157955. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157956. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157957. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157958. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157959. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157960. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157961. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157962. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157963. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157964. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157965. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157966. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157967. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157968. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157969. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157970. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157971. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157972. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157973. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157974. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157975. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157976. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157977. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157978. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157979. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157980. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157981. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157982. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157983. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157984. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157985. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157986. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157987. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157988. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157989. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157990. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157991. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157992. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157993. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157994. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157995. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157996. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157997. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157998. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157999. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  158000. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  158001. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  158002. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  158003. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  158004. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  158005. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  158006. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  158007. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  158008. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  158009. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  158010. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  158011. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  158012. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  158013. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  158014. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  158015. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  158016. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  158017. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  158018. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  158019. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  158020. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  158021. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  158022. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  158023. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  158024. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  158025. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  158026. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  158027. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  158028. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  158029. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  158030. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  158031. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  158032. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  158033. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  158034. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  158035. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  158036. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  158037. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  158038. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  158039. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  158040. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  158041. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  158042. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  158043. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  158044. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  158045. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  158046. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  158047. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  158048. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  158049. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  158050. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  158051. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  158052. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  158053. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  158054. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  158055. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  158056. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  158057. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  158058. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  158059. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  158060. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  158061. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  158062. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  158063. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  158064. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  158065. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  158066. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  158067. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  158068. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  158069. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  158070. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  158071. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  158072. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  158073. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  158074. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  158075. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  158076. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  158077. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  158078. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  158079. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  158080. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  158081. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  158082. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  158083. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  158084. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  158085. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  158086. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  158087. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  158088. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  158089. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  158090. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  158091. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  158092. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  158093. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  158094. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  158095. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  158096. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  158097. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  158098. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  158099. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  158100. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  158101. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  158102. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  158103. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  158104. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  158105. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  158106. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  158107. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  158108. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  158109. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  158110. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  158111. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  158112. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  158113. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  158114. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  158115. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  158116. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  158117. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  158118. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  158119. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  158120. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  158121. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  158122. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  158123. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  158124. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  158125. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  158126. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  158127. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  158128. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  158129. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  158130. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  158131. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  158132. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  158133. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  158134. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  158135. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  158136. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  158137. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  158138. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  158139. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  158140. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  158141. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  158142. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  158143. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  158144. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  158145. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  158146. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  158147. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  158148. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  158149. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  158150. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  158151. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  158152. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  158153. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  158154. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  158155. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  158156. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  158157. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  158158. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  158159. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  158160. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  158161. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  158162. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  158163. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  158164. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  158165. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  158166. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  158167. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  158168. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  158169. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  158170. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  158171. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  158172. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  158173. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  158174. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  158175. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  158176. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  158177. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  158178. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  158179. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  158180. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  158181. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  158182. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  158183. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  158184. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  158185. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  158186. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  158187. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  158188. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  158189. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  158190. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  158191. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  158192. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158193. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158194. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158195. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158196. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158197. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158198. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158199. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158200. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158201. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158202. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158203. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158204. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158205. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158206. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158207. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158208. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158209. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158210. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158211. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158212. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158213. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158214. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158215. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158216. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158217. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158218. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158219. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158220. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158221. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158222. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158223. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158224. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158225. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158226. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158227. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158228. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158229. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158230. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158231. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158232. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158233. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158234. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158235. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158236. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158237. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158238. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158239. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158240. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158241. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158242. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158243. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158244. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158245. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158246. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158247. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158248. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158249. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158250. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158251. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158252. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158253. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158254. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158255. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158256. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158257. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158258. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158259. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158260. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158261. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158262. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158263. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158264. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158265. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158266. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158267. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158268. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158269. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158270. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158271. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158272. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158273. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158274. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158275. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158276. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158277. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158278. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158279. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158280. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158281. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158282. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158283. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158284. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158285. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158286. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158287. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158288. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158289. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158290. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158291. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158292. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158293. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158294. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158295. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158296. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158297. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158298. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158299. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158300. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158301. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158302. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158303. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158304. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158305. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158306. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158307. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158308. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158309. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158310. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158311. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158312. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158313. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158314. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158315. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158316. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158317. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158318. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158319. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158320. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158321. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158322. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158323. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158324. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158325. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158326. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158327. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158328. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158329. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158330. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158331. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158332. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158333. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158334. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158335. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158336. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158337. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158338. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158339. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158340. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158341. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158342. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158343. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158344. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158345. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158346. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158347. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158348. };
  158349. static float vwin8192[4096] = {
  158350. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158351. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158352. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158353. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158354. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158355. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158356. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158357. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158358. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158359. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158360. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158361. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158362. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158363. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158364. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158365. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158366. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158367. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158368. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158369. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158370. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158371. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158372. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158373. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158374. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158375. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158376. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158377. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158378. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158379. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158380. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158381. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158382. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158383. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158384. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158385. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158386. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158387. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158388. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158389. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158390. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158391. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158392. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158393. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158394. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158395. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158396. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158397. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158398. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158399. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158400. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158401. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158402. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158403. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158404. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158405. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158406. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158407. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158408. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158409. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158410. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158411. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158412. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158413. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158414. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158415. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158416. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158417. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158418. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158419. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158420. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158421. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158422. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158423. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158424. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158425. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158426. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158427. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158428. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158429. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158430. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158431. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158432. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158433. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158434. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158435. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158436. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158437. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158438. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158439. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158440. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158441. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158442. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158443. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158444. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158445. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158446. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158447. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158448. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158449. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158450. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158451. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158452. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158453. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158454. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158455. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158456. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158457. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158458. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158459. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158460. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158461. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158462. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158463. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158464. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158465. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158466. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158467. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158468. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158469. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158470. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158471. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158472. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158473. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158474. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158475. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158476. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158477. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158478. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158479. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158480. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158481. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158482. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158483. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158484. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158485. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158486. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158487. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158488. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158489. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158490. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158491. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158492. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158493. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158494. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158495. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158496. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158497. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158498. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158499. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158500. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158501. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158502. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158503. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158504. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158505. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158506. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158507. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158508. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158509. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158510. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158511. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158512. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158513. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158514. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158515. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158516. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158517. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158518. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158519. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158520. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158521. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158522. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158523. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158524. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158525. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158526. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158527. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158528. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158529. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158530. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158531. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158532. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158533. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158534. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158535. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158536. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158537. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158538. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158539. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158540. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158541. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158542. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158543. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158544. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158545. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158546. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158547. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158548. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158549. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158550. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158551. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158552. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158553. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158554. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158555. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158556. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158557. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158558. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158559. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158560. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158561. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158562. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158563. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158564. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158565. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158566. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158567. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158568. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158569. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158570. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158571. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158572. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158573. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158574. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158575. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158576. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158577. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158578. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158579. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158580. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158581. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158582. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158583. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158584. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158585. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158586. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158587. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158588. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158589. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158590. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158591. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158592. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158593. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158594. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158595. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158596. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158597. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158598. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158599. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158600. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158601. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158602. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158603. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158604. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158605. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158606. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158607. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158608. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158609. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158610. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158611. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158612. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158613. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158614. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158615. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158616. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158617. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158618. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158619. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158620. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158621. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158622. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158623. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158624. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158625. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158626. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158627. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158628. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158629. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158630. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158631. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158632. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158633. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158634. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158635. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158636. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158637. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158638. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158639. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158640. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158641. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158642. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158643. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158644. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158645. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158646. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158647. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158648. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158649. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158650. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158651. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158652. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158653. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158654. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158655. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158656. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158657. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158658. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158659. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158660. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158661. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158662. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158663. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158664. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158665. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158666. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158667. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158668. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158669. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158670. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158671. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158672. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158673. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158674. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158675. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158676. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158677. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158678. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158679. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158680. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158681. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158682. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158683. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158684. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158685. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158686. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158687. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158688. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158689. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158690. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158691. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158692. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158693. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158694. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158695. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158696. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158697. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158698. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158699. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158700. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158701. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158702. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158703. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158704. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158705. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158706. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158707. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158708. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158709. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158710. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158711. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158712. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158713. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158714. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158715. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158716. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158717. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158718. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158719. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158720. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158721. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158722. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158723. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158724. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158725. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158726. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158727. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158728. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158729. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158730. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158731. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158732. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158733. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158734. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158735. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158736. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158737. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158738. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158739. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158740. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158741. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158742. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158743. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158744. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158745. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158746. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158747. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158748. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158749. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158750. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158751. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158752. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158753. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158754. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158755. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158756. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158757. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158758. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158759. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158760. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158761. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158762. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158763. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158764. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158765. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158766. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158767. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158768. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158769. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158770. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158771. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158772. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158773. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158774. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158775. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158776. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158777. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158778. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158779. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158780. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158781. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158782. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158783. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158784. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158785. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158786. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158787. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158788. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158789. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158790. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158791. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158792. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158793. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158794. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158795. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158796. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158797. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158798. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158799. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158800. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158801. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158802. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158803. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158804. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158805. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158806. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158807. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158808. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158809. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158810. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158811. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158812. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158813. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158814. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158815. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158816. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158817. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158818. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158819. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158820. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158821. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158822. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158823. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158824. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158825. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158826. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158827. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158828. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158829. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158830. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158831. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158832. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158833. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158834. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158835. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158836. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158837. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158838. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158839. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158840. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158841. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158842. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158843. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158844. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158845. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158846. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158847. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158848. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158849. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158850. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158851. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158852. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158853. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158854. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158855. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158856. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158857. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158858. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158859. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158860. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158861. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158862. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158863. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158864. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158865. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158866. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158867. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158868. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158869. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158870. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158871. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158872. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158873. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158874. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158875. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158876. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158877. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158878. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158879. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158880. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158881. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158882. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158883. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158884. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158885. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158886. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158887. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158888. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158889. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158890. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158891. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158892. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158893. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158894. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158895. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158896. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158897. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158898. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158899. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158900. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158901. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158902. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158903. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158904. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158905. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158906. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158907. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158908. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158909. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158910. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158911. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158912. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158913. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158914. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158915. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158916. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158917. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158918. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158919. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158920. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158921. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158922. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158923. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158924. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158925. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158926. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158927. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158928. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158929. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158930. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158931. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158932. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158933. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158934. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158935. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158936. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158937. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158938. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158939. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158940. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158941. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158942. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158943. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158944. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158945. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158946. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158947. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158948. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158949. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158950. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158951. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158952. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158953. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158954. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158955. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158956. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158957. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158958. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158959. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158960. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158961. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158962. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158963. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158964. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158965. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158966. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158967. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158968. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158969. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158970. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158971. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158972. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158973. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158974. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158975. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158976. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158977. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158978. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158979. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158980. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158981. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158982. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158983. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158984. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158985. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158986. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158987. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158988. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158989. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158990. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158991. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158992. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158993. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158994. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158995. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158996. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158997. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158998. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158999. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  159000. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  159001. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  159002. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  159003. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  159004. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  159005. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  159006. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  159007. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  159008. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  159009. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  159010. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  159011. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  159012. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  159013. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  159014. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  159015. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  159016. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  159017. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  159018. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  159019. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  159020. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  159021. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  159022. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  159023. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  159024. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  159025. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  159026. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  159027. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  159028. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  159029. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  159030. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  159031. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  159032. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  159033. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  159034. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  159035. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  159036. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  159037. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  159038. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  159039. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  159040. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  159041. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  159042. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  159043. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  159044. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  159045. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  159046. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  159047. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  159048. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  159049. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  159050. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  159051. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  159052. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  159053. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  159054. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  159055. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  159056. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  159057. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  159058. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  159059. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  159060. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  159061. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  159062. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  159063. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  159064. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  159065. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  159066. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  159067. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  159068. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  159069. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  159070. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  159071. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  159072. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  159073. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  159074. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  159075. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  159076. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  159077. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  159078. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  159079. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  159080. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  159081. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  159082. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  159083. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  159084. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  159085. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  159086. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  159087. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  159088. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  159089. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  159090. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  159091. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  159092. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  159093. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  159094. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  159095. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  159096. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  159097. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  159098. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  159099. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  159100. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  159101. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  159102. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  159103. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  159104. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  159105. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  159106. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  159107. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  159108. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  159109. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  159110. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  159111. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  159112. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  159113. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  159114. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  159115. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  159116. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  159117. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  159118. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  159119. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  159120. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  159121. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  159122. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  159123. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  159124. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  159125. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  159126. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  159127. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  159128. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  159129. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  159130. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  159131. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  159132. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  159133. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  159134. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  159135. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  159136. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  159137. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  159138. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  159139. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  159140. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  159141. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  159142. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  159143. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  159144. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  159145. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  159146. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  159147. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  159148. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  159149. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  159150. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  159151. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  159152. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  159153. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  159154. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  159155. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  159156. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  159157. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  159158. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  159159. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  159160. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  159161. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  159162. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  159163. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  159164. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  159165. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  159166. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  159167. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  159168. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  159169. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  159170. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  159171. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  159172. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  159173. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  159174. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  159175. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  159176. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  159177. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  159178. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  159179. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  159180. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  159181. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  159182. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  159183. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  159184. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  159185. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  159186. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  159187. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  159188. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  159189. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  159190. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  159191. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  159192. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159193. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159194. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159195. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159196. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159197. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159198. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159199. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159200. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159201. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159202. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159203. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159204. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159205. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159206. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159207. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159208. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159209. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159210. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159211. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159212. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159213. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159214. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159215. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159216. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159217. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159218. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159219. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159220. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159221. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159222. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159223. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159224. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159225. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159226. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159227. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159228. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159229. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159230. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159231. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159232. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159233. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159234. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159235. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159236. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159237. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159238. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159239. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159240. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159241. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159242. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159243. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159244. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159245. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159246. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159247. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159248. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159249. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159250. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159251. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159252. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159253. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159254. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159255. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159256. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159257. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159258. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159259. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159260. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159261. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159262. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159263. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159264. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159265. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159266. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159267. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159268. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159269. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159270. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159271. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159272. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159273. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159274. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159275. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159276. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159277. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159278. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159279. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159280. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159281. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159282. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159283. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159284. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159285. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159286. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159287. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159288. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159289. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159290. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159291. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159292. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159293. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159294. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159295. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159296. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159297. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159298. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159299. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159300. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159301. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159302. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159303. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159304. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159305. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159306. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159307. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159308. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159309. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159310. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159311. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159312. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159313. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159314. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159315. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159316. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159317. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159318. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159319. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159320. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159321. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159322. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159323. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159324. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159325. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159326. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159327. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159328. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159329. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159330. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159331. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159332. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159333. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159334. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159335. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159336. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159337. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159338. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159339. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159340. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159341. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159342. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159343. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159344. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159345. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159346. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159347. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159348. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159349. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159350. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159351. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159352. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159353. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159354. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159355. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159356. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159357. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159358. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159359. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159360. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159361. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159362. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159363. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159364. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159365. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159366. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159367. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159368. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159369. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159370. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159371. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159372. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159373. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159374. };
  159375. static float *vwin[8] = {
  159376. vwin64,
  159377. vwin128,
  159378. vwin256,
  159379. vwin512,
  159380. vwin1024,
  159381. vwin2048,
  159382. vwin4096,
  159383. vwin8192,
  159384. };
  159385. float *_vorbis_window_get(int n){
  159386. return vwin[n];
  159387. }
  159388. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159389. int lW,int W,int nW){
  159390. lW=(W?lW:0);
  159391. nW=(W?nW:0);
  159392. {
  159393. float *windowLW=vwin[winno[lW]];
  159394. float *windowNW=vwin[winno[nW]];
  159395. long n=blocksizes[W];
  159396. long ln=blocksizes[lW];
  159397. long rn=blocksizes[nW];
  159398. long leftbegin=n/4-ln/4;
  159399. long leftend=leftbegin+ln/2;
  159400. long rightbegin=n/2+n/4-rn/4;
  159401. long rightend=rightbegin+rn/2;
  159402. int i,p;
  159403. for(i=0;i<leftbegin;i++)
  159404. d[i]=0.f;
  159405. for(p=0;i<leftend;i++,p++)
  159406. d[i]*=windowLW[p];
  159407. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159408. d[i]*=windowNW[p];
  159409. for(;i<n;i++)
  159410. d[i]=0.f;
  159411. }
  159412. }
  159413. #endif
  159414. /*** End of inlined file: window.c ***/
  159415. #else
  159416. #include <vorbis/vorbisenc.h>
  159417. #include <vorbis/codec.h>
  159418. #include <vorbis/vorbisfile.h>
  159419. #endif
  159420. }
  159421. #undef max
  159422. #undef min
  159423. BEGIN_JUCE_NAMESPACE
  159424. static const char* const oggFormatName = "Ogg-Vorbis file";
  159425. static const char* const oggExtensions[] = { ".ogg", 0 };
  159426. class OggReader : public AudioFormatReader
  159427. {
  159428. OggVorbisNamespace::OggVorbis_File ovFile;
  159429. OggVorbisNamespace::ov_callbacks callbacks;
  159430. AudioSampleBuffer reservoir;
  159431. int reservoirStart, samplesInReservoir;
  159432. public:
  159433. OggReader (InputStream* const inp)
  159434. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159435. reservoir (2, 4096),
  159436. reservoirStart (0),
  159437. samplesInReservoir (0)
  159438. {
  159439. using namespace OggVorbisNamespace;
  159440. sampleRate = 0;
  159441. usesFloatingPointData = true;
  159442. callbacks.read_func = &oggReadCallback;
  159443. callbacks.seek_func = &oggSeekCallback;
  159444. callbacks.close_func = &oggCloseCallback;
  159445. callbacks.tell_func = &oggTellCallback;
  159446. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159447. if (err == 0)
  159448. {
  159449. vorbis_info* info = ov_info (&ovFile, -1);
  159450. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159451. numChannels = info->channels;
  159452. bitsPerSample = 16;
  159453. sampleRate = info->rate;
  159454. reservoir.setSize (numChannels,
  159455. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159456. }
  159457. }
  159458. ~OggReader()
  159459. {
  159460. OggVorbisNamespace::ov_clear (&ovFile);
  159461. }
  159462. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159463. int64 startSampleInFile, int numSamples)
  159464. {
  159465. while (numSamples > 0)
  159466. {
  159467. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159468. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159469. {
  159470. // got a few samples overlapping, so use them before seeking..
  159471. const int numToUse = jmin (numSamples, numAvailable);
  159472. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159473. if (destSamples[i] != 0)
  159474. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159475. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159476. sizeof (float) * numToUse);
  159477. startSampleInFile += numToUse;
  159478. numSamples -= numToUse;
  159479. startOffsetInDestBuffer += numToUse;
  159480. if (numSamples == 0)
  159481. break;
  159482. }
  159483. if (startSampleInFile < reservoirStart
  159484. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159485. {
  159486. // buffer miss, so refill the reservoir
  159487. int bitStream = 0;
  159488. reservoirStart = jmax (0, (int) startSampleInFile);
  159489. samplesInReservoir = reservoir.getNumSamples();
  159490. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159491. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159492. int offset = 0;
  159493. int numToRead = samplesInReservoir;
  159494. while (numToRead > 0)
  159495. {
  159496. float** dataIn = 0;
  159497. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159498. if (samps <= 0)
  159499. break;
  159500. jassert (samps <= numToRead);
  159501. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159502. {
  159503. memcpy (reservoir.getSampleData (i, offset),
  159504. dataIn[i],
  159505. sizeof (float) * samps);
  159506. }
  159507. numToRead -= samps;
  159508. offset += samps;
  159509. }
  159510. if (numToRead > 0)
  159511. reservoir.clear (offset, numToRead);
  159512. }
  159513. }
  159514. if (numSamples > 0)
  159515. {
  159516. for (int i = numDestChannels; --i >= 0;)
  159517. if (destSamples[i] != 0)
  159518. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159519. sizeof (int) * numSamples);
  159520. }
  159521. return true;
  159522. }
  159523. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159524. {
  159525. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159526. }
  159527. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159528. {
  159529. InputStream* const in = static_cast <InputStream*> (datasource);
  159530. if (whence == SEEK_CUR)
  159531. offset += in->getPosition();
  159532. else if (whence == SEEK_END)
  159533. offset += in->getTotalLength();
  159534. in->setPosition (offset);
  159535. return 0;
  159536. }
  159537. static int oggCloseCallback (void*)
  159538. {
  159539. return 0;
  159540. }
  159541. static long oggTellCallback (void* datasource)
  159542. {
  159543. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159544. }
  159545. private:
  159546. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggReader);
  159547. };
  159548. class OggWriter : public AudioFormatWriter
  159549. {
  159550. OggVorbisNamespace::ogg_stream_state os;
  159551. OggVorbisNamespace::ogg_page og;
  159552. OggVorbisNamespace::ogg_packet op;
  159553. OggVorbisNamespace::vorbis_info vi;
  159554. OggVorbisNamespace::vorbis_comment vc;
  159555. OggVorbisNamespace::vorbis_dsp_state vd;
  159556. OggVorbisNamespace::vorbis_block vb;
  159557. public:
  159558. bool ok;
  159559. OggWriter (OutputStream* const out,
  159560. const double sampleRate,
  159561. const int numChannels,
  159562. const int bitsPerSample,
  159563. const int qualityIndex)
  159564. : AudioFormatWriter (out, TRANS (oggFormatName),
  159565. sampleRate,
  159566. numChannels,
  159567. bitsPerSample)
  159568. {
  159569. using namespace OggVorbisNamespace;
  159570. ok = false;
  159571. vorbis_info_init (&vi);
  159572. if (vorbis_encode_init_vbr (&vi,
  159573. numChannels,
  159574. (int) sampleRate,
  159575. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159576. {
  159577. vorbis_comment_init (&vc);
  159578. if (JUCEApplication::getInstance() != 0)
  159579. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159580. vorbis_analysis_init (&vd, &vi);
  159581. vorbis_block_init (&vd, &vb);
  159582. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159583. ogg_packet header;
  159584. ogg_packet header_comm;
  159585. ogg_packet header_code;
  159586. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159587. ogg_stream_packetin (&os, &header);
  159588. ogg_stream_packetin (&os, &header_comm);
  159589. ogg_stream_packetin (&os, &header_code);
  159590. for (;;)
  159591. {
  159592. if (ogg_stream_flush (&os, &og) == 0)
  159593. break;
  159594. output->write (og.header, og.header_len);
  159595. output->write (og.body, og.body_len);
  159596. }
  159597. ok = true;
  159598. }
  159599. }
  159600. ~OggWriter()
  159601. {
  159602. using namespace OggVorbisNamespace;
  159603. if (ok)
  159604. {
  159605. // write a zero-length packet to show ogg that we're finished..
  159606. write (0, 0);
  159607. ogg_stream_clear (&os);
  159608. vorbis_block_clear (&vb);
  159609. vorbis_dsp_clear (&vd);
  159610. vorbis_comment_clear (&vc);
  159611. vorbis_info_clear (&vi);
  159612. output->flush();
  159613. }
  159614. else
  159615. {
  159616. vorbis_info_clear (&vi);
  159617. output = 0; // to stop the base class deleting this, as it needs to be returned
  159618. // to the caller of createWriter()
  159619. }
  159620. }
  159621. bool write (const int** samplesToWrite, int numSamples)
  159622. {
  159623. using namespace OggVorbisNamespace;
  159624. if (! ok)
  159625. return false;
  159626. if (numSamples > 0)
  159627. {
  159628. const double gain = 1.0 / 0x80000000u;
  159629. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159630. for (int i = numChannels; --i >= 0;)
  159631. {
  159632. float* const dst = vorbisBuffer[i];
  159633. const int* const src = samplesToWrite [i];
  159634. if (src != 0 && dst != 0)
  159635. {
  159636. for (int j = 0; j < numSamples; ++j)
  159637. dst[j] = (float) (src[j] * gain);
  159638. }
  159639. }
  159640. }
  159641. vorbis_analysis_wrote (&vd, numSamples);
  159642. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159643. {
  159644. vorbis_analysis (&vb, 0);
  159645. vorbis_bitrate_addblock (&vb);
  159646. while (vorbis_bitrate_flushpacket (&vd, &op))
  159647. {
  159648. ogg_stream_packetin (&os, &op);
  159649. for (;;)
  159650. {
  159651. if (ogg_stream_pageout (&os, &og) == 0)
  159652. break;
  159653. output->write (og.header, og.header_len);
  159654. output->write (og.body, og.body_len);
  159655. if (ogg_page_eos (&og))
  159656. break;
  159657. }
  159658. }
  159659. }
  159660. return true;
  159661. }
  159662. private:
  159663. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggWriter);
  159664. };
  159665. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159666. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159667. {
  159668. }
  159669. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159670. {
  159671. }
  159672. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159673. {
  159674. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159675. return Array <int> (rates);
  159676. }
  159677. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159678. {
  159679. const int depths[] = { 32, 0 };
  159680. return Array <int> (depths);
  159681. }
  159682. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159683. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159684. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159685. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159686. const bool deleteStreamIfOpeningFails)
  159687. {
  159688. ScopedPointer <OggReader> r (new OggReader (in));
  159689. if (r->sampleRate != 0)
  159690. return r.release();
  159691. if (! deleteStreamIfOpeningFails)
  159692. r->input = 0;
  159693. return 0;
  159694. }
  159695. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159696. double sampleRate,
  159697. unsigned int numChannels,
  159698. int bitsPerSample,
  159699. const StringPairArray& /*metadataValues*/,
  159700. int qualityOptionIndex)
  159701. {
  159702. ScopedPointer <OggWriter> w (new OggWriter (out,
  159703. sampleRate,
  159704. numChannels,
  159705. bitsPerSample,
  159706. qualityOptionIndex));
  159707. return w->ok ? w.release() : 0;
  159708. }
  159709. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159710. {
  159711. StringArray s;
  159712. s.add ("Low Quality");
  159713. s.add ("Medium Quality");
  159714. s.add ("High Quality");
  159715. return s;
  159716. }
  159717. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159718. {
  159719. FileInputStream* const in = source.createInputStream();
  159720. if (in != 0)
  159721. {
  159722. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159723. if (r != 0)
  159724. {
  159725. const int64 numSamps = r->lengthInSamples;
  159726. r = 0;
  159727. const int64 fileNumSamps = source.getSize() / 4;
  159728. const double ratio = numSamps / (double) fileNumSamps;
  159729. if (ratio > 12.0)
  159730. return 0;
  159731. else if (ratio > 6.0)
  159732. return 1;
  159733. else
  159734. return 2;
  159735. }
  159736. }
  159737. return 1;
  159738. }
  159739. END_JUCE_NAMESPACE
  159740. #endif
  159741. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159742. #endif
  159743. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159744. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159745. #if JUCE_MSVC
  159746. #pragma warning (push)
  159747. #endif
  159748. namespace jpeglibNamespace
  159749. {
  159750. #if JUCE_INCLUDE_JPEGLIB_CODE
  159751. #if JUCE_MINGW
  159752. typedef unsigned char boolean;
  159753. #endif
  159754. #define JPEG_INTERNALS
  159755. #undef FAR
  159756. /*** Start of inlined file: jpeglib.h ***/
  159757. #ifndef JPEGLIB_H
  159758. #define JPEGLIB_H
  159759. /*
  159760. * First we include the configuration files that record how this
  159761. * installation of the JPEG library is set up. jconfig.h can be
  159762. * generated automatically for many systems. jmorecfg.h contains
  159763. * manual configuration options that most people need not worry about.
  159764. */
  159765. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159766. /*** Start of inlined file: jconfig.h ***/
  159767. /* see jconfig.doc for explanations */
  159768. // disable all the warnings under MSVC
  159769. #ifdef _MSC_VER
  159770. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159771. #endif
  159772. #ifdef __BORLANDC__
  159773. #pragma warn -8057
  159774. #pragma warn -8019
  159775. #pragma warn -8004
  159776. #pragma warn -8008
  159777. #endif
  159778. #define HAVE_PROTOTYPES
  159779. #define HAVE_UNSIGNED_CHAR
  159780. #define HAVE_UNSIGNED_SHORT
  159781. /* #define void char */
  159782. /* #define const */
  159783. #undef CHAR_IS_UNSIGNED
  159784. #define HAVE_STDDEF_H
  159785. #define HAVE_STDLIB_H
  159786. #undef NEED_BSD_STRINGS
  159787. #undef NEED_SYS_TYPES_H
  159788. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159789. #undef NEED_SHORT_EXTERNAL_NAMES
  159790. #undef INCOMPLETE_TYPES_BROKEN
  159791. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159792. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159793. typedef unsigned char boolean;
  159794. #endif
  159795. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159796. #ifdef JPEG_INTERNALS
  159797. #undef RIGHT_SHIFT_IS_UNSIGNED
  159798. #endif /* JPEG_INTERNALS */
  159799. #ifdef JPEG_CJPEG_DJPEG
  159800. #define BMP_SUPPORTED /* BMP image file format */
  159801. #define GIF_SUPPORTED /* GIF image file format */
  159802. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159803. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159804. #define TARGA_SUPPORTED /* Targa image file format */
  159805. #define TWO_FILE_COMMANDLINE /* optional */
  159806. #define USE_SETMODE /* Microsoft has setmode() */
  159807. #undef NEED_SIGNAL_CATCHER
  159808. #undef DONT_USE_B_MODE
  159809. #undef PROGRESS_REPORT /* optional */
  159810. #endif /* JPEG_CJPEG_DJPEG */
  159811. /*** End of inlined file: jconfig.h ***/
  159812. /* widely used configuration options */
  159813. #endif
  159814. /*** Start of inlined file: jmorecfg.h ***/
  159815. /*
  159816. * Define BITS_IN_JSAMPLE as either
  159817. * 8 for 8-bit sample values (the usual setting)
  159818. * 12 for 12-bit sample values
  159819. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159820. * JPEG standard, and the IJG code does not support anything else!
  159821. * We do not support run-time selection of data precision, sorry.
  159822. */
  159823. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159824. /*
  159825. * Maximum number of components (color channels) allowed in JPEG image.
  159826. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159827. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159828. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159829. * really short on memory. (Each allowed component costs a hundred or so
  159830. * bytes of storage, whether actually used in an image or not.)
  159831. */
  159832. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159833. /*
  159834. * Basic data types.
  159835. * You may need to change these if you have a machine with unusual data
  159836. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159837. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159838. * but it had better be at least 16.
  159839. */
  159840. /* Representation of a single sample (pixel element value).
  159841. * We frequently allocate large arrays of these, so it's important to keep
  159842. * them small. But if you have memory to burn and access to char or short
  159843. * arrays is very slow on your hardware, you might want to change these.
  159844. */
  159845. #if BITS_IN_JSAMPLE == 8
  159846. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159847. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159848. */
  159849. #ifdef HAVE_UNSIGNED_CHAR
  159850. typedef unsigned char JSAMPLE;
  159851. #define GETJSAMPLE(value) ((int) (value))
  159852. #else /* not HAVE_UNSIGNED_CHAR */
  159853. typedef char JSAMPLE;
  159854. #ifdef CHAR_IS_UNSIGNED
  159855. #define GETJSAMPLE(value) ((int) (value))
  159856. #else
  159857. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159858. #endif /* CHAR_IS_UNSIGNED */
  159859. #endif /* HAVE_UNSIGNED_CHAR */
  159860. #define MAXJSAMPLE 255
  159861. #define CENTERJSAMPLE 128
  159862. #endif /* BITS_IN_JSAMPLE == 8 */
  159863. #if BITS_IN_JSAMPLE == 12
  159864. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159865. * On nearly all machines "short" will do nicely.
  159866. */
  159867. typedef short JSAMPLE;
  159868. #define GETJSAMPLE(value) ((int) (value))
  159869. #define MAXJSAMPLE 4095
  159870. #define CENTERJSAMPLE 2048
  159871. #endif /* BITS_IN_JSAMPLE == 12 */
  159872. /* Representation of a DCT frequency coefficient.
  159873. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159874. * Again, we allocate large arrays of these, but you can change to int
  159875. * if you have memory to burn and "short" is really slow.
  159876. */
  159877. typedef short JCOEF;
  159878. /* Compressed datastreams are represented as arrays of JOCTET.
  159879. * These must be EXACTLY 8 bits wide, at least once they are written to
  159880. * external storage. Note that when using the stdio data source/destination
  159881. * managers, this is also the data type passed to fread/fwrite.
  159882. */
  159883. #ifdef HAVE_UNSIGNED_CHAR
  159884. typedef unsigned char JOCTET;
  159885. #define GETJOCTET(value) (value)
  159886. #else /* not HAVE_UNSIGNED_CHAR */
  159887. typedef char JOCTET;
  159888. #ifdef CHAR_IS_UNSIGNED
  159889. #define GETJOCTET(value) (value)
  159890. #else
  159891. #define GETJOCTET(value) ((value) & 0xFF)
  159892. #endif /* CHAR_IS_UNSIGNED */
  159893. #endif /* HAVE_UNSIGNED_CHAR */
  159894. /* These typedefs are used for various table entries and so forth.
  159895. * They must be at least as wide as specified; but making them too big
  159896. * won't cost a huge amount of memory, so we don't provide special
  159897. * extraction code like we did for JSAMPLE. (In other words, these
  159898. * typedefs live at a different point on the speed/space tradeoff curve.)
  159899. */
  159900. /* UINT8 must hold at least the values 0..255. */
  159901. #ifdef HAVE_UNSIGNED_CHAR
  159902. typedef unsigned char UINT8;
  159903. #else /* not HAVE_UNSIGNED_CHAR */
  159904. #ifdef CHAR_IS_UNSIGNED
  159905. typedef char UINT8;
  159906. #else /* not CHAR_IS_UNSIGNED */
  159907. typedef short UINT8;
  159908. #endif /* CHAR_IS_UNSIGNED */
  159909. #endif /* HAVE_UNSIGNED_CHAR */
  159910. /* UINT16 must hold at least the values 0..65535. */
  159911. #ifdef HAVE_UNSIGNED_SHORT
  159912. typedef unsigned short UINT16;
  159913. #else /* not HAVE_UNSIGNED_SHORT */
  159914. typedef unsigned int UINT16;
  159915. #endif /* HAVE_UNSIGNED_SHORT */
  159916. /* INT16 must hold at least the values -32768..32767. */
  159917. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159918. typedef short INT16;
  159919. #endif
  159920. /* INT32 must hold at least signed 32-bit values. */
  159921. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159922. typedef long INT32;
  159923. #endif
  159924. /* Datatype used for image dimensions. The JPEG standard only supports
  159925. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159926. * "unsigned int" is sufficient on all machines. However, if you need to
  159927. * handle larger images and you don't mind deviating from the spec, you
  159928. * can change this datatype.
  159929. */
  159930. typedef unsigned int JDIMENSION;
  159931. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159932. /* These macros are used in all function definitions and extern declarations.
  159933. * You could modify them if you need to change function linkage conventions;
  159934. * in particular, you'll need to do that to make the library a Windows DLL.
  159935. * Another application is to make all functions global for use with debuggers
  159936. * or code profilers that require it.
  159937. */
  159938. /* a function called through method pointers: */
  159939. #define METHODDEF(type) static type
  159940. /* a function used only in its module: */
  159941. #define LOCAL(type) static type
  159942. /* a function referenced thru EXTERNs: */
  159943. #define GLOBAL(type) type
  159944. /* a reference to a GLOBAL function: */
  159945. #define EXTERN(type) extern type
  159946. /* This macro is used to declare a "method", that is, a function pointer.
  159947. * We want to supply prototype parameters if the compiler can cope.
  159948. * Note that the arglist parameter must be parenthesized!
  159949. * Again, you can customize this if you need special linkage keywords.
  159950. */
  159951. #ifdef HAVE_PROTOTYPES
  159952. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159953. #else
  159954. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159955. #endif
  159956. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159957. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159958. * by just saying "FAR *" where such a pointer is needed. In a few places
  159959. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159960. */
  159961. #ifdef NEED_FAR_POINTERS
  159962. #define FAR far
  159963. #else
  159964. #define FAR
  159965. #endif
  159966. /*
  159967. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159968. * in standard header files. Or you may have conflicts with application-
  159969. * specific header files that you want to include together with these files.
  159970. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159971. */
  159972. #ifndef HAVE_BOOLEAN
  159973. typedef int boolean;
  159974. #endif
  159975. #ifndef FALSE /* in case these macros already exist */
  159976. #define FALSE 0 /* values of boolean */
  159977. #endif
  159978. #ifndef TRUE
  159979. #define TRUE 1
  159980. #endif
  159981. /*
  159982. * The remaining options affect code selection within the JPEG library,
  159983. * but they don't need to be visible to most applications using the library.
  159984. * To minimize application namespace pollution, the symbols won't be
  159985. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159986. */
  159987. #ifdef JPEG_INTERNALS
  159988. #define JPEG_INTERNAL_OPTIONS
  159989. #endif
  159990. #ifdef JPEG_INTERNAL_OPTIONS
  159991. /*
  159992. * These defines indicate whether to include various optional functions.
  159993. * Undefining some of these symbols will produce a smaller but less capable
  159994. * library. Note that you can leave certain source files out of the
  159995. * compilation/linking process if you've #undef'd the corresponding symbols.
  159996. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159997. */
  159998. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159999. /* Capability options common to encoder and decoder: */
  160000. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  160001. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  160002. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  160003. /* Encoder capability options: */
  160004. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160005. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160006. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160007. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  160008. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  160009. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  160010. * precision, so jchuff.c normally uses entropy optimization to compute
  160011. * usable tables for higher precision. If you don't want to do optimization,
  160012. * you'll have to supply different default Huffman tables.
  160013. * The exact same statements apply for progressive JPEG: the default tables
  160014. * don't work for progressive mode. (This may get fixed, however.)
  160015. */
  160016. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  160017. /* Decoder capability options: */
  160018. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160019. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160020. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160021. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  160022. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  160023. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  160024. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  160025. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  160026. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  160027. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  160028. /* more capability options later, no doubt */
  160029. /*
  160030. * Ordering of RGB data in scanlines passed to or from the application.
  160031. * If your application wants to deal with data in the order B,G,R, just
  160032. * change these macros. You can also deal with formats such as R,G,B,X
  160033. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  160034. * the offsets will also change the order in which colormap data is organized.
  160035. * RESTRICTIONS:
  160036. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  160037. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  160038. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  160039. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  160040. * is not 3 (they don't understand about dummy color components!). So you
  160041. * can't use color quantization if you change that value.
  160042. */
  160043. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  160044. #define RGB_GREEN 1 /* Offset of Green */
  160045. #define RGB_BLUE 2 /* Offset of Blue */
  160046. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  160047. /* Definitions for speed-related optimizations. */
  160048. /* If your compiler supports inline functions, define INLINE
  160049. * as the inline keyword; otherwise define it as empty.
  160050. */
  160051. #ifndef INLINE
  160052. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  160053. #define INLINE __inline__
  160054. #endif
  160055. #ifndef INLINE
  160056. #define INLINE /* default is to define it as empty */
  160057. #endif
  160058. #endif
  160059. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  160060. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  160061. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  160062. */
  160063. #ifndef MULTIPLIER
  160064. #define MULTIPLIER int /* type for fastest integer multiply */
  160065. #endif
  160066. /* FAST_FLOAT should be either float or double, whichever is done faster
  160067. * by your compiler. (Note that this type is only used in the floating point
  160068. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  160069. * Typically, float is faster in ANSI C compilers, while double is faster in
  160070. * pre-ANSI compilers (because they insist on converting to double anyway).
  160071. * The code below therefore chooses float if we have ANSI-style prototypes.
  160072. */
  160073. #ifndef FAST_FLOAT
  160074. #ifdef HAVE_PROTOTYPES
  160075. #define FAST_FLOAT float
  160076. #else
  160077. #define FAST_FLOAT double
  160078. #endif
  160079. #endif
  160080. #endif /* JPEG_INTERNAL_OPTIONS */
  160081. /*** End of inlined file: jmorecfg.h ***/
  160082. /* seldom changed options */
  160083. /* Version ID for the JPEG library.
  160084. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  160085. */
  160086. #define JPEG_LIB_VERSION 62 /* Version 6b */
  160087. /* Various constants determining the sizes of things.
  160088. * All of these are specified by the JPEG standard, so don't change them
  160089. * if you want to be compatible.
  160090. */
  160091. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  160092. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  160093. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  160094. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  160095. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  160096. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  160097. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  160098. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  160099. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  160100. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  160101. * to handle it. We even let you do this from the jconfig.h file. However,
  160102. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  160103. * sometimes emits noncompliant files doesn't mean you should too.
  160104. */
  160105. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  160106. #ifndef D_MAX_BLOCKS_IN_MCU
  160107. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  160108. #endif
  160109. /* Data structures for images (arrays of samples and of DCT coefficients).
  160110. * On 80x86 machines, the image arrays are too big for near pointers,
  160111. * but the pointer arrays can fit in near memory.
  160112. */
  160113. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  160114. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  160115. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  160116. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  160117. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  160118. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  160119. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  160120. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  160121. /* Types for JPEG compression parameters and working tables. */
  160122. /* DCT coefficient quantization tables. */
  160123. typedef struct {
  160124. /* This array gives the coefficient quantizers in natural array order
  160125. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  160126. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  160127. */
  160128. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  160129. /* This field is used only during compression. It's initialized FALSE when
  160130. * the table is created, and set TRUE when it's been output to the file.
  160131. * You could suppress output of a table by setting this to TRUE.
  160132. * (See jpeg_suppress_tables for an example.)
  160133. */
  160134. boolean sent_table; /* TRUE when table has been output */
  160135. } JQUANT_TBL;
  160136. /* Huffman coding tables. */
  160137. typedef struct {
  160138. /* These two fields directly represent the contents of a JPEG DHT marker */
  160139. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  160140. /* length k bits; bits[0] is unused */
  160141. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  160142. /* This field is used only during compression. It's initialized FALSE when
  160143. * the table is created, and set TRUE when it's been output to the file.
  160144. * You could suppress output of a table by setting this to TRUE.
  160145. * (See jpeg_suppress_tables for an example.)
  160146. */
  160147. boolean sent_table; /* TRUE when table has been output */
  160148. } JHUFF_TBL;
  160149. /* Basic info about one component (color channel). */
  160150. typedef struct {
  160151. /* These values are fixed over the whole image. */
  160152. /* For compression, they must be supplied by parameter setup; */
  160153. /* for decompression, they are read from the SOF marker. */
  160154. int component_id; /* identifier for this component (0..255) */
  160155. int component_index; /* its index in SOF or cinfo->comp_info[] */
  160156. int h_samp_factor; /* horizontal sampling factor (1..4) */
  160157. int v_samp_factor; /* vertical sampling factor (1..4) */
  160158. int quant_tbl_no; /* quantization table selector (0..3) */
  160159. /* These values may vary between scans. */
  160160. /* For compression, they must be supplied by parameter setup; */
  160161. /* for decompression, they are read from the SOS marker. */
  160162. /* The decompressor output side may not use these variables. */
  160163. int dc_tbl_no; /* DC entropy table selector (0..3) */
  160164. int ac_tbl_no; /* AC entropy table selector (0..3) */
  160165. /* Remaining fields should be treated as private by applications. */
  160166. /* These values are computed during compression or decompression startup: */
  160167. /* Component's size in DCT blocks.
  160168. * Any dummy blocks added to complete an MCU are not counted; therefore
  160169. * these values do not depend on whether a scan is interleaved or not.
  160170. */
  160171. JDIMENSION width_in_blocks;
  160172. JDIMENSION height_in_blocks;
  160173. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  160174. * For decompression this is the size of the output from one DCT block,
  160175. * reflecting any scaling we choose to apply during the IDCT step.
  160176. * Values of 1,2,4,8 are likely to be supported. Note that different
  160177. * components may receive different IDCT scalings.
  160178. */
  160179. int DCT_scaled_size;
  160180. /* The downsampled dimensions are the component's actual, unpadded number
  160181. * of samples at the main buffer (preprocessing/compression interface), thus
  160182. * downsampled_width = ceil(image_width * Hi/Hmax)
  160183. * and similarly for height. For decompression, IDCT scaling is included, so
  160184. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  160185. */
  160186. JDIMENSION downsampled_width; /* actual width in samples */
  160187. JDIMENSION downsampled_height; /* actual height in samples */
  160188. /* This flag is used only for decompression. In cases where some of the
  160189. * components will be ignored (eg grayscale output from YCbCr image),
  160190. * we can skip most computations for the unused components.
  160191. */
  160192. boolean component_needed; /* do we need the value of this component? */
  160193. /* These values are computed before starting a scan of the component. */
  160194. /* The decompressor output side may not use these variables. */
  160195. int MCU_width; /* number of blocks per MCU, horizontally */
  160196. int MCU_height; /* number of blocks per MCU, vertically */
  160197. int MCU_blocks; /* MCU_width * MCU_height */
  160198. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  160199. int last_col_width; /* # of non-dummy blocks across in last MCU */
  160200. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160201. /* Saved quantization table for component; NULL if none yet saved.
  160202. * See jdinput.c comments about the need for this information.
  160203. * This field is currently used only for decompression.
  160204. */
  160205. JQUANT_TBL * quant_table;
  160206. /* Private per-component storage for DCT or IDCT subsystem. */
  160207. void * dct_table;
  160208. } jpeg_component_info;
  160209. /* The script for encoding a multiple-scan file is an array of these: */
  160210. typedef struct {
  160211. int comps_in_scan; /* number of components encoded in this scan */
  160212. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160213. int Ss, Se; /* progressive JPEG spectral selection parms */
  160214. int Ah, Al; /* progressive JPEG successive approx. parms */
  160215. } jpeg_scan_info;
  160216. /* The decompressor can save APPn and COM markers in a list of these: */
  160217. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160218. struct jpeg_marker_struct {
  160219. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160220. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160221. unsigned int original_length; /* # bytes of data in the file */
  160222. unsigned int data_length; /* # bytes of data saved at data[] */
  160223. JOCTET FAR * data; /* the data contained in the marker */
  160224. /* the marker length word is not counted in data_length or original_length */
  160225. };
  160226. /* Known color spaces. */
  160227. typedef enum {
  160228. JCS_UNKNOWN, /* error/unspecified */
  160229. JCS_GRAYSCALE, /* monochrome */
  160230. JCS_RGB, /* red/green/blue */
  160231. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160232. JCS_CMYK, /* C/M/Y/K */
  160233. JCS_YCCK /* Y/Cb/Cr/K */
  160234. } J_COLOR_SPACE;
  160235. /* DCT/IDCT algorithm options. */
  160236. typedef enum {
  160237. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160238. JDCT_IFAST, /* faster, less accurate integer method */
  160239. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160240. } J_DCT_METHOD;
  160241. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160242. #define JDCT_DEFAULT JDCT_ISLOW
  160243. #endif
  160244. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160245. #define JDCT_FASTEST JDCT_IFAST
  160246. #endif
  160247. /* Dithering options for decompression. */
  160248. typedef enum {
  160249. JDITHER_NONE, /* no dithering */
  160250. JDITHER_ORDERED, /* simple ordered dither */
  160251. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160252. } J_DITHER_MODE;
  160253. /* Common fields between JPEG compression and decompression master structs. */
  160254. #define jpeg_common_fields \
  160255. struct jpeg_error_mgr * err; /* Error handler module */\
  160256. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160257. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160258. void * client_data; /* Available for use by application */\
  160259. boolean is_decompressor; /* So common code can tell which is which */\
  160260. int global_state /* For checking call sequence validity */
  160261. /* Routines that are to be used by both halves of the library are declared
  160262. * to receive a pointer to this structure. There are no actual instances of
  160263. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160264. */
  160265. struct jpeg_common_struct {
  160266. jpeg_common_fields; /* Fields common to both master struct types */
  160267. /* Additional fields follow in an actual jpeg_compress_struct or
  160268. * jpeg_decompress_struct. All three structs must agree on these
  160269. * initial fields! (This would be a lot cleaner in C++.)
  160270. */
  160271. };
  160272. typedef struct jpeg_common_struct * j_common_ptr;
  160273. typedef struct jpeg_compress_struct * j_compress_ptr;
  160274. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160275. /* Master record for a compression instance */
  160276. struct jpeg_compress_struct {
  160277. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160278. /* Destination for compressed data */
  160279. struct jpeg_destination_mgr * dest;
  160280. /* Description of source image --- these fields must be filled in by
  160281. * outer application before starting compression. in_color_space must
  160282. * be correct before you can even call jpeg_set_defaults().
  160283. */
  160284. JDIMENSION image_width; /* input image width */
  160285. JDIMENSION image_height; /* input image height */
  160286. int input_components; /* # of color components in input image */
  160287. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160288. double input_gamma; /* image gamma of input image */
  160289. /* Compression parameters --- these fields must be set before calling
  160290. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160291. * initialize everything to reasonable defaults, then changing anything
  160292. * the application specifically wants to change. That way you won't get
  160293. * burnt when new parameters are added. Also note that there are several
  160294. * helper routines to simplify changing parameters.
  160295. */
  160296. int data_precision; /* bits of precision in image data */
  160297. int num_components; /* # of color components in JPEG image */
  160298. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160299. jpeg_component_info * comp_info;
  160300. /* comp_info[i] describes component that appears i'th in SOF */
  160301. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160302. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160303. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160304. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160305. /* ptrs to Huffman coding tables, or NULL if not defined */
  160306. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160307. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160308. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160309. int num_scans; /* # of entries in scan_info array */
  160310. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160311. /* The default value of scan_info is NULL, which causes a single-scan
  160312. * sequential JPEG file to be emitted. To create a multi-scan file,
  160313. * set num_scans and scan_info to point to an array of scan definitions.
  160314. */
  160315. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160316. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160317. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160318. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160319. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160320. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160321. /* The restart interval can be specified in absolute MCUs by setting
  160322. * restart_interval, or in MCU rows by setting restart_in_rows
  160323. * (in which case the correct restart_interval will be figured
  160324. * for each scan).
  160325. */
  160326. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160327. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160328. /* Parameters controlling emission of special markers. */
  160329. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160330. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160331. UINT8 JFIF_minor_version;
  160332. /* These three values are not used by the JPEG code, merely copied */
  160333. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160334. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160335. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160336. UINT8 density_unit; /* JFIF code for pixel size units */
  160337. UINT16 X_density; /* Horizontal pixel density */
  160338. UINT16 Y_density; /* Vertical pixel density */
  160339. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160340. /* State variable: index of next scanline to be written to
  160341. * jpeg_write_scanlines(). Application may use this to control its
  160342. * processing loop, e.g., "while (next_scanline < image_height)".
  160343. */
  160344. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160345. /* Remaining fields are known throughout compressor, but generally
  160346. * should not be touched by a surrounding application.
  160347. */
  160348. /*
  160349. * These fields are computed during compression startup
  160350. */
  160351. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160352. int max_h_samp_factor; /* largest h_samp_factor */
  160353. int max_v_samp_factor; /* largest v_samp_factor */
  160354. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160355. /* The coefficient controller receives data in units of MCU rows as defined
  160356. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160357. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160358. * "iMCU" (interleaved MCU) row.
  160359. */
  160360. /*
  160361. * These fields are valid during any one scan.
  160362. * They describe the components and MCUs actually appearing in the scan.
  160363. */
  160364. int comps_in_scan; /* # of JPEG components in this scan */
  160365. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160366. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160367. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160368. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160369. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160370. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160371. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160372. /* i'th block in an MCU */
  160373. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160374. /*
  160375. * Links to compression subobjects (methods and private variables of modules)
  160376. */
  160377. struct jpeg_comp_master * master;
  160378. struct jpeg_c_main_controller * main;
  160379. struct jpeg_c_prep_controller * prep;
  160380. struct jpeg_c_coef_controller * coef;
  160381. struct jpeg_marker_writer * marker;
  160382. struct jpeg_color_converter * cconvert;
  160383. struct jpeg_downsampler * downsample;
  160384. struct jpeg_forward_dct * fdct;
  160385. struct jpeg_entropy_encoder * entropy;
  160386. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160387. int script_space_size;
  160388. };
  160389. /* Master record for a decompression instance */
  160390. struct jpeg_decompress_struct {
  160391. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160392. /* Source of compressed data */
  160393. struct jpeg_source_mgr * src;
  160394. /* Basic description of image --- filled in by jpeg_read_header(). */
  160395. /* Application may inspect these values to decide how to process image. */
  160396. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160397. JDIMENSION image_height; /* nominal image height */
  160398. int num_components; /* # of color components in JPEG image */
  160399. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160400. /* Decompression processing parameters --- these fields must be set before
  160401. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160402. * them to default values.
  160403. */
  160404. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160405. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160406. double output_gamma; /* image gamma wanted in output */
  160407. boolean buffered_image; /* TRUE=multiple output passes */
  160408. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160409. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160410. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160411. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160412. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160413. /* the following are ignored if not quantize_colors: */
  160414. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160415. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160416. int desired_number_of_colors; /* max # colors to use in created colormap */
  160417. /* these are significant only in buffered-image mode: */
  160418. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160419. boolean enable_external_quant;/* enable future use of external colormap */
  160420. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160421. /* Description of actual output image that will be returned to application.
  160422. * These fields are computed by jpeg_start_decompress().
  160423. * You can also use jpeg_calc_output_dimensions() to determine these values
  160424. * in advance of calling jpeg_start_decompress().
  160425. */
  160426. JDIMENSION output_width; /* scaled image width */
  160427. JDIMENSION output_height; /* scaled image height */
  160428. int out_color_components; /* # of color components in out_color_space */
  160429. int output_components; /* # of color components returned */
  160430. /* output_components is 1 (a colormap index) when quantizing colors;
  160431. * otherwise it equals out_color_components.
  160432. */
  160433. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160434. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160435. * high, space and time will be wasted due to unnecessary data copying.
  160436. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160437. */
  160438. /* When quantizing colors, the output colormap is described by these fields.
  160439. * The application can supply a colormap by setting colormap non-NULL before
  160440. * calling jpeg_start_decompress; otherwise a colormap is created during
  160441. * jpeg_start_decompress or jpeg_start_output.
  160442. * The map has out_color_components rows and actual_number_of_colors columns.
  160443. */
  160444. int actual_number_of_colors; /* number of entries in use */
  160445. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160446. /* State variables: these variables indicate the progress of decompression.
  160447. * The application may examine these but must not modify them.
  160448. */
  160449. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160450. * Application may use this to control its processing loop, e.g.,
  160451. * "while (output_scanline < output_height)".
  160452. */
  160453. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160454. /* Current input scan number and number of iMCU rows completed in scan.
  160455. * These indicate the progress of the decompressor input side.
  160456. */
  160457. int input_scan_number; /* Number of SOS markers seen so far */
  160458. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160459. /* The "output scan number" is the notional scan being displayed by the
  160460. * output side. The decompressor will not allow output scan/row number
  160461. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160462. */
  160463. int output_scan_number; /* Nominal scan number being displayed */
  160464. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160465. /* Current progression status. coef_bits[c][i] indicates the precision
  160466. * with which component c's DCT coefficient i (in zigzag order) is known.
  160467. * It is -1 when no data has yet been received, otherwise it is the point
  160468. * transform (shift) value for the most recent scan of the coefficient
  160469. * (thus, 0 at completion of the progression).
  160470. * This pointer is NULL when reading a non-progressive file.
  160471. */
  160472. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160473. /* Internal JPEG parameters --- the application usually need not look at
  160474. * these fields. Note that the decompressor output side may not use
  160475. * any parameters that can change between scans.
  160476. */
  160477. /* Quantization and Huffman tables are carried forward across input
  160478. * datastreams when processing abbreviated JPEG datastreams.
  160479. */
  160480. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160481. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160482. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160483. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160484. /* ptrs to Huffman coding tables, or NULL if not defined */
  160485. /* These parameters are never carried across datastreams, since they
  160486. * are given in SOF/SOS markers or defined to be reset by SOI.
  160487. */
  160488. int data_precision; /* bits of precision in image data */
  160489. jpeg_component_info * comp_info;
  160490. /* comp_info[i] describes component that appears i'th in SOF */
  160491. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160492. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160493. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160494. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160495. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160496. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160497. /* These fields record data obtained from optional markers recognized by
  160498. * the JPEG library.
  160499. */
  160500. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160501. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160502. UINT8 JFIF_major_version; /* JFIF version number */
  160503. UINT8 JFIF_minor_version;
  160504. UINT8 density_unit; /* JFIF code for pixel size units */
  160505. UINT16 X_density; /* Horizontal pixel density */
  160506. UINT16 Y_density; /* Vertical pixel density */
  160507. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160508. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160509. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160510. /* Aside from the specific data retained from APPn markers known to the
  160511. * library, the uninterpreted contents of any or all APPn and COM markers
  160512. * can be saved in a list for examination by the application.
  160513. */
  160514. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160515. /* Remaining fields are known throughout decompressor, but generally
  160516. * should not be touched by a surrounding application.
  160517. */
  160518. /*
  160519. * These fields are computed during decompression startup
  160520. */
  160521. int max_h_samp_factor; /* largest h_samp_factor */
  160522. int max_v_samp_factor; /* largest v_samp_factor */
  160523. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160524. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160525. /* The coefficient controller's input and output progress is measured in
  160526. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160527. * in fully interleaved JPEG scans, but are used whether the scan is
  160528. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160529. * rows of each component. Therefore, the IDCT output contains
  160530. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160531. */
  160532. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160533. /*
  160534. * These fields are valid during any one scan.
  160535. * They describe the components and MCUs actually appearing in the scan.
  160536. * Note that the decompressor output side must not use these fields.
  160537. */
  160538. int comps_in_scan; /* # of JPEG components in this scan */
  160539. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160540. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160541. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160542. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160543. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160544. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160545. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160546. /* i'th block in an MCU */
  160547. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160548. /* This field is shared between entropy decoder and marker parser.
  160549. * It is either zero or the code of a JPEG marker that has been
  160550. * read from the data source, but has not yet been processed.
  160551. */
  160552. int unread_marker;
  160553. /*
  160554. * Links to decompression subobjects (methods, private variables of modules)
  160555. */
  160556. struct jpeg_decomp_master * master;
  160557. struct jpeg_d_main_controller * main;
  160558. struct jpeg_d_coef_controller * coef;
  160559. struct jpeg_d_post_controller * post;
  160560. struct jpeg_input_controller * inputctl;
  160561. struct jpeg_marker_reader * marker;
  160562. struct jpeg_entropy_decoder * entropy;
  160563. struct jpeg_inverse_dct * idct;
  160564. struct jpeg_upsampler * upsample;
  160565. struct jpeg_color_deconverter * cconvert;
  160566. struct jpeg_color_quantizer * cquantize;
  160567. };
  160568. /* "Object" declarations for JPEG modules that may be supplied or called
  160569. * directly by the surrounding application.
  160570. * As with all objects in the JPEG library, these structs only define the
  160571. * publicly visible methods and state variables of a module. Additional
  160572. * private fields may exist after the public ones.
  160573. */
  160574. /* Error handler object */
  160575. struct jpeg_error_mgr {
  160576. /* Error exit handler: does not return to caller */
  160577. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160578. /* Conditionally emit a trace or warning message */
  160579. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160580. /* Routine that actually outputs a trace or error message */
  160581. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160582. /* Format a message string for the most recent JPEG error or message */
  160583. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160584. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160585. /* Reset error state variables at start of a new image */
  160586. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160587. /* The message ID code and any parameters are saved here.
  160588. * A message can have one string parameter or up to 8 int parameters.
  160589. */
  160590. int msg_code;
  160591. #define JMSG_STR_PARM_MAX 80
  160592. union {
  160593. int i[8];
  160594. char s[JMSG_STR_PARM_MAX];
  160595. } msg_parm;
  160596. /* Standard state variables for error facility */
  160597. int trace_level; /* max msg_level that will be displayed */
  160598. /* For recoverable corrupt-data errors, we emit a warning message,
  160599. * but keep going unless emit_message chooses to abort. emit_message
  160600. * should count warnings in num_warnings. The surrounding application
  160601. * can check for bad data by seeing if num_warnings is nonzero at the
  160602. * end of processing.
  160603. */
  160604. long num_warnings; /* number of corrupt-data warnings */
  160605. /* These fields point to the table(s) of error message strings.
  160606. * An application can change the table pointer to switch to a different
  160607. * message list (typically, to change the language in which errors are
  160608. * reported). Some applications may wish to add additional error codes
  160609. * that will be handled by the JPEG library error mechanism; the second
  160610. * table pointer is used for this purpose.
  160611. *
  160612. * First table includes all errors generated by JPEG library itself.
  160613. * Error code 0 is reserved for a "no such error string" message.
  160614. */
  160615. const char * const * jpeg_message_table; /* Library errors */
  160616. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160617. /* Second table can be added by application (see cjpeg/djpeg for example).
  160618. * It contains strings numbered first_addon_message..last_addon_message.
  160619. */
  160620. const char * const * addon_message_table; /* Non-library errors */
  160621. int first_addon_message; /* code for first string in addon table */
  160622. int last_addon_message; /* code for last string in addon table */
  160623. };
  160624. /* Progress monitor object */
  160625. struct jpeg_progress_mgr {
  160626. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160627. long pass_counter; /* work units completed in this pass */
  160628. long pass_limit; /* total number of work units in this pass */
  160629. int completed_passes; /* passes completed so far */
  160630. int total_passes; /* total number of passes expected */
  160631. };
  160632. /* Data destination object for compression */
  160633. struct jpeg_destination_mgr {
  160634. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160635. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160636. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160637. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160638. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160639. };
  160640. /* Data source object for decompression */
  160641. struct jpeg_source_mgr {
  160642. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160643. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160644. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160645. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160646. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160647. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160648. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160649. };
  160650. /* Memory manager object.
  160651. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160652. * and "really big" objects (virtual arrays with backing store if needed).
  160653. * The memory manager does not allow individual objects to be freed; rather,
  160654. * each created object is assigned to a pool, and whole pools can be freed
  160655. * at once. This is faster and more convenient than remembering exactly what
  160656. * to free, especially where malloc()/free() are not too speedy.
  160657. * NB: alloc routines never return NULL. They exit to error_exit if not
  160658. * successful.
  160659. */
  160660. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160661. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160662. #define JPOOL_NUMPOOLS 2
  160663. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160664. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160665. struct jpeg_memory_mgr {
  160666. /* Method pointers */
  160667. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160668. size_t sizeofobject));
  160669. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160670. size_t sizeofobject));
  160671. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160672. JDIMENSION samplesperrow,
  160673. JDIMENSION numrows));
  160674. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160675. JDIMENSION blocksperrow,
  160676. JDIMENSION numrows));
  160677. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160678. int pool_id,
  160679. boolean pre_zero,
  160680. JDIMENSION samplesperrow,
  160681. JDIMENSION numrows,
  160682. JDIMENSION maxaccess));
  160683. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160684. int pool_id,
  160685. boolean pre_zero,
  160686. JDIMENSION blocksperrow,
  160687. JDIMENSION numrows,
  160688. JDIMENSION maxaccess));
  160689. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160690. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160691. jvirt_sarray_ptr ptr,
  160692. JDIMENSION start_row,
  160693. JDIMENSION num_rows,
  160694. boolean writable));
  160695. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160696. jvirt_barray_ptr ptr,
  160697. JDIMENSION start_row,
  160698. JDIMENSION num_rows,
  160699. boolean writable));
  160700. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160701. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160702. /* Limit on memory allocation for this JPEG object. (Note that this is
  160703. * merely advisory, not a guaranteed maximum; it only affects the space
  160704. * used for virtual-array buffers.) May be changed by outer application
  160705. * after creating the JPEG object.
  160706. */
  160707. long max_memory_to_use;
  160708. /* Maximum allocation request accepted by alloc_large. */
  160709. long max_alloc_chunk;
  160710. };
  160711. /* Routine signature for application-supplied marker processing methods.
  160712. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160713. */
  160714. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160715. /* Declarations for routines called by application.
  160716. * The JPP macro hides prototype parameters from compilers that can't cope.
  160717. * Note JPP requires double parentheses.
  160718. */
  160719. #ifdef HAVE_PROTOTYPES
  160720. #define JPP(arglist) arglist
  160721. #else
  160722. #define JPP(arglist) ()
  160723. #endif
  160724. /* Short forms of external names for systems with brain-damaged linkers.
  160725. * We shorten external names to be unique in the first six letters, which
  160726. * is good enough for all known systems.
  160727. * (If your compiler itself needs names to be unique in less than 15
  160728. * characters, you are out of luck. Get a better compiler.)
  160729. */
  160730. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160731. #define jpeg_std_error jStdError
  160732. #define jpeg_CreateCompress jCreaCompress
  160733. #define jpeg_CreateDecompress jCreaDecompress
  160734. #define jpeg_destroy_compress jDestCompress
  160735. #define jpeg_destroy_decompress jDestDecompress
  160736. #define jpeg_stdio_dest jStdDest
  160737. #define jpeg_stdio_src jStdSrc
  160738. #define jpeg_set_defaults jSetDefaults
  160739. #define jpeg_set_colorspace jSetColorspace
  160740. #define jpeg_default_colorspace jDefColorspace
  160741. #define jpeg_set_quality jSetQuality
  160742. #define jpeg_set_linear_quality jSetLQuality
  160743. #define jpeg_add_quant_table jAddQuantTable
  160744. #define jpeg_quality_scaling jQualityScaling
  160745. #define jpeg_simple_progression jSimProgress
  160746. #define jpeg_suppress_tables jSuppressTables
  160747. #define jpeg_alloc_quant_table jAlcQTable
  160748. #define jpeg_alloc_huff_table jAlcHTable
  160749. #define jpeg_start_compress jStrtCompress
  160750. #define jpeg_write_scanlines jWrtScanlines
  160751. #define jpeg_finish_compress jFinCompress
  160752. #define jpeg_write_raw_data jWrtRawData
  160753. #define jpeg_write_marker jWrtMarker
  160754. #define jpeg_write_m_header jWrtMHeader
  160755. #define jpeg_write_m_byte jWrtMByte
  160756. #define jpeg_write_tables jWrtTables
  160757. #define jpeg_read_header jReadHeader
  160758. #define jpeg_start_decompress jStrtDecompress
  160759. #define jpeg_read_scanlines jReadScanlines
  160760. #define jpeg_finish_decompress jFinDecompress
  160761. #define jpeg_read_raw_data jReadRawData
  160762. #define jpeg_has_multiple_scans jHasMultScn
  160763. #define jpeg_start_output jStrtOutput
  160764. #define jpeg_finish_output jFinOutput
  160765. #define jpeg_input_complete jInComplete
  160766. #define jpeg_new_colormap jNewCMap
  160767. #define jpeg_consume_input jConsumeInput
  160768. #define jpeg_calc_output_dimensions jCalcDimensions
  160769. #define jpeg_save_markers jSaveMarkers
  160770. #define jpeg_set_marker_processor jSetMarker
  160771. #define jpeg_read_coefficients jReadCoefs
  160772. #define jpeg_write_coefficients jWrtCoefs
  160773. #define jpeg_copy_critical_parameters jCopyCrit
  160774. #define jpeg_abort_compress jAbrtCompress
  160775. #define jpeg_abort_decompress jAbrtDecompress
  160776. #define jpeg_abort jAbort
  160777. #define jpeg_destroy jDestroy
  160778. #define jpeg_resync_to_restart jResyncRestart
  160779. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160780. /* Default error-management setup */
  160781. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160782. JPP((struct jpeg_error_mgr * err));
  160783. /* Initialization of JPEG compression objects.
  160784. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160785. * names that applications should call. These expand to calls on
  160786. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160787. * passed for version mismatch checking.
  160788. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160789. */
  160790. #define jpeg_create_compress(cinfo) \
  160791. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160792. (size_t) sizeof(struct jpeg_compress_struct))
  160793. #define jpeg_create_decompress(cinfo) \
  160794. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160795. (size_t) sizeof(struct jpeg_decompress_struct))
  160796. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160797. int version, size_t structsize));
  160798. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160799. int version, size_t structsize));
  160800. /* Destruction of JPEG compression objects */
  160801. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160802. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160803. /* Standard data source and destination managers: stdio streams. */
  160804. /* Caller is responsible for opening the file before and closing after. */
  160805. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160806. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160807. /* Default parameter setup for compression */
  160808. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160809. /* Compression parameter setup aids */
  160810. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160811. J_COLOR_SPACE colorspace));
  160812. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160813. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160814. boolean force_baseline));
  160815. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160816. int scale_factor,
  160817. boolean force_baseline));
  160818. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160819. const unsigned int *basic_table,
  160820. int scale_factor,
  160821. boolean force_baseline));
  160822. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160823. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160824. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160825. boolean suppress));
  160826. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160827. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160828. /* Main entry points for compression */
  160829. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160830. boolean write_all_tables));
  160831. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160832. JSAMPARRAY scanlines,
  160833. JDIMENSION num_lines));
  160834. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160835. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160836. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160837. JSAMPIMAGE data,
  160838. JDIMENSION num_lines));
  160839. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160840. EXTERN(void) jpeg_write_marker
  160841. JPP((j_compress_ptr cinfo, int marker,
  160842. const JOCTET * dataptr, unsigned int datalen));
  160843. /* Same, but piecemeal. */
  160844. EXTERN(void) jpeg_write_m_header
  160845. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160846. EXTERN(void) jpeg_write_m_byte
  160847. JPP((j_compress_ptr cinfo, int val));
  160848. /* Alternate compression function: just write an abbreviated table file */
  160849. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160850. /* Decompression startup: read start of JPEG datastream to see what's there */
  160851. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160852. boolean require_image));
  160853. /* Return value is one of: */
  160854. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160855. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160856. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160857. /* If you pass require_image = TRUE (normal case), you need not check for
  160858. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160859. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160860. * give a suspension return (the stdio source module doesn't).
  160861. */
  160862. /* Main entry points for decompression */
  160863. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160864. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160865. JSAMPARRAY scanlines,
  160866. JDIMENSION max_lines));
  160867. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160868. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160869. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160870. JSAMPIMAGE data,
  160871. JDIMENSION max_lines));
  160872. /* Additional entry points for buffered-image mode. */
  160873. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160874. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160875. int scan_number));
  160876. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160877. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160878. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160879. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160880. /* Return value is one of: */
  160881. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160882. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160883. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160884. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160885. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160886. /* Precalculate output dimensions for current decompression parameters. */
  160887. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160888. /* Control saving of COM and APPn markers into marker_list. */
  160889. EXTERN(void) jpeg_save_markers
  160890. JPP((j_decompress_ptr cinfo, int marker_code,
  160891. unsigned int length_limit));
  160892. /* Install a special processing method for COM or APPn markers. */
  160893. EXTERN(void) jpeg_set_marker_processor
  160894. JPP((j_decompress_ptr cinfo, int marker_code,
  160895. jpeg_marker_parser_method routine));
  160896. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160897. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160898. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160899. jvirt_barray_ptr * coef_arrays));
  160900. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160901. j_compress_ptr dstinfo));
  160902. /* If you choose to abort compression or decompression before completing
  160903. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160904. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160905. * if you're done with the JPEG object, but if you want to clean it up and
  160906. * reuse it, call this:
  160907. */
  160908. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160909. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160910. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160911. * flavor of JPEG object. These may be more convenient in some places.
  160912. */
  160913. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160914. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160915. /* Default restart-marker-resync procedure for use by data source modules */
  160916. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160917. int desired));
  160918. /* These marker codes are exported since applications and data source modules
  160919. * are likely to want to use them.
  160920. */
  160921. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160922. #define JPEG_EOI 0xD9 /* EOI marker code */
  160923. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160924. #define JPEG_COM 0xFE /* COM marker code */
  160925. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160926. * for structure definitions that are never filled in, keep it quiet by
  160927. * supplying dummy definitions for the various substructures.
  160928. */
  160929. #ifdef INCOMPLETE_TYPES_BROKEN
  160930. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160931. struct jvirt_sarray_control { long dummy; };
  160932. struct jvirt_barray_control { long dummy; };
  160933. struct jpeg_comp_master { long dummy; };
  160934. struct jpeg_c_main_controller { long dummy; };
  160935. struct jpeg_c_prep_controller { long dummy; };
  160936. struct jpeg_c_coef_controller { long dummy; };
  160937. struct jpeg_marker_writer { long dummy; };
  160938. struct jpeg_color_converter { long dummy; };
  160939. struct jpeg_downsampler { long dummy; };
  160940. struct jpeg_forward_dct { long dummy; };
  160941. struct jpeg_entropy_encoder { long dummy; };
  160942. struct jpeg_decomp_master { long dummy; };
  160943. struct jpeg_d_main_controller { long dummy; };
  160944. struct jpeg_d_coef_controller { long dummy; };
  160945. struct jpeg_d_post_controller { long dummy; };
  160946. struct jpeg_input_controller { long dummy; };
  160947. struct jpeg_marker_reader { long dummy; };
  160948. struct jpeg_entropy_decoder { long dummy; };
  160949. struct jpeg_inverse_dct { long dummy; };
  160950. struct jpeg_upsampler { long dummy; };
  160951. struct jpeg_color_deconverter { long dummy; };
  160952. struct jpeg_color_quantizer { long dummy; };
  160953. #endif /* JPEG_INTERNALS */
  160954. #endif /* INCOMPLETE_TYPES_BROKEN */
  160955. /*
  160956. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160957. * The internal structure declarations are read only when that is true.
  160958. * Applications using the library should not include jpegint.h, but may wish
  160959. * to include jerror.h.
  160960. */
  160961. #ifdef JPEG_INTERNALS
  160962. /*** Start of inlined file: jpegint.h ***/
  160963. /* Declarations for both compression & decompression */
  160964. typedef enum { /* Operating modes for buffer controllers */
  160965. JBUF_PASS_THRU, /* Plain stripwise operation */
  160966. /* Remaining modes require a full-image buffer to have been created */
  160967. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160968. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160969. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160970. } J_BUF_MODE;
  160971. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160972. #define CSTATE_START 100 /* after create_compress */
  160973. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160974. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160975. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160976. #define DSTATE_START 200 /* after create_decompress */
  160977. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160978. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160979. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160980. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160981. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160982. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160983. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160984. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160985. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160986. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160987. /* Declarations for compression modules */
  160988. /* Master control module */
  160989. struct jpeg_comp_master {
  160990. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160991. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160992. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160993. /* State variables made visible to other modules */
  160994. boolean call_pass_startup; /* True if pass_startup must be called */
  160995. boolean is_last_pass; /* True during last pass */
  160996. };
  160997. /* Main buffer control (downsampled-data buffer) */
  160998. struct jpeg_c_main_controller {
  160999. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161000. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  161001. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161002. JDIMENSION in_rows_avail));
  161003. };
  161004. /* Compression preprocessing (downsampling input buffer control) */
  161005. struct jpeg_c_prep_controller {
  161006. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161007. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  161008. JSAMPARRAY input_buf,
  161009. JDIMENSION *in_row_ctr,
  161010. JDIMENSION in_rows_avail,
  161011. JSAMPIMAGE output_buf,
  161012. JDIMENSION *out_row_group_ctr,
  161013. JDIMENSION out_row_groups_avail));
  161014. };
  161015. /* Coefficient buffer control */
  161016. struct jpeg_c_coef_controller {
  161017. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161018. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  161019. JSAMPIMAGE input_buf));
  161020. };
  161021. /* Colorspace conversion */
  161022. struct jpeg_color_converter {
  161023. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161024. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  161025. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161026. JDIMENSION output_row, int num_rows));
  161027. };
  161028. /* Downsampling */
  161029. struct jpeg_downsampler {
  161030. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161031. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  161032. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  161033. JSAMPIMAGE output_buf,
  161034. JDIMENSION out_row_group_index));
  161035. boolean need_context_rows; /* TRUE if need rows above & below */
  161036. };
  161037. /* Forward DCT (also controls coefficient quantization) */
  161038. struct jpeg_forward_dct {
  161039. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161040. /* perhaps this should be an array??? */
  161041. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  161042. jpeg_component_info * compptr,
  161043. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  161044. JDIMENSION start_row, JDIMENSION start_col,
  161045. JDIMENSION num_blocks));
  161046. };
  161047. /* Entropy encoding */
  161048. struct jpeg_entropy_encoder {
  161049. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  161050. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  161051. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161052. };
  161053. /* Marker writing */
  161054. struct jpeg_marker_writer {
  161055. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  161056. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  161057. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  161058. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  161059. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  161060. /* These routines are exported to allow insertion of extra markers */
  161061. /* Probably only COM and APPn markers should be written this way */
  161062. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  161063. unsigned int datalen));
  161064. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  161065. };
  161066. /* Declarations for decompression modules */
  161067. /* Master control module */
  161068. struct jpeg_decomp_master {
  161069. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  161070. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  161071. /* State variables made visible to other modules */
  161072. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  161073. };
  161074. /* Input control module */
  161075. struct jpeg_input_controller {
  161076. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  161077. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  161078. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161079. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  161080. /* State variables made visible to other modules */
  161081. boolean has_multiple_scans; /* True if file has multiple scans */
  161082. boolean eoi_reached; /* True when EOI has been consumed */
  161083. };
  161084. /* Main buffer control (downsampled-data buffer) */
  161085. struct jpeg_d_main_controller {
  161086. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161087. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  161088. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  161089. JDIMENSION out_rows_avail));
  161090. };
  161091. /* Coefficient buffer control */
  161092. struct jpeg_d_coef_controller {
  161093. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161094. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  161095. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  161096. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  161097. JSAMPIMAGE output_buf));
  161098. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  161099. jvirt_barray_ptr *coef_arrays;
  161100. };
  161101. /* Decompression postprocessing (color quantization buffer control) */
  161102. struct jpeg_d_post_controller {
  161103. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161104. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  161105. JSAMPIMAGE input_buf,
  161106. JDIMENSION *in_row_group_ctr,
  161107. JDIMENSION in_row_groups_avail,
  161108. JSAMPARRAY output_buf,
  161109. JDIMENSION *out_row_ctr,
  161110. JDIMENSION out_rows_avail));
  161111. };
  161112. /* Marker reading & parsing */
  161113. struct jpeg_marker_reader {
  161114. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  161115. /* Read markers until SOS or EOI.
  161116. * Returns same codes as are defined for jpeg_consume_input:
  161117. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  161118. */
  161119. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  161120. /* Read a restart marker --- exported for use by entropy decoder only */
  161121. jpeg_marker_parser_method read_restart_marker;
  161122. /* State of marker reader --- nominally internal, but applications
  161123. * supplying COM or APPn handlers might like to know the state.
  161124. */
  161125. boolean saw_SOI; /* found SOI? */
  161126. boolean saw_SOF; /* found SOF? */
  161127. int next_restart_num; /* next restart number expected (0-7) */
  161128. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  161129. };
  161130. /* Entropy decoding */
  161131. struct jpeg_entropy_decoder {
  161132. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161133. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  161134. JBLOCKROW *MCU_data));
  161135. /* This is here to share code between baseline and progressive decoders; */
  161136. /* other modules probably should not use it */
  161137. boolean insufficient_data; /* set TRUE after emitting warning */
  161138. };
  161139. /* Inverse DCT (also performs dequantization) */
  161140. typedef JMETHOD(void, inverse_DCT_method_ptr,
  161141. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161142. JCOEFPTR coef_block,
  161143. JSAMPARRAY output_buf, JDIMENSION output_col));
  161144. struct jpeg_inverse_dct {
  161145. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161146. /* It is useful to allow each component to have a separate IDCT method. */
  161147. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  161148. };
  161149. /* Upsampling (note that upsampler must also call color converter) */
  161150. struct jpeg_upsampler {
  161151. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161152. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  161153. JSAMPIMAGE input_buf,
  161154. JDIMENSION *in_row_group_ctr,
  161155. JDIMENSION in_row_groups_avail,
  161156. JSAMPARRAY output_buf,
  161157. JDIMENSION *out_row_ctr,
  161158. JDIMENSION out_rows_avail));
  161159. boolean need_context_rows; /* TRUE if need rows above & below */
  161160. };
  161161. /* Colorspace conversion */
  161162. struct jpeg_color_deconverter {
  161163. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161164. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  161165. JSAMPIMAGE input_buf, JDIMENSION input_row,
  161166. JSAMPARRAY output_buf, int num_rows));
  161167. };
  161168. /* Color quantization or color precision reduction */
  161169. struct jpeg_color_quantizer {
  161170. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  161171. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  161172. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  161173. int num_rows));
  161174. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  161175. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  161176. };
  161177. /* Miscellaneous useful macros */
  161178. #undef MAX
  161179. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  161180. #undef MIN
  161181. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  161182. /* We assume that right shift corresponds to signed division by 2 with
  161183. * rounding towards minus infinity. This is correct for typical "arithmetic
  161184. * shift" instructions that shift in copies of the sign bit. But some
  161185. * C compilers implement >> with an unsigned shift. For these machines you
  161186. * must define RIGHT_SHIFT_IS_UNSIGNED.
  161187. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  161188. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  161189. * included in the variables of any routine using RIGHT_SHIFT.
  161190. */
  161191. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161192. #define SHIFT_TEMPS INT32 shift_temp;
  161193. #define RIGHT_SHIFT(x,shft) \
  161194. ((shift_temp = (x)) < 0 ? \
  161195. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  161196. (shift_temp >> (shft)))
  161197. #else
  161198. #define SHIFT_TEMPS
  161199. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  161200. #endif
  161201. /* Short forms of external names for systems with brain-damaged linkers. */
  161202. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161203. #define jinit_compress_master jICompress
  161204. #define jinit_c_master_control jICMaster
  161205. #define jinit_c_main_controller jICMainC
  161206. #define jinit_c_prep_controller jICPrepC
  161207. #define jinit_c_coef_controller jICCoefC
  161208. #define jinit_color_converter jICColor
  161209. #define jinit_downsampler jIDownsampler
  161210. #define jinit_forward_dct jIFDCT
  161211. #define jinit_huff_encoder jIHEncoder
  161212. #define jinit_phuff_encoder jIPHEncoder
  161213. #define jinit_marker_writer jIMWriter
  161214. #define jinit_master_decompress jIDMaster
  161215. #define jinit_d_main_controller jIDMainC
  161216. #define jinit_d_coef_controller jIDCoefC
  161217. #define jinit_d_post_controller jIDPostC
  161218. #define jinit_input_controller jIInCtlr
  161219. #define jinit_marker_reader jIMReader
  161220. #define jinit_huff_decoder jIHDecoder
  161221. #define jinit_phuff_decoder jIPHDecoder
  161222. #define jinit_inverse_dct jIIDCT
  161223. #define jinit_upsampler jIUpsampler
  161224. #define jinit_color_deconverter jIDColor
  161225. #define jinit_1pass_quantizer jI1Quant
  161226. #define jinit_2pass_quantizer jI2Quant
  161227. #define jinit_merged_upsampler jIMUpsampler
  161228. #define jinit_memory_mgr jIMemMgr
  161229. #define jdiv_round_up jDivRound
  161230. #define jround_up jRound
  161231. #define jcopy_sample_rows jCopySamples
  161232. #define jcopy_block_row jCopyBlocks
  161233. #define jzero_far jZeroFar
  161234. #define jpeg_zigzag_order jZIGTable
  161235. #define jpeg_natural_order jZAGTable
  161236. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161237. /* Compression module initialization routines */
  161238. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161239. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161240. boolean transcode_only));
  161241. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161242. boolean need_full_buffer));
  161243. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161244. boolean need_full_buffer));
  161245. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161246. boolean need_full_buffer));
  161247. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161248. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161249. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161250. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161251. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161252. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161253. /* Decompression module initialization routines */
  161254. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161255. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161256. boolean need_full_buffer));
  161257. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161258. boolean need_full_buffer));
  161259. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161260. boolean need_full_buffer));
  161261. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161262. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161263. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161264. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161265. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161266. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161267. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161268. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161269. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161270. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161271. /* Memory manager initialization */
  161272. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161273. /* Utility routines in jutils.c */
  161274. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161275. EXTERN(long) jround_up JPP((long a, long b));
  161276. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161277. JSAMPARRAY output_array, int dest_row,
  161278. int num_rows, JDIMENSION num_cols));
  161279. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161280. JDIMENSION num_blocks));
  161281. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161282. /* Constant tables in jutils.c */
  161283. #if 0 /* This table is not actually needed in v6a */
  161284. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161285. #endif
  161286. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161287. /* Suppress undefined-structure complaints if necessary. */
  161288. #ifdef INCOMPLETE_TYPES_BROKEN
  161289. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161290. struct jvirt_sarray_control { long dummy; };
  161291. struct jvirt_barray_control { long dummy; };
  161292. #endif
  161293. #endif /* INCOMPLETE_TYPES_BROKEN */
  161294. /*** End of inlined file: jpegint.h ***/
  161295. /* fetch private declarations */
  161296. /*** Start of inlined file: jerror.h ***/
  161297. /*
  161298. * To define the enum list of message codes, include this file without
  161299. * defining macro JMESSAGE. To create a message string table, include it
  161300. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161301. */
  161302. #ifndef JMESSAGE
  161303. #ifndef JERROR_H
  161304. /* First time through, define the enum list */
  161305. #define JMAKE_ENUM_LIST
  161306. #else
  161307. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161308. #define JMESSAGE(code,string)
  161309. #endif /* JERROR_H */
  161310. #endif /* JMESSAGE */
  161311. #ifdef JMAKE_ENUM_LIST
  161312. typedef enum {
  161313. #define JMESSAGE(code,string) code ,
  161314. #endif /* JMAKE_ENUM_LIST */
  161315. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161316. /* For maintenance convenience, list is alphabetical by message code name */
  161317. JMESSAGE(JERR_ARITH_NOTIMPL,
  161318. "Sorry, there are legal restrictions on arithmetic coding")
  161319. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161320. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161321. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161322. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161323. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161324. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161325. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161326. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161327. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161328. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161329. JMESSAGE(JERR_BAD_LIB_VERSION,
  161330. "Wrong JPEG library version: library is %d, caller expects %d")
  161331. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161332. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161333. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161334. JMESSAGE(JERR_BAD_PROGRESSION,
  161335. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161336. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161337. "Invalid progressive parameters at scan script entry %d")
  161338. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161339. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161340. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161341. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161342. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161343. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161344. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161345. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161346. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161347. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161348. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161349. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161350. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161351. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161352. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161353. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161354. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161355. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161356. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161357. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161358. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161359. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161360. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161361. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161362. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161363. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161364. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161365. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161366. "Cannot transcode due to multiple use of quantization table %d")
  161367. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161368. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161369. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161370. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161371. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161372. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161373. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161374. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161375. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161376. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161377. JMESSAGE(JERR_QUANT_COMPONENTS,
  161378. "Cannot quantize more than %d color components")
  161379. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161380. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161381. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161382. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161383. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161384. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161385. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161386. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161387. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161388. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161389. JMESSAGE(JERR_TFILE_WRITE,
  161390. "Write failed on temporary file --- out of disk space?")
  161391. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161392. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161393. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161394. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161395. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161396. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161397. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161398. JMESSAGE(JMSG_VERSION, JVERSION)
  161399. JMESSAGE(JTRC_16BIT_TABLES,
  161400. "Caution: quantization tables are too coarse for baseline JPEG")
  161401. JMESSAGE(JTRC_ADOBE,
  161402. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161403. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161404. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161405. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161406. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161407. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161408. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161409. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161410. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161411. JMESSAGE(JTRC_EOI, "End Of Image")
  161412. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161413. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161414. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161415. "Warning: thumbnail image size does not match data length %u")
  161416. JMESSAGE(JTRC_JFIF_EXTENSION,
  161417. "JFIF extension marker: type 0x%02x, length %u")
  161418. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161419. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161420. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161421. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161422. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161423. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161424. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161425. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161426. JMESSAGE(JTRC_RST, "RST%d")
  161427. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161428. "Smoothing not supported with nonstandard sampling ratios")
  161429. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161430. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161431. JMESSAGE(JTRC_SOI, "Start of Image")
  161432. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161433. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161434. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161435. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161436. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161437. JMESSAGE(JTRC_THUMB_JPEG,
  161438. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161439. JMESSAGE(JTRC_THUMB_PALETTE,
  161440. "JFIF extension marker: palette thumbnail image, length %u")
  161441. JMESSAGE(JTRC_THUMB_RGB,
  161442. "JFIF extension marker: RGB thumbnail image, length %u")
  161443. JMESSAGE(JTRC_UNKNOWN_IDS,
  161444. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161445. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161446. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161447. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161448. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161449. "Inconsistent progression sequence for component %d coefficient %d")
  161450. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161451. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161452. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161453. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161454. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161455. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161456. JMESSAGE(JWRN_MUST_RESYNC,
  161457. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161458. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161459. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161460. #ifdef JMAKE_ENUM_LIST
  161461. JMSG_LASTMSGCODE
  161462. } J_MESSAGE_CODE;
  161463. #undef JMAKE_ENUM_LIST
  161464. #endif /* JMAKE_ENUM_LIST */
  161465. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161466. #undef JMESSAGE
  161467. #ifndef JERROR_H
  161468. #define JERROR_H
  161469. /* Macros to simplify using the error and trace message stuff */
  161470. /* The first parameter is either type of cinfo pointer */
  161471. /* Fatal errors (print message and exit) */
  161472. #define ERREXIT(cinfo,code) \
  161473. ((cinfo)->err->msg_code = (code), \
  161474. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161475. #define ERREXIT1(cinfo,code,p1) \
  161476. ((cinfo)->err->msg_code = (code), \
  161477. (cinfo)->err->msg_parm.i[0] = (p1), \
  161478. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161479. #define ERREXIT2(cinfo,code,p1,p2) \
  161480. ((cinfo)->err->msg_code = (code), \
  161481. (cinfo)->err->msg_parm.i[0] = (p1), \
  161482. (cinfo)->err->msg_parm.i[1] = (p2), \
  161483. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161484. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161485. ((cinfo)->err->msg_code = (code), \
  161486. (cinfo)->err->msg_parm.i[0] = (p1), \
  161487. (cinfo)->err->msg_parm.i[1] = (p2), \
  161488. (cinfo)->err->msg_parm.i[2] = (p3), \
  161489. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161490. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161491. ((cinfo)->err->msg_code = (code), \
  161492. (cinfo)->err->msg_parm.i[0] = (p1), \
  161493. (cinfo)->err->msg_parm.i[1] = (p2), \
  161494. (cinfo)->err->msg_parm.i[2] = (p3), \
  161495. (cinfo)->err->msg_parm.i[3] = (p4), \
  161496. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161497. #define ERREXITS(cinfo,code,str) \
  161498. ((cinfo)->err->msg_code = (code), \
  161499. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161500. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161501. #define MAKESTMT(stuff) do { stuff } while (0)
  161502. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161503. #define WARNMS(cinfo,code) \
  161504. ((cinfo)->err->msg_code = (code), \
  161505. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161506. #define WARNMS1(cinfo,code,p1) \
  161507. ((cinfo)->err->msg_code = (code), \
  161508. (cinfo)->err->msg_parm.i[0] = (p1), \
  161509. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161510. #define WARNMS2(cinfo,code,p1,p2) \
  161511. ((cinfo)->err->msg_code = (code), \
  161512. (cinfo)->err->msg_parm.i[0] = (p1), \
  161513. (cinfo)->err->msg_parm.i[1] = (p2), \
  161514. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161515. /* Informational/debugging messages */
  161516. #define TRACEMS(cinfo,lvl,code) \
  161517. ((cinfo)->err->msg_code = (code), \
  161518. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161519. #define TRACEMS1(cinfo,lvl,code,p1) \
  161520. ((cinfo)->err->msg_code = (code), \
  161521. (cinfo)->err->msg_parm.i[0] = (p1), \
  161522. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161523. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161524. ((cinfo)->err->msg_code = (code), \
  161525. (cinfo)->err->msg_parm.i[0] = (p1), \
  161526. (cinfo)->err->msg_parm.i[1] = (p2), \
  161527. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161528. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161529. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161530. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161531. (cinfo)->err->msg_code = (code); \
  161532. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161533. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161534. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161535. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161536. (cinfo)->err->msg_code = (code); \
  161537. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161538. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161539. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161540. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161541. _mp[4] = (p5); \
  161542. (cinfo)->err->msg_code = (code); \
  161543. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161544. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161545. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161546. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161547. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161548. (cinfo)->err->msg_code = (code); \
  161549. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161550. #define TRACEMSS(cinfo,lvl,code,str) \
  161551. ((cinfo)->err->msg_code = (code), \
  161552. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161553. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161554. #endif /* JERROR_H */
  161555. /*** End of inlined file: jerror.h ***/
  161556. /* fetch error codes too */
  161557. #endif
  161558. #endif /* JPEGLIB_H */
  161559. /*** End of inlined file: jpeglib.h ***/
  161560. /*** Start of inlined file: jcapimin.c ***/
  161561. #define JPEG_INTERNALS
  161562. /*** Start of inlined file: jinclude.h ***/
  161563. /* Include auto-config file to find out which system include files we need. */
  161564. #ifndef __jinclude_h__
  161565. #define __jinclude_h__
  161566. /*** Start of inlined file: jconfig.h ***/
  161567. /* see jconfig.doc for explanations */
  161568. // disable all the warnings under MSVC
  161569. #ifdef _MSC_VER
  161570. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161571. #endif
  161572. #ifdef __BORLANDC__
  161573. #pragma warn -8057
  161574. #pragma warn -8019
  161575. #pragma warn -8004
  161576. #pragma warn -8008
  161577. #endif
  161578. #define HAVE_PROTOTYPES
  161579. #define HAVE_UNSIGNED_CHAR
  161580. #define HAVE_UNSIGNED_SHORT
  161581. /* #define void char */
  161582. /* #define const */
  161583. #undef CHAR_IS_UNSIGNED
  161584. #define HAVE_STDDEF_H
  161585. #define HAVE_STDLIB_H
  161586. #undef NEED_BSD_STRINGS
  161587. #undef NEED_SYS_TYPES_H
  161588. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161589. #undef NEED_SHORT_EXTERNAL_NAMES
  161590. #undef INCOMPLETE_TYPES_BROKEN
  161591. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161592. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161593. typedef unsigned char boolean;
  161594. #endif
  161595. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161596. #ifdef JPEG_INTERNALS
  161597. #undef RIGHT_SHIFT_IS_UNSIGNED
  161598. #endif /* JPEG_INTERNALS */
  161599. #ifdef JPEG_CJPEG_DJPEG
  161600. #define BMP_SUPPORTED /* BMP image file format */
  161601. #define GIF_SUPPORTED /* GIF image file format */
  161602. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161603. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161604. #define TARGA_SUPPORTED /* Targa image file format */
  161605. #define TWO_FILE_COMMANDLINE /* optional */
  161606. #define USE_SETMODE /* Microsoft has setmode() */
  161607. #undef NEED_SIGNAL_CATCHER
  161608. #undef DONT_USE_B_MODE
  161609. #undef PROGRESS_REPORT /* optional */
  161610. #endif /* JPEG_CJPEG_DJPEG */
  161611. /*** End of inlined file: jconfig.h ***/
  161612. /* auto configuration options */
  161613. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161614. /*
  161615. * We need the NULL macro and size_t typedef.
  161616. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161617. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161618. * pull in <sys/types.h> as well.
  161619. * Note that the core JPEG library does not require <stdio.h>;
  161620. * only the default error handler and data source/destination modules do.
  161621. * But we must pull it in because of the references to FILE in jpeglib.h.
  161622. * You can remove those references if you want to compile without <stdio.h>.
  161623. */
  161624. #ifdef HAVE_STDDEF_H
  161625. #include <stddef.h>
  161626. #endif
  161627. #ifdef HAVE_STDLIB_H
  161628. #include <stdlib.h>
  161629. #endif
  161630. #ifdef NEED_SYS_TYPES_H
  161631. #include <sys/types.h>
  161632. #endif
  161633. #include <stdio.h>
  161634. /*
  161635. * We need memory copying and zeroing functions, plus strncpy().
  161636. * ANSI and System V implementations declare these in <string.h>.
  161637. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161638. * Some systems may declare memset and memcpy in <memory.h>.
  161639. *
  161640. * NOTE: we assume the size parameters to these functions are of type size_t.
  161641. * Change the casts in these macros if not!
  161642. */
  161643. #ifdef NEED_BSD_STRINGS
  161644. #include <strings.h>
  161645. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161646. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161647. #else /* not BSD, assume ANSI/SysV string lib */
  161648. #include <string.h>
  161649. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161650. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161651. #endif
  161652. /*
  161653. * In ANSI C, and indeed any rational implementation, size_t is also the
  161654. * type returned by sizeof(). However, it seems there are some irrational
  161655. * implementations out there, in which sizeof() returns an int even though
  161656. * size_t is defined as long or unsigned long. To ensure consistent results
  161657. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161658. */
  161659. #define SIZEOF(object) ((size_t) sizeof(object))
  161660. /*
  161661. * The modules that use fread() and fwrite() always invoke them through
  161662. * these macros. On some systems you may need to twiddle the argument casts.
  161663. * CAUTION: argument order is different from underlying functions!
  161664. */
  161665. #define JFREAD(file,buf,sizeofbuf) \
  161666. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161667. #define JFWRITE(file,buf,sizeofbuf) \
  161668. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161669. typedef enum { /* JPEG marker codes */
  161670. M_SOF0 = 0xc0,
  161671. M_SOF1 = 0xc1,
  161672. M_SOF2 = 0xc2,
  161673. M_SOF3 = 0xc3,
  161674. M_SOF5 = 0xc5,
  161675. M_SOF6 = 0xc6,
  161676. M_SOF7 = 0xc7,
  161677. M_JPG = 0xc8,
  161678. M_SOF9 = 0xc9,
  161679. M_SOF10 = 0xca,
  161680. M_SOF11 = 0xcb,
  161681. M_SOF13 = 0xcd,
  161682. M_SOF14 = 0xce,
  161683. M_SOF15 = 0xcf,
  161684. M_DHT = 0xc4,
  161685. M_DAC = 0xcc,
  161686. M_RST0 = 0xd0,
  161687. M_RST1 = 0xd1,
  161688. M_RST2 = 0xd2,
  161689. M_RST3 = 0xd3,
  161690. M_RST4 = 0xd4,
  161691. M_RST5 = 0xd5,
  161692. M_RST6 = 0xd6,
  161693. M_RST7 = 0xd7,
  161694. M_SOI = 0xd8,
  161695. M_EOI = 0xd9,
  161696. M_SOS = 0xda,
  161697. M_DQT = 0xdb,
  161698. M_DNL = 0xdc,
  161699. M_DRI = 0xdd,
  161700. M_DHP = 0xde,
  161701. M_EXP = 0xdf,
  161702. M_APP0 = 0xe0,
  161703. M_APP1 = 0xe1,
  161704. M_APP2 = 0xe2,
  161705. M_APP3 = 0xe3,
  161706. M_APP4 = 0xe4,
  161707. M_APP5 = 0xe5,
  161708. M_APP6 = 0xe6,
  161709. M_APP7 = 0xe7,
  161710. M_APP8 = 0xe8,
  161711. M_APP9 = 0xe9,
  161712. M_APP10 = 0xea,
  161713. M_APP11 = 0xeb,
  161714. M_APP12 = 0xec,
  161715. M_APP13 = 0xed,
  161716. M_APP14 = 0xee,
  161717. M_APP15 = 0xef,
  161718. M_JPG0 = 0xf0,
  161719. M_JPG13 = 0xfd,
  161720. M_COM = 0xfe,
  161721. M_TEM = 0x01,
  161722. M_ERROR = 0x100
  161723. } JPEG_MARKER;
  161724. /*
  161725. * Figure F.12: extend sign bit.
  161726. * On some machines, a shift and add will be faster than a table lookup.
  161727. */
  161728. #ifdef AVOID_TABLES
  161729. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161730. #else
  161731. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161732. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161733. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161734. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161735. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161736. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161737. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161738. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161739. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161740. #endif /* AVOID_TABLES */
  161741. #endif
  161742. /*** End of inlined file: jinclude.h ***/
  161743. /*
  161744. * Initialization of a JPEG compression object.
  161745. * The error manager must already be set up (in case memory manager fails).
  161746. */
  161747. GLOBAL(void)
  161748. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161749. {
  161750. int i;
  161751. /* Guard against version mismatches between library and caller. */
  161752. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161753. if (version != JPEG_LIB_VERSION)
  161754. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161755. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161756. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161757. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161758. /* For debugging purposes, we zero the whole master structure.
  161759. * But the application has already set the err pointer, and may have set
  161760. * client_data, so we have to save and restore those fields.
  161761. * Note: if application hasn't set client_data, tools like Purify may
  161762. * complain here.
  161763. */
  161764. {
  161765. struct jpeg_error_mgr * err = cinfo->err;
  161766. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161767. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161768. cinfo->err = err;
  161769. cinfo->client_data = client_data;
  161770. }
  161771. cinfo->is_decompressor = FALSE;
  161772. /* Initialize a memory manager instance for this object */
  161773. jinit_memory_mgr((j_common_ptr) cinfo);
  161774. /* Zero out pointers to permanent structures. */
  161775. cinfo->progress = NULL;
  161776. cinfo->dest = NULL;
  161777. cinfo->comp_info = NULL;
  161778. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161779. cinfo->quant_tbl_ptrs[i] = NULL;
  161780. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161781. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161782. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161783. }
  161784. cinfo->script_space = NULL;
  161785. cinfo->input_gamma = 1.0; /* in case application forgets */
  161786. /* OK, I'm ready */
  161787. cinfo->global_state = CSTATE_START;
  161788. }
  161789. /*
  161790. * Destruction of a JPEG compression object
  161791. */
  161792. GLOBAL(void)
  161793. jpeg_destroy_compress (j_compress_ptr cinfo)
  161794. {
  161795. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161796. }
  161797. /*
  161798. * Abort processing of a JPEG compression operation,
  161799. * but don't destroy the object itself.
  161800. */
  161801. GLOBAL(void)
  161802. jpeg_abort_compress (j_compress_ptr cinfo)
  161803. {
  161804. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161805. }
  161806. /*
  161807. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161808. * Marks all currently defined tables as already written (if suppress)
  161809. * or not written (if !suppress). This will control whether they get emitted
  161810. * by a subsequent jpeg_start_compress call.
  161811. *
  161812. * This routine is exported for use by applications that want to produce
  161813. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161814. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161815. * jcparam.o would be linked whether the application used it or not.
  161816. */
  161817. GLOBAL(void)
  161818. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161819. {
  161820. int i;
  161821. JQUANT_TBL * qtbl;
  161822. JHUFF_TBL * htbl;
  161823. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161824. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161825. qtbl->sent_table = suppress;
  161826. }
  161827. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161828. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161829. htbl->sent_table = suppress;
  161830. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161831. htbl->sent_table = suppress;
  161832. }
  161833. }
  161834. /*
  161835. * Finish JPEG compression.
  161836. *
  161837. * If a multipass operating mode was selected, this may do a great deal of
  161838. * work including most of the actual output.
  161839. */
  161840. GLOBAL(void)
  161841. jpeg_finish_compress (j_compress_ptr cinfo)
  161842. {
  161843. JDIMENSION iMCU_row;
  161844. if (cinfo->global_state == CSTATE_SCANNING ||
  161845. cinfo->global_state == CSTATE_RAW_OK) {
  161846. /* Terminate first pass */
  161847. if (cinfo->next_scanline < cinfo->image_height)
  161848. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161849. (*cinfo->master->finish_pass) (cinfo);
  161850. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161851. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161852. /* Perform any remaining passes */
  161853. while (! cinfo->master->is_last_pass) {
  161854. (*cinfo->master->prepare_for_pass) (cinfo);
  161855. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161856. if (cinfo->progress != NULL) {
  161857. cinfo->progress->pass_counter = (long) iMCU_row;
  161858. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161859. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161860. }
  161861. /* We bypass the main controller and invoke coef controller directly;
  161862. * all work is being done from the coefficient buffer.
  161863. */
  161864. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161865. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161866. }
  161867. (*cinfo->master->finish_pass) (cinfo);
  161868. }
  161869. /* Write EOI, do final cleanup */
  161870. (*cinfo->marker->write_file_trailer) (cinfo);
  161871. (*cinfo->dest->term_destination) (cinfo);
  161872. /* We can use jpeg_abort to release memory and reset global_state */
  161873. jpeg_abort((j_common_ptr) cinfo);
  161874. }
  161875. /*
  161876. * Write a special marker.
  161877. * This is only recommended for writing COM or APPn markers.
  161878. * Must be called after jpeg_start_compress() and before
  161879. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161880. */
  161881. GLOBAL(void)
  161882. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161883. const JOCTET *dataptr, unsigned int datalen)
  161884. {
  161885. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161886. if (cinfo->next_scanline != 0 ||
  161887. (cinfo->global_state != CSTATE_SCANNING &&
  161888. cinfo->global_state != CSTATE_RAW_OK &&
  161889. cinfo->global_state != CSTATE_WRCOEFS))
  161890. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161891. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161892. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161893. while (datalen--) {
  161894. (*write_marker_byte) (cinfo, *dataptr);
  161895. dataptr++;
  161896. }
  161897. }
  161898. /* Same, but piecemeal. */
  161899. GLOBAL(void)
  161900. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161901. {
  161902. if (cinfo->next_scanline != 0 ||
  161903. (cinfo->global_state != CSTATE_SCANNING &&
  161904. cinfo->global_state != CSTATE_RAW_OK &&
  161905. cinfo->global_state != CSTATE_WRCOEFS))
  161906. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161907. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161908. }
  161909. GLOBAL(void)
  161910. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161911. {
  161912. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161913. }
  161914. /*
  161915. * Alternate compression function: just write an abbreviated table file.
  161916. * Before calling this, all parameters and a data destination must be set up.
  161917. *
  161918. * To produce a pair of files containing abbreviated tables and abbreviated
  161919. * image data, one would proceed as follows:
  161920. *
  161921. * initialize JPEG object
  161922. * set JPEG parameters
  161923. * set destination to table file
  161924. * jpeg_write_tables(cinfo);
  161925. * set destination to image file
  161926. * jpeg_start_compress(cinfo, FALSE);
  161927. * write data...
  161928. * jpeg_finish_compress(cinfo);
  161929. *
  161930. * jpeg_write_tables has the side effect of marking all tables written
  161931. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161932. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161933. */
  161934. GLOBAL(void)
  161935. jpeg_write_tables (j_compress_ptr cinfo)
  161936. {
  161937. if (cinfo->global_state != CSTATE_START)
  161938. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161939. /* (Re)initialize error mgr and destination modules */
  161940. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161941. (*cinfo->dest->init_destination) (cinfo);
  161942. /* Initialize the marker writer ... bit of a crock to do it here. */
  161943. jinit_marker_writer(cinfo);
  161944. /* Write them tables! */
  161945. (*cinfo->marker->write_tables_only) (cinfo);
  161946. /* And clean up. */
  161947. (*cinfo->dest->term_destination) (cinfo);
  161948. /*
  161949. * In library releases up through v6a, we called jpeg_abort() here to free
  161950. * any working memory allocated by the destination manager and marker
  161951. * writer. Some applications had a problem with that: they allocated space
  161952. * of their own from the library memory manager, and didn't want it to go
  161953. * away during write_tables. So now we do nothing. This will cause a
  161954. * memory leak if an app calls write_tables repeatedly without doing a full
  161955. * compression cycle or otherwise resetting the JPEG object. However, that
  161956. * seems less bad than unexpectedly freeing memory in the normal case.
  161957. * An app that prefers the old behavior can call jpeg_abort for itself after
  161958. * each call to jpeg_write_tables().
  161959. */
  161960. }
  161961. /*** End of inlined file: jcapimin.c ***/
  161962. /*** Start of inlined file: jcapistd.c ***/
  161963. #define JPEG_INTERNALS
  161964. /*
  161965. * Compression initialization.
  161966. * Before calling this, all parameters and a data destination must be set up.
  161967. *
  161968. * We require a write_all_tables parameter as a failsafe check when writing
  161969. * multiple datastreams from the same compression object. Since prior runs
  161970. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161971. * would emit an abbreviated stream (no tables) by default. This may be what
  161972. * is wanted, but for safety's sake it should not be the default behavior:
  161973. * programmers should have to make a deliberate choice to emit abbreviated
  161974. * images. Therefore the documentation and examples should encourage people
  161975. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161976. * wrong thing.
  161977. */
  161978. GLOBAL(void)
  161979. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161980. {
  161981. if (cinfo->global_state != CSTATE_START)
  161982. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161983. if (write_all_tables)
  161984. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161985. /* (Re)initialize error mgr and destination modules */
  161986. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161987. (*cinfo->dest->init_destination) (cinfo);
  161988. /* Perform master selection of active modules */
  161989. jinit_compress_master(cinfo);
  161990. /* Set up for the first pass */
  161991. (*cinfo->master->prepare_for_pass) (cinfo);
  161992. /* Ready for application to drive first pass through jpeg_write_scanlines
  161993. * or jpeg_write_raw_data.
  161994. */
  161995. cinfo->next_scanline = 0;
  161996. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161997. }
  161998. /*
  161999. * Write some scanlines of data to the JPEG compressor.
  162000. *
  162001. * The return value will be the number of lines actually written.
  162002. * This should be less than the supplied num_lines only in case that
  162003. * the data destination module has requested suspension of the compressor,
  162004. * or if more than image_height scanlines are passed in.
  162005. *
  162006. * Note: we warn about excess calls to jpeg_write_scanlines() since
  162007. * this likely signals an application programmer error. However,
  162008. * excess scanlines passed in the last valid call are *silently* ignored,
  162009. * so that the application need not adjust num_lines for end-of-image
  162010. * when using a multiple-scanline buffer.
  162011. */
  162012. GLOBAL(JDIMENSION)
  162013. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  162014. JDIMENSION num_lines)
  162015. {
  162016. JDIMENSION row_ctr, rows_left;
  162017. if (cinfo->global_state != CSTATE_SCANNING)
  162018. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162019. if (cinfo->next_scanline >= cinfo->image_height)
  162020. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162021. /* Call progress monitor hook if present */
  162022. if (cinfo->progress != NULL) {
  162023. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162024. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162025. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162026. }
  162027. /* Give master control module another chance if this is first call to
  162028. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  162029. * delayed so that application can write COM, etc, markers between
  162030. * jpeg_start_compress and jpeg_write_scanlines.
  162031. */
  162032. if (cinfo->master->call_pass_startup)
  162033. (*cinfo->master->pass_startup) (cinfo);
  162034. /* Ignore any extra scanlines at bottom of image. */
  162035. rows_left = cinfo->image_height - cinfo->next_scanline;
  162036. if (num_lines > rows_left)
  162037. num_lines = rows_left;
  162038. row_ctr = 0;
  162039. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  162040. cinfo->next_scanline += row_ctr;
  162041. return row_ctr;
  162042. }
  162043. /*
  162044. * Alternate entry point to write raw data.
  162045. * Processes exactly one iMCU row per call, unless suspended.
  162046. */
  162047. GLOBAL(JDIMENSION)
  162048. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  162049. JDIMENSION num_lines)
  162050. {
  162051. JDIMENSION lines_per_iMCU_row;
  162052. if (cinfo->global_state != CSTATE_RAW_OK)
  162053. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162054. if (cinfo->next_scanline >= cinfo->image_height) {
  162055. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162056. return 0;
  162057. }
  162058. /* Call progress monitor hook if present */
  162059. if (cinfo->progress != NULL) {
  162060. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162061. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162062. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162063. }
  162064. /* Give master control module another chance if this is first call to
  162065. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  162066. * delayed so that application can write COM, etc, markers between
  162067. * jpeg_start_compress and jpeg_write_raw_data.
  162068. */
  162069. if (cinfo->master->call_pass_startup)
  162070. (*cinfo->master->pass_startup) (cinfo);
  162071. /* Verify that at least one iMCU row has been passed. */
  162072. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  162073. if (num_lines < lines_per_iMCU_row)
  162074. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  162075. /* Directly compress the row. */
  162076. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  162077. /* If compressor did not consume the whole row, suspend processing. */
  162078. return 0;
  162079. }
  162080. /* OK, we processed one iMCU row. */
  162081. cinfo->next_scanline += lines_per_iMCU_row;
  162082. return lines_per_iMCU_row;
  162083. }
  162084. /*** End of inlined file: jcapistd.c ***/
  162085. /*** Start of inlined file: jccoefct.c ***/
  162086. #define JPEG_INTERNALS
  162087. /* We use a full-image coefficient buffer when doing Huffman optimization,
  162088. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  162089. * step is run during the first pass, and subsequent passes need only read
  162090. * the buffered coefficients.
  162091. */
  162092. #ifdef ENTROPY_OPT_SUPPORTED
  162093. #define FULL_COEF_BUFFER_SUPPORTED
  162094. #else
  162095. #ifdef C_MULTISCAN_FILES_SUPPORTED
  162096. #define FULL_COEF_BUFFER_SUPPORTED
  162097. #endif
  162098. #endif
  162099. /* Private buffer controller object */
  162100. typedef struct {
  162101. struct jpeg_c_coef_controller pub; /* public fields */
  162102. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162103. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162104. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162105. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162106. /* For single-pass compression, it's sufficient to buffer just one MCU
  162107. * (although this may prove a bit slow in practice). We allocate a
  162108. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  162109. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  162110. * it's not really very big; this is to keep the module interfaces unchanged
  162111. * when a large coefficient buffer is necessary.)
  162112. * In multi-pass modes, this array points to the current MCU's blocks
  162113. * within the virtual arrays.
  162114. */
  162115. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162116. /* In multi-pass modes, we need a virtual block array for each component. */
  162117. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162118. } my_coef_controller;
  162119. typedef my_coef_controller * my_coef_ptr;
  162120. /* Forward declarations */
  162121. METHODDEF(boolean) compress_data
  162122. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162123. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162124. METHODDEF(boolean) compress_first_pass
  162125. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162126. METHODDEF(boolean) compress_output
  162127. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162128. #endif
  162129. LOCAL(void)
  162130. start_iMCU_row (j_compress_ptr cinfo)
  162131. /* Reset within-iMCU-row counters for a new row */
  162132. {
  162133. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162134. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162135. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162136. * But at the bottom of the image, process only what's left.
  162137. */
  162138. if (cinfo->comps_in_scan > 1) {
  162139. coef->MCU_rows_per_iMCU_row = 1;
  162140. } else {
  162141. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162142. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162143. else
  162144. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162145. }
  162146. coef->mcu_ctr = 0;
  162147. coef->MCU_vert_offset = 0;
  162148. }
  162149. /*
  162150. * Initialize for a processing pass.
  162151. */
  162152. METHODDEF(void)
  162153. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162154. {
  162155. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162156. coef->iMCU_row_num = 0;
  162157. start_iMCU_row(cinfo);
  162158. switch (pass_mode) {
  162159. case JBUF_PASS_THRU:
  162160. if (coef->whole_image[0] != NULL)
  162161. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162162. coef->pub.compress_data = compress_data;
  162163. break;
  162164. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162165. case JBUF_SAVE_AND_PASS:
  162166. if (coef->whole_image[0] == NULL)
  162167. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162168. coef->pub.compress_data = compress_first_pass;
  162169. break;
  162170. case JBUF_CRANK_DEST:
  162171. if (coef->whole_image[0] == NULL)
  162172. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162173. coef->pub.compress_data = compress_output;
  162174. break;
  162175. #endif
  162176. default:
  162177. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162178. break;
  162179. }
  162180. }
  162181. /*
  162182. * Process some data in the single-pass case.
  162183. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162184. * per call, ie, v_samp_factor block rows for each component in the image.
  162185. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162186. *
  162187. * NB: input_buf contains a plane for each component in image,
  162188. * which we index according to the component's SOF position.
  162189. */
  162190. METHODDEF(boolean)
  162191. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162192. {
  162193. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162194. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162195. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162196. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162197. int blkn, bi, ci, yindex, yoffset, blockcnt;
  162198. JDIMENSION ypos, xpos;
  162199. jpeg_component_info *compptr;
  162200. /* Loop to write as much as one whole iMCU row */
  162201. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162202. yoffset++) {
  162203. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162204. MCU_col_num++) {
  162205. /* Determine where data comes from in input_buf and do the DCT thing.
  162206. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162207. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162208. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162209. * specially. The data in them does not matter for image reconstruction,
  162210. * so we fill them with values that will encode to the smallest amount of
  162211. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162212. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162213. */
  162214. blkn = 0;
  162215. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162216. compptr = cinfo->cur_comp_info[ci];
  162217. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162218. : compptr->last_col_width;
  162219. xpos = MCU_col_num * compptr->MCU_sample_width;
  162220. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162221. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162222. if (coef->iMCU_row_num < last_iMCU_row ||
  162223. yoffset+yindex < compptr->last_row_height) {
  162224. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162225. input_buf[compptr->component_index],
  162226. coef->MCU_buffer[blkn],
  162227. ypos, xpos, (JDIMENSION) blockcnt);
  162228. if (blockcnt < compptr->MCU_width) {
  162229. /* Create some dummy blocks at the right edge of the image. */
  162230. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162231. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162232. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162233. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162234. }
  162235. }
  162236. } else {
  162237. /* Create a row of dummy blocks at the bottom of the image. */
  162238. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162239. compptr->MCU_width * SIZEOF(JBLOCK));
  162240. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162241. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162242. }
  162243. }
  162244. blkn += compptr->MCU_width;
  162245. ypos += DCTSIZE;
  162246. }
  162247. }
  162248. /* Try to write the MCU. In event of a suspension failure, we will
  162249. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162250. */
  162251. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162252. /* Suspension forced; update state counters and exit */
  162253. coef->MCU_vert_offset = yoffset;
  162254. coef->mcu_ctr = MCU_col_num;
  162255. return FALSE;
  162256. }
  162257. }
  162258. /* Completed an MCU row, but perhaps not an iMCU row */
  162259. coef->mcu_ctr = 0;
  162260. }
  162261. /* Completed the iMCU row, advance counters for next one */
  162262. coef->iMCU_row_num++;
  162263. start_iMCU_row(cinfo);
  162264. return TRUE;
  162265. }
  162266. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162267. /*
  162268. * Process some data in the first pass of a multi-pass case.
  162269. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162270. * per call, ie, v_samp_factor block rows for each component in the image.
  162271. * This amount of data is read from the source buffer, DCT'd and quantized,
  162272. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162273. * as needed at the right and lower edges. (The dummy blocks are constructed
  162274. * in the virtual arrays, which have been padded appropriately.) This makes
  162275. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162276. *
  162277. * We must also emit the data to the entropy encoder. This is conveniently
  162278. * done by calling compress_output() after we've loaded the current strip
  162279. * of the virtual arrays.
  162280. *
  162281. * NB: input_buf contains a plane for each component in image. All
  162282. * components are DCT'd and loaded into the virtual arrays in this pass.
  162283. * However, it may be that only a subset of the components are emitted to
  162284. * the entropy encoder during this first pass; be careful about looking
  162285. * at the scan-dependent variables (MCU dimensions, etc).
  162286. */
  162287. METHODDEF(boolean)
  162288. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162289. {
  162290. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162291. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162292. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162293. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162294. JCOEF lastDC;
  162295. jpeg_component_info *compptr;
  162296. JBLOCKARRAY buffer;
  162297. JBLOCKROW thisblockrow, lastblockrow;
  162298. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162299. ci++, compptr++) {
  162300. /* Align the virtual buffer for this component. */
  162301. buffer = (*cinfo->mem->access_virt_barray)
  162302. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162303. coef->iMCU_row_num * compptr->v_samp_factor,
  162304. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162305. /* Count non-dummy DCT block rows in this iMCU row. */
  162306. if (coef->iMCU_row_num < last_iMCU_row)
  162307. block_rows = compptr->v_samp_factor;
  162308. else {
  162309. /* NB: can't use last_row_height here, since may not be set! */
  162310. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162311. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162312. }
  162313. blocks_across = compptr->width_in_blocks;
  162314. h_samp_factor = compptr->h_samp_factor;
  162315. /* Count number of dummy blocks to be added at the right margin. */
  162316. ndummy = (int) (blocks_across % h_samp_factor);
  162317. if (ndummy > 0)
  162318. ndummy = h_samp_factor - ndummy;
  162319. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162320. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162321. */
  162322. for (block_row = 0; block_row < block_rows; block_row++) {
  162323. thisblockrow = buffer[block_row];
  162324. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162325. input_buf[ci], thisblockrow,
  162326. (JDIMENSION) (block_row * DCTSIZE),
  162327. (JDIMENSION) 0, blocks_across);
  162328. if (ndummy > 0) {
  162329. /* Create dummy blocks at the right edge of the image. */
  162330. thisblockrow += blocks_across; /* => first dummy block */
  162331. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162332. lastDC = thisblockrow[-1][0];
  162333. for (bi = 0; bi < ndummy; bi++) {
  162334. thisblockrow[bi][0] = lastDC;
  162335. }
  162336. }
  162337. }
  162338. /* If at end of image, create dummy block rows as needed.
  162339. * The tricky part here is that within each MCU, we want the DC values
  162340. * of the dummy blocks to match the last real block's DC value.
  162341. * This squeezes a few more bytes out of the resulting file...
  162342. */
  162343. if (coef->iMCU_row_num == last_iMCU_row) {
  162344. blocks_across += ndummy; /* include lower right corner */
  162345. MCUs_across = blocks_across / h_samp_factor;
  162346. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162347. block_row++) {
  162348. thisblockrow = buffer[block_row];
  162349. lastblockrow = buffer[block_row-1];
  162350. jzero_far((void FAR *) thisblockrow,
  162351. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162352. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162353. lastDC = lastblockrow[h_samp_factor-1][0];
  162354. for (bi = 0; bi < h_samp_factor; bi++) {
  162355. thisblockrow[bi][0] = lastDC;
  162356. }
  162357. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162358. lastblockrow += h_samp_factor;
  162359. }
  162360. }
  162361. }
  162362. }
  162363. /* NB: compress_output will increment iMCU_row_num if successful.
  162364. * A suspension return will result in redoing all the work above next time.
  162365. */
  162366. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162367. return compress_output(cinfo, input_buf);
  162368. }
  162369. /*
  162370. * Process some data in subsequent passes of a multi-pass case.
  162371. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162372. * per call, ie, v_samp_factor block rows for each component in the scan.
  162373. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162374. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162375. *
  162376. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162377. */
  162378. METHODDEF(boolean)
  162379. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162380. {
  162381. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162382. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162383. int blkn, ci, xindex, yindex, yoffset;
  162384. JDIMENSION start_col;
  162385. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162386. JBLOCKROW buffer_ptr;
  162387. jpeg_component_info *compptr;
  162388. /* Align the virtual buffers for the components used in this scan.
  162389. * NB: during first pass, this is safe only because the buffers will
  162390. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162391. */
  162392. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162393. compptr = cinfo->cur_comp_info[ci];
  162394. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162395. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162396. coef->iMCU_row_num * compptr->v_samp_factor,
  162397. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162398. }
  162399. /* Loop to process one whole iMCU row */
  162400. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162401. yoffset++) {
  162402. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162403. MCU_col_num++) {
  162404. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162405. blkn = 0; /* index of current DCT block within MCU */
  162406. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162407. compptr = cinfo->cur_comp_info[ci];
  162408. start_col = MCU_col_num * compptr->MCU_width;
  162409. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162410. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162411. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162412. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162413. }
  162414. }
  162415. }
  162416. /* Try to write the MCU. */
  162417. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162418. /* Suspension forced; update state counters and exit */
  162419. coef->MCU_vert_offset = yoffset;
  162420. coef->mcu_ctr = MCU_col_num;
  162421. return FALSE;
  162422. }
  162423. }
  162424. /* Completed an MCU row, but perhaps not an iMCU row */
  162425. coef->mcu_ctr = 0;
  162426. }
  162427. /* Completed the iMCU row, advance counters for next one */
  162428. coef->iMCU_row_num++;
  162429. start_iMCU_row(cinfo);
  162430. return TRUE;
  162431. }
  162432. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162433. /*
  162434. * Initialize coefficient buffer controller.
  162435. */
  162436. GLOBAL(void)
  162437. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162438. {
  162439. my_coef_ptr coef;
  162440. coef = (my_coef_ptr)
  162441. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162442. SIZEOF(my_coef_controller));
  162443. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162444. coef->pub.start_pass = start_pass_coef;
  162445. /* Create the coefficient buffer. */
  162446. if (need_full_buffer) {
  162447. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162448. /* Allocate a full-image virtual array for each component, */
  162449. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162450. int ci;
  162451. jpeg_component_info *compptr;
  162452. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162453. ci++, compptr++) {
  162454. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162455. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162456. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162457. (long) compptr->h_samp_factor),
  162458. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162459. (long) compptr->v_samp_factor),
  162460. (JDIMENSION) compptr->v_samp_factor);
  162461. }
  162462. #else
  162463. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162464. #endif
  162465. } else {
  162466. /* We only need a single-MCU buffer. */
  162467. JBLOCKROW buffer;
  162468. int i;
  162469. buffer = (JBLOCKROW)
  162470. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162471. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162472. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162473. coef->MCU_buffer[i] = buffer + i;
  162474. }
  162475. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162476. }
  162477. }
  162478. /*** End of inlined file: jccoefct.c ***/
  162479. /*** Start of inlined file: jccolor.c ***/
  162480. #define JPEG_INTERNALS
  162481. /* Private subobject */
  162482. typedef struct {
  162483. struct jpeg_color_converter pub; /* public fields */
  162484. /* Private state for RGB->YCC conversion */
  162485. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162486. } my_color_converter;
  162487. typedef my_color_converter * my_cconvert_ptr;
  162488. /**************** RGB -> YCbCr conversion: most common case **************/
  162489. /*
  162490. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162491. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162492. * The conversion equations to be implemented are therefore
  162493. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162494. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162495. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162496. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162497. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162498. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162499. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162500. * were not represented exactly. Now we sacrifice exact representation of
  162501. * maximum red and maximum blue in order to get exact grayscales.
  162502. *
  162503. * To avoid floating-point arithmetic, we represent the fractional constants
  162504. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162505. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162506. *
  162507. * For even more speed, we avoid doing any multiplications in the inner loop
  162508. * by precalculating the constants times R,G,B for all possible values.
  162509. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162510. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162511. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162512. * colorspace anyway.
  162513. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162514. * in the tables to save adding them separately in the inner loop.
  162515. */
  162516. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162517. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162518. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162519. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162520. /* We allocate one big table and divide it up into eight parts, instead of
  162521. * doing eight alloc_small requests. This lets us use a single table base
  162522. * address, which can be held in a register in the inner loops on many
  162523. * machines (more than can hold all eight addresses, anyway).
  162524. */
  162525. #define R_Y_OFF 0 /* offset to R => Y section */
  162526. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162527. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162528. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162529. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162530. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162531. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162532. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162533. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162534. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162535. /*
  162536. * Initialize for RGB->YCC colorspace conversion.
  162537. */
  162538. METHODDEF(void)
  162539. rgb_ycc_start (j_compress_ptr cinfo)
  162540. {
  162541. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162542. INT32 * rgb_ycc_tab;
  162543. INT32 i;
  162544. /* Allocate and fill in the conversion tables. */
  162545. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162546. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162547. (TABLE_SIZE * SIZEOF(INT32)));
  162548. for (i = 0; i <= MAXJSAMPLE; i++) {
  162549. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162550. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162551. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162552. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162553. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162554. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162555. * This ensures that the maximum output will round to MAXJSAMPLE
  162556. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162557. */
  162558. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162559. /* B=>Cb and R=>Cr tables are the same
  162560. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162561. */
  162562. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162563. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162564. }
  162565. }
  162566. /*
  162567. * Convert some rows of samples to the JPEG colorspace.
  162568. *
  162569. * Note that we change from the application's interleaved-pixel format
  162570. * to our internal noninterleaved, one-plane-per-component format.
  162571. * The input buffer is therefore three times as wide as the output buffer.
  162572. *
  162573. * A starting row offset is provided only for the output buffer. The caller
  162574. * can easily adjust the passed input_buf value to accommodate any row
  162575. * offset required on that side.
  162576. */
  162577. METHODDEF(void)
  162578. rgb_ycc_convert (j_compress_ptr cinfo,
  162579. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162580. JDIMENSION output_row, int num_rows)
  162581. {
  162582. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162583. register int r, g, b;
  162584. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162585. register JSAMPROW inptr;
  162586. register JSAMPROW outptr0, outptr1, outptr2;
  162587. register JDIMENSION col;
  162588. JDIMENSION num_cols = cinfo->image_width;
  162589. while (--num_rows >= 0) {
  162590. inptr = *input_buf++;
  162591. outptr0 = output_buf[0][output_row];
  162592. outptr1 = output_buf[1][output_row];
  162593. outptr2 = output_buf[2][output_row];
  162594. output_row++;
  162595. for (col = 0; col < num_cols; col++) {
  162596. r = GETJSAMPLE(inptr[RGB_RED]);
  162597. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162598. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162599. inptr += RGB_PIXELSIZE;
  162600. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162601. * must be too; we do not need an explicit range-limiting operation.
  162602. * Hence the value being shifted is never negative, and we don't
  162603. * need the general RIGHT_SHIFT macro.
  162604. */
  162605. /* Y */
  162606. outptr0[col] = (JSAMPLE)
  162607. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162608. >> SCALEBITS);
  162609. /* Cb */
  162610. outptr1[col] = (JSAMPLE)
  162611. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162612. >> SCALEBITS);
  162613. /* Cr */
  162614. outptr2[col] = (JSAMPLE)
  162615. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162616. >> SCALEBITS);
  162617. }
  162618. }
  162619. }
  162620. /**************** Cases other than RGB -> YCbCr **************/
  162621. /*
  162622. * Convert some rows of samples to the JPEG colorspace.
  162623. * This version handles RGB->grayscale conversion, which is the same
  162624. * as the RGB->Y portion of RGB->YCbCr.
  162625. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162626. */
  162627. METHODDEF(void)
  162628. rgb_gray_convert (j_compress_ptr cinfo,
  162629. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162630. JDIMENSION output_row, int num_rows)
  162631. {
  162632. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162633. register int r, g, b;
  162634. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162635. register JSAMPROW inptr;
  162636. register JSAMPROW outptr;
  162637. register JDIMENSION col;
  162638. JDIMENSION num_cols = cinfo->image_width;
  162639. while (--num_rows >= 0) {
  162640. inptr = *input_buf++;
  162641. outptr = output_buf[0][output_row];
  162642. output_row++;
  162643. for (col = 0; col < num_cols; col++) {
  162644. r = GETJSAMPLE(inptr[RGB_RED]);
  162645. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162646. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162647. inptr += RGB_PIXELSIZE;
  162648. /* Y */
  162649. outptr[col] = (JSAMPLE)
  162650. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162651. >> SCALEBITS);
  162652. }
  162653. }
  162654. }
  162655. /*
  162656. * Convert some rows of samples to the JPEG colorspace.
  162657. * This version handles Adobe-style CMYK->YCCK conversion,
  162658. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162659. * conversion as above, while passing K (black) unchanged.
  162660. * We assume rgb_ycc_start has been called.
  162661. */
  162662. METHODDEF(void)
  162663. cmyk_ycck_convert (j_compress_ptr cinfo,
  162664. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162665. JDIMENSION output_row, int num_rows)
  162666. {
  162667. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162668. register int r, g, b;
  162669. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162670. register JSAMPROW inptr;
  162671. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162672. register JDIMENSION col;
  162673. JDIMENSION num_cols = cinfo->image_width;
  162674. while (--num_rows >= 0) {
  162675. inptr = *input_buf++;
  162676. outptr0 = output_buf[0][output_row];
  162677. outptr1 = output_buf[1][output_row];
  162678. outptr2 = output_buf[2][output_row];
  162679. outptr3 = output_buf[3][output_row];
  162680. output_row++;
  162681. for (col = 0; col < num_cols; col++) {
  162682. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162683. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162684. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162685. /* K passes through as-is */
  162686. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162687. inptr += 4;
  162688. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162689. * must be too; we do not need an explicit range-limiting operation.
  162690. * Hence the value being shifted is never negative, and we don't
  162691. * need the general RIGHT_SHIFT macro.
  162692. */
  162693. /* Y */
  162694. outptr0[col] = (JSAMPLE)
  162695. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162696. >> SCALEBITS);
  162697. /* Cb */
  162698. outptr1[col] = (JSAMPLE)
  162699. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162700. >> SCALEBITS);
  162701. /* Cr */
  162702. outptr2[col] = (JSAMPLE)
  162703. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162704. >> SCALEBITS);
  162705. }
  162706. }
  162707. }
  162708. /*
  162709. * Convert some rows of samples to the JPEG colorspace.
  162710. * This version handles grayscale output with no conversion.
  162711. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162712. */
  162713. METHODDEF(void)
  162714. grayscale_convert (j_compress_ptr cinfo,
  162715. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162716. JDIMENSION output_row, int num_rows)
  162717. {
  162718. register JSAMPROW inptr;
  162719. register JSAMPROW outptr;
  162720. register JDIMENSION col;
  162721. JDIMENSION num_cols = cinfo->image_width;
  162722. int instride = cinfo->input_components;
  162723. while (--num_rows >= 0) {
  162724. inptr = *input_buf++;
  162725. outptr = output_buf[0][output_row];
  162726. output_row++;
  162727. for (col = 0; col < num_cols; col++) {
  162728. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162729. inptr += instride;
  162730. }
  162731. }
  162732. }
  162733. /*
  162734. * Convert some rows of samples to the JPEG colorspace.
  162735. * This version handles multi-component colorspaces without conversion.
  162736. * We assume input_components == num_components.
  162737. */
  162738. METHODDEF(void)
  162739. null_convert (j_compress_ptr cinfo,
  162740. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162741. JDIMENSION output_row, int num_rows)
  162742. {
  162743. register JSAMPROW inptr;
  162744. register JSAMPROW outptr;
  162745. register JDIMENSION col;
  162746. register int ci;
  162747. int nc = cinfo->num_components;
  162748. JDIMENSION num_cols = cinfo->image_width;
  162749. while (--num_rows >= 0) {
  162750. /* It seems fastest to make a separate pass for each component. */
  162751. for (ci = 0; ci < nc; ci++) {
  162752. inptr = *input_buf;
  162753. outptr = output_buf[ci][output_row];
  162754. for (col = 0; col < num_cols; col++) {
  162755. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162756. inptr += nc;
  162757. }
  162758. }
  162759. input_buf++;
  162760. output_row++;
  162761. }
  162762. }
  162763. /*
  162764. * Empty method for start_pass.
  162765. */
  162766. METHODDEF(void)
  162767. null_method (j_compress_ptr)
  162768. {
  162769. /* no work needed */
  162770. }
  162771. /*
  162772. * Module initialization routine for input colorspace conversion.
  162773. */
  162774. GLOBAL(void)
  162775. jinit_color_converter (j_compress_ptr cinfo)
  162776. {
  162777. my_cconvert_ptr cconvert;
  162778. cconvert = (my_cconvert_ptr)
  162779. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162780. SIZEOF(my_color_converter));
  162781. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162782. /* set start_pass to null method until we find out differently */
  162783. cconvert->pub.start_pass = null_method;
  162784. /* Make sure input_components agrees with in_color_space */
  162785. switch (cinfo->in_color_space) {
  162786. case JCS_GRAYSCALE:
  162787. if (cinfo->input_components != 1)
  162788. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162789. break;
  162790. case JCS_RGB:
  162791. #if RGB_PIXELSIZE != 3
  162792. if (cinfo->input_components != RGB_PIXELSIZE)
  162793. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162794. break;
  162795. #endif /* else share code with YCbCr */
  162796. case JCS_YCbCr:
  162797. if (cinfo->input_components != 3)
  162798. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162799. break;
  162800. case JCS_CMYK:
  162801. case JCS_YCCK:
  162802. if (cinfo->input_components != 4)
  162803. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162804. break;
  162805. default: /* JCS_UNKNOWN can be anything */
  162806. if (cinfo->input_components < 1)
  162807. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162808. break;
  162809. }
  162810. /* Check num_components, set conversion method based on requested space */
  162811. switch (cinfo->jpeg_color_space) {
  162812. case JCS_GRAYSCALE:
  162813. if (cinfo->num_components != 1)
  162814. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162815. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162816. cconvert->pub.color_convert = grayscale_convert;
  162817. else if (cinfo->in_color_space == JCS_RGB) {
  162818. cconvert->pub.start_pass = rgb_ycc_start;
  162819. cconvert->pub.color_convert = rgb_gray_convert;
  162820. } else if (cinfo->in_color_space == JCS_YCbCr)
  162821. cconvert->pub.color_convert = grayscale_convert;
  162822. else
  162823. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162824. break;
  162825. case JCS_RGB:
  162826. if (cinfo->num_components != 3)
  162827. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162828. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162829. cconvert->pub.color_convert = null_convert;
  162830. else
  162831. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162832. break;
  162833. case JCS_YCbCr:
  162834. if (cinfo->num_components != 3)
  162835. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162836. if (cinfo->in_color_space == JCS_RGB) {
  162837. cconvert->pub.start_pass = rgb_ycc_start;
  162838. cconvert->pub.color_convert = rgb_ycc_convert;
  162839. } else if (cinfo->in_color_space == JCS_YCbCr)
  162840. cconvert->pub.color_convert = null_convert;
  162841. else
  162842. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162843. break;
  162844. case JCS_CMYK:
  162845. if (cinfo->num_components != 4)
  162846. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162847. if (cinfo->in_color_space == JCS_CMYK)
  162848. cconvert->pub.color_convert = null_convert;
  162849. else
  162850. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162851. break;
  162852. case JCS_YCCK:
  162853. if (cinfo->num_components != 4)
  162854. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162855. if (cinfo->in_color_space == JCS_CMYK) {
  162856. cconvert->pub.start_pass = rgb_ycc_start;
  162857. cconvert->pub.color_convert = cmyk_ycck_convert;
  162858. } else if (cinfo->in_color_space == JCS_YCCK)
  162859. cconvert->pub.color_convert = null_convert;
  162860. else
  162861. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162862. break;
  162863. default: /* allow null conversion of JCS_UNKNOWN */
  162864. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162865. cinfo->num_components != cinfo->input_components)
  162866. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162867. cconvert->pub.color_convert = null_convert;
  162868. break;
  162869. }
  162870. }
  162871. /*** End of inlined file: jccolor.c ***/
  162872. #undef FIX
  162873. /*** Start of inlined file: jcdctmgr.c ***/
  162874. #define JPEG_INTERNALS
  162875. /*** Start of inlined file: jdct.h ***/
  162876. /*
  162877. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162878. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162879. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162880. * implementations use an array of type FAST_FLOAT, instead.)
  162881. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162882. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162883. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162884. * convention improves accuracy in integer implementations and saves some
  162885. * work in floating-point ones.
  162886. * Quantization of the output coefficients is done by jcdctmgr.c.
  162887. */
  162888. #ifndef __jdct_h__
  162889. #define __jdct_h__
  162890. #if BITS_IN_JSAMPLE == 8
  162891. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162892. #else
  162893. typedef INT32 DCTELEM; /* must have 32 bits */
  162894. #endif
  162895. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162896. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162897. /*
  162898. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162899. * to an output sample array. The routine must dequantize the input data as
  162900. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162901. * pointed to by compptr->dct_table. The output data is to be placed into the
  162902. * sample array starting at a specified column. (Any row offset needed will
  162903. * be applied to the array pointer before it is passed to the IDCT code.)
  162904. * Note that the number of samples emitted by the IDCT routine is
  162905. * DCT_scaled_size * DCT_scaled_size.
  162906. */
  162907. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162908. /*
  162909. * Each IDCT routine has its own ideas about the best dct_table element type.
  162910. */
  162911. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162912. #if BITS_IN_JSAMPLE == 8
  162913. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162914. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162915. #else
  162916. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162917. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162918. #endif
  162919. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162920. /*
  162921. * Each IDCT routine is responsible for range-limiting its results and
  162922. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162923. * be quite far out of range if the input data is corrupt, so a bulletproof
  162924. * range-limiting step is required. We use a mask-and-table-lookup method
  162925. * to do the combined operations quickly. See the comments with
  162926. * prepare_range_limit_table (in jdmaster.c) for more info.
  162927. */
  162928. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162929. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162930. /* Short forms of external names for systems with brain-damaged linkers. */
  162931. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162932. #define jpeg_fdct_islow jFDislow
  162933. #define jpeg_fdct_ifast jFDifast
  162934. #define jpeg_fdct_float jFDfloat
  162935. #define jpeg_idct_islow jRDislow
  162936. #define jpeg_idct_ifast jRDifast
  162937. #define jpeg_idct_float jRDfloat
  162938. #define jpeg_idct_4x4 jRD4x4
  162939. #define jpeg_idct_2x2 jRD2x2
  162940. #define jpeg_idct_1x1 jRD1x1
  162941. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162942. /* Extern declarations for the forward and inverse DCT routines. */
  162943. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162944. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162945. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162946. EXTERN(void) jpeg_idct_islow
  162947. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162948. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162949. EXTERN(void) jpeg_idct_ifast
  162950. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162951. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162952. EXTERN(void) jpeg_idct_float
  162953. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162954. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162955. EXTERN(void) jpeg_idct_4x4
  162956. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162957. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162958. EXTERN(void) jpeg_idct_2x2
  162959. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162960. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162961. EXTERN(void) jpeg_idct_1x1
  162962. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162963. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162964. /*
  162965. * Macros for handling fixed-point arithmetic; these are used by many
  162966. * but not all of the DCT/IDCT modules.
  162967. *
  162968. * All values are expected to be of type INT32.
  162969. * Fractional constants are scaled left by CONST_BITS bits.
  162970. * CONST_BITS is defined within each module using these macros,
  162971. * and may differ from one module to the next.
  162972. */
  162973. #define ONE ((INT32) 1)
  162974. #define CONST_SCALE (ONE << CONST_BITS)
  162975. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162976. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162977. * thus causing a lot of useless floating-point operations at run time.
  162978. */
  162979. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162980. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162981. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162982. * the fudge factor is correct for either sign of X.
  162983. */
  162984. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162985. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162986. * This macro is used only when the two inputs will actually be no more than
  162987. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162988. * full 32x32 multiply. This provides a useful speedup on many machines.
  162989. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162990. * in C, but some C compilers will do the right thing if you provide the
  162991. * correct combination of casts.
  162992. */
  162993. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162994. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162995. #endif
  162996. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162997. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162998. #endif
  162999. #ifndef MULTIPLY16C16 /* default definition */
  163000. #define MULTIPLY16C16(var,const) ((var) * (const))
  163001. #endif
  163002. /* Same except both inputs are variables. */
  163003. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  163004. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  163005. #endif
  163006. #ifndef MULTIPLY16V16 /* default definition */
  163007. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  163008. #endif
  163009. #endif
  163010. /*** End of inlined file: jdct.h ***/
  163011. /* Private declarations for DCT subsystem */
  163012. /* Private subobject for this module */
  163013. typedef struct {
  163014. struct jpeg_forward_dct pub; /* public fields */
  163015. /* Pointer to the DCT routine actually in use */
  163016. forward_DCT_method_ptr do_dct;
  163017. /* The actual post-DCT divisors --- not identical to the quant table
  163018. * entries, because of scaling (especially for an unnormalized DCT).
  163019. * Each table is given in normal array order.
  163020. */
  163021. DCTELEM * divisors[NUM_QUANT_TBLS];
  163022. #ifdef DCT_FLOAT_SUPPORTED
  163023. /* Same as above for the floating-point case. */
  163024. float_DCT_method_ptr do_float_dct;
  163025. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  163026. #endif
  163027. } my_fdct_controller;
  163028. typedef my_fdct_controller * my_fdct_ptr;
  163029. /*
  163030. * Initialize for a processing pass.
  163031. * Verify that all referenced Q-tables are present, and set up
  163032. * the divisor table for each one.
  163033. * In the current implementation, DCT of all components is done during
  163034. * the first pass, even if only some components will be output in the
  163035. * first scan. Hence all components should be examined here.
  163036. */
  163037. METHODDEF(void)
  163038. start_pass_fdctmgr (j_compress_ptr cinfo)
  163039. {
  163040. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163041. int ci, qtblno, i;
  163042. jpeg_component_info *compptr;
  163043. JQUANT_TBL * qtbl;
  163044. DCTELEM * dtbl;
  163045. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163046. ci++, compptr++) {
  163047. qtblno = compptr->quant_tbl_no;
  163048. /* Make sure specified quantization table is present */
  163049. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  163050. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  163051. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  163052. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  163053. /* Compute divisors for this quant table */
  163054. /* We may do this more than once for same table, but it's not a big deal */
  163055. switch (cinfo->dct_method) {
  163056. #ifdef DCT_ISLOW_SUPPORTED
  163057. case JDCT_ISLOW:
  163058. /* For LL&M IDCT method, divisors are equal to raw quantization
  163059. * coefficients multiplied by 8 (to counteract scaling).
  163060. */
  163061. if (fdct->divisors[qtblno] == NULL) {
  163062. fdct->divisors[qtblno] = (DCTELEM *)
  163063. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163064. DCTSIZE2 * SIZEOF(DCTELEM));
  163065. }
  163066. dtbl = fdct->divisors[qtblno];
  163067. for (i = 0; i < DCTSIZE2; i++) {
  163068. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  163069. }
  163070. break;
  163071. #endif
  163072. #ifdef DCT_IFAST_SUPPORTED
  163073. case JDCT_IFAST:
  163074. {
  163075. /* For AA&N IDCT method, divisors are equal to quantization
  163076. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163077. * scalefactor[0] = 1
  163078. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163079. * We apply a further scale factor of 8.
  163080. */
  163081. #define CONST_BITS 14
  163082. static const INT16 aanscales[DCTSIZE2] = {
  163083. /* precomputed values scaled up by 14 bits */
  163084. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163085. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  163086. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  163087. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  163088. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163089. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  163090. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  163091. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  163092. };
  163093. SHIFT_TEMPS
  163094. if (fdct->divisors[qtblno] == NULL) {
  163095. fdct->divisors[qtblno] = (DCTELEM *)
  163096. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163097. DCTSIZE2 * SIZEOF(DCTELEM));
  163098. }
  163099. dtbl = fdct->divisors[qtblno];
  163100. for (i = 0; i < DCTSIZE2; i++) {
  163101. dtbl[i] = (DCTELEM)
  163102. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  163103. (INT32) aanscales[i]),
  163104. CONST_BITS-3);
  163105. }
  163106. }
  163107. break;
  163108. #endif
  163109. #ifdef DCT_FLOAT_SUPPORTED
  163110. case JDCT_FLOAT:
  163111. {
  163112. /* For float AA&N IDCT method, divisors are equal to quantization
  163113. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163114. * scalefactor[0] = 1
  163115. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163116. * We apply a further scale factor of 8.
  163117. * What's actually stored is 1/divisor so that the inner loop can
  163118. * use a multiplication rather than a division.
  163119. */
  163120. FAST_FLOAT * fdtbl;
  163121. int row, col;
  163122. static const double aanscalefactor[DCTSIZE] = {
  163123. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163124. 1.0, 0.785694958, 0.541196100, 0.275899379
  163125. };
  163126. if (fdct->float_divisors[qtblno] == NULL) {
  163127. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  163128. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163129. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  163130. }
  163131. fdtbl = fdct->float_divisors[qtblno];
  163132. i = 0;
  163133. for (row = 0; row < DCTSIZE; row++) {
  163134. for (col = 0; col < DCTSIZE; col++) {
  163135. fdtbl[i] = (FAST_FLOAT)
  163136. (1.0 / (((double) qtbl->quantval[i] *
  163137. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  163138. i++;
  163139. }
  163140. }
  163141. }
  163142. break;
  163143. #endif
  163144. default:
  163145. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163146. break;
  163147. }
  163148. }
  163149. }
  163150. /*
  163151. * Perform forward DCT on one or more blocks of a component.
  163152. *
  163153. * The input samples are taken from the sample_data[] array starting at
  163154. * position start_row/start_col, and moving to the right for any additional
  163155. * blocks. The quantized coefficients are returned in coef_blocks[].
  163156. */
  163157. METHODDEF(void)
  163158. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163159. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163160. JDIMENSION start_row, JDIMENSION start_col,
  163161. JDIMENSION num_blocks)
  163162. /* This version is used for integer DCT implementations. */
  163163. {
  163164. /* This routine is heavily used, so it's worth coding it tightly. */
  163165. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163166. forward_DCT_method_ptr do_dct = fdct->do_dct;
  163167. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  163168. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163169. JDIMENSION bi;
  163170. sample_data += start_row; /* fold in the vertical offset once */
  163171. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163172. /* Load data into workspace, applying unsigned->signed conversion */
  163173. { register DCTELEM *workspaceptr;
  163174. register JSAMPROW elemptr;
  163175. register int elemr;
  163176. workspaceptr = workspace;
  163177. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163178. elemptr = sample_data[elemr] + start_col;
  163179. #if DCTSIZE == 8 /* unroll the inner loop */
  163180. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163181. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163182. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163183. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163184. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163185. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163186. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163187. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163188. #else
  163189. { register int elemc;
  163190. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163191. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163192. }
  163193. }
  163194. #endif
  163195. }
  163196. }
  163197. /* Perform the DCT */
  163198. (*do_dct) (workspace);
  163199. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163200. { register DCTELEM temp, qval;
  163201. register int i;
  163202. register JCOEFPTR output_ptr = coef_blocks[bi];
  163203. for (i = 0; i < DCTSIZE2; i++) {
  163204. qval = divisors[i];
  163205. temp = workspace[i];
  163206. /* Divide the coefficient value by qval, ensuring proper rounding.
  163207. * Since C does not specify the direction of rounding for negative
  163208. * quotients, we have to force the dividend positive for portability.
  163209. *
  163210. * In most files, at least half of the output values will be zero
  163211. * (at default quantization settings, more like three-quarters...)
  163212. * so we should ensure that this case is fast. On many machines,
  163213. * a comparison is enough cheaper than a divide to make a special test
  163214. * a win. Since both inputs will be nonnegative, we need only test
  163215. * for a < b to discover whether a/b is 0.
  163216. * If your machine's division is fast enough, define FAST_DIVIDE.
  163217. */
  163218. #ifdef FAST_DIVIDE
  163219. #define DIVIDE_BY(a,b) a /= b
  163220. #else
  163221. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163222. #endif
  163223. if (temp < 0) {
  163224. temp = -temp;
  163225. temp += qval>>1; /* for rounding */
  163226. DIVIDE_BY(temp, qval);
  163227. temp = -temp;
  163228. } else {
  163229. temp += qval>>1; /* for rounding */
  163230. DIVIDE_BY(temp, qval);
  163231. }
  163232. output_ptr[i] = (JCOEF) temp;
  163233. }
  163234. }
  163235. }
  163236. }
  163237. #ifdef DCT_FLOAT_SUPPORTED
  163238. METHODDEF(void)
  163239. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163240. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163241. JDIMENSION start_row, JDIMENSION start_col,
  163242. JDIMENSION num_blocks)
  163243. /* This version is used for floating-point DCT implementations. */
  163244. {
  163245. /* This routine is heavily used, so it's worth coding it tightly. */
  163246. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163247. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163248. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163249. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163250. JDIMENSION bi;
  163251. sample_data += start_row; /* fold in the vertical offset once */
  163252. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163253. /* Load data into workspace, applying unsigned->signed conversion */
  163254. { register FAST_FLOAT *workspaceptr;
  163255. register JSAMPROW elemptr;
  163256. register int elemr;
  163257. workspaceptr = workspace;
  163258. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163259. elemptr = sample_data[elemr] + start_col;
  163260. #if DCTSIZE == 8 /* unroll the inner loop */
  163261. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163262. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163263. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163264. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163265. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163266. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163267. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163268. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163269. #else
  163270. { register int elemc;
  163271. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163272. *workspaceptr++ = (FAST_FLOAT)
  163273. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163274. }
  163275. }
  163276. #endif
  163277. }
  163278. }
  163279. /* Perform the DCT */
  163280. (*do_dct) (workspace);
  163281. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163282. { register FAST_FLOAT temp;
  163283. register int i;
  163284. register JCOEFPTR output_ptr = coef_blocks[bi];
  163285. for (i = 0; i < DCTSIZE2; i++) {
  163286. /* Apply the quantization and scaling factor */
  163287. temp = workspace[i] * divisors[i];
  163288. /* Round to nearest integer.
  163289. * Since C does not specify the direction of rounding for negative
  163290. * quotients, we have to force the dividend positive for portability.
  163291. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163292. * code should work for either 16-bit or 32-bit ints.
  163293. */
  163294. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163295. }
  163296. }
  163297. }
  163298. }
  163299. #endif /* DCT_FLOAT_SUPPORTED */
  163300. /*
  163301. * Initialize FDCT manager.
  163302. */
  163303. GLOBAL(void)
  163304. jinit_forward_dct (j_compress_ptr cinfo)
  163305. {
  163306. my_fdct_ptr fdct;
  163307. int i;
  163308. fdct = (my_fdct_ptr)
  163309. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163310. SIZEOF(my_fdct_controller));
  163311. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163312. fdct->pub.start_pass = start_pass_fdctmgr;
  163313. switch (cinfo->dct_method) {
  163314. #ifdef DCT_ISLOW_SUPPORTED
  163315. case JDCT_ISLOW:
  163316. fdct->pub.forward_DCT = forward_DCT;
  163317. fdct->do_dct = jpeg_fdct_islow;
  163318. break;
  163319. #endif
  163320. #ifdef DCT_IFAST_SUPPORTED
  163321. case JDCT_IFAST:
  163322. fdct->pub.forward_DCT = forward_DCT;
  163323. fdct->do_dct = jpeg_fdct_ifast;
  163324. break;
  163325. #endif
  163326. #ifdef DCT_FLOAT_SUPPORTED
  163327. case JDCT_FLOAT:
  163328. fdct->pub.forward_DCT = forward_DCT_float;
  163329. fdct->do_float_dct = jpeg_fdct_float;
  163330. break;
  163331. #endif
  163332. default:
  163333. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163334. break;
  163335. }
  163336. /* Mark divisor tables unallocated */
  163337. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163338. fdct->divisors[i] = NULL;
  163339. #ifdef DCT_FLOAT_SUPPORTED
  163340. fdct->float_divisors[i] = NULL;
  163341. #endif
  163342. }
  163343. }
  163344. /*** End of inlined file: jcdctmgr.c ***/
  163345. #undef CONST_BITS
  163346. /*** Start of inlined file: jchuff.c ***/
  163347. #define JPEG_INTERNALS
  163348. /*** Start of inlined file: jchuff.h ***/
  163349. /* The legal range of a DCT coefficient is
  163350. * -1024 .. +1023 for 8-bit data;
  163351. * -16384 .. +16383 for 12-bit data.
  163352. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163353. */
  163354. #ifndef _jchuff_h_
  163355. #define _jchuff_h_
  163356. #if BITS_IN_JSAMPLE == 8
  163357. #define MAX_COEF_BITS 10
  163358. #else
  163359. #define MAX_COEF_BITS 14
  163360. #endif
  163361. /* Derived data constructed for each Huffman table */
  163362. typedef struct {
  163363. unsigned int ehufco[256]; /* code for each symbol */
  163364. char ehufsi[256]; /* length of code for each symbol */
  163365. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163366. } c_derived_tbl;
  163367. /* Short forms of external names for systems with brain-damaged linkers. */
  163368. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163369. #define jpeg_make_c_derived_tbl jMkCDerived
  163370. #define jpeg_gen_optimal_table jGenOptTbl
  163371. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163372. /* Expand a Huffman table definition into the derived format */
  163373. EXTERN(void) jpeg_make_c_derived_tbl
  163374. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163375. c_derived_tbl ** pdtbl));
  163376. /* Generate an optimal table definition given the specified counts */
  163377. EXTERN(void) jpeg_gen_optimal_table
  163378. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163379. #endif
  163380. /*** End of inlined file: jchuff.h ***/
  163381. /* Declarations shared with jcphuff.c */
  163382. /* Expanded entropy encoder object for Huffman encoding.
  163383. *
  163384. * The savable_state subrecord contains fields that change within an MCU,
  163385. * but must not be updated permanently until we complete the MCU.
  163386. */
  163387. typedef struct {
  163388. INT32 put_buffer; /* current bit-accumulation buffer */
  163389. int put_bits; /* # of bits now in it */
  163390. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163391. } savable_state;
  163392. /* This macro is to work around compilers with missing or broken
  163393. * structure assignment. You'll need to fix this code if you have
  163394. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163395. */
  163396. #ifndef NO_STRUCT_ASSIGN
  163397. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163398. #else
  163399. #if MAX_COMPS_IN_SCAN == 4
  163400. #define ASSIGN_STATE(dest,src) \
  163401. ((dest).put_buffer = (src).put_buffer, \
  163402. (dest).put_bits = (src).put_bits, \
  163403. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163404. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163405. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163406. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163407. #endif
  163408. #endif
  163409. typedef struct {
  163410. struct jpeg_entropy_encoder pub; /* public fields */
  163411. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163412. /* These fields are NOT loaded into local working state. */
  163413. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163414. int next_restart_num; /* next restart number to write (0-7) */
  163415. /* Pointers to derived tables (these workspaces have image lifespan) */
  163416. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163417. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163418. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163419. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163420. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163421. #endif
  163422. } huff_entropy_encoder;
  163423. typedef huff_entropy_encoder * huff_entropy_ptr;
  163424. /* Working state while writing an MCU.
  163425. * This struct contains all the fields that are needed by subroutines.
  163426. */
  163427. typedef struct {
  163428. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163429. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163430. savable_state cur; /* Current bit buffer & DC state */
  163431. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163432. } working_state;
  163433. /* Forward declarations */
  163434. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163435. JBLOCKROW *MCU_data));
  163436. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163437. #ifdef ENTROPY_OPT_SUPPORTED
  163438. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163439. JBLOCKROW *MCU_data));
  163440. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163441. #endif
  163442. /*
  163443. * Initialize for a Huffman-compressed scan.
  163444. * If gather_statistics is TRUE, we do not output anything during the scan,
  163445. * just count the Huffman symbols used and generate Huffman code tables.
  163446. */
  163447. METHODDEF(void)
  163448. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163449. {
  163450. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163451. int ci, dctbl, actbl;
  163452. jpeg_component_info * compptr;
  163453. if (gather_statistics) {
  163454. #ifdef ENTROPY_OPT_SUPPORTED
  163455. entropy->pub.encode_mcu = encode_mcu_gather;
  163456. entropy->pub.finish_pass = finish_pass_gather;
  163457. #else
  163458. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163459. #endif
  163460. } else {
  163461. entropy->pub.encode_mcu = encode_mcu_huff;
  163462. entropy->pub.finish_pass = finish_pass_huff;
  163463. }
  163464. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163465. compptr = cinfo->cur_comp_info[ci];
  163466. dctbl = compptr->dc_tbl_no;
  163467. actbl = compptr->ac_tbl_no;
  163468. if (gather_statistics) {
  163469. #ifdef ENTROPY_OPT_SUPPORTED
  163470. /* Check for invalid table indexes */
  163471. /* (make_c_derived_tbl does this in the other path) */
  163472. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163473. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163474. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163475. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163476. /* Allocate and zero the statistics tables */
  163477. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163478. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163479. entropy->dc_count_ptrs[dctbl] = (long *)
  163480. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163481. 257 * SIZEOF(long));
  163482. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163483. if (entropy->ac_count_ptrs[actbl] == NULL)
  163484. entropy->ac_count_ptrs[actbl] = (long *)
  163485. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163486. 257 * SIZEOF(long));
  163487. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163488. #endif
  163489. } else {
  163490. /* Compute derived values for Huffman tables */
  163491. /* We may do this more than once for a table, but it's not expensive */
  163492. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163493. & entropy->dc_derived_tbls[dctbl]);
  163494. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163495. & entropy->ac_derived_tbls[actbl]);
  163496. }
  163497. /* Initialize DC predictions to 0 */
  163498. entropy->saved.last_dc_val[ci] = 0;
  163499. }
  163500. /* Initialize bit buffer to empty */
  163501. entropy->saved.put_buffer = 0;
  163502. entropy->saved.put_bits = 0;
  163503. /* Initialize restart stuff */
  163504. entropy->restarts_to_go = cinfo->restart_interval;
  163505. entropy->next_restart_num = 0;
  163506. }
  163507. /*
  163508. * Compute the derived values for a Huffman table.
  163509. * This routine also performs some validation checks on the table.
  163510. *
  163511. * Note this is also used by jcphuff.c.
  163512. */
  163513. GLOBAL(void)
  163514. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163515. c_derived_tbl ** pdtbl)
  163516. {
  163517. JHUFF_TBL *htbl;
  163518. c_derived_tbl *dtbl;
  163519. int p, i, l, lastp, si, maxsymbol;
  163520. char huffsize[257];
  163521. unsigned int huffcode[257];
  163522. unsigned int code;
  163523. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163524. * paralleling the order of the symbols themselves in htbl->huffval[].
  163525. */
  163526. /* Find the input Huffman table */
  163527. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163528. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163529. htbl =
  163530. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163531. if (htbl == NULL)
  163532. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163533. /* Allocate a workspace if we haven't already done so. */
  163534. if (*pdtbl == NULL)
  163535. *pdtbl = (c_derived_tbl *)
  163536. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163537. SIZEOF(c_derived_tbl));
  163538. dtbl = *pdtbl;
  163539. /* Figure C.1: make table of Huffman code length for each symbol */
  163540. p = 0;
  163541. for (l = 1; l <= 16; l++) {
  163542. i = (int) htbl->bits[l];
  163543. if (i < 0 || p + i > 256) /* protect against table overrun */
  163544. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163545. while (i--)
  163546. huffsize[p++] = (char) l;
  163547. }
  163548. huffsize[p] = 0;
  163549. lastp = p;
  163550. /* Figure C.2: generate the codes themselves */
  163551. /* We also validate that the counts represent a legal Huffman code tree. */
  163552. code = 0;
  163553. si = huffsize[0];
  163554. p = 0;
  163555. while (huffsize[p]) {
  163556. while (((int) huffsize[p]) == si) {
  163557. huffcode[p++] = code;
  163558. code++;
  163559. }
  163560. /* code is now 1 more than the last code used for codelength si; but
  163561. * it must still fit in si bits, since no code is allowed to be all ones.
  163562. */
  163563. if (((INT32) code) >= (((INT32) 1) << si))
  163564. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163565. code <<= 1;
  163566. si++;
  163567. }
  163568. /* Figure C.3: generate encoding tables */
  163569. /* These are code and size indexed by symbol value */
  163570. /* Set all codeless symbols to have code length 0;
  163571. * this lets us detect duplicate VAL entries here, and later
  163572. * allows emit_bits to detect any attempt to emit such symbols.
  163573. */
  163574. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163575. /* This is also a convenient place to check for out-of-range
  163576. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163577. * but only 0..15 for DC. (We could constrain them further
  163578. * based on data depth and mode, but this seems enough.)
  163579. */
  163580. maxsymbol = isDC ? 15 : 255;
  163581. for (p = 0; p < lastp; p++) {
  163582. i = htbl->huffval[p];
  163583. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163584. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163585. dtbl->ehufco[i] = huffcode[p];
  163586. dtbl->ehufsi[i] = huffsize[p];
  163587. }
  163588. }
  163589. /* Outputting bytes to the file */
  163590. /* Emit a byte, taking 'action' if must suspend. */
  163591. #define emit_byte(state,val,action) \
  163592. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163593. if (--(state)->free_in_buffer == 0) \
  163594. if (! dump_buffer(state)) \
  163595. { action; } }
  163596. LOCAL(boolean)
  163597. dump_buffer (working_state * state)
  163598. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163599. {
  163600. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163601. if (! (*dest->empty_output_buffer) (state->cinfo))
  163602. return FALSE;
  163603. /* After a successful buffer dump, must reset buffer pointers */
  163604. state->next_output_byte = dest->next_output_byte;
  163605. state->free_in_buffer = dest->free_in_buffer;
  163606. return TRUE;
  163607. }
  163608. /* Outputting bits to the file */
  163609. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163610. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163611. * in one call, and we never retain more than 7 bits in put_buffer
  163612. * between calls, so 24 bits are sufficient.
  163613. */
  163614. INLINE
  163615. LOCAL(boolean)
  163616. emit_bits (working_state * state, unsigned int code, int size)
  163617. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163618. {
  163619. /* This routine is heavily used, so it's worth coding tightly. */
  163620. register INT32 put_buffer = (INT32) code;
  163621. register int put_bits = state->cur.put_bits;
  163622. /* if size is 0, caller used an invalid Huffman table entry */
  163623. if (size == 0)
  163624. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163625. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163626. put_bits += size; /* new number of bits in buffer */
  163627. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163628. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163629. while (put_bits >= 8) {
  163630. int c = (int) ((put_buffer >> 16) & 0xFF);
  163631. emit_byte(state, c, return FALSE);
  163632. if (c == 0xFF) { /* need to stuff a zero byte? */
  163633. emit_byte(state, 0, return FALSE);
  163634. }
  163635. put_buffer <<= 8;
  163636. put_bits -= 8;
  163637. }
  163638. state->cur.put_buffer = put_buffer; /* update state variables */
  163639. state->cur.put_bits = put_bits;
  163640. return TRUE;
  163641. }
  163642. LOCAL(boolean)
  163643. flush_bits (working_state * state)
  163644. {
  163645. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163646. return FALSE;
  163647. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163648. state->cur.put_bits = 0;
  163649. return TRUE;
  163650. }
  163651. /* Encode a single block's worth of coefficients */
  163652. LOCAL(boolean)
  163653. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163654. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163655. {
  163656. register int temp, temp2;
  163657. register int nbits;
  163658. register int k, r, i;
  163659. /* Encode the DC coefficient difference per section F.1.2.1 */
  163660. temp = temp2 = block[0] - last_dc_val;
  163661. if (temp < 0) {
  163662. temp = -temp; /* temp is abs value of input */
  163663. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163664. /* This code assumes we are on a two's complement machine */
  163665. temp2--;
  163666. }
  163667. /* Find the number of bits needed for the magnitude of the coefficient */
  163668. nbits = 0;
  163669. while (temp) {
  163670. nbits++;
  163671. temp >>= 1;
  163672. }
  163673. /* Check for out-of-range coefficient values.
  163674. * Since we're encoding a difference, the range limit is twice as much.
  163675. */
  163676. if (nbits > MAX_COEF_BITS+1)
  163677. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163678. /* Emit the Huffman-coded symbol for the number of bits */
  163679. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163680. return FALSE;
  163681. /* Emit that number of bits of the value, if positive, */
  163682. /* or the complement of its magnitude, if negative. */
  163683. if (nbits) /* emit_bits rejects calls with size 0 */
  163684. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163685. return FALSE;
  163686. /* Encode the AC coefficients per section F.1.2.2 */
  163687. r = 0; /* r = run length of zeros */
  163688. for (k = 1; k < DCTSIZE2; k++) {
  163689. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163690. r++;
  163691. } else {
  163692. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163693. while (r > 15) {
  163694. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163695. return FALSE;
  163696. r -= 16;
  163697. }
  163698. temp2 = temp;
  163699. if (temp < 0) {
  163700. temp = -temp; /* temp is abs value of input */
  163701. /* This code assumes we are on a two's complement machine */
  163702. temp2--;
  163703. }
  163704. /* Find the number of bits needed for the magnitude of the coefficient */
  163705. nbits = 1; /* there must be at least one 1 bit */
  163706. while ((temp >>= 1))
  163707. nbits++;
  163708. /* Check for out-of-range coefficient values */
  163709. if (nbits > MAX_COEF_BITS)
  163710. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163711. /* Emit Huffman symbol for run length / number of bits */
  163712. i = (r << 4) + nbits;
  163713. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163714. return FALSE;
  163715. /* Emit that number of bits of the value, if positive, */
  163716. /* or the complement of its magnitude, if negative. */
  163717. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163718. return FALSE;
  163719. r = 0;
  163720. }
  163721. }
  163722. /* If the last coef(s) were zero, emit an end-of-block code */
  163723. if (r > 0)
  163724. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163725. return FALSE;
  163726. return TRUE;
  163727. }
  163728. /*
  163729. * Emit a restart marker & resynchronize predictions.
  163730. */
  163731. LOCAL(boolean)
  163732. emit_restart (working_state * state, int restart_num)
  163733. {
  163734. int ci;
  163735. if (! flush_bits(state))
  163736. return FALSE;
  163737. emit_byte(state, 0xFF, return FALSE);
  163738. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163739. /* Re-initialize DC predictions to 0 */
  163740. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163741. state->cur.last_dc_val[ci] = 0;
  163742. /* The restart counter is not updated until we successfully write the MCU. */
  163743. return TRUE;
  163744. }
  163745. /*
  163746. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163747. */
  163748. METHODDEF(boolean)
  163749. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163750. {
  163751. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163752. working_state state;
  163753. int blkn, ci;
  163754. jpeg_component_info * compptr;
  163755. /* Load up working state */
  163756. state.next_output_byte = cinfo->dest->next_output_byte;
  163757. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163758. ASSIGN_STATE(state.cur, entropy->saved);
  163759. state.cinfo = cinfo;
  163760. /* Emit restart marker if needed */
  163761. if (cinfo->restart_interval) {
  163762. if (entropy->restarts_to_go == 0)
  163763. if (! emit_restart(&state, entropy->next_restart_num))
  163764. return FALSE;
  163765. }
  163766. /* Encode the MCU data blocks */
  163767. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163768. ci = cinfo->MCU_membership[blkn];
  163769. compptr = cinfo->cur_comp_info[ci];
  163770. if (! encode_one_block(&state,
  163771. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163772. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163773. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163774. return FALSE;
  163775. /* Update last_dc_val */
  163776. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163777. }
  163778. /* Completed MCU, so update state */
  163779. cinfo->dest->next_output_byte = state.next_output_byte;
  163780. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163781. ASSIGN_STATE(entropy->saved, state.cur);
  163782. /* Update restart-interval state too */
  163783. if (cinfo->restart_interval) {
  163784. if (entropy->restarts_to_go == 0) {
  163785. entropy->restarts_to_go = cinfo->restart_interval;
  163786. entropy->next_restart_num++;
  163787. entropy->next_restart_num &= 7;
  163788. }
  163789. entropy->restarts_to_go--;
  163790. }
  163791. return TRUE;
  163792. }
  163793. /*
  163794. * Finish up at the end of a Huffman-compressed scan.
  163795. */
  163796. METHODDEF(void)
  163797. finish_pass_huff (j_compress_ptr cinfo)
  163798. {
  163799. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163800. working_state state;
  163801. /* Load up working state ... flush_bits needs it */
  163802. state.next_output_byte = cinfo->dest->next_output_byte;
  163803. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163804. ASSIGN_STATE(state.cur, entropy->saved);
  163805. state.cinfo = cinfo;
  163806. /* Flush out the last data */
  163807. if (! flush_bits(&state))
  163808. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163809. /* Update state */
  163810. cinfo->dest->next_output_byte = state.next_output_byte;
  163811. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163812. ASSIGN_STATE(entropy->saved, state.cur);
  163813. }
  163814. /*
  163815. * Huffman coding optimization.
  163816. *
  163817. * We first scan the supplied data and count the number of uses of each symbol
  163818. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163819. * Then we build a Huffman coding tree for the observed counts.
  163820. * Symbols which are not needed at all for the particular image are not
  163821. * assigned any code, which saves space in the DHT marker as well as in
  163822. * the compressed data.
  163823. */
  163824. #ifdef ENTROPY_OPT_SUPPORTED
  163825. /* Process a single block's worth of coefficients */
  163826. LOCAL(void)
  163827. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163828. long dc_counts[], long ac_counts[])
  163829. {
  163830. register int temp;
  163831. register int nbits;
  163832. register int k, r;
  163833. /* Encode the DC coefficient difference per section F.1.2.1 */
  163834. temp = block[0] - last_dc_val;
  163835. if (temp < 0)
  163836. temp = -temp;
  163837. /* Find the number of bits needed for the magnitude of the coefficient */
  163838. nbits = 0;
  163839. while (temp) {
  163840. nbits++;
  163841. temp >>= 1;
  163842. }
  163843. /* Check for out-of-range coefficient values.
  163844. * Since we're encoding a difference, the range limit is twice as much.
  163845. */
  163846. if (nbits > MAX_COEF_BITS+1)
  163847. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163848. /* Count the Huffman symbol for the number of bits */
  163849. dc_counts[nbits]++;
  163850. /* Encode the AC coefficients per section F.1.2.2 */
  163851. r = 0; /* r = run length of zeros */
  163852. for (k = 1; k < DCTSIZE2; k++) {
  163853. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163854. r++;
  163855. } else {
  163856. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163857. while (r > 15) {
  163858. ac_counts[0xF0]++;
  163859. r -= 16;
  163860. }
  163861. /* Find the number of bits needed for the magnitude of the coefficient */
  163862. if (temp < 0)
  163863. temp = -temp;
  163864. /* Find the number of bits needed for the magnitude of the coefficient */
  163865. nbits = 1; /* there must be at least one 1 bit */
  163866. while ((temp >>= 1))
  163867. nbits++;
  163868. /* Check for out-of-range coefficient values */
  163869. if (nbits > MAX_COEF_BITS)
  163870. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163871. /* Count Huffman symbol for run length / number of bits */
  163872. ac_counts[(r << 4) + nbits]++;
  163873. r = 0;
  163874. }
  163875. }
  163876. /* If the last coef(s) were zero, emit an end-of-block code */
  163877. if (r > 0)
  163878. ac_counts[0]++;
  163879. }
  163880. /*
  163881. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163882. * No data is actually output, so no suspension return is possible.
  163883. */
  163884. METHODDEF(boolean)
  163885. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163886. {
  163887. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163888. int blkn, ci;
  163889. jpeg_component_info * compptr;
  163890. /* Take care of restart intervals if needed */
  163891. if (cinfo->restart_interval) {
  163892. if (entropy->restarts_to_go == 0) {
  163893. /* Re-initialize DC predictions to 0 */
  163894. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163895. entropy->saved.last_dc_val[ci] = 0;
  163896. /* Update restart state */
  163897. entropy->restarts_to_go = cinfo->restart_interval;
  163898. }
  163899. entropy->restarts_to_go--;
  163900. }
  163901. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163902. ci = cinfo->MCU_membership[blkn];
  163903. compptr = cinfo->cur_comp_info[ci];
  163904. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163905. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163906. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163907. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163908. }
  163909. return TRUE;
  163910. }
  163911. /*
  163912. * Generate the best Huffman code table for the given counts, fill htbl.
  163913. * Note this is also used by jcphuff.c.
  163914. *
  163915. * The JPEG standard requires that no symbol be assigned a codeword of all
  163916. * one bits (so that padding bits added at the end of a compressed segment
  163917. * can't look like a valid code). Because of the canonical ordering of
  163918. * codewords, this just means that there must be an unused slot in the
  163919. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163920. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163921. * with count 1. In theory that's not optimal; giving it count zero but
  163922. * including it in the symbol set anyway should give a better Huffman code.
  163923. * But the theoretically better code actually seems to come out worse in
  163924. * practice, because it produces more all-ones bytes (which incur stuffed
  163925. * zero bytes in the final file). In any case the difference is tiny.
  163926. *
  163927. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163928. * If some symbols have a very small but nonzero probability, the Huffman tree
  163929. * must be adjusted to meet the code length restriction. We currently use
  163930. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163931. * optimal; it may not choose the best possible limited-length code. But
  163932. * typically only very-low-frequency symbols will be given less-than-optimal
  163933. * lengths, so the code is almost optimal. Experimental comparisons against
  163934. * an optimal limited-length-code algorithm indicate that the difference is
  163935. * microscopic --- usually less than a hundredth of a percent of total size.
  163936. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163937. */
  163938. GLOBAL(void)
  163939. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163940. {
  163941. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163942. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163943. int codesize[257]; /* codesize[k] = code length of symbol k */
  163944. int others[257]; /* next symbol in current branch of tree */
  163945. int c1, c2;
  163946. int p, i, j;
  163947. long v;
  163948. /* This algorithm is explained in section K.2 of the JPEG standard */
  163949. MEMZERO(bits, SIZEOF(bits));
  163950. MEMZERO(codesize, SIZEOF(codesize));
  163951. for (i = 0; i < 257; i++)
  163952. others[i] = -1; /* init links to empty */
  163953. freq[256] = 1; /* make sure 256 has a nonzero count */
  163954. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163955. * that no real symbol is given code-value of all ones, because 256
  163956. * will be placed last in the largest codeword category.
  163957. */
  163958. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163959. for (;;) {
  163960. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163961. /* In case of ties, take the larger symbol number */
  163962. c1 = -1;
  163963. v = 1000000000L;
  163964. for (i = 0; i <= 256; i++) {
  163965. if (freq[i] && freq[i] <= v) {
  163966. v = freq[i];
  163967. c1 = i;
  163968. }
  163969. }
  163970. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163971. /* In case of ties, take the larger symbol number */
  163972. c2 = -1;
  163973. v = 1000000000L;
  163974. for (i = 0; i <= 256; i++) {
  163975. if (freq[i] && freq[i] <= v && i != c1) {
  163976. v = freq[i];
  163977. c2 = i;
  163978. }
  163979. }
  163980. /* Done if we've merged everything into one frequency */
  163981. if (c2 < 0)
  163982. break;
  163983. /* Else merge the two counts/trees */
  163984. freq[c1] += freq[c2];
  163985. freq[c2] = 0;
  163986. /* Increment the codesize of everything in c1's tree branch */
  163987. codesize[c1]++;
  163988. while (others[c1] >= 0) {
  163989. c1 = others[c1];
  163990. codesize[c1]++;
  163991. }
  163992. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163993. /* Increment the codesize of everything in c2's tree branch */
  163994. codesize[c2]++;
  163995. while (others[c2] >= 0) {
  163996. c2 = others[c2];
  163997. codesize[c2]++;
  163998. }
  163999. }
  164000. /* Now count the number of symbols of each code length */
  164001. for (i = 0; i <= 256; i++) {
  164002. if (codesize[i]) {
  164003. /* The JPEG standard seems to think that this can't happen, */
  164004. /* but I'm paranoid... */
  164005. if (codesize[i] > MAX_CLEN)
  164006. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  164007. bits[codesize[i]]++;
  164008. }
  164009. }
  164010. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  164011. * Huffman procedure assigned any such lengths, we must adjust the coding.
  164012. * Here is what the JPEG spec says about how this next bit works:
  164013. * Since symbols are paired for the longest Huffman code, the symbols are
  164014. * removed from this length category two at a time. The prefix for the pair
  164015. * (which is one bit shorter) is allocated to one of the pair; then,
  164016. * skipping the BITS entry for that prefix length, a code word from the next
  164017. * shortest nonzero BITS entry is converted into a prefix for two code words
  164018. * one bit longer.
  164019. */
  164020. for (i = MAX_CLEN; i > 16; i--) {
  164021. while (bits[i] > 0) {
  164022. j = i - 2; /* find length of new prefix to be used */
  164023. while (bits[j] == 0)
  164024. j--;
  164025. bits[i] -= 2; /* remove two symbols */
  164026. bits[i-1]++; /* one goes in this length */
  164027. bits[j+1] += 2; /* two new symbols in this length */
  164028. bits[j]--; /* symbol of this length is now a prefix */
  164029. }
  164030. }
  164031. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  164032. while (bits[i] == 0) /* find largest codelength still in use */
  164033. i--;
  164034. bits[i]--;
  164035. /* Return final symbol counts (only for lengths 0..16) */
  164036. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  164037. /* Return a list of the symbols sorted by code length */
  164038. /* It's not real clear to me why we don't need to consider the codelength
  164039. * changes made above, but the JPEG spec seems to think this works.
  164040. */
  164041. p = 0;
  164042. for (i = 1; i <= MAX_CLEN; i++) {
  164043. for (j = 0; j <= 255; j++) {
  164044. if (codesize[j] == i) {
  164045. htbl->huffval[p] = (UINT8) j;
  164046. p++;
  164047. }
  164048. }
  164049. }
  164050. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  164051. htbl->sent_table = FALSE;
  164052. }
  164053. /*
  164054. * Finish up a statistics-gathering pass and create the new Huffman tables.
  164055. */
  164056. METHODDEF(void)
  164057. finish_pass_gather (j_compress_ptr cinfo)
  164058. {
  164059. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164060. int ci, dctbl, actbl;
  164061. jpeg_component_info * compptr;
  164062. JHUFF_TBL **htblptr;
  164063. boolean did_dc[NUM_HUFF_TBLS];
  164064. boolean did_ac[NUM_HUFF_TBLS];
  164065. /* It's important not to apply jpeg_gen_optimal_table more than once
  164066. * per table, because it clobbers the input frequency counts!
  164067. */
  164068. MEMZERO(did_dc, SIZEOF(did_dc));
  164069. MEMZERO(did_ac, SIZEOF(did_ac));
  164070. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164071. compptr = cinfo->cur_comp_info[ci];
  164072. dctbl = compptr->dc_tbl_no;
  164073. actbl = compptr->ac_tbl_no;
  164074. if (! did_dc[dctbl]) {
  164075. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  164076. if (*htblptr == NULL)
  164077. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164078. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  164079. did_dc[dctbl] = TRUE;
  164080. }
  164081. if (! did_ac[actbl]) {
  164082. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  164083. if (*htblptr == NULL)
  164084. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164085. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  164086. did_ac[actbl] = TRUE;
  164087. }
  164088. }
  164089. }
  164090. #endif /* ENTROPY_OPT_SUPPORTED */
  164091. /*
  164092. * Module initialization routine for Huffman entropy encoding.
  164093. */
  164094. GLOBAL(void)
  164095. jinit_huff_encoder (j_compress_ptr cinfo)
  164096. {
  164097. huff_entropy_ptr entropy;
  164098. int i;
  164099. entropy = (huff_entropy_ptr)
  164100. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164101. SIZEOF(huff_entropy_encoder));
  164102. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  164103. entropy->pub.start_pass = start_pass_huff;
  164104. /* Mark tables unallocated */
  164105. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164106. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  164107. #ifdef ENTROPY_OPT_SUPPORTED
  164108. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  164109. #endif
  164110. }
  164111. }
  164112. /*** End of inlined file: jchuff.c ***/
  164113. #undef emit_byte
  164114. /*** Start of inlined file: jcinit.c ***/
  164115. #define JPEG_INTERNALS
  164116. /*
  164117. * Master selection of compression modules.
  164118. * This is done once at the start of processing an image. We determine
  164119. * which modules will be used and give them appropriate initialization calls.
  164120. */
  164121. GLOBAL(void)
  164122. jinit_compress_master (j_compress_ptr cinfo)
  164123. {
  164124. /* Initialize master control (includes parameter checking/processing) */
  164125. jinit_c_master_control(cinfo, FALSE /* full compression */);
  164126. /* Preprocessing */
  164127. if (! cinfo->raw_data_in) {
  164128. jinit_color_converter(cinfo);
  164129. jinit_downsampler(cinfo);
  164130. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  164131. }
  164132. /* Forward DCT */
  164133. jinit_forward_dct(cinfo);
  164134. /* Entropy encoding: either Huffman or arithmetic coding. */
  164135. if (cinfo->arith_code) {
  164136. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  164137. } else {
  164138. if (cinfo->progressive_mode) {
  164139. #ifdef C_PROGRESSIVE_SUPPORTED
  164140. jinit_phuff_encoder(cinfo);
  164141. #else
  164142. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164143. #endif
  164144. } else
  164145. jinit_huff_encoder(cinfo);
  164146. }
  164147. /* Need a full-image coefficient buffer in any multi-pass mode. */
  164148. jinit_c_coef_controller(cinfo,
  164149. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  164150. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  164151. jinit_marker_writer(cinfo);
  164152. /* We can now tell the memory manager to allocate virtual arrays. */
  164153. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164154. /* Write the datastream header (SOI) immediately.
  164155. * Frame and scan headers are postponed till later.
  164156. * This lets application insert special markers after the SOI.
  164157. */
  164158. (*cinfo->marker->write_file_header) (cinfo);
  164159. }
  164160. /*** End of inlined file: jcinit.c ***/
  164161. /*** Start of inlined file: jcmainct.c ***/
  164162. #define JPEG_INTERNALS
  164163. /* Note: currently, there is no operating mode in which a full-image buffer
  164164. * is needed at this step. If there were, that mode could not be used with
  164165. * "raw data" input, since this module is bypassed in that case. However,
  164166. * we've left the code here for possible use in special applications.
  164167. */
  164168. #undef FULL_MAIN_BUFFER_SUPPORTED
  164169. /* Private buffer controller object */
  164170. typedef struct {
  164171. struct jpeg_c_main_controller pub; /* public fields */
  164172. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  164173. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  164174. boolean suspended; /* remember if we suspended output */
  164175. J_BUF_MODE pass_mode; /* current operating mode */
  164176. /* If using just a strip buffer, this points to the entire set of buffers
  164177. * (we allocate one for each component). In the full-image case, this
  164178. * points to the currently accessible strips of the virtual arrays.
  164179. */
  164180. JSAMPARRAY buffer[MAX_COMPONENTS];
  164181. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164182. /* If using full-image storage, this array holds pointers to virtual-array
  164183. * control blocks for each component. Unused if not full-image storage.
  164184. */
  164185. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  164186. #endif
  164187. } my_main_controller;
  164188. typedef my_main_controller * my_main_ptr;
  164189. /* Forward declarations */
  164190. METHODDEF(void) process_data_simple_main
  164191. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164192. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164193. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164194. METHODDEF(void) process_data_buffer_main
  164195. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164196. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164197. #endif
  164198. /*
  164199. * Initialize for a processing pass.
  164200. */
  164201. METHODDEF(void)
  164202. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164203. {
  164204. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164205. /* Do nothing in raw-data mode. */
  164206. if (cinfo->raw_data_in)
  164207. return;
  164208. main_->cur_iMCU_row = 0; /* initialize counters */
  164209. main_->rowgroup_ctr = 0;
  164210. main_->suspended = FALSE;
  164211. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164212. switch (pass_mode) {
  164213. case JBUF_PASS_THRU:
  164214. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164215. if (main_->whole_image[0] != NULL)
  164216. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164217. #endif
  164218. main_->pub.process_data = process_data_simple_main;
  164219. break;
  164220. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164221. case JBUF_SAVE_SOURCE:
  164222. case JBUF_CRANK_DEST:
  164223. case JBUF_SAVE_AND_PASS:
  164224. if (main_->whole_image[0] == NULL)
  164225. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164226. main_->pub.process_data = process_data_buffer_main;
  164227. break;
  164228. #endif
  164229. default:
  164230. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164231. break;
  164232. }
  164233. }
  164234. /*
  164235. * Process some data.
  164236. * This routine handles the simple pass-through mode,
  164237. * where we have only a strip buffer.
  164238. */
  164239. METHODDEF(void)
  164240. process_data_simple_main (j_compress_ptr cinfo,
  164241. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164242. JDIMENSION in_rows_avail)
  164243. {
  164244. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164245. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164246. /* Read input data if we haven't filled the main buffer yet */
  164247. if (main_->rowgroup_ctr < DCTSIZE)
  164248. (*cinfo->prep->pre_process_data) (cinfo,
  164249. input_buf, in_row_ctr, in_rows_avail,
  164250. main_->buffer, &main_->rowgroup_ctr,
  164251. (JDIMENSION) DCTSIZE);
  164252. /* If we don't have a full iMCU row buffered, return to application for
  164253. * more data. Note that preprocessor will always pad to fill the iMCU row
  164254. * at the bottom of the image.
  164255. */
  164256. if (main_->rowgroup_ctr != DCTSIZE)
  164257. return;
  164258. /* Send the completed row to the compressor */
  164259. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164260. /* If compressor did not consume the whole row, then we must need to
  164261. * suspend processing and return to the application. In this situation
  164262. * we pretend we didn't yet consume the last input row; otherwise, if
  164263. * it happened to be the last row of the image, the application would
  164264. * think we were done.
  164265. */
  164266. if (! main_->suspended) {
  164267. (*in_row_ctr)--;
  164268. main_->suspended = TRUE;
  164269. }
  164270. return;
  164271. }
  164272. /* We did finish the row. Undo our little suspension hack if a previous
  164273. * call suspended; then mark the main buffer empty.
  164274. */
  164275. if (main_->suspended) {
  164276. (*in_row_ctr)++;
  164277. main_->suspended = FALSE;
  164278. }
  164279. main_->rowgroup_ctr = 0;
  164280. main_->cur_iMCU_row++;
  164281. }
  164282. }
  164283. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164284. /*
  164285. * Process some data.
  164286. * This routine handles all of the modes that use a full-size buffer.
  164287. */
  164288. METHODDEF(void)
  164289. process_data_buffer_main (j_compress_ptr cinfo,
  164290. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164291. JDIMENSION in_rows_avail)
  164292. {
  164293. my_main_ptr main = (my_main_ptr) cinfo->main;
  164294. int ci;
  164295. jpeg_component_info *compptr;
  164296. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164297. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164298. /* Realign the virtual buffers if at the start of an iMCU row. */
  164299. if (main->rowgroup_ctr == 0) {
  164300. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164301. ci++, compptr++) {
  164302. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164303. ((j_common_ptr) cinfo, main->whole_image[ci],
  164304. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164305. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164306. }
  164307. /* In a read pass, pretend we just read some source data. */
  164308. if (! writing) {
  164309. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164310. main->rowgroup_ctr = DCTSIZE;
  164311. }
  164312. }
  164313. /* If a write pass, read input data until the current iMCU row is full. */
  164314. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164315. if (writing) {
  164316. (*cinfo->prep->pre_process_data) (cinfo,
  164317. input_buf, in_row_ctr, in_rows_avail,
  164318. main->buffer, &main->rowgroup_ctr,
  164319. (JDIMENSION) DCTSIZE);
  164320. /* Return to application if we need more data to fill the iMCU row. */
  164321. if (main->rowgroup_ctr < DCTSIZE)
  164322. return;
  164323. }
  164324. /* Emit data, unless this is a sink-only pass. */
  164325. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164326. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164327. /* If compressor did not consume the whole row, then we must need to
  164328. * suspend processing and return to the application. In this situation
  164329. * we pretend we didn't yet consume the last input row; otherwise, if
  164330. * it happened to be the last row of the image, the application would
  164331. * think we were done.
  164332. */
  164333. if (! main->suspended) {
  164334. (*in_row_ctr)--;
  164335. main->suspended = TRUE;
  164336. }
  164337. return;
  164338. }
  164339. /* We did finish the row. Undo our little suspension hack if a previous
  164340. * call suspended; then mark the main buffer empty.
  164341. */
  164342. if (main->suspended) {
  164343. (*in_row_ctr)++;
  164344. main->suspended = FALSE;
  164345. }
  164346. }
  164347. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164348. main->rowgroup_ctr = 0;
  164349. main->cur_iMCU_row++;
  164350. }
  164351. }
  164352. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164353. /*
  164354. * Initialize main buffer controller.
  164355. */
  164356. GLOBAL(void)
  164357. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164358. {
  164359. my_main_ptr main_;
  164360. int ci;
  164361. jpeg_component_info *compptr;
  164362. main_ = (my_main_ptr)
  164363. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164364. SIZEOF(my_main_controller));
  164365. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164366. main_->pub.start_pass = start_pass_main;
  164367. /* We don't need to create a buffer in raw-data mode. */
  164368. if (cinfo->raw_data_in)
  164369. return;
  164370. /* Create the buffer. It holds downsampled data, so each component
  164371. * may be of a different size.
  164372. */
  164373. if (need_full_buffer) {
  164374. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164375. /* Allocate a full-image virtual array for each component */
  164376. /* Note we pad the bottom to a multiple of the iMCU height */
  164377. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164378. ci++, compptr++) {
  164379. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164380. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164381. compptr->width_in_blocks * DCTSIZE,
  164382. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164383. (long) compptr->v_samp_factor) * DCTSIZE,
  164384. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164385. }
  164386. #else
  164387. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164388. #endif
  164389. } else {
  164390. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164391. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164392. #endif
  164393. /* Allocate a strip buffer for each component */
  164394. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164395. ci++, compptr++) {
  164396. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164397. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164398. compptr->width_in_blocks * DCTSIZE,
  164399. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164400. }
  164401. }
  164402. }
  164403. /*** End of inlined file: jcmainct.c ***/
  164404. /*** Start of inlined file: jcmarker.c ***/
  164405. #define JPEG_INTERNALS
  164406. /* Private state */
  164407. typedef struct {
  164408. struct jpeg_marker_writer pub; /* public fields */
  164409. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164410. } my_marker_writer;
  164411. typedef my_marker_writer * my_marker_ptr;
  164412. /*
  164413. * Basic output routines.
  164414. *
  164415. * Note that we do not support suspension while writing a marker.
  164416. * Therefore, an application using suspension must ensure that there is
  164417. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164418. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164419. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164420. * modes are not supported at all with suspension, so those two are the only
  164421. * points where markers will be written.
  164422. */
  164423. LOCAL(void)
  164424. emit_byte (j_compress_ptr cinfo, int val)
  164425. /* Emit a byte */
  164426. {
  164427. struct jpeg_destination_mgr * dest = cinfo->dest;
  164428. *(dest->next_output_byte)++ = (JOCTET) val;
  164429. if (--dest->free_in_buffer == 0) {
  164430. if (! (*dest->empty_output_buffer) (cinfo))
  164431. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164432. }
  164433. }
  164434. LOCAL(void)
  164435. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164436. /* Emit a marker code */
  164437. {
  164438. emit_byte(cinfo, 0xFF);
  164439. emit_byte(cinfo, (int) mark);
  164440. }
  164441. LOCAL(void)
  164442. emit_2bytes (j_compress_ptr cinfo, int value)
  164443. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164444. {
  164445. emit_byte(cinfo, (value >> 8) & 0xFF);
  164446. emit_byte(cinfo, value & 0xFF);
  164447. }
  164448. /*
  164449. * Routines to write specific marker types.
  164450. */
  164451. LOCAL(int)
  164452. emit_dqt (j_compress_ptr cinfo, int index)
  164453. /* Emit a DQT marker */
  164454. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164455. {
  164456. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164457. int prec;
  164458. int i;
  164459. if (qtbl == NULL)
  164460. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164461. prec = 0;
  164462. for (i = 0; i < DCTSIZE2; i++) {
  164463. if (qtbl->quantval[i] > 255)
  164464. prec = 1;
  164465. }
  164466. if (! qtbl->sent_table) {
  164467. emit_marker(cinfo, M_DQT);
  164468. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164469. emit_byte(cinfo, index + (prec<<4));
  164470. for (i = 0; i < DCTSIZE2; i++) {
  164471. /* The table entries must be emitted in zigzag order. */
  164472. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164473. if (prec)
  164474. emit_byte(cinfo, (int) (qval >> 8));
  164475. emit_byte(cinfo, (int) (qval & 0xFF));
  164476. }
  164477. qtbl->sent_table = TRUE;
  164478. }
  164479. return prec;
  164480. }
  164481. LOCAL(void)
  164482. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164483. /* Emit a DHT marker */
  164484. {
  164485. JHUFF_TBL * htbl;
  164486. int length, i;
  164487. if (is_ac) {
  164488. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164489. index += 0x10; /* output index has AC bit set */
  164490. } else {
  164491. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164492. }
  164493. if (htbl == NULL)
  164494. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164495. if (! htbl->sent_table) {
  164496. emit_marker(cinfo, M_DHT);
  164497. length = 0;
  164498. for (i = 1; i <= 16; i++)
  164499. length += htbl->bits[i];
  164500. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164501. emit_byte(cinfo, index);
  164502. for (i = 1; i <= 16; i++)
  164503. emit_byte(cinfo, htbl->bits[i]);
  164504. for (i = 0; i < length; i++)
  164505. emit_byte(cinfo, htbl->huffval[i]);
  164506. htbl->sent_table = TRUE;
  164507. }
  164508. }
  164509. LOCAL(void)
  164510. emit_dac (j_compress_ptr)
  164511. /* Emit a DAC marker */
  164512. /* Since the useful info is so small, we want to emit all the tables in */
  164513. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164514. {
  164515. #ifdef C_ARITH_CODING_SUPPORTED
  164516. char dc_in_use[NUM_ARITH_TBLS];
  164517. char ac_in_use[NUM_ARITH_TBLS];
  164518. int length, i;
  164519. jpeg_component_info *compptr;
  164520. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164521. dc_in_use[i] = ac_in_use[i] = 0;
  164522. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164523. compptr = cinfo->cur_comp_info[i];
  164524. dc_in_use[compptr->dc_tbl_no] = 1;
  164525. ac_in_use[compptr->ac_tbl_no] = 1;
  164526. }
  164527. length = 0;
  164528. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164529. length += dc_in_use[i] + ac_in_use[i];
  164530. emit_marker(cinfo, M_DAC);
  164531. emit_2bytes(cinfo, length*2 + 2);
  164532. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164533. if (dc_in_use[i]) {
  164534. emit_byte(cinfo, i);
  164535. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164536. }
  164537. if (ac_in_use[i]) {
  164538. emit_byte(cinfo, i + 0x10);
  164539. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164540. }
  164541. }
  164542. #endif /* C_ARITH_CODING_SUPPORTED */
  164543. }
  164544. LOCAL(void)
  164545. emit_dri (j_compress_ptr cinfo)
  164546. /* Emit a DRI marker */
  164547. {
  164548. emit_marker(cinfo, M_DRI);
  164549. emit_2bytes(cinfo, 4); /* fixed length */
  164550. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164551. }
  164552. LOCAL(void)
  164553. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164554. /* Emit a SOF marker */
  164555. {
  164556. int ci;
  164557. jpeg_component_info *compptr;
  164558. emit_marker(cinfo, code);
  164559. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164560. /* Make sure image isn't bigger than SOF field can handle */
  164561. if ((long) cinfo->image_height > 65535L ||
  164562. (long) cinfo->image_width > 65535L)
  164563. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164564. emit_byte(cinfo, cinfo->data_precision);
  164565. emit_2bytes(cinfo, (int) cinfo->image_height);
  164566. emit_2bytes(cinfo, (int) cinfo->image_width);
  164567. emit_byte(cinfo, cinfo->num_components);
  164568. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164569. ci++, compptr++) {
  164570. emit_byte(cinfo, compptr->component_id);
  164571. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164572. emit_byte(cinfo, compptr->quant_tbl_no);
  164573. }
  164574. }
  164575. LOCAL(void)
  164576. emit_sos (j_compress_ptr cinfo)
  164577. /* Emit a SOS marker */
  164578. {
  164579. int i, td, ta;
  164580. jpeg_component_info *compptr;
  164581. emit_marker(cinfo, M_SOS);
  164582. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164583. emit_byte(cinfo, cinfo->comps_in_scan);
  164584. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164585. compptr = cinfo->cur_comp_info[i];
  164586. emit_byte(cinfo, compptr->component_id);
  164587. td = compptr->dc_tbl_no;
  164588. ta = compptr->ac_tbl_no;
  164589. if (cinfo->progressive_mode) {
  164590. /* Progressive mode: only DC or only AC tables are used in one scan;
  164591. * furthermore, Huffman coding of DC refinement uses no table at all.
  164592. * We emit 0 for unused field(s); this is recommended by the P&M text
  164593. * but does not seem to be specified in the standard.
  164594. */
  164595. if (cinfo->Ss == 0) {
  164596. ta = 0; /* DC scan */
  164597. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164598. td = 0; /* no DC table either */
  164599. } else {
  164600. td = 0; /* AC scan */
  164601. }
  164602. }
  164603. emit_byte(cinfo, (td << 4) + ta);
  164604. }
  164605. emit_byte(cinfo, cinfo->Ss);
  164606. emit_byte(cinfo, cinfo->Se);
  164607. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164608. }
  164609. LOCAL(void)
  164610. emit_jfif_app0 (j_compress_ptr cinfo)
  164611. /* Emit a JFIF-compliant APP0 marker */
  164612. {
  164613. /*
  164614. * Length of APP0 block (2 bytes)
  164615. * Block ID (4 bytes - ASCII "JFIF")
  164616. * Zero byte (1 byte to terminate the ID string)
  164617. * Version Major, Minor (2 bytes - major first)
  164618. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164619. * Xdpu (2 bytes - dots per unit horizontal)
  164620. * Ydpu (2 bytes - dots per unit vertical)
  164621. * Thumbnail X size (1 byte)
  164622. * Thumbnail Y size (1 byte)
  164623. */
  164624. emit_marker(cinfo, M_APP0);
  164625. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164626. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164627. emit_byte(cinfo, 0x46);
  164628. emit_byte(cinfo, 0x49);
  164629. emit_byte(cinfo, 0x46);
  164630. emit_byte(cinfo, 0);
  164631. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164632. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164633. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164634. emit_2bytes(cinfo, (int) cinfo->X_density);
  164635. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164636. emit_byte(cinfo, 0); /* No thumbnail image */
  164637. emit_byte(cinfo, 0);
  164638. }
  164639. LOCAL(void)
  164640. emit_adobe_app14 (j_compress_ptr cinfo)
  164641. /* Emit an Adobe APP14 marker */
  164642. {
  164643. /*
  164644. * Length of APP14 block (2 bytes)
  164645. * Block ID (5 bytes - ASCII "Adobe")
  164646. * Version Number (2 bytes - currently 100)
  164647. * Flags0 (2 bytes - currently 0)
  164648. * Flags1 (2 bytes - currently 0)
  164649. * Color transform (1 byte)
  164650. *
  164651. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164652. * now in circulation seem to use Version = 100, so that's what we write.
  164653. *
  164654. * We write the color transform byte as 1 if the JPEG color space is
  164655. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164656. * whether the encoder performed a transformation, which is pretty useless.
  164657. */
  164658. emit_marker(cinfo, M_APP14);
  164659. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164660. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164661. emit_byte(cinfo, 0x64);
  164662. emit_byte(cinfo, 0x6F);
  164663. emit_byte(cinfo, 0x62);
  164664. emit_byte(cinfo, 0x65);
  164665. emit_2bytes(cinfo, 100); /* Version */
  164666. emit_2bytes(cinfo, 0); /* Flags0 */
  164667. emit_2bytes(cinfo, 0); /* Flags1 */
  164668. switch (cinfo->jpeg_color_space) {
  164669. case JCS_YCbCr:
  164670. emit_byte(cinfo, 1); /* Color transform = 1 */
  164671. break;
  164672. case JCS_YCCK:
  164673. emit_byte(cinfo, 2); /* Color transform = 2 */
  164674. break;
  164675. default:
  164676. emit_byte(cinfo, 0); /* Color transform = 0 */
  164677. break;
  164678. }
  164679. }
  164680. /*
  164681. * These routines allow writing an arbitrary marker with parameters.
  164682. * The only intended use is to emit COM or APPn markers after calling
  164683. * write_file_header and before calling write_frame_header.
  164684. * Other uses are not guaranteed to produce desirable results.
  164685. * Counting the parameter bytes properly is the caller's responsibility.
  164686. */
  164687. METHODDEF(void)
  164688. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164689. /* Emit an arbitrary marker header */
  164690. {
  164691. if (datalen > (unsigned int) 65533) /* safety check */
  164692. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164693. emit_marker(cinfo, (JPEG_MARKER) marker);
  164694. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164695. }
  164696. METHODDEF(void)
  164697. write_marker_byte (j_compress_ptr cinfo, int val)
  164698. /* Emit one byte of marker parameters following write_marker_header */
  164699. {
  164700. emit_byte(cinfo, val);
  164701. }
  164702. /*
  164703. * Write datastream header.
  164704. * This consists of an SOI and optional APPn markers.
  164705. * We recommend use of the JFIF marker, but not the Adobe marker,
  164706. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164707. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164708. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164709. * Note that an application can write additional header markers after
  164710. * jpeg_start_compress returns.
  164711. */
  164712. METHODDEF(void)
  164713. write_file_header (j_compress_ptr cinfo)
  164714. {
  164715. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164716. emit_marker(cinfo, M_SOI); /* first the SOI */
  164717. /* SOI is defined to reset restart interval to 0 */
  164718. marker->last_restart_interval = 0;
  164719. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164720. emit_jfif_app0(cinfo);
  164721. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164722. emit_adobe_app14(cinfo);
  164723. }
  164724. /*
  164725. * Write frame header.
  164726. * This consists of DQT and SOFn markers.
  164727. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164728. * This avoids compatibility problems with incorrect implementations that
  164729. * try to error-check the quant table numbers as soon as they see the SOF.
  164730. */
  164731. METHODDEF(void)
  164732. write_frame_header (j_compress_ptr cinfo)
  164733. {
  164734. int ci, prec;
  164735. boolean is_baseline;
  164736. jpeg_component_info *compptr;
  164737. /* Emit DQT for each quantization table.
  164738. * Note that emit_dqt() suppresses any duplicate tables.
  164739. */
  164740. prec = 0;
  164741. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164742. ci++, compptr++) {
  164743. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164744. }
  164745. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164746. /* Check for a non-baseline specification.
  164747. * Note we assume that Huffman table numbers won't be changed later.
  164748. */
  164749. if (cinfo->arith_code || cinfo->progressive_mode ||
  164750. cinfo->data_precision != 8) {
  164751. is_baseline = FALSE;
  164752. } else {
  164753. is_baseline = TRUE;
  164754. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164755. ci++, compptr++) {
  164756. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164757. is_baseline = FALSE;
  164758. }
  164759. if (prec && is_baseline) {
  164760. is_baseline = FALSE;
  164761. /* If it's baseline except for quantizer size, warn the user */
  164762. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164763. }
  164764. }
  164765. /* Emit the proper SOF marker */
  164766. if (cinfo->arith_code) {
  164767. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164768. } else {
  164769. if (cinfo->progressive_mode)
  164770. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164771. else if (is_baseline)
  164772. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164773. else
  164774. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164775. }
  164776. }
  164777. /*
  164778. * Write scan header.
  164779. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164780. * Compressed data will be written following the SOS.
  164781. */
  164782. METHODDEF(void)
  164783. write_scan_header (j_compress_ptr cinfo)
  164784. {
  164785. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164786. int i;
  164787. jpeg_component_info *compptr;
  164788. if (cinfo->arith_code) {
  164789. /* Emit arith conditioning info. We may have some duplication
  164790. * if the file has multiple scans, but it's so small it's hardly
  164791. * worth worrying about.
  164792. */
  164793. emit_dac(cinfo);
  164794. } else {
  164795. /* Emit Huffman tables.
  164796. * Note that emit_dht() suppresses any duplicate tables.
  164797. */
  164798. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164799. compptr = cinfo->cur_comp_info[i];
  164800. if (cinfo->progressive_mode) {
  164801. /* Progressive mode: only DC or only AC tables are used in one scan */
  164802. if (cinfo->Ss == 0) {
  164803. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164804. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164805. } else {
  164806. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164807. }
  164808. } else {
  164809. /* Sequential mode: need both DC and AC tables */
  164810. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164811. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164812. }
  164813. }
  164814. }
  164815. /* Emit DRI if required --- note that DRI value could change for each scan.
  164816. * We avoid wasting space with unnecessary DRIs, however.
  164817. */
  164818. if (cinfo->restart_interval != marker->last_restart_interval) {
  164819. emit_dri(cinfo);
  164820. marker->last_restart_interval = cinfo->restart_interval;
  164821. }
  164822. emit_sos(cinfo);
  164823. }
  164824. /*
  164825. * Write datastream trailer.
  164826. */
  164827. METHODDEF(void)
  164828. write_file_trailer (j_compress_ptr cinfo)
  164829. {
  164830. emit_marker(cinfo, M_EOI);
  164831. }
  164832. /*
  164833. * Write an abbreviated table-specification datastream.
  164834. * This consists of SOI, DQT and DHT tables, and EOI.
  164835. * Any table that is defined and not marked sent_table = TRUE will be
  164836. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164837. */
  164838. METHODDEF(void)
  164839. write_tables_only (j_compress_ptr cinfo)
  164840. {
  164841. int i;
  164842. emit_marker(cinfo, M_SOI);
  164843. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164844. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164845. (void) emit_dqt(cinfo, i);
  164846. }
  164847. if (! cinfo->arith_code) {
  164848. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164849. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164850. emit_dht(cinfo, i, FALSE);
  164851. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164852. emit_dht(cinfo, i, TRUE);
  164853. }
  164854. }
  164855. emit_marker(cinfo, M_EOI);
  164856. }
  164857. /*
  164858. * Initialize the marker writer module.
  164859. */
  164860. GLOBAL(void)
  164861. jinit_marker_writer (j_compress_ptr cinfo)
  164862. {
  164863. my_marker_ptr marker;
  164864. /* Create the subobject */
  164865. marker = (my_marker_ptr)
  164866. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164867. SIZEOF(my_marker_writer));
  164868. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164869. /* Initialize method pointers */
  164870. marker->pub.write_file_header = write_file_header;
  164871. marker->pub.write_frame_header = write_frame_header;
  164872. marker->pub.write_scan_header = write_scan_header;
  164873. marker->pub.write_file_trailer = write_file_trailer;
  164874. marker->pub.write_tables_only = write_tables_only;
  164875. marker->pub.write_marker_header = write_marker_header;
  164876. marker->pub.write_marker_byte = write_marker_byte;
  164877. /* Initialize private state */
  164878. marker->last_restart_interval = 0;
  164879. }
  164880. /*** End of inlined file: jcmarker.c ***/
  164881. /*** Start of inlined file: jcmaster.c ***/
  164882. #define JPEG_INTERNALS
  164883. /* Private state */
  164884. typedef enum {
  164885. main_pass, /* input data, also do first output step */
  164886. huff_opt_pass, /* Huffman code optimization pass */
  164887. output_pass /* data output pass */
  164888. } c_pass_type;
  164889. typedef struct {
  164890. struct jpeg_comp_master pub; /* public fields */
  164891. c_pass_type pass_type; /* the type of the current pass */
  164892. int pass_number; /* # of passes completed */
  164893. int total_passes; /* total # of passes needed */
  164894. int scan_number; /* current index in scan_info[] */
  164895. } my_comp_master;
  164896. typedef my_comp_master * my_master_ptr;
  164897. /*
  164898. * Support routines that do various essential calculations.
  164899. */
  164900. LOCAL(void)
  164901. initial_setup (j_compress_ptr cinfo)
  164902. /* Do computations that are needed before master selection phase */
  164903. {
  164904. int ci;
  164905. jpeg_component_info *compptr;
  164906. long samplesperrow;
  164907. JDIMENSION jd_samplesperrow;
  164908. /* Sanity check on image dimensions */
  164909. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164910. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164911. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164912. /* Make sure image isn't bigger than I can handle */
  164913. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164914. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164915. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164916. /* Width of an input scanline must be representable as JDIMENSION. */
  164917. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164918. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164919. if ((long) jd_samplesperrow != samplesperrow)
  164920. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164921. /* For now, precision must match compiled-in value... */
  164922. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164923. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164924. /* Check that number of components won't exceed internal array sizes */
  164925. if (cinfo->num_components > MAX_COMPONENTS)
  164926. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164927. MAX_COMPONENTS);
  164928. /* Compute maximum sampling factors; check factor validity */
  164929. cinfo->max_h_samp_factor = 1;
  164930. cinfo->max_v_samp_factor = 1;
  164931. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164932. ci++, compptr++) {
  164933. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164934. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164935. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164936. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164937. compptr->h_samp_factor);
  164938. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164939. compptr->v_samp_factor);
  164940. }
  164941. /* Compute dimensions of components */
  164942. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164943. ci++, compptr++) {
  164944. /* Fill in the correct component_index value; don't rely on application */
  164945. compptr->component_index = ci;
  164946. /* For compression, we never do DCT scaling. */
  164947. compptr->DCT_scaled_size = DCTSIZE;
  164948. /* Size in DCT blocks */
  164949. compptr->width_in_blocks = (JDIMENSION)
  164950. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164951. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164952. compptr->height_in_blocks = (JDIMENSION)
  164953. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164954. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164955. /* Size in samples */
  164956. compptr->downsampled_width = (JDIMENSION)
  164957. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164958. (long) cinfo->max_h_samp_factor);
  164959. compptr->downsampled_height = (JDIMENSION)
  164960. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164961. (long) cinfo->max_v_samp_factor);
  164962. /* Mark component needed (this flag isn't actually used for compression) */
  164963. compptr->component_needed = TRUE;
  164964. }
  164965. /* Compute number of fully interleaved MCU rows (number of times that
  164966. * main controller will call coefficient controller).
  164967. */
  164968. cinfo->total_iMCU_rows = (JDIMENSION)
  164969. jdiv_round_up((long) cinfo->image_height,
  164970. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164971. }
  164972. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164973. LOCAL(void)
  164974. validate_script (j_compress_ptr cinfo)
  164975. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164976. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164977. */
  164978. {
  164979. const jpeg_scan_info * scanptr;
  164980. int scanno, ncomps, ci, coefi, thisi;
  164981. int Ss, Se, Ah, Al;
  164982. boolean component_sent[MAX_COMPONENTS];
  164983. #ifdef C_PROGRESSIVE_SUPPORTED
  164984. int * last_bitpos_ptr;
  164985. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164986. /* -1 until that coefficient has been seen; then last Al for it */
  164987. #endif
  164988. if (cinfo->num_scans <= 0)
  164989. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164990. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164991. * for progressive JPEG, no scan can have this.
  164992. */
  164993. scanptr = cinfo->scan_info;
  164994. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164995. #ifdef C_PROGRESSIVE_SUPPORTED
  164996. cinfo->progressive_mode = TRUE;
  164997. last_bitpos_ptr = & last_bitpos[0][0];
  164998. for (ci = 0; ci < cinfo->num_components; ci++)
  164999. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  165000. *last_bitpos_ptr++ = -1;
  165001. #else
  165002. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165003. #endif
  165004. } else {
  165005. cinfo->progressive_mode = FALSE;
  165006. for (ci = 0; ci < cinfo->num_components; ci++)
  165007. component_sent[ci] = FALSE;
  165008. }
  165009. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  165010. /* Validate component indexes */
  165011. ncomps = scanptr->comps_in_scan;
  165012. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  165013. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  165014. for (ci = 0; ci < ncomps; ci++) {
  165015. thisi = scanptr->component_index[ci];
  165016. if (thisi < 0 || thisi >= cinfo->num_components)
  165017. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165018. /* Components must appear in SOF order within each scan */
  165019. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  165020. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165021. }
  165022. /* Validate progression parameters */
  165023. Ss = scanptr->Ss;
  165024. Se = scanptr->Se;
  165025. Ah = scanptr->Ah;
  165026. Al = scanptr->Al;
  165027. if (cinfo->progressive_mode) {
  165028. #ifdef C_PROGRESSIVE_SUPPORTED
  165029. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  165030. * seems wrong: the upper bound ought to depend on data precision.
  165031. * Perhaps they really meant 0..N+1 for N-bit precision.
  165032. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  165033. * out-of-range reconstructed DC values during the first DC scan,
  165034. * which might cause problems for some decoders.
  165035. */
  165036. #if BITS_IN_JSAMPLE == 8
  165037. #define MAX_AH_AL 10
  165038. #else
  165039. #define MAX_AH_AL 13
  165040. #endif
  165041. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  165042. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  165043. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165044. if (Ss == 0) {
  165045. if (Se != 0) /* DC and AC together not OK */
  165046. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165047. } else {
  165048. if (ncomps != 1) /* AC scans must be for only one component */
  165049. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165050. }
  165051. for (ci = 0; ci < ncomps; ci++) {
  165052. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  165053. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  165054. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165055. for (coefi = Ss; coefi <= Se; coefi++) {
  165056. if (last_bitpos_ptr[coefi] < 0) {
  165057. /* first scan of this coefficient */
  165058. if (Ah != 0)
  165059. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165060. } else {
  165061. /* not first scan */
  165062. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  165063. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165064. }
  165065. last_bitpos_ptr[coefi] = Al;
  165066. }
  165067. }
  165068. #endif
  165069. } else {
  165070. /* For sequential JPEG, all progression parameters must be these: */
  165071. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  165072. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165073. /* Make sure components are not sent twice */
  165074. for (ci = 0; ci < ncomps; ci++) {
  165075. thisi = scanptr->component_index[ci];
  165076. if (component_sent[thisi])
  165077. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165078. component_sent[thisi] = TRUE;
  165079. }
  165080. }
  165081. }
  165082. /* Now verify that everything got sent. */
  165083. if (cinfo->progressive_mode) {
  165084. #ifdef C_PROGRESSIVE_SUPPORTED
  165085. /* For progressive mode, we only check that at least some DC data
  165086. * got sent for each component; the spec does not require that all bits
  165087. * of all coefficients be transmitted. Would it be wiser to enforce
  165088. * transmission of all coefficient bits??
  165089. */
  165090. for (ci = 0; ci < cinfo->num_components; ci++) {
  165091. if (last_bitpos[ci][0] < 0)
  165092. ERREXIT(cinfo, JERR_MISSING_DATA);
  165093. }
  165094. #endif
  165095. } else {
  165096. for (ci = 0; ci < cinfo->num_components; ci++) {
  165097. if (! component_sent[ci])
  165098. ERREXIT(cinfo, JERR_MISSING_DATA);
  165099. }
  165100. }
  165101. }
  165102. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  165103. LOCAL(void)
  165104. select_scan_parameters (j_compress_ptr cinfo)
  165105. /* Set up the scan parameters for the current scan */
  165106. {
  165107. int ci;
  165108. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165109. if (cinfo->scan_info != NULL) {
  165110. /* Prepare for current scan --- the script is already validated */
  165111. my_master_ptr master = (my_master_ptr) cinfo->master;
  165112. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  165113. cinfo->comps_in_scan = scanptr->comps_in_scan;
  165114. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  165115. cinfo->cur_comp_info[ci] =
  165116. &cinfo->comp_info[scanptr->component_index[ci]];
  165117. }
  165118. cinfo->Ss = scanptr->Ss;
  165119. cinfo->Se = scanptr->Se;
  165120. cinfo->Ah = scanptr->Ah;
  165121. cinfo->Al = scanptr->Al;
  165122. }
  165123. else
  165124. #endif
  165125. {
  165126. /* Prepare for single sequential-JPEG scan containing all components */
  165127. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  165128. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165129. MAX_COMPS_IN_SCAN);
  165130. cinfo->comps_in_scan = cinfo->num_components;
  165131. for (ci = 0; ci < cinfo->num_components; ci++) {
  165132. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  165133. }
  165134. cinfo->Ss = 0;
  165135. cinfo->Se = DCTSIZE2-1;
  165136. cinfo->Ah = 0;
  165137. cinfo->Al = 0;
  165138. }
  165139. }
  165140. LOCAL(void)
  165141. per_scan_setup (j_compress_ptr cinfo)
  165142. /* Do computations that are needed before processing a JPEG scan */
  165143. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  165144. {
  165145. int ci, mcublks, tmp;
  165146. jpeg_component_info *compptr;
  165147. if (cinfo->comps_in_scan == 1) {
  165148. /* Noninterleaved (single-component) scan */
  165149. compptr = cinfo->cur_comp_info[0];
  165150. /* Overall image size in MCUs */
  165151. cinfo->MCUs_per_row = compptr->width_in_blocks;
  165152. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165153. /* For noninterleaved scan, always one block per MCU */
  165154. compptr->MCU_width = 1;
  165155. compptr->MCU_height = 1;
  165156. compptr->MCU_blocks = 1;
  165157. compptr->MCU_sample_width = DCTSIZE;
  165158. compptr->last_col_width = 1;
  165159. /* For noninterleaved scans, it is convenient to define last_row_height
  165160. * as the number of block rows present in the last iMCU row.
  165161. */
  165162. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165163. if (tmp == 0) tmp = compptr->v_samp_factor;
  165164. compptr->last_row_height = tmp;
  165165. /* Prepare array describing MCU composition */
  165166. cinfo->blocks_in_MCU = 1;
  165167. cinfo->MCU_membership[0] = 0;
  165168. } else {
  165169. /* Interleaved (multi-component) scan */
  165170. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165171. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165172. MAX_COMPS_IN_SCAN);
  165173. /* Overall image size in MCUs */
  165174. cinfo->MCUs_per_row = (JDIMENSION)
  165175. jdiv_round_up((long) cinfo->image_width,
  165176. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165177. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165178. jdiv_round_up((long) cinfo->image_height,
  165179. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165180. cinfo->blocks_in_MCU = 0;
  165181. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165182. compptr = cinfo->cur_comp_info[ci];
  165183. /* Sampling factors give # of blocks of component in each MCU */
  165184. compptr->MCU_width = compptr->h_samp_factor;
  165185. compptr->MCU_height = compptr->v_samp_factor;
  165186. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165187. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  165188. /* Figure number of non-dummy blocks in last MCU column & row */
  165189. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165190. if (tmp == 0) tmp = compptr->MCU_width;
  165191. compptr->last_col_width = tmp;
  165192. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165193. if (tmp == 0) tmp = compptr->MCU_height;
  165194. compptr->last_row_height = tmp;
  165195. /* Prepare array describing MCU composition */
  165196. mcublks = compptr->MCU_blocks;
  165197. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  165198. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165199. while (mcublks-- > 0) {
  165200. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165201. }
  165202. }
  165203. }
  165204. /* Convert restart specified in rows to actual MCU count. */
  165205. /* Note that count must fit in 16 bits, so we provide limiting. */
  165206. if (cinfo->restart_in_rows > 0) {
  165207. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165208. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165209. }
  165210. }
  165211. /*
  165212. * Per-pass setup.
  165213. * This is called at the beginning of each pass. We determine which modules
  165214. * will be active during this pass and give them appropriate start_pass calls.
  165215. * We also set is_last_pass to indicate whether any more passes will be
  165216. * required.
  165217. */
  165218. METHODDEF(void)
  165219. prepare_for_pass (j_compress_ptr cinfo)
  165220. {
  165221. my_master_ptr master = (my_master_ptr) cinfo->master;
  165222. switch (master->pass_type) {
  165223. case main_pass:
  165224. /* Initial pass: will collect input data, and do either Huffman
  165225. * optimization or data output for the first scan.
  165226. */
  165227. select_scan_parameters(cinfo);
  165228. per_scan_setup(cinfo);
  165229. if (! cinfo->raw_data_in) {
  165230. (*cinfo->cconvert->start_pass) (cinfo);
  165231. (*cinfo->downsample->start_pass) (cinfo);
  165232. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165233. }
  165234. (*cinfo->fdct->start_pass) (cinfo);
  165235. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165236. (*cinfo->coef->start_pass) (cinfo,
  165237. (master->total_passes > 1 ?
  165238. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165239. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165240. if (cinfo->optimize_coding) {
  165241. /* No immediate data output; postpone writing frame/scan headers */
  165242. master->pub.call_pass_startup = FALSE;
  165243. } else {
  165244. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165245. master->pub.call_pass_startup = TRUE;
  165246. }
  165247. break;
  165248. #ifdef ENTROPY_OPT_SUPPORTED
  165249. case huff_opt_pass:
  165250. /* Do Huffman optimization for a scan after the first one. */
  165251. select_scan_parameters(cinfo);
  165252. per_scan_setup(cinfo);
  165253. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165254. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165255. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165256. master->pub.call_pass_startup = FALSE;
  165257. break;
  165258. }
  165259. /* Special case: Huffman DC refinement scans need no Huffman table
  165260. * and therefore we can skip the optimization pass for them.
  165261. */
  165262. master->pass_type = output_pass;
  165263. master->pass_number++;
  165264. /*FALLTHROUGH*/
  165265. #endif
  165266. case output_pass:
  165267. /* Do a data-output pass. */
  165268. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165269. if (! cinfo->optimize_coding) {
  165270. select_scan_parameters(cinfo);
  165271. per_scan_setup(cinfo);
  165272. }
  165273. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165274. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165275. /* We emit frame/scan headers now */
  165276. if (master->scan_number == 0)
  165277. (*cinfo->marker->write_frame_header) (cinfo);
  165278. (*cinfo->marker->write_scan_header) (cinfo);
  165279. master->pub.call_pass_startup = FALSE;
  165280. break;
  165281. default:
  165282. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165283. }
  165284. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165285. /* Set up progress monitor's pass info if present */
  165286. if (cinfo->progress != NULL) {
  165287. cinfo->progress->completed_passes = master->pass_number;
  165288. cinfo->progress->total_passes = master->total_passes;
  165289. }
  165290. }
  165291. /*
  165292. * Special start-of-pass hook.
  165293. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165294. * In single-pass processing, we need this hook because we don't want to
  165295. * write frame/scan headers during jpeg_start_compress; we want to let the
  165296. * application write COM markers etc. between jpeg_start_compress and the
  165297. * jpeg_write_scanlines loop.
  165298. * In multi-pass processing, this routine is not used.
  165299. */
  165300. METHODDEF(void)
  165301. pass_startup (j_compress_ptr cinfo)
  165302. {
  165303. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165304. (*cinfo->marker->write_frame_header) (cinfo);
  165305. (*cinfo->marker->write_scan_header) (cinfo);
  165306. }
  165307. /*
  165308. * Finish up at end of pass.
  165309. */
  165310. METHODDEF(void)
  165311. finish_pass_master (j_compress_ptr cinfo)
  165312. {
  165313. my_master_ptr master = (my_master_ptr) cinfo->master;
  165314. /* The entropy coder always needs an end-of-pass call,
  165315. * either to analyze statistics or to flush its output buffer.
  165316. */
  165317. (*cinfo->entropy->finish_pass) (cinfo);
  165318. /* Update state for next pass */
  165319. switch (master->pass_type) {
  165320. case main_pass:
  165321. /* next pass is either output of scan 0 (after optimization)
  165322. * or output of scan 1 (if no optimization).
  165323. */
  165324. master->pass_type = output_pass;
  165325. if (! cinfo->optimize_coding)
  165326. master->scan_number++;
  165327. break;
  165328. case huff_opt_pass:
  165329. /* next pass is always output of current scan */
  165330. master->pass_type = output_pass;
  165331. break;
  165332. case output_pass:
  165333. /* next pass is either optimization or output of next scan */
  165334. if (cinfo->optimize_coding)
  165335. master->pass_type = huff_opt_pass;
  165336. master->scan_number++;
  165337. break;
  165338. }
  165339. master->pass_number++;
  165340. }
  165341. /*
  165342. * Initialize master compression control.
  165343. */
  165344. GLOBAL(void)
  165345. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165346. {
  165347. my_master_ptr master;
  165348. master = (my_master_ptr)
  165349. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165350. SIZEOF(my_comp_master));
  165351. cinfo->master = (struct jpeg_comp_master *) master;
  165352. master->pub.prepare_for_pass = prepare_for_pass;
  165353. master->pub.pass_startup = pass_startup;
  165354. master->pub.finish_pass = finish_pass_master;
  165355. master->pub.is_last_pass = FALSE;
  165356. /* Validate parameters, determine derived values */
  165357. initial_setup(cinfo);
  165358. if (cinfo->scan_info != NULL) {
  165359. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165360. validate_script(cinfo);
  165361. #else
  165362. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165363. #endif
  165364. } else {
  165365. cinfo->progressive_mode = FALSE;
  165366. cinfo->num_scans = 1;
  165367. }
  165368. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165369. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165370. /* Initialize my private state */
  165371. if (transcode_only) {
  165372. /* no main pass in transcoding */
  165373. if (cinfo->optimize_coding)
  165374. master->pass_type = huff_opt_pass;
  165375. else
  165376. master->pass_type = output_pass;
  165377. } else {
  165378. /* for normal compression, first pass is always this type: */
  165379. master->pass_type = main_pass;
  165380. }
  165381. master->scan_number = 0;
  165382. master->pass_number = 0;
  165383. if (cinfo->optimize_coding)
  165384. master->total_passes = cinfo->num_scans * 2;
  165385. else
  165386. master->total_passes = cinfo->num_scans;
  165387. }
  165388. /*** End of inlined file: jcmaster.c ***/
  165389. /*** Start of inlined file: jcomapi.c ***/
  165390. #define JPEG_INTERNALS
  165391. /*
  165392. * Abort processing of a JPEG compression or decompression operation,
  165393. * but don't destroy the object itself.
  165394. *
  165395. * For this, we merely clean up all the nonpermanent memory pools.
  165396. * Note that temp files (virtual arrays) are not allowed to belong to
  165397. * the permanent pool, so we will be able to close all temp files here.
  165398. * Closing a data source or destination, if necessary, is the application's
  165399. * responsibility.
  165400. */
  165401. GLOBAL(void)
  165402. jpeg_abort (j_common_ptr cinfo)
  165403. {
  165404. int pool;
  165405. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165406. if (cinfo->mem == NULL)
  165407. return;
  165408. /* Releasing pools in reverse order might help avoid fragmentation
  165409. * with some (brain-damaged) malloc libraries.
  165410. */
  165411. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165412. (*cinfo->mem->free_pool) (cinfo, pool);
  165413. }
  165414. /* Reset overall state for possible reuse of object */
  165415. if (cinfo->is_decompressor) {
  165416. cinfo->global_state = DSTATE_START;
  165417. /* Try to keep application from accessing now-deleted marker list.
  165418. * A bit kludgy to do it here, but this is the most central place.
  165419. */
  165420. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165421. } else {
  165422. cinfo->global_state = CSTATE_START;
  165423. }
  165424. }
  165425. /*
  165426. * Destruction of a JPEG object.
  165427. *
  165428. * Everything gets deallocated except the master jpeg_compress_struct itself
  165429. * and the error manager struct. Both of these are supplied by the application
  165430. * and must be freed, if necessary, by the application. (Often they are on
  165431. * the stack and so don't need to be freed anyway.)
  165432. * Closing a data source or destination, if necessary, is the application's
  165433. * responsibility.
  165434. */
  165435. GLOBAL(void)
  165436. jpeg_destroy (j_common_ptr cinfo)
  165437. {
  165438. /* We need only tell the memory manager to release everything. */
  165439. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165440. if (cinfo->mem != NULL)
  165441. (*cinfo->mem->self_destruct) (cinfo);
  165442. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165443. cinfo->global_state = 0; /* mark it destroyed */
  165444. }
  165445. /*
  165446. * Convenience routines for allocating quantization and Huffman tables.
  165447. * (Would jutils.c be a more reasonable place to put these?)
  165448. */
  165449. GLOBAL(JQUANT_TBL *)
  165450. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165451. {
  165452. JQUANT_TBL *tbl;
  165453. tbl = (JQUANT_TBL *)
  165454. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165455. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165456. return tbl;
  165457. }
  165458. GLOBAL(JHUFF_TBL *)
  165459. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165460. {
  165461. JHUFF_TBL *tbl;
  165462. tbl = (JHUFF_TBL *)
  165463. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165464. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165465. return tbl;
  165466. }
  165467. /*** End of inlined file: jcomapi.c ***/
  165468. /*** Start of inlined file: jcparam.c ***/
  165469. #define JPEG_INTERNALS
  165470. /*
  165471. * Quantization table setup routines
  165472. */
  165473. GLOBAL(void)
  165474. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165475. const unsigned int *basic_table,
  165476. int scale_factor, boolean force_baseline)
  165477. /* Define a quantization table equal to the basic_table times
  165478. * a scale factor (given as a percentage).
  165479. * If force_baseline is TRUE, the computed quantization table entries
  165480. * are limited to 1..255 for JPEG baseline compatibility.
  165481. */
  165482. {
  165483. JQUANT_TBL ** qtblptr;
  165484. int i;
  165485. long temp;
  165486. /* Safety check to ensure start_compress not called yet. */
  165487. if (cinfo->global_state != CSTATE_START)
  165488. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165489. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165490. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165491. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165492. if (*qtblptr == NULL)
  165493. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165494. for (i = 0; i < DCTSIZE2; i++) {
  165495. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165496. /* limit the values to the valid range */
  165497. if (temp <= 0L) temp = 1L;
  165498. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165499. if (force_baseline && temp > 255L)
  165500. temp = 255L; /* limit to baseline range if requested */
  165501. (*qtblptr)->quantval[i] = (UINT16) temp;
  165502. }
  165503. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165504. (*qtblptr)->sent_table = FALSE;
  165505. }
  165506. GLOBAL(void)
  165507. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165508. boolean force_baseline)
  165509. /* Set or change the 'quality' (quantization) setting, using default tables
  165510. * and a straight percentage-scaling quality scale. In most cases it's better
  165511. * to use jpeg_set_quality (below); this entry point is provided for
  165512. * applications that insist on a linear percentage scaling.
  165513. */
  165514. {
  165515. /* These are the sample quantization tables given in JPEG spec section K.1.
  165516. * The spec says that the values given produce "good" quality, and
  165517. * when divided by 2, "very good" quality.
  165518. */
  165519. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165520. 16, 11, 10, 16, 24, 40, 51, 61,
  165521. 12, 12, 14, 19, 26, 58, 60, 55,
  165522. 14, 13, 16, 24, 40, 57, 69, 56,
  165523. 14, 17, 22, 29, 51, 87, 80, 62,
  165524. 18, 22, 37, 56, 68, 109, 103, 77,
  165525. 24, 35, 55, 64, 81, 104, 113, 92,
  165526. 49, 64, 78, 87, 103, 121, 120, 101,
  165527. 72, 92, 95, 98, 112, 100, 103, 99
  165528. };
  165529. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165530. 17, 18, 24, 47, 99, 99, 99, 99,
  165531. 18, 21, 26, 66, 99, 99, 99, 99,
  165532. 24, 26, 56, 99, 99, 99, 99, 99,
  165533. 47, 66, 99, 99, 99, 99, 99, 99,
  165534. 99, 99, 99, 99, 99, 99, 99, 99,
  165535. 99, 99, 99, 99, 99, 99, 99, 99,
  165536. 99, 99, 99, 99, 99, 99, 99, 99,
  165537. 99, 99, 99, 99, 99, 99, 99, 99
  165538. };
  165539. /* Set up two quantization tables using the specified scaling */
  165540. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165541. scale_factor, force_baseline);
  165542. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165543. scale_factor, force_baseline);
  165544. }
  165545. GLOBAL(int)
  165546. jpeg_quality_scaling (int quality)
  165547. /* Convert a user-specified quality rating to a percentage scaling factor
  165548. * for an underlying quantization table, using our recommended scaling curve.
  165549. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165550. */
  165551. {
  165552. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165553. if (quality <= 0) quality = 1;
  165554. if (quality > 100) quality = 100;
  165555. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165556. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165557. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165558. * to make all the table entries 1 (hence, minimum quantization loss).
  165559. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165560. */
  165561. if (quality < 50)
  165562. quality = 5000 / quality;
  165563. else
  165564. quality = 200 - quality*2;
  165565. return quality;
  165566. }
  165567. GLOBAL(void)
  165568. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165569. /* Set or change the 'quality' (quantization) setting, using default tables.
  165570. * This is the standard quality-adjusting entry point for typical user
  165571. * interfaces; only those who want detailed control over quantization tables
  165572. * would use the preceding three routines directly.
  165573. */
  165574. {
  165575. /* Convert user 0-100 rating to percentage scaling */
  165576. quality = jpeg_quality_scaling(quality);
  165577. /* Set up standard quality tables */
  165578. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165579. }
  165580. /*
  165581. * Huffman table setup routines
  165582. */
  165583. LOCAL(void)
  165584. add_huff_table (j_compress_ptr cinfo,
  165585. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165586. /* Define a Huffman table */
  165587. {
  165588. int nsymbols, len;
  165589. if (*htblptr == NULL)
  165590. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165591. /* Copy the number-of-symbols-of-each-code-length counts */
  165592. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165593. /* Validate the counts. We do this here mainly so we can copy the right
  165594. * number of symbols from the val[] array, without risking marching off
  165595. * the end of memory. jchuff.c will do a more thorough test later.
  165596. */
  165597. nsymbols = 0;
  165598. for (len = 1; len <= 16; len++)
  165599. nsymbols += bits[len];
  165600. if (nsymbols < 1 || nsymbols > 256)
  165601. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165602. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165603. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165604. (*htblptr)->sent_table = FALSE;
  165605. }
  165606. LOCAL(void)
  165607. std_huff_tables (j_compress_ptr cinfo)
  165608. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165609. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165610. {
  165611. static const UINT8 bits_dc_luminance[17] =
  165612. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165613. static const UINT8 val_dc_luminance[] =
  165614. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165615. static const UINT8 bits_dc_chrominance[17] =
  165616. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165617. static const UINT8 val_dc_chrominance[] =
  165618. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165619. static const UINT8 bits_ac_luminance[17] =
  165620. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165621. static const UINT8 val_ac_luminance[] =
  165622. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165623. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165624. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165625. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165626. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165627. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165628. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165629. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165630. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165631. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165632. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165633. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165634. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165635. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165636. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165637. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165638. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165639. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165640. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165641. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165642. 0xf9, 0xfa };
  165643. static const UINT8 bits_ac_chrominance[17] =
  165644. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165645. static const UINT8 val_ac_chrominance[] =
  165646. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165647. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165648. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165649. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165650. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165651. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165652. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165653. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165654. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165655. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165656. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165657. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165658. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165659. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165660. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165661. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165662. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165663. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165664. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165665. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165666. 0xf9, 0xfa };
  165667. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165668. bits_dc_luminance, val_dc_luminance);
  165669. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165670. bits_ac_luminance, val_ac_luminance);
  165671. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165672. bits_dc_chrominance, val_dc_chrominance);
  165673. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165674. bits_ac_chrominance, val_ac_chrominance);
  165675. }
  165676. /*
  165677. * Default parameter setup for compression.
  165678. *
  165679. * Applications that don't choose to use this routine must do their
  165680. * own setup of all these parameters. Alternately, you can call this
  165681. * to establish defaults and then alter parameters selectively. This
  165682. * is the recommended approach since, if we add any new parameters,
  165683. * your code will still work (they'll be set to reasonable defaults).
  165684. */
  165685. GLOBAL(void)
  165686. jpeg_set_defaults (j_compress_ptr cinfo)
  165687. {
  165688. int i;
  165689. /* Safety check to ensure start_compress not called yet. */
  165690. if (cinfo->global_state != CSTATE_START)
  165691. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165692. /* Allocate comp_info array large enough for maximum component count.
  165693. * Array is made permanent in case application wants to compress
  165694. * multiple images at same param settings.
  165695. */
  165696. if (cinfo->comp_info == NULL)
  165697. cinfo->comp_info = (jpeg_component_info *)
  165698. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165699. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165700. /* Initialize everything not dependent on the color space */
  165701. cinfo->data_precision = BITS_IN_JSAMPLE;
  165702. /* Set up two quantization tables using default quality of 75 */
  165703. jpeg_set_quality(cinfo, 75, TRUE);
  165704. /* Set up two Huffman tables */
  165705. std_huff_tables(cinfo);
  165706. /* Initialize default arithmetic coding conditioning */
  165707. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165708. cinfo->arith_dc_L[i] = 0;
  165709. cinfo->arith_dc_U[i] = 1;
  165710. cinfo->arith_ac_K[i] = 5;
  165711. }
  165712. /* Default is no multiple-scan output */
  165713. cinfo->scan_info = NULL;
  165714. cinfo->num_scans = 0;
  165715. /* Expect normal source image, not raw downsampled data */
  165716. cinfo->raw_data_in = FALSE;
  165717. /* Use Huffman coding, not arithmetic coding, by default */
  165718. cinfo->arith_code = FALSE;
  165719. /* By default, don't do extra passes to optimize entropy coding */
  165720. cinfo->optimize_coding = FALSE;
  165721. /* The standard Huffman tables are only valid for 8-bit data precision.
  165722. * If the precision is higher, force optimization on so that usable
  165723. * tables will be computed. This test can be removed if default tables
  165724. * are supplied that are valid for the desired precision.
  165725. */
  165726. if (cinfo->data_precision > 8)
  165727. cinfo->optimize_coding = TRUE;
  165728. /* By default, use the simpler non-cosited sampling alignment */
  165729. cinfo->CCIR601_sampling = FALSE;
  165730. /* No input smoothing */
  165731. cinfo->smoothing_factor = 0;
  165732. /* DCT algorithm preference */
  165733. cinfo->dct_method = JDCT_DEFAULT;
  165734. /* No restart markers */
  165735. cinfo->restart_interval = 0;
  165736. cinfo->restart_in_rows = 0;
  165737. /* Fill in default JFIF marker parameters. Note that whether the marker
  165738. * will actually be written is determined by jpeg_set_colorspace.
  165739. *
  165740. * By default, the library emits JFIF version code 1.01.
  165741. * An application that wants to emit JFIF 1.02 extension markers should set
  165742. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165743. * to 1.02, but there may still be some decoders in use that will complain
  165744. * about that; saying 1.01 should minimize compatibility problems.
  165745. */
  165746. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165747. cinfo->JFIF_minor_version = 1;
  165748. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165749. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165750. cinfo->Y_density = 1;
  165751. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165752. jpeg_default_colorspace(cinfo);
  165753. }
  165754. /*
  165755. * Select an appropriate JPEG colorspace for in_color_space.
  165756. */
  165757. GLOBAL(void)
  165758. jpeg_default_colorspace (j_compress_ptr cinfo)
  165759. {
  165760. switch (cinfo->in_color_space) {
  165761. case JCS_GRAYSCALE:
  165762. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165763. break;
  165764. case JCS_RGB:
  165765. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165766. break;
  165767. case JCS_YCbCr:
  165768. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165769. break;
  165770. case JCS_CMYK:
  165771. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165772. break;
  165773. case JCS_YCCK:
  165774. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165775. break;
  165776. case JCS_UNKNOWN:
  165777. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165778. break;
  165779. default:
  165780. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165781. }
  165782. }
  165783. /*
  165784. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165785. */
  165786. GLOBAL(void)
  165787. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165788. {
  165789. jpeg_component_info * compptr;
  165790. int ci;
  165791. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165792. (compptr = &cinfo->comp_info[index], \
  165793. compptr->component_id = (id), \
  165794. compptr->h_samp_factor = (hsamp), \
  165795. compptr->v_samp_factor = (vsamp), \
  165796. compptr->quant_tbl_no = (quant), \
  165797. compptr->dc_tbl_no = (dctbl), \
  165798. compptr->ac_tbl_no = (actbl) )
  165799. /* Safety check to ensure start_compress not called yet. */
  165800. if (cinfo->global_state != CSTATE_START)
  165801. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165802. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165803. * tables 1 for chrominance components.
  165804. */
  165805. cinfo->jpeg_color_space = colorspace;
  165806. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165807. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165808. switch (colorspace) {
  165809. case JCS_GRAYSCALE:
  165810. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165811. cinfo->num_components = 1;
  165812. /* JFIF specifies component ID 1 */
  165813. SET_COMP(0, 1, 1,1, 0, 0,0);
  165814. break;
  165815. case JCS_RGB:
  165816. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165817. cinfo->num_components = 3;
  165818. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165819. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165820. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165821. break;
  165822. case JCS_YCbCr:
  165823. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165824. cinfo->num_components = 3;
  165825. /* JFIF specifies component IDs 1,2,3 */
  165826. /* We default to 2x2 subsamples of chrominance */
  165827. SET_COMP(0, 1, 2,2, 0, 0,0);
  165828. SET_COMP(1, 2, 1,1, 1, 1,1);
  165829. SET_COMP(2, 3, 1,1, 1, 1,1);
  165830. break;
  165831. case JCS_CMYK:
  165832. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165833. cinfo->num_components = 4;
  165834. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165835. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165836. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165837. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165838. break;
  165839. case JCS_YCCK:
  165840. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165841. cinfo->num_components = 4;
  165842. SET_COMP(0, 1, 2,2, 0, 0,0);
  165843. SET_COMP(1, 2, 1,1, 1, 1,1);
  165844. SET_COMP(2, 3, 1,1, 1, 1,1);
  165845. SET_COMP(3, 4, 2,2, 0, 0,0);
  165846. break;
  165847. case JCS_UNKNOWN:
  165848. cinfo->num_components = cinfo->input_components;
  165849. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165850. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165851. MAX_COMPONENTS);
  165852. for (ci = 0; ci < cinfo->num_components; ci++) {
  165853. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165854. }
  165855. break;
  165856. default:
  165857. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165858. }
  165859. }
  165860. #ifdef C_PROGRESSIVE_SUPPORTED
  165861. LOCAL(jpeg_scan_info *)
  165862. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165863. int Ss, int Se, int Ah, int Al)
  165864. /* Support routine: generate one scan for specified component */
  165865. {
  165866. scanptr->comps_in_scan = 1;
  165867. scanptr->component_index[0] = ci;
  165868. scanptr->Ss = Ss;
  165869. scanptr->Se = Se;
  165870. scanptr->Ah = Ah;
  165871. scanptr->Al = Al;
  165872. scanptr++;
  165873. return scanptr;
  165874. }
  165875. LOCAL(jpeg_scan_info *)
  165876. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165877. int Ss, int Se, int Ah, int Al)
  165878. /* Support routine: generate one scan for each component */
  165879. {
  165880. int ci;
  165881. for (ci = 0; ci < ncomps; ci++) {
  165882. scanptr->comps_in_scan = 1;
  165883. scanptr->component_index[0] = ci;
  165884. scanptr->Ss = Ss;
  165885. scanptr->Se = Se;
  165886. scanptr->Ah = Ah;
  165887. scanptr->Al = Al;
  165888. scanptr++;
  165889. }
  165890. return scanptr;
  165891. }
  165892. LOCAL(jpeg_scan_info *)
  165893. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165894. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165895. {
  165896. int ci;
  165897. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165898. /* Single interleaved DC scan */
  165899. scanptr->comps_in_scan = ncomps;
  165900. for (ci = 0; ci < ncomps; ci++)
  165901. scanptr->component_index[ci] = ci;
  165902. scanptr->Ss = scanptr->Se = 0;
  165903. scanptr->Ah = Ah;
  165904. scanptr->Al = Al;
  165905. scanptr++;
  165906. } else {
  165907. /* Noninterleaved DC scan for each component */
  165908. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165909. }
  165910. return scanptr;
  165911. }
  165912. /*
  165913. * Create a recommended progressive-JPEG script.
  165914. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165915. */
  165916. GLOBAL(void)
  165917. jpeg_simple_progression (j_compress_ptr cinfo)
  165918. {
  165919. int ncomps = cinfo->num_components;
  165920. int nscans;
  165921. jpeg_scan_info * scanptr;
  165922. /* Safety check to ensure start_compress not called yet. */
  165923. if (cinfo->global_state != CSTATE_START)
  165924. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165925. /* Figure space needed for script. Calculation must match code below! */
  165926. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165927. /* Custom script for YCbCr color images. */
  165928. nscans = 10;
  165929. } else {
  165930. /* All-purpose script for other color spaces. */
  165931. if (ncomps > MAX_COMPS_IN_SCAN)
  165932. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165933. else
  165934. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165935. }
  165936. /* Allocate space for script.
  165937. * We need to put it in the permanent pool in case the application performs
  165938. * multiple compressions without changing the settings. To avoid a memory
  165939. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165940. * object, we try to re-use previously allocated space, and we allocate
  165941. * enough space to handle YCbCr even if initially asked for grayscale.
  165942. */
  165943. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165944. cinfo->script_space_size = MAX(nscans, 10);
  165945. cinfo->script_space = (jpeg_scan_info *)
  165946. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165947. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165948. }
  165949. scanptr = cinfo->script_space;
  165950. cinfo->scan_info = scanptr;
  165951. cinfo->num_scans = nscans;
  165952. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165953. /* Custom script for YCbCr color images. */
  165954. /* Initial DC scan */
  165955. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165956. /* Initial AC scan: get some luma data out in a hurry */
  165957. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165958. /* Chroma data is too small to be worth expending many scans on */
  165959. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165960. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165961. /* Complete spectral selection for luma AC */
  165962. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165963. /* Refine next bit of luma AC */
  165964. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165965. /* Finish DC successive approximation */
  165966. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165967. /* Finish AC successive approximation */
  165968. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165969. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165970. /* Luma bottom bit comes last since it's usually largest scan */
  165971. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165972. } else {
  165973. /* All-purpose script for other color spaces. */
  165974. /* Successive approximation first pass */
  165975. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165976. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165977. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165978. /* Successive approximation second pass */
  165979. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165980. /* Successive approximation final pass */
  165981. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165982. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165983. }
  165984. }
  165985. #endif /* C_PROGRESSIVE_SUPPORTED */
  165986. /*** End of inlined file: jcparam.c ***/
  165987. /*** Start of inlined file: jcphuff.c ***/
  165988. #define JPEG_INTERNALS
  165989. #ifdef C_PROGRESSIVE_SUPPORTED
  165990. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165991. typedef struct {
  165992. struct jpeg_entropy_encoder pub; /* public fields */
  165993. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165994. boolean gather_statistics;
  165995. /* Bit-level coding status.
  165996. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165997. */
  165998. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165999. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  166000. INT32 put_buffer; /* current bit-accumulation buffer */
  166001. int put_bits; /* # of bits now in it */
  166002. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  166003. /* Coding status for DC components */
  166004. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166005. /* Coding status for AC components */
  166006. int ac_tbl_no; /* the table number of the single component */
  166007. unsigned int EOBRUN; /* run length of EOBs */
  166008. unsigned int BE; /* # of buffered correction bits before MCU */
  166009. char * bit_buffer; /* buffer for correction bits (1 per char) */
  166010. /* packing correction bits tightly would save some space but cost time... */
  166011. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166012. int next_restart_num; /* next restart number to write (0-7) */
  166013. /* Pointers to derived tables (these workspaces have image lifespan).
  166014. * Since any one scan codes only DC or only AC, we only need one set
  166015. * of tables, not one for DC and one for AC.
  166016. */
  166017. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  166018. /* Statistics tables for optimization; again, one set is enough */
  166019. long * count_ptrs[NUM_HUFF_TBLS];
  166020. } phuff_entropy_encoder;
  166021. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  166022. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  166023. * buffer can hold. Larger sizes may slightly improve compression, but
  166024. * 1000 is already well into the realm of overkill.
  166025. * The minimum safe size is 64 bits.
  166026. */
  166027. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  166028. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  166029. * We assume that int right shift is unsigned if INT32 right shift is,
  166030. * which should be safe.
  166031. */
  166032. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  166033. #define ISHIFT_TEMPS int ishift_temp;
  166034. #define IRIGHT_SHIFT(x,shft) \
  166035. ((ishift_temp = (x)) < 0 ? \
  166036. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  166037. (ishift_temp >> (shft)))
  166038. #else
  166039. #define ISHIFT_TEMPS
  166040. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  166041. #endif
  166042. /* Forward declarations */
  166043. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  166044. JBLOCKROW *MCU_data));
  166045. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  166046. JBLOCKROW *MCU_data));
  166047. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  166048. JBLOCKROW *MCU_data));
  166049. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  166050. JBLOCKROW *MCU_data));
  166051. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  166052. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  166053. /*
  166054. * Initialize for a Huffman-compressed scan using progressive JPEG.
  166055. */
  166056. METHODDEF(void)
  166057. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  166058. {
  166059. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166060. boolean is_DC_band;
  166061. int ci, tbl;
  166062. jpeg_component_info * compptr;
  166063. entropy->cinfo = cinfo;
  166064. entropy->gather_statistics = gather_statistics;
  166065. is_DC_band = (cinfo->Ss == 0);
  166066. /* We assume jcmaster.c already validated the scan parameters. */
  166067. /* Select execution routines */
  166068. if (cinfo->Ah == 0) {
  166069. if (is_DC_band)
  166070. entropy->pub.encode_mcu = encode_mcu_DC_first;
  166071. else
  166072. entropy->pub.encode_mcu = encode_mcu_AC_first;
  166073. } else {
  166074. if (is_DC_band)
  166075. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  166076. else {
  166077. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  166078. /* AC refinement needs a correction bit buffer */
  166079. if (entropy->bit_buffer == NULL)
  166080. entropy->bit_buffer = (char *)
  166081. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166082. MAX_CORR_BITS * SIZEOF(char));
  166083. }
  166084. }
  166085. if (gather_statistics)
  166086. entropy->pub.finish_pass = finish_pass_gather_phuff;
  166087. else
  166088. entropy->pub.finish_pass = finish_pass_phuff;
  166089. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  166090. * for AC coefficients.
  166091. */
  166092. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166093. compptr = cinfo->cur_comp_info[ci];
  166094. /* Initialize DC predictions to 0 */
  166095. entropy->last_dc_val[ci] = 0;
  166096. /* Get table index */
  166097. if (is_DC_band) {
  166098. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166099. continue;
  166100. tbl = compptr->dc_tbl_no;
  166101. } else {
  166102. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  166103. }
  166104. if (gather_statistics) {
  166105. /* Check for invalid table index */
  166106. /* (make_c_derived_tbl does this in the other path) */
  166107. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  166108. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  166109. /* Allocate and zero the statistics tables */
  166110. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  166111. if (entropy->count_ptrs[tbl] == NULL)
  166112. entropy->count_ptrs[tbl] = (long *)
  166113. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166114. 257 * SIZEOF(long));
  166115. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  166116. } else {
  166117. /* Compute derived values for Huffman table */
  166118. /* We may do this more than once for a table, but it's not expensive */
  166119. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  166120. & entropy->derived_tbls[tbl]);
  166121. }
  166122. }
  166123. /* Initialize AC stuff */
  166124. entropy->EOBRUN = 0;
  166125. entropy->BE = 0;
  166126. /* Initialize bit buffer to empty */
  166127. entropy->put_buffer = 0;
  166128. entropy->put_bits = 0;
  166129. /* Initialize restart stuff */
  166130. entropy->restarts_to_go = cinfo->restart_interval;
  166131. entropy->next_restart_num = 0;
  166132. }
  166133. /* Outputting bytes to the file.
  166134. * NB: these must be called only when actually outputting,
  166135. * that is, entropy->gather_statistics == FALSE.
  166136. */
  166137. /* Emit a byte */
  166138. #define emit_byte(entropy,val) \
  166139. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  166140. if (--(entropy)->free_in_buffer == 0) \
  166141. dump_buffer_p(entropy); }
  166142. LOCAL(void)
  166143. dump_buffer_p (phuff_entropy_ptr entropy)
  166144. /* Empty the output buffer; we do not support suspension in this module. */
  166145. {
  166146. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  166147. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  166148. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  166149. /* After a successful buffer dump, must reset buffer pointers */
  166150. entropy->next_output_byte = dest->next_output_byte;
  166151. entropy->free_in_buffer = dest->free_in_buffer;
  166152. }
  166153. /* Outputting bits to the file */
  166154. /* Only the right 24 bits of put_buffer are used; the valid bits are
  166155. * left-justified in this part. At most 16 bits can be passed to emit_bits
  166156. * in one call, and we never retain more than 7 bits in put_buffer
  166157. * between calls, so 24 bits are sufficient.
  166158. */
  166159. INLINE
  166160. LOCAL(void)
  166161. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  166162. /* Emit some bits, unless we are in gather mode */
  166163. {
  166164. /* This routine is heavily used, so it's worth coding tightly. */
  166165. register INT32 put_buffer = (INT32) code;
  166166. register int put_bits = entropy->put_bits;
  166167. /* if size is 0, caller used an invalid Huffman table entry */
  166168. if (size == 0)
  166169. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166170. if (entropy->gather_statistics)
  166171. return; /* do nothing if we're only getting stats */
  166172. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  166173. put_bits += size; /* new number of bits in buffer */
  166174. put_buffer <<= 24 - put_bits; /* align incoming bits */
  166175. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  166176. while (put_bits >= 8) {
  166177. int c = (int) ((put_buffer >> 16) & 0xFF);
  166178. emit_byte(entropy, c);
  166179. if (c == 0xFF) { /* need to stuff a zero byte? */
  166180. emit_byte(entropy, 0);
  166181. }
  166182. put_buffer <<= 8;
  166183. put_bits -= 8;
  166184. }
  166185. entropy->put_buffer = put_buffer; /* update variables */
  166186. entropy->put_bits = put_bits;
  166187. }
  166188. LOCAL(void)
  166189. flush_bits_p (phuff_entropy_ptr entropy)
  166190. {
  166191. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  166192. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  166193. entropy->put_bits = 0;
  166194. }
  166195. /*
  166196. * Emit (or just count) a Huffman symbol.
  166197. */
  166198. INLINE
  166199. LOCAL(void)
  166200. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166201. {
  166202. if (entropy->gather_statistics)
  166203. entropy->count_ptrs[tbl_no][symbol]++;
  166204. else {
  166205. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166206. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166207. }
  166208. }
  166209. /*
  166210. * Emit bits from a correction bit buffer.
  166211. */
  166212. LOCAL(void)
  166213. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166214. unsigned int nbits)
  166215. {
  166216. if (entropy->gather_statistics)
  166217. return; /* no real work */
  166218. while (nbits > 0) {
  166219. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166220. bufstart++;
  166221. nbits--;
  166222. }
  166223. }
  166224. /*
  166225. * Emit any pending EOBRUN symbol.
  166226. */
  166227. LOCAL(void)
  166228. emit_eobrun (phuff_entropy_ptr entropy)
  166229. {
  166230. register int temp, nbits;
  166231. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166232. temp = entropy->EOBRUN;
  166233. nbits = 0;
  166234. while ((temp >>= 1))
  166235. nbits++;
  166236. /* safety check: shouldn't happen given limited correction-bit buffer */
  166237. if (nbits > 14)
  166238. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166239. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166240. if (nbits)
  166241. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166242. entropy->EOBRUN = 0;
  166243. /* Emit any buffered correction bits */
  166244. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166245. entropy->BE = 0;
  166246. }
  166247. }
  166248. /*
  166249. * Emit a restart marker & resynchronize predictions.
  166250. */
  166251. LOCAL(void)
  166252. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166253. {
  166254. int ci;
  166255. emit_eobrun(entropy);
  166256. if (! entropy->gather_statistics) {
  166257. flush_bits_p(entropy);
  166258. emit_byte(entropy, 0xFF);
  166259. emit_byte(entropy, JPEG_RST0 + restart_num);
  166260. }
  166261. if (entropy->cinfo->Ss == 0) {
  166262. /* Re-initialize DC predictions to 0 */
  166263. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166264. entropy->last_dc_val[ci] = 0;
  166265. } else {
  166266. /* Re-initialize all AC-related fields to 0 */
  166267. entropy->EOBRUN = 0;
  166268. entropy->BE = 0;
  166269. }
  166270. }
  166271. /*
  166272. * MCU encoding for DC initial scan (either spectral selection,
  166273. * or first pass of successive approximation).
  166274. */
  166275. METHODDEF(boolean)
  166276. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166277. {
  166278. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166279. register int temp, temp2;
  166280. register int nbits;
  166281. int blkn, ci;
  166282. int Al = cinfo->Al;
  166283. JBLOCKROW block;
  166284. jpeg_component_info * compptr;
  166285. ISHIFT_TEMPS
  166286. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166287. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166288. /* Emit restart marker if needed */
  166289. if (cinfo->restart_interval)
  166290. if (entropy->restarts_to_go == 0)
  166291. emit_restart_p(entropy, entropy->next_restart_num);
  166292. /* Encode the MCU data blocks */
  166293. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166294. block = MCU_data[blkn];
  166295. ci = cinfo->MCU_membership[blkn];
  166296. compptr = cinfo->cur_comp_info[ci];
  166297. /* Compute the DC value after the required point transform by Al.
  166298. * This is simply an arithmetic right shift.
  166299. */
  166300. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166301. /* DC differences are figured on the point-transformed values. */
  166302. temp = temp2 - entropy->last_dc_val[ci];
  166303. entropy->last_dc_val[ci] = temp2;
  166304. /* Encode the DC coefficient difference per section G.1.2.1 */
  166305. temp2 = temp;
  166306. if (temp < 0) {
  166307. temp = -temp; /* temp is abs value of input */
  166308. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166309. /* This code assumes we are on a two's complement machine */
  166310. temp2--;
  166311. }
  166312. /* Find the number of bits needed for the magnitude of the coefficient */
  166313. nbits = 0;
  166314. while (temp) {
  166315. nbits++;
  166316. temp >>= 1;
  166317. }
  166318. /* Check for out-of-range coefficient values.
  166319. * Since we're encoding a difference, the range limit is twice as much.
  166320. */
  166321. if (nbits > MAX_COEF_BITS+1)
  166322. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166323. /* Count/emit the Huffman-coded symbol for the number of bits */
  166324. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166325. /* Emit that number of bits of the value, if positive, */
  166326. /* or the complement of its magnitude, if negative. */
  166327. if (nbits) /* emit_bits rejects calls with size 0 */
  166328. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166329. }
  166330. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166331. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166332. /* Update restart-interval state too */
  166333. if (cinfo->restart_interval) {
  166334. if (entropy->restarts_to_go == 0) {
  166335. entropy->restarts_to_go = cinfo->restart_interval;
  166336. entropy->next_restart_num++;
  166337. entropy->next_restart_num &= 7;
  166338. }
  166339. entropy->restarts_to_go--;
  166340. }
  166341. return TRUE;
  166342. }
  166343. /*
  166344. * MCU encoding for AC initial scan (either spectral selection,
  166345. * or first pass of successive approximation).
  166346. */
  166347. METHODDEF(boolean)
  166348. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166349. {
  166350. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166351. register int temp, temp2;
  166352. register int nbits;
  166353. register int r, k;
  166354. int Se = cinfo->Se;
  166355. int Al = cinfo->Al;
  166356. JBLOCKROW block;
  166357. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166358. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166359. /* Emit restart marker if needed */
  166360. if (cinfo->restart_interval)
  166361. if (entropy->restarts_to_go == 0)
  166362. emit_restart_p(entropy, entropy->next_restart_num);
  166363. /* Encode the MCU data block */
  166364. block = MCU_data[0];
  166365. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166366. r = 0; /* r = run length of zeros */
  166367. for (k = cinfo->Ss; k <= Se; k++) {
  166368. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166369. r++;
  166370. continue;
  166371. }
  166372. /* We must apply the point transform by Al. For AC coefficients this
  166373. * is an integer division with rounding towards 0. To do this portably
  166374. * in C, we shift after obtaining the absolute value; so the code is
  166375. * interwoven with finding the abs value (temp) and output bits (temp2).
  166376. */
  166377. if (temp < 0) {
  166378. temp = -temp; /* temp is abs value of input */
  166379. temp >>= Al; /* apply the point transform */
  166380. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166381. temp2 = ~temp;
  166382. } else {
  166383. temp >>= Al; /* apply the point transform */
  166384. temp2 = temp;
  166385. }
  166386. /* Watch out for case that nonzero coef is zero after point transform */
  166387. if (temp == 0) {
  166388. r++;
  166389. continue;
  166390. }
  166391. /* Emit any pending EOBRUN */
  166392. if (entropy->EOBRUN > 0)
  166393. emit_eobrun(entropy);
  166394. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166395. while (r > 15) {
  166396. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166397. r -= 16;
  166398. }
  166399. /* Find the number of bits needed for the magnitude of the coefficient */
  166400. nbits = 1; /* there must be at least one 1 bit */
  166401. while ((temp >>= 1))
  166402. nbits++;
  166403. /* Check for out-of-range coefficient values */
  166404. if (nbits > MAX_COEF_BITS)
  166405. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166406. /* Count/emit Huffman symbol for run length / number of bits */
  166407. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166408. /* Emit that number of bits of the value, if positive, */
  166409. /* or the complement of its magnitude, if negative. */
  166410. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166411. r = 0; /* reset zero run length */
  166412. }
  166413. if (r > 0) { /* If there are trailing zeroes, */
  166414. entropy->EOBRUN++; /* count an EOB */
  166415. if (entropy->EOBRUN == 0x7FFF)
  166416. emit_eobrun(entropy); /* force it out to avoid overflow */
  166417. }
  166418. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166419. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166420. /* Update restart-interval state too */
  166421. if (cinfo->restart_interval) {
  166422. if (entropy->restarts_to_go == 0) {
  166423. entropy->restarts_to_go = cinfo->restart_interval;
  166424. entropy->next_restart_num++;
  166425. entropy->next_restart_num &= 7;
  166426. }
  166427. entropy->restarts_to_go--;
  166428. }
  166429. return TRUE;
  166430. }
  166431. /*
  166432. * MCU encoding for DC successive approximation refinement scan.
  166433. * Note: we assume such scans can be multi-component, although the spec
  166434. * is not very clear on the point.
  166435. */
  166436. METHODDEF(boolean)
  166437. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166438. {
  166439. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166440. register int temp;
  166441. int blkn;
  166442. int Al = cinfo->Al;
  166443. JBLOCKROW block;
  166444. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166445. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166446. /* Emit restart marker if needed */
  166447. if (cinfo->restart_interval)
  166448. if (entropy->restarts_to_go == 0)
  166449. emit_restart_p(entropy, entropy->next_restart_num);
  166450. /* Encode the MCU data blocks */
  166451. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166452. block = MCU_data[blkn];
  166453. /* We simply emit the Al'th bit of the DC coefficient value. */
  166454. temp = (*block)[0];
  166455. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166456. }
  166457. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166458. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166459. /* Update restart-interval state too */
  166460. if (cinfo->restart_interval) {
  166461. if (entropy->restarts_to_go == 0) {
  166462. entropy->restarts_to_go = cinfo->restart_interval;
  166463. entropy->next_restart_num++;
  166464. entropy->next_restart_num &= 7;
  166465. }
  166466. entropy->restarts_to_go--;
  166467. }
  166468. return TRUE;
  166469. }
  166470. /*
  166471. * MCU encoding for AC successive approximation refinement scan.
  166472. */
  166473. METHODDEF(boolean)
  166474. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166475. {
  166476. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166477. register int temp;
  166478. register int r, k;
  166479. int EOB;
  166480. char *BR_buffer;
  166481. unsigned int BR;
  166482. int Se = cinfo->Se;
  166483. int Al = cinfo->Al;
  166484. JBLOCKROW block;
  166485. int absvalues[DCTSIZE2];
  166486. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166487. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166488. /* Emit restart marker if needed */
  166489. if (cinfo->restart_interval)
  166490. if (entropy->restarts_to_go == 0)
  166491. emit_restart_p(entropy, entropy->next_restart_num);
  166492. /* Encode the MCU data block */
  166493. block = MCU_data[0];
  166494. /* It is convenient to make a pre-pass to determine the transformed
  166495. * coefficients' absolute values and the EOB position.
  166496. */
  166497. EOB = 0;
  166498. for (k = cinfo->Ss; k <= Se; k++) {
  166499. temp = (*block)[jpeg_natural_order[k]];
  166500. /* We must apply the point transform by Al. For AC coefficients this
  166501. * is an integer division with rounding towards 0. To do this portably
  166502. * in C, we shift after obtaining the absolute value.
  166503. */
  166504. if (temp < 0)
  166505. temp = -temp; /* temp is abs value of input */
  166506. temp >>= Al; /* apply the point transform */
  166507. absvalues[k] = temp; /* save abs value for main pass */
  166508. if (temp == 1)
  166509. EOB = k; /* EOB = index of last newly-nonzero coef */
  166510. }
  166511. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166512. r = 0; /* r = run length of zeros */
  166513. BR = 0; /* BR = count of buffered bits added now */
  166514. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166515. for (k = cinfo->Ss; k <= Se; k++) {
  166516. if ((temp = absvalues[k]) == 0) {
  166517. r++;
  166518. continue;
  166519. }
  166520. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166521. while (r > 15 && k <= EOB) {
  166522. /* emit any pending EOBRUN and the BE correction bits */
  166523. emit_eobrun(entropy);
  166524. /* Emit ZRL */
  166525. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166526. r -= 16;
  166527. /* Emit buffered correction bits that must be associated with ZRL */
  166528. emit_buffered_bits(entropy, BR_buffer, BR);
  166529. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166530. BR = 0;
  166531. }
  166532. /* If the coef was previously nonzero, it only needs a correction bit.
  166533. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166534. * that we also need to test r > 15. But if r > 15, we can only get here
  166535. * if k > EOB, which implies that this coefficient is not 1.
  166536. */
  166537. if (temp > 1) {
  166538. /* The correction bit is the next bit of the absolute value. */
  166539. BR_buffer[BR++] = (char) (temp & 1);
  166540. continue;
  166541. }
  166542. /* Emit any pending EOBRUN and the BE correction bits */
  166543. emit_eobrun(entropy);
  166544. /* Count/emit Huffman symbol for run length / number of bits */
  166545. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166546. /* Emit output bit for newly-nonzero coef */
  166547. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166548. emit_bits_p(entropy, (unsigned int) temp, 1);
  166549. /* Emit buffered correction bits that must be associated with this code */
  166550. emit_buffered_bits(entropy, BR_buffer, BR);
  166551. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166552. BR = 0;
  166553. r = 0; /* reset zero run length */
  166554. }
  166555. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166556. entropy->EOBRUN++; /* count an EOB */
  166557. entropy->BE += BR; /* concat my correction bits to older ones */
  166558. /* We force out the EOB if we risk either:
  166559. * 1. overflow of the EOB counter;
  166560. * 2. overflow of the correction bit buffer during the next MCU.
  166561. */
  166562. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166563. emit_eobrun(entropy);
  166564. }
  166565. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166566. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166567. /* Update restart-interval state too */
  166568. if (cinfo->restart_interval) {
  166569. if (entropy->restarts_to_go == 0) {
  166570. entropy->restarts_to_go = cinfo->restart_interval;
  166571. entropy->next_restart_num++;
  166572. entropy->next_restart_num &= 7;
  166573. }
  166574. entropy->restarts_to_go--;
  166575. }
  166576. return TRUE;
  166577. }
  166578. /*
  166579. * Finish up at the end of a Huffman-compressed progressive scan.
  166580. */
  166581. METHODDEF(void)
  166582. finish_pass_phuff (j_compress_ptr cinfo)
  166583. {
  166584. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166585. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166586. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166587. /* Flush out any buffered data */
  166588. emit_eobrun(entropy);
  166589. flush_bits_p(entropy);
  166590. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166591. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166592. }
  166593. /*
  166594. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166595. */
  166596. METHODDEF(void)
  166597. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166598. {
  166599. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166600. boolean is_DC_band;
  166601. int ci, tbl;
  166602. jpeg_component_info * compptr;
  166603. JHUFF_TBL **htblptr;
  166604. boolean did[NUM_HUFF_TBLS];
  166605. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166606. emit_eobrun(entropy);
  166607. is_DC_band = (cinfo->Ss == 0);
  166608. /* It's important not to apply jpeg_gen_optimal_table more than once
  166609. * per table, because it clobbers the input frequency counts!
  166610. */
  166611. MEMZERO(did, SIZEOF(did));
  166612. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166613. compptr = cinfo->cur_comp_info[ci];
  166614. if (is_DC_band) {
  166615. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166616. continue;
  166617. tbl = compptr->dc_tbl_no;
  166618. } else {
  166619. tbl = compptr->ac_tbl_no;
  166620. }
  166621. if (! did[tbl]) {
  166622. if (is_DC_band)
  166623. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166624. else
  166625. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166626. if (*htblptr == NULL)
  166627. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166628. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166629. did[tbl] = TRUE;
  166630. }
  166631. }
  166632. }
  166633. /*
  166634. * Module initialization routine for progressive Huffman entropy encoding.
  166635. */
  166636. GLOBAL(void)
  166637. jinit_phuff_encoder (j_compress_ptr cinfo)
  166638. {
  166639. phuff_entropy_ptr entropy;
  166640. int i;
  166641. entropy = (phuff_entropy_ptr)
  166642. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166643. SIZEOF(phuff_entropy_encoder));
  166644. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166645. entropy->pub.start_pass = start_pass_phuff;
  166646. /* Mark tables unallocated */
  166647. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166648. entropy->derived_tbls[i] = NULL;
  166649. entropy->count_ptrs[i] = NULL;
  166650. }
  166651. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166652. }
  166653. #endif /* C_PROGRESSIVE_SUPPORTED */
  166654. /*** End of inlined file: jcphuff.c ***/
  166655. /*** Start of inlined file: jcprepct.c ***/
  166656. #define JPEG_INTERNALS
  166657. /* At present, jcsample.c can request context rows only for smoothing.
  166658. * In the future, we might also need context rows for CCIR601 sampling
  166659. * or other more-complex downsampling procedures. The code to support
  166660. * context rows should be compiled only if needed.
  166661. */
  166662. #ifdef INPUT_SMOOTHING_SUPPORTED
  166663. #define CONTEXT_ROWS_SUPPORTED
  166664. #endif
  166665. /*
  166666. * For the simple (no-context-row) case, we just need to buffer one
  166667. * row group's worth of pixels for the downsampling step. At the bottom of
  166668. * the image, we pad to a full row group by replicating the last pixel row.
  166669. * The downsampler's last output row is then replicated if needed to pad
  166670. * out to a full iMCU row.
  166671. *
  166672. * When providing context rows, we must buffer three row groups' worth of
  166673. * pixels. Three row groups are physically allocated, but the row pointer
  166674. * arrays are made five row groups high, with the extra pointers above and
  166675. * below "wrapping around" to point to the last and first real row groups.
  166676. * This allows the downsampler to access the proper context rows.
  166677. * At the top and bottom of the image, we create dummy context rows by
  166678. * copying the first or last real pixel row. This copying could be avoided
  166679. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166680. * trouble on the compression side.
  166681. */
  166682. /* Private buffer controller object */
  166683. typedef struct {
  166684. struct jpeg_c_prep_controller pub; /* public fields */
  166685. /* Downsampling input buffer. This buffer holds color-converted data
  166686. * until we have enough to do a downsample step.
  166687. */
  166688. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166689. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166690. int next_buf_row; /* index of next row to store in color_buf */
  166691. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166692. int this_row_group; /* starting row index of group to process */
  166693. int next_buf_stop; /* downsample when we reach this index */
  166694. #endif
  166695. } my_prep_controller;
  166696. typedef my_prep_controller * my_prep_ptr;
  166697. /*
  166698. * Initialize for a processing pass.
  166699. */
  166700. METHODDEF(void)
  166701. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166702. {
  166703. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166704. if (pass_mode != JBUF_PASS_THRU)
  166705. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166706. /* Initialize total-height counter for detecting bottom of image */
  166707. prep->rows_to_go = cinfo->image_height;
  166708. /* Mark the conversion buffer empty */
  166709. prep->next_buf_row = 0;
  166710. #ifdef CONTEXT_ROWS_SUPPORTED
  166711. /* Preset additional state variables for context mode.
  166712. * These aren't used in non-context mode, so we needn't test which mode.
  166713. */
  166714. prep->this_row_group = 0;
  166715. /* Set next_buf_stop to stop after two row groups have been read in. */
  166716. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166717. #endif
  166718. }
  166719. /*
  166720. * Expand an image vertically from height input_rows to height output_rows,
  166721. * by duplicating the bottom row.
  166722. */
  166723. LOCAL(void)
  166724. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166725. int input_rows, int output_rows)
  166726. {
  166727. register int row;
  166728. for (row = input_rows; row < output_rows; row++) {
  166729. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166730. 1, num_cols);
  166731. }
  166732. }
  166733. /*
  166734. * Process some data in the simple no-context case.
  166735. *
  166736. * Preprocessor output data is counted in "row groups". A row group
  166737. * is defined to be v_samp_factor sample rows of each component.
  166738. * Downsampling will produce this much data from each max_v_samp_factor
  166739. * input rows.
  166740. */
  166741. METHODDEF(void)
  166742. pre_process_data (j_compress_ptr cinfo,
  166743. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166744. JDIMENSION in_rows_avail,
  166745. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166746. JDIMENSION out_row_groups_avail)
  166747. {
  166748. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166749. int numrows, ci;
  166750. JDIMENSION inrows;
  166751. jpeg_component_info * compptr;
  166752. while (*in_row_ctr < in_rows_avail &&
  166753. *out_row_group_ctr < out_row_groups_avail) {
  166754. /* Do color conversion to fill the conversion buffer. */
  166755. inrows = in_rows_avail - *in_row_ctr;
  166756. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166757. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166758. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166759. prep->color_buf,
  166760. (JDIMENSION) prep->next_buf_row,
  166761. numrows);
  166762. *in_row_ctr += numrows;
  166763. prep->next_buf_row += numrows;
  166764. prep->rows_to_go -= numrows;
  166765. /* If at bottom of image, pad to fill the conversion buffer. */
  166766. if (prep->rows_to_go == 0 &&
  166767. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166768. for (ci = 0; ci < cinfo->num_components; ci++) {
  166769. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166770. prep->next_buf_row, cinfo->max_v_samp_factor);
  166771. }
  166772. prep->next_buf_row = cinfo->max_v_samp_factor;
  166773. }
  166774. /* If we've filled the conversion buffer, empty it. */
  166775. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166776. (*cinfo->downsample->downsample) (cinfo,
  166777. prep->color_buf, (JDIMENSION) 0,
  166778. output_buf, *out_row_group_ctr);
  166779. prep->next_buf_row = 0;
  166780. (*out_row_group_ctr)++;
  166781. }
  166782. /* If at bottom of image, pad the output to a full iMCU height.
  166783. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166784. */
  166785. if (prep->rows_to_go == 0 &&
  166786. *out_row_group_ctr < out_row_groups_avail) {
  166787. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166788. ci++, compptr++) {
  166789. expand_bottom_edge(output_buf[ci],
  166790. compptr->width_in_blocks * DCTSIZE,
  166791. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166792. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166793. }
  166794. *out_row_group_ctr = out_row_groups_avail;
  166795. break; /* can exit outer loop without test */
  166796. }
  166797. }
  166798. }
  166799. #ifdef CONTEXT_ROWS_SUPPORTED
  166800. /*
  166801. * Process some data in the context case.
  166802. */
  166803. METHODDEF(void)
  166804. pre_process_context (j_compress_ptr cinfo,
  166805. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166806. JDIMENSION in_rows_avail,
  166807. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166808. JDIMENSION out_row_groups_avail)
  166809. {
  166810. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166811. int numrows, ci;
  166812. int buf_height = cinfo->max_v_samp_factor * 3;
  166813. JDIMENSION inrows;
  166814. while (*out_row_group_ctr < out_row_groups_avail) {
  166815. if (*in_row_ctr < in_rows_avail) {
  166816. /* Do color conversion to fill the conversion buffer. */
  166817. inrows = in_rows_avail - *in_row_ctr;
  166818. numrows = prep->next_buf_stop - prep->next_buf_row;
  166819. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166820. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166821. prep->color_buf,
  166822. (JDIMENSION) prep->next_buf_row,
  166823. numrows);
  166824. /* Pad at top of image, if first time through */
  166825. if (prep->rows_to_go == cinfo->image_height) {
  166826. for (ci = 0; ci < cinfo->num_components; ci++) {
  166827. int row;
  166828. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166829. jcopy_sample_rows(prep->color_buf[ci], 0,
  166830. prep->color_buf[ci], -row,
  166831. 1, cinfo->image_width);
  166832. }
  166833. }
  166834. }
  166835. *in_row_ctr += numrows;
  166836. prep->next_buf_row += numrows;
  166837. prep->rows_to_go -= numrows;
  166838. } else {
  166839. /* Return for more data, unless we are at the bottom of the image. */
  166840. if (prep->rows_to_go != 0)
  166841. break;
  166842. /* When at bottom of image, pad to fill the conversion buffer. */
  166843. if (prep->next_buf_row < prep->next_buf_stop) {
  166844. for (ci = 0; ci < cinfo->num_components; ci++) {
  166845. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166846. prep->next_buf_row, prep->next_buf_stop);
  166847. }
  166848. prep->next_buf_row = prep->next_buf_stop;
  166849. }
  166850. }
  166851. /* If we've gotten enough data, downsample a row group. */
  166852. if (prep->next_buf_row == prep->next_buf_stop) {
  166853. (*cinfo->downsample->downsample) (cinfo,
  166854. prep->color_buf,
  166855. (JDIMENSION) prep->this_row_group,
  166856. output_buf, *out_row_group_ctr);
  166857. (*out_row_group_ctr)++;
  166858. /* Advance pointers with wraparound as necessary. */
  166859. prep->this_row_group += cinfo->max_v_samp_factor;
  166860. if (prep->this_row_group >= buf_height)
  166861. prep->this_row_group = 0;
  166862. if (prep->next_buf_row >= buf_height)
  166863. prep->next_buf_row = 0;
  166864. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166865. }
  166866. }
  166867. }
  166868. /*
  166869. * Create the wrapped-around downsampling input buffer needed for context mode.
  166870. */
  166871. LOCAL(void)
  166872. create_context_buffer (j_compress_ptr cinfo)
  166873. {
  166874. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166875. int rgroup_height = cinfo->max_v_samp_factor;
  166876. int ci, i;
  166877. jpeg_component_info * compptr;
  166878. JSAMPARRAY true_buffer, fake_buffer;
  166879. /* Grab enough space for fake row pointers for all the components;
  166880. * we need five row groups' worth of pointers for each component.
  166881. */
  166882. fake_buffer = (JSAMPARRAY)
  166883. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166884. (cinfo->num_components * 5 * rgroup_height) *
  166885. SIZEOF(JSAMPROW));
  166886. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166887. ci++, compptr++) {
  166888. /* Allocate the actual buffer space (3 row groups) for this component.
  166889. * We make the buffer wide enough to allow the downsampler to edge-expand
  166890. * horizontally within the buffer, if it so chooses.
  166891. */
  166892. true_buffer = (*cinfo->mem->alloc_sarray)
  166893. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166894. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166895. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166896. (JDIMENSION) (3 * rgroup_height));
  166897. /* Copy true buffer row pointers into the middle of the fake row array */
  166898. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166899. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166900. /* Fill in the above and below wraparound pointers */
  166901. for (i = 0; i < rgroup_height; i++) {
  166902. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166903. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166904. }
  166905. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166906. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166907. }
  166908. }
  166909. #endif /* CONTEXT_ROWS_SUPPORTED */
  166910. /*
  166911. * Initialize preprocessing controller.
  166912. */
  166913. GLOBAL(void)
  166914. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166915. {
  166916. my_prep_ptr prep;
  166917. int ci;
  166918. jpeg_component_info * compptr;
  166919. if (need_full_buffer) /* safety check */
  166920. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166921. prep = (my_prep_ptr)
  166922. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166923. SIZEOF(my_prep_controller));
  166924. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166925. prep->pub.start_pass = start_pass_prep;
  166926. /* Allocate the color conversion buffer.
  166927. * We make the buffer wide enough to allow the downsampler to edge-expand
  166928. * horizontally within the buffer, if it so chooses.
  166929. */
  166930. if (cinfo->downsample->need_context_rows) {
  166931. /* Set up to provide context rows */
  166932. #ifdef CONTEXT_ROWS_SUPPORTED
  166933. prep->pub.pre_process_data = pre_process_context;
  166934. create_context_buffer(cinfo);
  166935. #else
  166936. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166937. #endif
  166938. } else {
  166939. /* No context, just make it tall enough for one row group */
  166940. prep->pub.pre_process_data = pre_process_data;
  166941. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166942. ci++, compptr++) {
  166943. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166944. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166945. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166946. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166947. (JDIMENSION) cinfo->max_v_samp_factor);
  166948. }
  166949. }
  166950. }
  166951. /*** End of inlined file: jcprepct.c ***/
  166952. /*** Start of inlined file: jcsample.c ***/
  166953. #define JPEG_INTERNALS
  166954. /* Pointer to routine to downsample a single component */
  166955. typedef JMETHOD(void, downsample1_ptr,
  166956. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166957. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166958. /* Private subobject */
  166959. typedef struct {
  166960. struct jpeg_downsampler pub; /* public fields */
  166961. /* Downsampling method pointers, one per component */
  166962. downsample1_ptr methods[MAX_COMPONENTS];
  166963. } my_downsampler;
  166964. typedef my_downsampler * my_downsample_ptr;
  166965. /*
  166966. * Initialize for a downsampling pass.
  166967. */
  166968. METHODDEF(void)
  166969. start_pass_downsample (j_compress_ptr)
  166970. {
  166971. /* no work for now */
  166972. }
  166973. /*
  166974. * Expand a component horizontally from width input_cols to width output_cols,
  166975. * by duplicating the rightmost samples.
  166976. */
  166977. LOCAL(void)
  166978. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166979. JDIMENSION input_cols, JDIMENSION output_cols)
  166980. {
  166981. register JSAMPROW ptr;
  166982. register JSAMPLE pixval;
  166983. register int count;
  166984. int row;
  166985. int numcols = (int) (output_cols - input_cols);
  166986. if (numcols > 0) {
  166987. for (row = 0; row < num_rows; row++) {
  166988. ptr = image_data[row] + input_cols;
  166989. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166990. for (count = numcols; count > 0; count--)
  166991. *ptr++ = pixval;
  166992. }
  166993. }
  166994. }
  166995. /*
  166996. * Do downsampling for a whole row group (all components).
  166997. *
  166998. * In this version we simply downsample each component independently.
  166999. */
  167000. METHODDEF(void)
  167001. sep_downsample (j_compress_ptr cinfo,
  167002. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  167003. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  167004. {
  167005. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  167006. int ci;
  167007. jpeg_component_info * compptr;
  167008. JSAMPARRAY in_ptr, out_ptr;
  167009. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167010. ci++, compptr++) {
  167011. in_ptr = input_buf[ci] + in_row_index;
  167012. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  167013. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  167014. }
  167015. }
  167016. /*
  167017. * Downsample pixel values of a single component.
  167018. * One row group is processed per call.
  167019. * This version handles arbitrary integral sampling ratios, without smoothing.
  167020. * Note that this version is not actually used for customary sampling ratios.
  167021. */
  167022. METHODDEF(void)
  167023. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167024. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167025. {
  167026. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  167027. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  167028. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167029. JSAMPROW inptr, outptr;
  167030. INT32 outvalue;
  167031. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  167032. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  167033. numpix = h_expand * v_expand;
  167034. numpix2 = numpix/2;
  167035. /* Expand input data enough to let all the output samples be generated
  167036. * by the standard loop. Special-casing padded output would be more
  167037. * efficient.
  167038. */
  167039. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167040. cinfo->image_width, output_cols * h_expand);
  167041. inrow = 0;
  167042. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167043. outptr = output_data[outrow];
  167044. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  167045. outcol++, outcol_h += h_expand) {
  167046. outvalue = 0;
  167047. for (v = 0; v < v_expand; v++) {
  167048. inptr = input_data[inrow+v] + outcol_h;
  167049. for (h = 0; h < h_expand; h++) {
  167050. outvalue += (INT32) GETJSAMPLE(*inptr++);
  167051. }
  167052. }
  167053. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  167054. }
  167055. inrow += v_expand;
  167056. }
  167057. }
  167058. /*
  167059. * Downsample pixel values of a single component.
  167060. * This version handles the special case of a full-size component,
  167061. * without smoothing.
  167062. */
  167063. METHODDEF(void)
  167064. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167065. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167066. {
  167067. /* Copy the data */
  167068. jcopy_sample_rows(input_data, 0, output_data, 0,
  167069. cinfo->max_v_samp_factor, cinfo->image_width);
  167070. /* Edge-expand */
  167071. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  167072. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  167073. }
  167074. /*
  167075. * Downsample pixel values of a single component.
  167076. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  167077. * without smoothing.
  167078. *
  167079. * A note about the "bias" calculations: when rounding fractional values to
  167080. * integer, we do not want to always round 0.5 up to the next integer.
  167081. * If we did that, we'd introduce a noticeable bias towards larger values.
  167082. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  167083. * alternate pixel locations (a simple ordered dither pattern).
  167084. */
  167085. METHODDEF(void)
  167086. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167087. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167088. {
  167089. int outrow;
  167090. JDIMENSION outcol;
  167091. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167092. register JSAMPROW inptr, outptr;
  167093. register int bias;
  167094. /* Expand input data enough to let all the output samples be generated
  167095. * by the standard loop. Special-casing padded output would be more
  167096. * efficient.
  167097. */
  167098. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167099. cinfo->image_width, output_cols * 2);
  167100. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167101. outptr = output_data[outrow];
  167102. inptr = input_data[outrow];
  167103. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  167104. for (outcol = 0; outcol < output_cols; outcol++) {
  167105. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  167106. + bias) >> 1);
  167107. bias ^= 1; /* 0=>1, 1=>0 */
  167108. inptr += 2;
  167109. }
  167110. }
  167111. }
  167112. /*
  167113. * Downsample pixel values of a single component.
  167114. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167115. * without smoothing.
  167116. */
  167117. METHODDEF(void)
  167118. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167119. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167120. {
  167121. int inrow, outrow;
  167122. JDIMENSION outcol;
  167123. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167124. register JSAMPROW inptr0, inptr1, outptr;
  167125. register int bias;
  167126. /* Expand input data enough to let all the output samples be generated
  167127. * by the standard loop. Special-casing padded output would be more
  167128. * efficient.
  167129. */
  167130. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167131. cinfo->image_width, output_cols * 2);
  167132. inrow = 0;
  167133. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167134. outptr = output_data[outrow];
  167135. inptr0 = input_data[inrow];
  167136. inptr1 = input_data[inrow+1];
  167137. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  167138. for (outcol = 0; outcol < output_cols; outcol++) {
  167139. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167140. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  167141. + bias) >> 2);
  167142. bias ^= 3; /* 1=>2, 2=>1 */
  167143. inptr0 += 2; inptr1 += 2;
  167144. }
  167145. inrow += 2;
  167146. }
  167147. }
  167148. #ifdef INPUT_SMOOTHING_SUPPORTED
  167149. /*
  167150. * Downsample pixel values of a single component.
  167151. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167152. * with smoothing. One row of context is required.
  167153. */
  167154. METHODDEF(void)
  167155. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167156. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167157. {
  167158. int inrow, outrow;
  167159. JDIMENSION colctr;
  167160. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167161. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  167162. INT32 membersum, neighsum, memberscale, neighscale;
  167163. /* Expand input data enough to let all the output samples be generated
  167164. * by the standard loop. Special-casing padded output would be more
  167165. * efficient.
  167166. */
  167167. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167168. cinfo->image_width, output_cols * 2);
  167169. /* We don't bother to form the individual "smoothed" input pixel values;
  167170. * we can directly compute the output which is the average of the four
  167171. * smoothed values. Each of the four member pixels contributes a fraction
  167172. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  167173. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  167174. * output. The four corner-adjacent neighbor pixels contribute a fraction
  167175. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  167176. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  167177. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  167178. * factors are scaled by 2^16 = 65536.
  167179. * Also recall that SF = smoothing_factor / 1024.
  167180. */
  167181. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  167182. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  167183. inrow = 0;
  167184. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167185. outptr = output_data[outrow];
  167186. inptr0 = input_data[inrow];
  167187. inptr1 = input_data[inrow+1];
  167188. above_ptr = input_data[inrow-1];
  167189. below_ptr = input_data[inrow+2];
  167190. /* Special case for first column: pretend column -1 is same as column 0 */
  167191. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167192. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167193. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167194. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167195. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  167196. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  167197. neighsum += neighsum;
  167198. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  167199. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  167200. membersum = membersum * memberscale + neighsum * neighscale;
  167201. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167202. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167203. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167204. /* sum of pixels directly mapped to this output element */
  167205. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167206. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167207. /* sum of edge-neighbor pixels */
  167208. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167209. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167210. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167211. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167212. /* The edge-neighbors count twice as much as corner-neighbors */
  167213. neighsum += neighsum;
  167214. /* Add in the corner-neighbors */
  167215. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167216. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167217. /* form final output scaled up by 2^16 */
  167218. membersum = membersum * memberscale + neighsum * neighscale;
  167219. /* round, descale and output it */
  167220. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167221. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167222. }
  167223. /* Special case for last column */
  167224. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167225. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167226. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167227. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167228. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167229. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167230. neighsum += neighsum;
  167231. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167232. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167233. membersum = membersum * memberscale + neighsum * neighscale;
  167234. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167235. inrow += 2;
  167236. }
  167237. }
  167238. /*
  167239. * Downsample pixel values of a single component.
  167240. * This version handles the special case of a full-size component,
  167241. * with smoothing. One row of context is required.
  167242. */
  167243. METHODDEF(void)
  167244. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167245. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167246. {
  167247. int outrow;
  167248. JDIMENSION colctr;
  167249. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167250. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167251. INT32 membersum, neighsum, memberscale, neighscale;
  167252. int colsum, lastcolsum, nextcolsum;
  167253. /* Expand input data enough to let all the output samples be generated
  167254. * by the standard loop. Special-casing padded output would be more
  167255. * efficient.
  167256. */
  167257. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167258. cinfo->image_width, output_cols);
  167259. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167260. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167261. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167262. * Also recall that SF = smoothing_factor / 1024.
  167263. */
  167264. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167265. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167266. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167267. outptr = output_data[outrow];
  167268. inptr = input_data[outrow];
  167269. above_ptr = input_data[outrow-1];
  167270. below_ptr = input_data[outrow+1];
  167271. /* Special case for first column */
  167272. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167273. GETJSAMPLE(*inptr);
  167274. membersum = GETJSAMPLE(*inptr++);
  167275. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167276. GETJSAMPLE(*inptr);
  167277. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167278. membersum = membersum * memberscale + neighsum * neighscale;
  167279. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167280. lastcolsum = colsum; colsum = nextcolsum;
  167281. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167282. membersum = GETJSAMPLE(*inptr++);
  167283. above_ptr++; below_ptr++;
  167284. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167285. GETJSAMPLE(*inptr);
  167286. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167287. membersum = membersum * memberscale + neighsum * neighscale;
  167288. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167289. lastcolsum = colsum; colsum = nextcolsum;
  167290. }
  167291. /* Special case for last column */
  167292. membersum = GETJSAMPLE(*inptr);
  167293. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167294. membersum = membersum * memberscale + neighsum * neighscale;
  167295. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167296. }
  167297. }
  167298. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167299. /*
  167300. * Module initialization routine for downsampling.
  167301. * Note that we must select a routine for each component.
  167302. */
  167303. GLOBAL(void)
  167304. jinit_downsampler (j_compress_ptr cinfo)
  167305. {
  167306. my_downsample_ptr downsample;
  167307. int ci;
  167308. jpeg_component_info * compptr;
  167309. boolean smoothok = TRUE;
  167310. downsample = (my_downsample_ptr)
  167311. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167312. SIZEOF(my_downsampler));
  167313. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167314. downsample->pub.start_pass = start_pass_downsample;
  167315. downsample->pub.downsample = sep_downsample;
  167316. downsample->pub.need_context_rows = FALSE;
  167317. if (cinfo->CCIR601_sampling)
  167318. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167319. /* Verify we can handle the sampling factors, and set up method pointers */
  167320. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167321. ci++, compptr++) {
  167322. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167323. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167324. #ifdef INPUT_SMOOTHING_SUPPORTED
  167325. if (cinfo->smoothing_factor) {
  167326. downsample->methods[ci] = fullsize_smooth_downsample;
  167327. downsample->pub.need_context_rows = TRUE;
  167328. } else
  167329. #endif
  167330. downsample->methods[ci] = fullsize_downsample;
  167331. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167332. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167333. smoothok = FALSE;
  167334. downsample->methods[ci] = h2v1_downsample;
  167335. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167336. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167337. #ifdef INPUT_SMOOTHING_SUPPORTED
  167338. if (cinfo->smoothing_factor) {
  167339. downsample->methods[ci] = h2v2_smooth_downsample;
  167340. downsample->pub.need_context_rows = TRUE;
  167341. } else
  167342. #endif
  167343. downsample->methods[ci] = h2v2_downsample;
  167344. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167345. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167346. smoothok = FALSE;
  167347. downsample->methods[ci] = int_downsample;
  167348. } else
  167349. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167350. }
  167351. #ifdef INPUT_SMOOTHING_SUPPORTED
  167352. if (cinfo->smoothing_factor && !smoothok)
  167353. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167354. #endif
  167355. }
  167356. /*** End of inlined file: jcsample.c ***/
  167357. /*** Start of inlined file: jctrans.c ***/
  167358. #define JPEG_INTERNALS
  167359. /* Forward declarations */
  167360. LOCAL(void) transencode_master_selection
  167361. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167362. LOCAL(void) transencode_coef_controller
  167363. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167364. /*
  167365. * Compression initialization for writing raw-coefficient data.
  167366. * Before calling this, all parameters and a data destination must be set up.
  167367. * Call jpeg_finish_compress() to actually write the data.
  167368. *
  167369. * The number of passed virtual arrays must match cinfo->num_components.
  167370. * Note that the virtual arrays need not be filled or even realized at
  167371. * the time write_coefficients is called; indeed, if the virtual arrays
  167372. * were requested from this compression object's memory manager, they
  167373. * typically will be realized during this routine and filled afterwards.
  167374. */
  167375. GLOBAL(void)
  167376. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167377. {
  167378. if (cinfo->global_state != CSTATE_START)
  167379. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167380. /* Mark all tables to be written */
  167381. jpeg_suppress_tables(cinfo, FALSE);
  167382. /* (Re)initialize error mgr and destination modules */
  167383. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167384. (*cinfo->dest->init_destination) (cinfo);
  167385. /* Perform master selection of active modules */
  167386. transencode_master_selection(cinfo, coef_arrays);
  167387. /* Wait for jpeg_finish_compress() call */
  167388. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167389. cinfo->global_state = CSTATE_WRCOEFS;
  167390. }
  167391. /*
  167392. * Initialize the compression object with default parameters,
  167393. * then copy from the source object all parameters needed for lossless
  167394. * transcoding. Parameters that can be varied without loss (such as
  167395. * scan script and Huffman optimization) are left in their default states.
  167396. */
  167397. GLOBAL(void)
  167398. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167399. j_compress_ptr dstinfo)
  167400. {
  167401. JQUANT_TBL ** qtblptr;
  167402. jpeg_component_info *incomp, *outcomp;
  167403. JQUANT_TBL *c_quant, *slot_quant;
  167404. int tblno, ci, coefi;
  167405. /* Safety check to ensure start_compress not called yet. */
  167406. if (dstinfo->global_state != CSTATE_START)
  167407. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167408. /* Copy fundamental image dimensions */
  167409. dstinfo->image_width = srcinfo->image_width;
  167410. dstinfo->image_height = srcinfo->image_height;
  167411. dstinfo->input_components = srcinfo->num_components;
  167412. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167413. /* Initialize all parameters to default values */
  167414. jpeg_set_defaults(dstinfo);
  167415. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167416. * Fix it to get the right header markers for the image colorspace.
  167417. */
  167418. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167419. dstinfo->data_precision = srcinfo->data_precision;
  167420. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167421. /* Copy the source's quantization tables. */
  167422. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167423. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167424. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167425. if (*qtblptr == NULL)
  167426. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167427. MEMCOPY((*qtblptr)->quantval,
  167428. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167429. SIZEOF((*qtblptr)->quantval));
  167430. (*qtblptr)->sent_table = FALSE;
  167431. }
  167432. }
  167433. /* Copy the source's per-component info.
  167434. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167435. */
  167436. dstinfo->num_components = srcinfo->num_components;
  167437. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167438. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167439. MAX_COMPONENTS);
  167440. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167441. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167442. outcomp->component_id = incomp->component_id;
  167443. outcomp->h_samp_factor = incomp->h_samp_factor;
  167444. outcomp->v_samp_factor = incomp->v_samp_factor;
  167445. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167446. /* Make sure saved quantization table for component matches the qtable
  167447. * slot. If not, the input file re-used this qtable slot.
  167448. * IJG encoder currently cannot duplicate this.
  167449. */
  167450. tblno = outcomp->quant_tbl_no;
  167451. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167452. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167453. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167454. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167455. c_quant = incomp->quant_table;
  167456. if (c_quant != NULL) {
  167457. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167458. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167459. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167460. }
  167461. }
  167462. /* Note: we do not copy the source's Huffman table assignments;
  167463. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167464. */
  167465. }
  167466. /* Also copy JFIF version and resolution information, if available.
  167467. * Strictly speaking this isn't "critical" info, but it's nearly
  167468. * always appropriate to copy it if available. In particular,
  167469. * if the application chooses to copy JFIF 1.02 extension markers from
  167470. * the source file, we need to copy the version to make sure we don't
  167471. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167472. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167473. */
  167474. if (srcinfo->saw_JFIF_marker) {
  167475. if (srcinfo->JFIF_major_version == 1) {
  167476. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167477. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167478. }
  167479. dstinfo->density_unit = srcinfo->density_unit;
  167480. dstinfo->X_density = srcinfo->X_density;
  167481. dstinfo->Y_density = srcinfo->Y_density;
  167482. }
  167483. }
  167484. /*
  167485. * Master selection of compression modules for transcoding.
  167486. * This substitutes for jcinit.c's initialization of the full compressor.
  167487. */
  167488. LOCAL(void)
  167489. transencode_master_selection (j_compress_ptr cinfo,
  167490. jvirt_barray_ptr * coef_arrays)
  167491. {
  167492. /* Although we don't actually use input_components for transcoding,
  167493. * jcmaster.c's initial_setup will complain if input_components is 0.
  167494. */
  167495. cinfo->input_components = 1;
  167496. /* Initialize master control (includes parameter checking/processing) */
  167497. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167498. /* Entropy encoding: either Huffman or arithmetic coding. */
  167499. if (cinfo->arith_code) {
  167500. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167501. } else {
  167502. if (cinfo->progressive_mode) {
  167503. #ifdef C_PROGRESSIVE_SUPPORTED
  167504. jinit_phuff_encoder(cinfo);
  167505. #else
  167506. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167507. #endif
  167508. } else
  167509. jinit_huff_encoder(cinfo);
  167510. }
  167511. /* We need a special coefficient buffer controller. */
  167512. transencode_coef_controller(cinfo, coef_arrays);
  167513. jinit_marker_writer(cinfo);
  167514. /* We can now tell the memory manager to allocate virtual arrays. */
  167515. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167516. /* Write the datastream header (SOI, JFIF) immediately.
  167517. * Frame and scan headers are postponed till later.
  167518. * This lets application insert special markers after the SOI.
  167519. */
  167520. (*cinfo->marker->write_file_header) (cinfo);
  167521. }
  167522. /*
  167523. * The rest of this file is a special implementation of the coefficient
  167524. * buffer controller. This is similar to jccoefct.c, but it handles only
  167525. * output from presupplied virtual arrays. Furthermore, we generate any
  167526. * dummy padding blocks on-the-fly rather than expecting them to be present
  167527. * in the arrays.
  167528. */
  167529. /* Private buffer controller object */
  167530. typedef struct {
  167531. struct jpeg_c_coef_controller pub; /* public fields */
  167532. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167533. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167534. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167535. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167536. /* Virtual block array for each component. */
  167537. jvirt_barray_ptr * whole_image;
  167538. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167539. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167540. } my_coef_controller2;
  167541. typedef my_coef_controller2 * my_coef_ptr2;
  167542. LOCAL(void)
  167543. start_iMCU_row2 (j_compress_ptr cinfo)
  167544. /* Reset within-iMCU-row counters for a new row */
  167545. {
  167546. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167547. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167548. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167549. * But at the bottom of the image, process only what's left.
  167550. */
  167551. if (cinfo->comps_in_scan > 1) {
  167552. coef->MCU_rows_per_iMCU_row = 1;
  167553. } else {
  167554. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167555. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167556. else
  167557. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167558. }
  167559. coef->mcu_ctr = 0;
  167560. coef->MCU_vert_offset = 0;
  167561. }
  167562. /*
  167563. * Initialize for a processing pass.
  167564. */
  167565. METHODDEF(void)
  167566. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167567. {
  167568. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167569. if (pass_mode != JBUF_CRANK_DEST)
  167570. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167571. coef->iMCU_row_num = 0;
  167572. start_iMCU_row2(cinfo);
  167573. }
  167574. /*
  167575. * Process some data.
  167576. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167577. * per call, ie, v_samp_factor block rows for each component in the scan.
  167578. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167579. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167580. *
  167581. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167582. */
  167583. METHODDEF(boolean)
  167584. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167585. {
  167586. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167587. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167588. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167589. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167590. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167591. JDIMENSION start_col;
  167592. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167593. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167594. JBLOCKROW buffer_ptr;
  167595. jpeg_component_info *compptr;
  167596. /* Align the virtual buffers for the components used in this scan. */
  167597. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167598. compptr = cinfo->cur_comp_info[ci];
  167599. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167600. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167601. coef->iMCU_row_num * compptr->v_samp_factor,
  167602. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167603. }
  167604. /* Loop to process one whole iMCU row */
  167605. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167606. yoffset++) {
  167607. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167608. MCU_col_num++) {
  167609. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167610. blkn = 0; /* index of current DCT block within MCU */
  167611. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167612. compptr = cinfo->cur_comp_info[ci];
  167613. start_col = MCU_col_num * compptr->MCU_width;
  167614. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167615. : compptr->last_col_width;
  167616. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167617. if (coef->iMCU_row_num < last_iMCU_row ||
  167618. yindex+yoffset < compptr->last_row_height) {
  167619. /* Fill in pointers to real blocks in this row */
  167620. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167621. for (xindex = 0; xindex < blockcnt; xindex++)
  167622. MCU_buffer[blkn++] = buffer_ptr++;
  167623. } else {
  167624. /* At bottom of image, need a whole row of dummy blocks */
  167625. xindex = 0;
  167626. }
  167627. /* Fill in any dummy blocks needed in this row.
  167628. * Dummy blocks are filled in the same way as in jccoefct.c:
  167629. * all zeroes in the AC entries, DC entries equal to previous
  167630. * block's DC value. The init routine has already zeroed the
  167631. * AC entries, so we need only set the DC entries correctly.
  167632. */
  167633. for (; xindex < compptr->MCU_width; xindex++) {
  167634. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167635. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167636. blkn++;
  167637. }
  167638. }
  167639. }
  167640. /* Try to write the MCU. */
  167641. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167642. /* Suspension forced; update state counters and exit */
  167643. coef->MCU_vert_offset = yoffset;
  167644. coef->mcu_ctr = MCU_col_num;
  167645. return FALSE;
  167646. }
  167647. }
  167648. /* Completed an MCU row, but perhaps not an iMCU row */
  167649. coef->mcu_ctr = 0;
  167650. }
  167651. /* Completed the iMCU row, advance counters for next one */
  167652. coef->iMCU_row_num++;
  167653. start_iMCU_row2(cinfo);
  167654. return TRUE;
  167655. }
  167656. /*
  167657. * Initialize coefficient buffer controller.
  167658. *
  167659. * Each passed coefficient array must be the right size for that
  167660. * coefficient: width_in_blocks wide and height_in_blocks high,
  167661. * with unitheight at least v_samp_factor.
  167662. */
  167663. LOCAL(void)
  167664. transencode_coef_controller (j_compress_ptr cinfo,
  167665. jvirt_barray_ptr * coef_arrays)
  167666. {
  167667. my_coef_ptr2 coef;
  167668. JBLOCKROW buffer;
  167669. int i;
  167670. coef = (my_coef_ptr2)
  167671. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167672. SIZEOF(my_coef_controller2));
  167673. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167674. coef->pub.start_pass = start_pass_coef2;
  167675. coef->pub.compress_data = compress_output2;
  167676. /* Save pointer to virtual arrays */
  167677. coef->whole_image = coef_arrays;
  167678. /* Allocate and pre-zero space for dummy DCT blocks. */
  167679. buffer = (JBLOCKROW)
  167680. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167681. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167682. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167683. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167684. coef->dummy_buffer[i] = buffer + i;
  167685. }
  167686. }
  167687. /*** End of inlined file: jctrans.c ***/
  167688. /*** Start of inlined file: jdapistd.c ***/
  167689. #define JPEG_INTERNALS
  167690. /* Forward declarations */
  167691. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167692. /*
  167693. * Decompression initialization.
  167694. * jpeg_read_header must be completed before calling this.
  167695. *
  167696. * If a multipass operating mode was selected, this will do all but the
  167697. * last pass, and thus may take a great deal of time.
  167698. *
  167699. * Returns FALSE if suspended. The return value need be inspected only if
  167700. * a suspending data source is used.
  167701. */
  167702. GLOBAL(boolean)
  167703. jpeg_start_decompress (j_decompress_ptr cinfo)
  167704. {
  167705. if (cinfo->global_state == DSTATE_READY) {
  167706. /* First call: initialize master control, select active modules */
  167707. jinit_master_decompress(cinfo);
  167708. if (cinfo->buffered_image) {
  167709. /* No more work here; expecting jpeg_start_output next */
  167710. cinfo->global_state = DSTATE_BUFIMAGE;
  167711. return TRUE;
  167712. }
  167713. cinfo->global_state = DSTATE_PRELOAD;
  167714. }
  167715. if (cinfo->global_state == DSTATE_PRELOAD) {
  167716. /* If file has multiple scans, absorb them all into the coef buffer */
  167717. if (cinfo->inputctl->has_multiple_scans) {
  167718. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167719. for (;;) {
  167720. int retcode;
  167721. /* Call progress monitor hook if present */
  167722. if (cinfo->progress != NULL)
  167723. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167724. /* Absorb some more input */
  167725. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167726. if (retcode == JPEG_SUSPENDED)
  167727. return FALSE;
  167728. if (retcode == JPEG_REACHED_EOI)
  167729. break;
  167730. /* Advance progress counter if appropriate */
  167731. if (cinfo->progress != NULL &&
  167732. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167733. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167734. /* jdmaster underestimated number of scans; ratchet up one scan */
  167735. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167736. }
  167737. }
  167738. }
  167739. #else
  167740. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167741. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167742. }
  167743. cinfo->output_scan_number = cinfo->input_scan_number;
  167744. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167745. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167746. /* Perform any dummy output passes, and set up for the final pass */
  167747. return output_pass_setup(cinfo);
  167748. }
  167749. /*
  167750. * Set up for an output pass, and perform any dummy pass(es) needed.
  167751. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167752. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167753. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167754. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167755. */
  167756. LOCAL(boolean)
  167757. output_pass_setup (j_decompress_ptr cinfo)
  167758. {
  167759. if (cinfo->global_state != DSTATE_PRESCAN) {
  167760. /* First call: do pass setup */
  167761. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167762. cinfo->output_scanline = 0;
  167763. cinfo->global_state = DSTATE_PRESCAN;
  167764. }
  167765. /* Loop over any required dummy passes */
  167766. while (cinfo->master->is_dummy_pass) {
  167767. #ifdef QUANT_2PASS_SUPPORTED
  167768. /* Crank through the dummy pass */
  167769. while (cinfo->output_scanline < cinfo->output_height) {
  167770. JDIMENSION last_scanline;
  167771. /* Call progress monitor hook if present */
  167772. if (cinfo->progress != NULL) {
  167773. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167774. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167775. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167776. }
  167777. /* Process some data */
  167778. last_scanline = cinfo->output_scanline;
  167779. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167780. &cinfo->output_scanline, (JDIMENSION) 0);
  167781. if (cinfo->output_scanline == last_scanline)
  167782. return FALSE; /* No progress made, must suspend */
  167783. }
  167784. /* Finish up dummy pass, and set up for another one */
  167785. (*cinfo->master->finish_output_pass) (cinfo);
  167786. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167787. cinfo->output_scanline = 0;
  167788. #else
  167789. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167790. #endif /* QUANT_2PASS_SUPPORTED */
  167791. }
  167792. /* Ready for application to drive output pass through
  167793. * jpeg_read_scanlines or jpeg_read_raw_data.
  167794. */
  167795. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167796. return TRUE;
  167797. }
  167798. /*
  167799. * Read some scanlines of data from the JPEG decompressor.
  167800. *
  167801. * The return value will be the number of lines actually read.
  167802. * This may be less than the number requested in several cases,
  167803. * including bottom of image, data source suspension, and operating
  167804. * modes that emit multiple scanlines at a time.
  167805. *
  167806. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167807. * this likely signals an application programmer error. However,
  167808. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167809. */
  167810. GLOBAL(JDIMENSION)
  167811. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167812. JDIMENSION max_lines)
  167813. {
  167814. JDIMENSION row_ctr;
  167815. if (cinfo->global_state != DSTATE_SCANNING)
  167816. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167817. if (cinfo->output_scanline >= cinfo->output_height) {
  167818. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167819. return 0;
  167820. }
  167821. /* Call progress monitor hook if present */
  167822. if (cinfo->progress != NULL) {
  167823. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167824. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167825. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167826. }
  167827. /* Process some data */
  167828. row_ctr = 0;
  167829. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167830. cinfo->output_scanline += row_ctr;
  167831. return row_ctr;
  167832. }
  167833. /*
  167834. * Alternate entry point to read raw data.
  167835. * Processes exactly one iMCU row per call, unless suspended.
  167836. */
  167837. GLOBAL(JDIMENSION)
  167838. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167839. JDIMENSION max_lines)
  167840. {
  167841. JDIMENSION lines_per_iMCU_row;
  167842. if (cinfo->global_state != DSTATE_RAW_OK)
  167843. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167844. if (cinfo->output_scanline >= cinfo->output_height) {
  167845. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167846. return 0;
  167847. }
  167848. /* Call progress monitor hook if present */
  167849. if (cinfo->progress != NULL) {
  167850. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167851. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167852. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167853. }
  167854. /* Verify that at least one iMCU row can be returned. */
  167855. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167856. if (max_lines < lines_per_iMCU_row)
  167857. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167858. /* Decompress directly into user's buffer. */
  167859. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167860. return 0; /* suspension forced, can do nothing more */
  167861. /* OK, we processed one iMCU row. */
  167862. cinfo->output_scanline += lines_per_iMCU_row;
  167863. return lines_per_iMCU_row;
  167864. }
  167865. /* Additional entry points for buffered-image mode. */
  167866. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167867. /*
  167868. * Initialize for an output pass in buffered-image mode.
  167869. */
  167870. GLOBAL(boolean)
  167871. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167872. {
  167873. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167874. cinfo->global_state != DSTATE_PRESCAN)
  167875. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167876. /* Limit scan number to valid range */
  167877. if (scan_number <= 0)
  167878. scan_number = 1;
  167879. if (cinfo->inputctl->eoi_reached &&
  167880. scan_number > cinfo->input_scan_number)
  167881. scan_number = cinfo->input_scan_number;
  167882. cinfo->output_scan_number = scan_number;
  167883. /* Perform any dummy output passes, and set up for the real pass */
  167884. return output_pass_setup(cinfo);
  167885. }
  167886. /*
  167887. * Finish up after an output pass in buffered-image mode.
  167888. *
  167889. * Returns FALSE if suspended. The return value need be inspected only if
  167890. * a suspending data source is used.
  167891. */
  167892. GLOBAL(boolean)
  167893. jpeg_finish_output (j_decompress_ptr cinfo)
  167894. {
  167895. if ((cinfo->global_state == DSTATE_SCANNING ||
  167896. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167897. /* Terminate this pass. */
  167898. /* We do not require the whole pass to have been completed. */
  167899. (*cinfo->master->finish_output_pass) (cinfo);
  167900. cinfo->global_state = DSTATE_BUFPOST;
  167901. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167902. /* BUFPOST = repeat call after a suspension, anything else is error */
  167903. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167904. }
  167905. /* Read markers looking for SOS or EOI */
  167906. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167907. ! cinfo->inputctl->eoi_reached) {
  167908. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167909. return FALSE; /* Suspend, come back later */
  167910. }
  167911. cinfo->global_state = DSTATE_BUFIMAGE;
  167912. return TRUE;
  167913. }
  167914. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167915. /*** End of inlined file: jdapistd.c ***/
  167916. /*** Start of inlined file: jdapimin.c ***/
  167917. #define JPEG_INTERNALS
  167918. /*
  167919. * Initialization of a JPEG decompression object.
  167920. * The error manager must already be set up (in case memory manager fails).
  167921. */
  167922. GLOBAL(void)
  167923. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167924. {
  167925. int i;
  167926. /* Guard against version mismatches between library and caller. */
  167927. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167928. if (version != JPEG_LIB_VERSION)
  167929. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167930. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167931. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167932. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167933. /* For debugging purposes, we zero the whole master structure.
  167934. * But the application has already set the err pointer, and may have set
  167935. * client_data, so we have to save and restore those fields.
  167936. * Note: if application hasn't set client_data, tools like Purify may
  167937. * complain here.
  167938. */
  167939. {
  167940. struct jpeg_error_mgr * err = cinfo->err;
  167941. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167942. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167943. cinfo->err = err;
  167944. cinfo->client_data = client_data;
  167945. }
  167946. cinfo->is_decompressor = TRUE;
  167947. /* Initialize a memory manager instance for this object */
  167948. jinit_memory_mgr((j_common_ptr) cinfo);
  167949. /* Zero out pointers to permanent structures. */
  167950. cinfo->progress = NULL;
  167951. cinfo->src = NULL;
  167952. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167953. cinfo->quant_tbl_ptrs[i] = NULL;
  167954. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167955. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167956. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167957. }
  167958. /* Initialize marker processor so application can override methods
  167959. * for COM, APPn markers before calling jpeg_read_header.
  167960. */
  167961. cinfo->marker_list = NULL;
  167962. jinit_marker_reader(cinfo);
  167963. /* And initialize the overall input controller. */
  167964. jinit_input_controller(cinfo);
  167965. /* OK, I'm ready */
  167966. cinfo->global_state = DSTATE_START;
  167967. }
  167968. /*
  167969. * Destruction of a JPEG decompression object
  167970. */
  167971. GLOBAL(void)
  167972. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167973. {
  167974. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167975. }
  167976. /*
  167977. * Abort processing of a JPEG decompression operation,
  167978. * but don't destroy the object itself.
  167979. */
  167980. GLOBAL(void)
  167981. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167982. {
  167983. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167984. }
  167985. /*
  167986. * Set default decompression parameters.
  167987. */
  167988. LOCAL(void)
  167989. default_decompress_parms (j_decompress_ptr cinfo)
  167990. {
  167991. /* Guess the input colorspace, and set output colorspace accordingly. */
  167992. /* (Wish JPEG committee had provided a real way to specify this...) */
  167993. /* Note application may override our guesses. */
  167994. switch (cinfo->num_components) {
  167995. case 1:
  167996. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167997. cinfo->out_color_space = JCS_GRAYSCALE;
  167998. break;
  167999. case 3:
  168000. if (cinfo->saw_JFIF_marker) {
  168001. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  168002. } else if (cinfo->saw_Adobe_marker) {
  168003. switch (cinfo->Adobe_transform) {
  168004. case 0:
  168005. cinfo->jpeg_color_space = JCS_RGB;
  168006. break;
  168007. case 1:
  168008. cinfo->jpeg_color_space = JCS_YCbCr;
  168009. break;
  168010. default:
  168011. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168012. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168013. break;
  168014. }
  168015. } else {
  168016. /* Saw no special markers, try to guess from the component IDs */
  168017. int cid0 = cinfo->comp_info[0].component_id;
  168018. int cid1 = cinfo->comp_info[1].component_id;
  168019. int cid2 = cinfo->comp_info[2].component_id;
  168020. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  168021. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  168022. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  168023. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  168024. else {
  168025. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  168026. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168027. }
  168028. }
  168029. /* Always guess RGB is proper output colorspace. */
  168030. cinfo->out_color_space = JCS_RGB;
  168031. break;
  168032. case 4:
  168033. if (cinfo->saw_Adobe_marker) {
  168034. switch (cinfo->Adobe_transform) {
  168035. case 0:
  168036. cinfo->jpeg_color_space = JCS_CMYK;
  168037. break;
  168038. case 2:
  168039. cinfo->jpeg_color_space = JCS_YCCK;
  168040. break;
  168041. default:
  168042. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168043. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  168044. break;
  168045. }
  168046. } else {
  168047. /* No special markers, assume straight CMYK. */
  168048. cinfo->jpeg_color_space = JCS_CMYK;
  168049. }
  168050. cinfo->out_color_space = JCS_CMYK;
  168051. break;
  168052. default:
  168053. cinfo->jpeg_color_space = JCS_UNKNOWN;
  168054. cinfo->out_color_space = JCS_UNKNOWN;
  168055. break;
  168056. }
  168057. /* Set defaults for other decompression parameters. */
  168058. cinfo->scale_num = 1; /* 1:1 scaling */
  168059. cinfo->scale_denom = 1;
  168060. cinfo->output_gamma = 1.0;
  168061. cinfo->buffered_image = FALSE;
  168062. cinfo->raw_data_out = FALSE;
  168063. cinfo->dct_method = JDCT_DEFAULT;
  168064. cinfo->do_fancy_upsampling = TRUE;
  168065. cinfo->do_block_smoothing = TRUE;
  168066. cinfo->quantize_colors = FALSE;
  168067. /* We set these in case application only sets quantize_colors. */
  168068. cinfo->dither_mode = JDITHER_FS;
  168069. #ifdef QUANT_2PASS_SUPPORTED
  168070. cinfo->two_pass_quantize = TRUE;
  168071. #else
  168072. cinfo->two_pass_quantize = FALSE;
  168073. #endif
  168074. cinfo->desired_number_of_colors = 256;
  168075. cinfo->colormap = NULL;
  168076. /* Initialize for no mode change in buffered-image mode. */
  168077. cinfo->enable_1pass_quant = FALSE;
  168078. cinfo->enable_external_quant = FALSE;
  168079. cinfo->enable_2pass_quant = FALSE;
  168080. }
  168081. /*
  168082. * Decompression startup: read start of JPEG datastream to see what's there.
  168083. * Need only initialize JPEG object and supply a data source before calling.
  168084. *
  168085. * This routine will read as far as the first SOS marker (ie, actual start of
  168086. * compressed data), and will save all tables and parameters in the JPEG
  168087. * object. It will also initialize the decompression parameters to default
  168088. * values, and finally return JPEG_HEADER_OK. On return, the application may
  168089. * adjust the decompression parameters and then call jpeg_start_decompress.
  168090. * (Or, if the application only wanted to determine the image parameters,
  168091. * the data need not be decompressed. In that case, call jpeg_abort or
  168092. * jpeg_destroy to release any temporary space.)
  168093. * If an abbreviated (tables only) datastream is presented, the routine will
  168094. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  168095. * re-use the JPEG object to read the abbreviated image datastream(s).
  168096. * It is unnecessary (but OK) to call jpeg_abort in this case.
  168097. * The JPEG_SUSPENDED return code only occurs if the data source module
  168098. * requests suspension of the decompressor. In this case the application
  168099. * should load more source data and then re-call jpeg_read_header to resume
  168100. * processing.
  168101. * If a non-suspending data source is used and require_image is TRUE, then the
  168102. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  168103. *
  168104. * This routine is now just a front end to jpeg_consume_input, with some
  168105. * extra error checking.
  168106. */
  168107. GLOBAL(int)
  168108. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  168109. {
  168110. int retcode;
  168111. if (cinfo->global_state != DSTATE_START &&
  168112. cinfo->global_state != DSTATE_INHEADER)
  168113. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168114. retcode = jpeg_consume_input(cinfo);
  168115. switch (retcode) {
  168116. case JPEG_REACHED_SOS:
  168117. retcode = JPEG_HEADER_OK;
  168118. break;
  168119. case JPEG_REACHED_EOI:
  168120. if (require_image) /* Complain if application wanted an image */
  168121. ERREXIT(cinfo, JERR_NO_IMAGE);
  168122. /* Reset to start state; it would be safer to require the application to
  168123. * call jpeg_abort, but we can't change it now for compatibility reasons.
  168124. * A side effect is to free any temporary memory (there shouldn't be any).
  168125. */
  168126. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  168127. retcode = JPEG_HEADER_TABLES_ONLY;
  168128. break;
  168129. case JPEG_SUSPENDED:
  168130. /* no work */
  168131. break;
  168132. }
  168133. return retcode;
  168134. }
  168135. /*
  168136. * Consume data in advance of what the decompressor requires.
  168137. * This can be called at any time once the decompressor object has
  168138. * been created and a data source has been set up.
  168139. *
  168140. * This routine is essentially a state machine that handles a couple
  168141. * of critical state-transition actions, namely initial setup and
  168142. * transition from header scanning to ready-for-start_decompress.
  168143. * All the actual input is done via the input controller's consume_input
  168144. * method.
  168145. */
  168146. GLOBAL(int)
  168147. jpeg_consume_input (j_decompress_ptr cinfo)
  168148. {
  168149. int retcode = JPEG_SUSPENDED;
  168150. /* NB: every possible DSTATE value should be listed in this switch */
  168151. switch (cinfo->global_state) {
  168152. case DSTATE_START:
  168153. /* Start-of-datastream actions: reset appropriate modules */
  168154. (*cinfo->inputctl->reset_input_controller) (cinfo);
  168155. /* Initialize application's data source module */
  168156. (*cinfo->src->init_source) (cinfo);
  168157. cinfo->global_state = DSTATE_INHEADER;
  168158. /*FALLTHROUGH*/
  168159. case DSTATE_INHEADER:
  168160. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168161. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  168162. /* Set up default parameters based on header data */
  168163. default_decompress_parms(cinfo);
  168164. /* Set global state: ready for start_decompress */
  168165. cinfo->global_state = DSTATE_READY;
  168166. }
  168167. break;
  168168. case DSTATE_READY:
  168169. /* Can't advance past first SOS until start_decompress is called */
  168170. retcode = JPEG_REACHED_SOS;
  168171. break;
  168172. case DSTATE_PRELOAD:
  168173. case DSTATE_PRESCAN:
  168174. case DSTATE_SCANNING:
  168175. case DSTATE_RAW_OK:
  168176. case DSTATE_BUFIMAGE:
  168177. case DSTATE_BUFPOST:
  168178. case DSTATE_STOPPING:
  168179. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168180. break;
  168181. default:
  168182. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168183. }
  168184. return retcode;
  168185. }
  168186. /*
  168187. * Have we finished reading the input file?
  168188. */
  168189. GLOBAL(boolean)
  168190. jpeg_input_complete (j_decompress_ptr cinfo)
  168191. {
  168192. /* Check for valid jpeg object */
  168193. if (cinfo->global_state < DSTATE_START ||
  168194. cinfo->global_state > DSTATE_STOPPING)
  168195. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168196. return cinfo->inputctl->eoi_reached;
  168197. }
  168198. /*
  168199. * Is there more than one scan?
  168200. */
  168201. GLOBAL(boolean)
  168202. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168203. {
  168204. /* Only valid after jpeg_read_header completes */
  168205. if (cinfo->global_state < DSTATE_READY ||
  168206. cinfo->global_state > DSTATE_STOPPING)
  168207. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168208. return cinfo->inputctl->has_multiple_scans;
  168209. }
  168210. /*
  168211. * Finish JPEG decompression.
  168212. *
  168213. * This will normally just verify the file trailer and release temp storage.
  168214. *
  168215. * Returns FALSE if suspended. The return value need be inspected only if
  168216. * a suspending data source is used.
  168217. */
  168218. GLOBAL(boolean)
  168219. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168220. {
  168221. if ((cinfo->global_state == DSTATE_SCANNING ||
  168222. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168223. /* Terminate final pass of non-buffered mode */
  168224. if (cinfo->output_scanline < cinfo->output_height)
  168225. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168226. (*cinfo->master->finish_output_pass) (cinfo);
  168227. cinfo->global_state = DSTATE_STOPPING;
  168228. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168229. /* Finishing after a buffered-image operation */
  168230. cinfo->global_state = DSTATE_STOPPING;
  168231. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168232. /* STOPPING = repeat call after a suspension, anything else is error */
  168233. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168234. }
  168235. /* Read until EOI */
  168236. while (! cinfo->inputctl->eoi_reached) {
  168237. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168238. return FALSE; /* Suspend, come back later */
  168239. }
  168240. /* Do final cleanup */
  168241. (*cinfo->src->term_source) (cinfo);
  168242. /* We can use jpeg_abort to release memory and reset global_state */
  168243. jpeg_abort((j_common_ptr) cinfo);
  168244. return TRUE;
  168245. }
  168246. /*** End of inlined file: jdapimin.c ***/
  168247. /*** Start of inlined file: jdatasrc.c ***/
  168248. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168249. /*** Start of inlined file: jerror.h ***/
  168250. /*
  168251. * To define the enum list of message codes, include this file without
  168252. * defining macro JMESSAGE. To create a message string table, include it
  168253. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168254. */
  168255. #ifndef JMESSAGE
  168256. #ifndef JERROR_H
  168257. /* First time through, define the enum list */
  168258. #define JMAKE_ENUM_LIST
  168259. #else
  168260. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168261. #define JMESSAGE(code,string)
  168262. #endif /* JERROR_H */
  168263. #endif /* JMESSAGE */
  168264. #ifdef JMAKE_ENUM_LIST
  168265. typedef enum {
  168266. #define JMESSAGE(code,string) code ,
  168267. #endif /* JMAKE_ENUM_LIST */
  168268. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168269. /* For maintenance convenience, list is alphabetical by message code name */
  168270. JMESSAGE(JERR_ARITH_NOTIMPL,
  168271. "Sorry, there are legal restrictions on arithmetic coding")
  168272. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168273. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168274. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168275. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168276. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168277. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168278. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168279. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168280. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168281. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168282. JMESSAGE(JERR_BAD_LIB_VERSION,
  168283. "Wrong JPEG library version: library is %d, caller expects %d")
  168284. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168285. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168286. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168287. JMESSAGE(JERR_BAD_PROGRESSION,
  168288. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168289. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168290. "Invalid progressive parameters at scan script entry %d")
  168291. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168292. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168293. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168294. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168295. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168296. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168297. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168298. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168299. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168300. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168301. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168302. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168303. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168304. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168305. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168306. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168307. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168308. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168309. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168310. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168311. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168312. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168313. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168314. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168315. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168316. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168317. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168318. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168319. "Cannot transcode due to multiple use of quantization table %d")
  168320. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168321. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168322. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168323. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168324. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168325. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168326. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168327. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168328. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168329. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168330. JMESSAGE(JERR_QUANT_COMPONENTS,
  168331. "Cannot quantize more than %d color components")
  168332. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168333. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168334. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168335. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168336. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168337. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168338. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168339. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168340. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168341. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168342. JMESSAGE(JERR_TFILE_WRITE,
  168343. "Write failed on temporary file --- out of disk space?")
  168344. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168345. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168346. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168347. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168348. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168349. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168350. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168351. JMESSAGE(JMSG_VERSION, JVERSION)
  168352. JMESSAGE(JTRC_16BIT_TABLES,
  168353. "Caution: quantization tables are too coarse for baseline JPEG")
  168354. JMESSAGE(JTRC_ADOBE,
  168355. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168356. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168357. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168358. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168359. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168360. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168361. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168362. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168363. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168364. JMESSAGE(JTRC_EOI, "End Of Image")
  168365. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168366. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168367. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168368. "Warning: thumbnail image size does not match data length %u")
  168369. JMESSAGE(JTRC_JFIF_EXTENSION,
  168370. "JFIF extension marker: type 0x%02x, length %u")
  168371. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168372. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168373. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168374. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168375. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168376. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168377. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168378. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168379. JMESSAGE(JTRC_RST, "RST%d")
  168380. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168381. "Smoothing not supported with nonstandard sampling ratios")
  168382. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168383. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168384. JMESSAGE(JTRC_SOI, "Start of Image")
  168385. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168386. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168387. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168388. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168389. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168390. JMESSAGE(JTRC_THUMB_JPEG,
  168391. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168392. JMESSAGE(JTRC_THUMB_PALETTE,
  168393. "JFIF extension marker: palette thumbnail image, length %u")
  168394. JMESSAGE(JTRC_THUMB_RGB,
  168395. "JFIF extension marker: RGB thumbnail image, length %u")
  168396. JMESSAGE(JTRC_UNKNOWN_IDS,
  168397. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168398. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168399. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168400. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168401. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168402. "Inconsistent progression sequence for component %d coefficient %d")
  168403. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168404. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168405. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168406. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168407. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168408. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168409. JMESSAGE(JWRN_MUST_RESYNC,
  168410. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168411. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168412. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168413. #ifdef JMAKE_ENUM_LIST
  168414. JMSG_LASTMSGCODE
  168415. } J_MESSAGE_CODE;
  168416. #undef JMAKE_ENUM_LIST
  168417. #endif /* JMAKE_ENUM_LIST */
  168418. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168419. #undef JMESSAGE
  168420. #ifndef JERROR_H
  168421. #define JERROR_H
  168422. /* Macros to simplify using the error and trace message stuff */
  168423. /* The first parameter is either type of cinfo pointer */
  168424. /* Fatal errors (print message and exit) */
  168425. #define ERREXIT(cinfo,code) \
  168426. ((cinfo)->err->msg_code = (code), \
  168427. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168428. #define ERREXIT1(cinfo,code,p1) \
  168429. ((cinfo)->err->msg_code = (code), \
  168430. (cinfo)->err->msg_parm.i[0] = (p1), \
  168431. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168432. #define ERREXIT2(cinfo,code,p1,p2) \
  168433. ((cinfo)->err->msg_code = (code), \
  168434. (cinfo)->err->msg_parm.i[0] = (p1), \
  168435. (cinfo)->err->msg_parm.i[1] = (p2), \
  168436. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168437. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168438. ((cinfo)->err->msg_code = (code), \
  168439. (cinfo)->err->msg_parm.i[0] = (p1), \
  168440. (cinfo)->err->msg_parm.i[1] = (p2), \
  168441. (cinfo)->err->msg_parm.i[2] = (p3), \
  168442. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168443. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168444. ((cinfo)->err->msg_code = (code), \
  168445. (cinfo)->err->msg_parm.i[0] = (p1), \
  168446. (cinfo)->err->msg_parm.i[1] = (p2), \
  168447. (cinfo)->err->msg_parm.i[2] = (p3), \
  168448. (cinfo)->err->msg_parm.i[3] = (p4), \
  168449. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168450. #define ERREXITS(cinfo,code,str) \
  168451. ((cinfo)->err->msg_code = (code), \
  168452. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168453. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168454. #define MAKESTMT(stuff) do { stuff } while (0)
  168455. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168456. #define WARNMS(cinfo,code) \
  168457. ((cinfo)->err->msg_code = (code), \
  168458. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168459. #define WARNMS1(cinfo,code,p1) \
  168460. ((cinfo)->err->msg_code = (code), \
  168461. (cinfo)->err->msg_parm.i[0] = (p1), \
  168462. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168463. #define WARNMS2(cinfo,code,p1,p2) \
  168464. ((cinfo)->err->msg_code = (code), \
  168465. (cinfo)->err->msg_parm.i[0] = (p1), \
  168466. (cinfo)->err->msg_parm.i[1] = (p2), \
  168467. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168468. /* Informational/debugging messages */
  168469. #define TRACEMS(cinfo,lvl,code) \
  168470. ((cinfo)->err->msg_code = (code), \
  168471. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168472. #define TRACEMS1(cinfo,lvl,code,p1) \
  168473. ((cinfo)->err->msg_code = (code), \
  168474. (cinfo)->err->msg_parm.i[0] = (p1), \
  168475. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168476. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168477. ((cinfo)->err->msg_code = (code), \
  168478. (cinfo)->err->msg_parm.i[0] = (p1), \
  168479. (cinfo)->err->msg_parm.i[1] = (p2), \
  168480. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168481. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168482. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168483. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168484. (cinfo)->err->msg_code = (code); \
  168485. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168486. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168487. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168488. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168489. (cinfo)->err->msg_code = (code); \
  168490. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168491. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168492. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168493. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168494. _mp[4] = (p5); \
  168495. (cinfo)->err->msg_code = (code); \
  168496. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168497. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168498. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168499. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168500. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168501. (cinfo)->err->msg_code = (code); \
  168502. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168503. #define TRACEMSS(cinfo,lvl,code,str) \
  168504. ((cinfo)->err->msg_code = (code), \
  168505. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168506. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168507. #endif /* JERROR_H */
  168508. /*** End of inlined file: jerror.h ***/
  168509. /* Expanded data source object for stdio input */
  168510. typedef struct {
  168511. struct jpeg_source_mgr pub; /* public fields */
  168512. FILE * infile; /* source stream */
  168513. JOCTET * buffer; /* start of buffer */
  168514. boolean start_of_file; /* have we gotten any data yet? */
  168515. } my_source_mgr;
  168516. typedef my_source_mgr * my_src_ptr;
  168517. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168518. /*
  168519. * Initialize source --- called by jpeg_read_header
  168520. * before any data is actually read.
  168521. */
  168522. METHODDEF(void)
  168523. init_source (j_decompress_ptr cinfo)
  168524. {
  168525. my_src_ptr src = (my_src_ptr) cinfo->src;
  168526. /* We reset the empty-input-file flag for each image,
  168527. * but we don't clear the input buffer.
  168528. * This is correct behavior for reading a series of images from one source.
  168529. */
  168530. src->start_of_file = TRUE;
  168531. }
  168532. /*
  168533. * Fill the input buffer --- called whenever buffer is emptied.
  168534. *
  168535. * In typical applications, this should read fresh data into the buffer
  168536. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168537. * reset the pointer & count to the start of the buffer, and return TRUE
  168538. * indicating that the buffer has been reloaded. It is not necessary to
  168539. * fill the buffer entirely, only to obtain at least one more byte.
  168540. *
  168541. * There is no such thing as an EOF return. If the end of the file has been
  168542. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168543. * the buffer. In most cases, generating a warning message and inserting a
  168544. * fake EOI marker is the best course of action --- this will allow the
  168545. * decompressor to output however much of the image is there. However,
  168546. * the resulting error message is misleading if the real problem is an empty
  168547. * input file, so we handle that case specially.
  168548. *
  168549. * In applications that need to be able to suspend compression due to input
  168550. * not being available yet, a FALSE return indicates that no more data can be
  168551. * obtained right now, but more may be forthcoming later. In this situation,
  168552. * the decompressor will return to its caller (with an indication of the
  168553. * number of scanlines it has read, if any). The application should resume
  168554. * decompression after it has loaded more data into the input buffer. Note
  168555. * that there are substantial restrictions on the use of suspension --- see
  168556. * the documentation.
  168557. *
  168558. * When suspending, the decompressor will back up to a convenient restart point
  168559. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168560. * indicate where the restart point will be if the current call returns FALSE.
  168561. * Data beyond this point must be rescanned after resumption, so move it to
  168562. * the front of the buffer rather than discarding it.
  168563. */
  168564. METHODDEF(boolean)
  168565. fill_input_buffer (j_decompress_ptr cinfo)
  168566. {
  168567. my_src_ptr src = (my_src_ptr) cinfo->src;
  168568. size_t nbytes;
  168569. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168570. if (nbytes <= 0) {
  168571. if (src->start_of_file) /* Treat empty input file as fatal error */
  168572. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168573. WARNMS(cinfo, JWRN_JPEG_EOF);
  168574. /* Insert a fake EOI marker */
  168575. src->buffer[0] = (JOCTET) 0xFF;
  168576. src->buffer[1] = (JOCTET) JPEG_EOI;
  168577. nbytes = 2;
  168578. }
  168579. src->pub.next_input_byte = src->buffer;
  168580. src->pub.bytes_in_buffer = nbytes;
  168581. src->start_of_file = FALSE;
  168582. return TRUE;
  168583. }
  168584. /*
  168585. * Skip data --- used to skip over a potentially large amount of
  168586. * uninteresting data (such as an APPn marker).
  168587. *
  168588. * Writers of suspendable-input applications must note that skip_input_data
  168589. * is not granted the right to give a suspension return. If the skip extends
  168590. * beyond the data currently in the buffer, the buffer can be marked empty so
  168591. * that the next read will cause a fill_input_buffer call that can suspend.
  168592. * Arranging for additional bytes to be discarded before reloading the input
  168593. * buffer is the application writer's problem.
  168594. */
  168595. METHODDEF(void)
  168596. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168597. {
  168598. my_src_ptr src = (my_src_ptr) cinfo->src;
  168599. /* Just a dumb implementation for now. Could use fseek() except
  168600. * it doesn't work on pipes. Not clear that being smart is worth
  168601. * any trouble anyway --- large skips are infrequent.
  168602. */
  168603. if (num_bytes > 0) {
  168604. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168605. num_bytes -= (long) src->pub.bytes_in_buffer;
  168606. (void) fill_input_buffer(cinfo);
  168607. /* note we assume that fill_input_buffer will never return FALSE,
  168608. * so suspension need not be handled.
  168609. */
  168610. }
  168611. src->pub.next_input_byte += (size_t) num_bytes;
  168612. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168613. }
  168614. }
  168615. /*
  168616. * An additional method that can be provided by data source modules is the
  168617. * resync_to_restart method for error recovery in the presence of RST markers.
  168618. * For the moment, this source module just uses the default resync method
  168619. * provided by the JPEG library. That method assumes that no backtracking
  168620. * is possible.
  168621. */
  168622. /*
  168623. * Terminate source --- called by jpeg_finish_decompress
  168624. * after all data has been read. Often a no-op.
  168625. *
  168626. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168627. * application must deal with any cleanup that should happen even
  168628. * for error exit.
  168629. */
  168630. METHODDEF(void)
  168631. term_source (j_decompress_ptr)
  168632. {
  168633. /* no work necessary here */
  168634. }
  168635. /*
  168636. * Prepare for input from a stdio stream.
  168637. * The caller must have already opened the stream, and is responsible
  168638. * for closing it after finishing decompression.
  168639. */
  168640. GLOBAL(void)
  168641. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168642. {
  168643. my_src_ptr src;
  168644. /* The source object and input buffer are made permanent so that a series
  168645. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168646. * only before the first one. (If we discarded the buffer at the end of
  168647. * one image, we'd likely lose the start of the next one.)
  168648. * This makes it unsafe to use this manager and a different source
  168649. * manager serially with the same JPEG object. Caveat programmer.
  168650. */
  168651. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168652. cinfo->src = (struct jpeg_source_mgr *)
  168653. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168654. SIZEOF(my_source_mgr));
  168655. src = (my_src_ptr) cinfo->src;
  168656. src->buffer = (JOCTET *)
  168657. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168658. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168659. }
  168660. src = (my_src_ptr) cinfo->src;
  168661. src->pub.init_source = init_source;
  168662. src->pub.fill_input_buffer = fill_input_buffer;
  168663. src->pub.skip_input_data = skip_input_data;
  168664. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168665. src->pub.term_source = term_source;
  168666. src->infile = infile;
  168667. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168668. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168669. }
  168670. /*** End of inlined file: jdatasrc.c ***/
  168671. /*** Start of inlined file: jdcoefct.c ***/
  168672. #define JPEG_INTERNALS
  168673. /* Block smoothing is only applicable for progressive JPEG, so: */
  168674. #ifndef D_PROGRESSIVE_SUPPORTED
  168675. #undef BLOCK_SMOOTHING_SUPPORTED
  168676. #endif
  168677. /* Private buffer controller object */
  168678. typedef struct {
  168679. struct jpeg_d_coef_controller pub; /* public fields */
  168680. /* These variables keep track of the current location of the input side. */
  168681. /* cinfo->input_iMCU_row is also used for this. */
  168682. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168683. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168684. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168685. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168686. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168687. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168688. * and let the entropy decoder write into that workspace each time.
  168689. * (On 80x86, the workspace is FAR even though it's not really very big;
  168690. * this is to keep the module interfaces unchanged when a large coefficient
  168691. * buffer is necessary.)
  168692. * In multi-pass modes, this array points to the current MCU's blocks
  168693. * within the virtual arrays; it is used only by the input side.
  168694. */
  168695. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168696. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168697. /* In multi-pass modes, we need a virtual block array for each component. */
  168698. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168699. #endif
  168700. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168701. /* When doing block smoothing, we latch coefficient Al values here */
  168702. int * coef_bits_latch;
  168703. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168704. #endif
  168705. } my_coef_controller3;
  168706. typedef my_coef_controller3 * my_coef_ptr3;
  168707. /* Forward declarations */
  168708. METHODDEF(int) decompress_onepass
  168709. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168710. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168711. METHODDEF(int) decompress_data
  168712. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168713. #endif
  168714. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168715. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168716. METHODDEF(int) decompress_smooth_data
  168717. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168718. #endif
  168719. LOCAL(void)
  168720. start_iMCU_row3 (j_decompress_ptr cinfo)
  168721. /* Reset within-iMCU-row counters for a new row (input side) */
  168722. {
  168723. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168724. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168725. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168726. * But at the bottom of the image, process only what's left.
  168727. */
  168728. if (cinfo->comps_in_scan > 1) {
  168729. coef->MCU_rows_per_iMCU_row = 1;
  168730. } else {
  168731. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168732. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168733. else
  168734. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168735. }
  168736. coef->MCU_ctr = 0;
  168737. coef->MCU_vert_offset = 0;
  168738. }
  168739. /*
  168740. * Initialize for an input processing pass.
  168741. */
  168742. METHODDEF(void)
  168743. start_input_pass (j_decompress_ptr cinfo)
  168744. {
  168745. cinfo->input_iMCU_row = 0;
  168746. start_iMCU_row3(cinfo);
  168747. }
  168748. /*
  168749. * Initialize for an output processing pass.
  168750. */
  168751. METHODDEF(void)
  168752. start_output_pass (j_decompress_ptr cinfo)
  168753. {
  168754. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168755. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168756. /* If multipass, check to see whether to use block smoothing on this pass */
  168757. if (coef->pub.coef_arrays != NULL) {
  168758. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168759. coef->pub.decompress_data = decompress_smooth_data;
  168760. else
  168761. coef->pub.decompress_data = decompress_data;
  168762. }
  168763. #endif
  168764. cinfo->output_iMCU_row = 0;
  168765. }
  168766. /*
  168767. * Decompress and return some data in the single-pass case.
  168768. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168769. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168770. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168771. *
  168772. * NB: output_buf contains a plane for each component in image,
  168773. * which we index according to the component's SOF position.
  168774. */
  168775. METHODDEF(int)
  168776. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168777. {
  168778. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168779. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168780. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168781. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168782. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168783. JSAMPARRAY output_ptr;
  168784. JDIMENSION start_col, output_col;
  168785. jpeg_component_info *compptr;
  168786. inverse_DCT_method_ptr inverse_DCT;
  168787. /* Loop to process as much as one whole iMCU row */
  168788. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168789. yoffset++) {
  168790. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168791. MCU_col_num++) {
  168792. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168793. jzero_far((void FAR *) coef->MCU_buffer[0],
  168794. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168795. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168796. /* Suspension forced; update state counters and exit */
  168797. coef->MCU_vert_offset = yoffset;
  168798. coef->MCU_ctr = MCU_col_num;
  168799. return JPEG_SUSPENDED;
  168800. }
  168801. /* Determine where data should go in output_buf and do the IDCT thing.
  168802. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168803. * incremented past them!). Note the inner loop relies on having
  168804. * allocated the MCU_buffer[] blocks sequentially.
  168805. */
  168806. blkn = 0; /* index of current DCT block within MCU */
  168807. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168808. compptr = cinfo->cur_comp_info[ci];
  168809. /* Don't bother to IDCT an uninteresting component. */
  168810. if (! compptr->component_needed) {
  168811. blkn += compptr->MCU_blocks;
  168812. continue;
  168813. }
  168814. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168815. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168816. : compptr->last_col_width;
  168817. output_ptr = output_buf[compptr->component_index] +
  168818. yoffset * compptr->DCT_scaled_size;
  168819. start_col = MCU_col_num * compptr->MCU_sample_width;
  168820. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168821. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168822. yoffset+yindex < compptr->last_row_height) {
  168823. output_col = start_col;
  168824. for (xindex = 0; xindex < useful_width; xindex++) {
  168825. (*inverse_DCT) (cinfo, compptr,
  168826. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168827. output_ptr, output_col);
  168828. output_col += compptr->DCT_scaled_size;
  168829. }
  168830. }
  168831. blkn += compptr->MCU_width;
  168832. output_ptr += compptr->DCT_scaled_size;
  168833. }
  168834. }
  168835. }
  168836. /* Completed an MCU row, but perhaps not an iMCU row */
  168837. coef->MCU_ctr = 0;
  168838. }
  168839. /* Completed the iMCU row, advance counters for next one */
  168840. cinfo->output_iMCU_row++;
  168841. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168842. start_iMCU_row3(cinfo);
  168843. return JPEG_ROW_COMPLETED;
  168844. }
  168845. /* Completed the scan */
  168846. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168847. return JPEG_SCAN_COMPLETED;
  168848. }
  168849. /*
  168850. * Dummy consume-input routine for single-pass operation.
  168851. */
  168852. METHODDEF(int)
  168853. dummy_consume_data (j_decompress_ptr)
  168854. {
  168855. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168856. }
  168857. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168858. /*
  168859. * Consume input data and store it in the full-image coefficient buffer.
  168860. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168861. * ie, v_samp_factor block rows for each component in the scan.
  168862. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168863. */
  168864. METHODDEF(int)
  168865. consume_data (j_decompress_ptr cinfo)
  168866. {
  168867. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168868. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168869. int blkn, ci, xindex, yindex, yoffset;
  168870. JDIMENSION start_col;
  168871. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168872. JBLOCKROW buffer_ptr;
  168873. jpeg_component_info *compptr;
  168874. /* Align the virtual buffers for the components used in this scan. */
  168875. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168876. compptr = cinfo->cur_comp_info[ci];
  168877. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168878. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168879. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168880. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168881. /* Note: entropy decoder expects buffer to be zeroed,
  168882. * but this is handled automatically by the memory manager
  168883. * because we requested a pre-zeroed array.
  168884. */
  168885. }
  168886. /* Loop to process one whole iMCU row */
  168887. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168888. yoffset++) {
  168889. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168890. MCU_col_num++) {
  168891. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168892. blkn = 0; /* index of current DCT block within MCU */
  168893. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168894. compptr = cinfo->cur_comp_info[ci];
  168895. start_col = MCU_col_num * compptr->MCU_width;
  168896. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168897. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168898. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168899. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168900. }
  168901. }
  168902. }
  168903. /* Try to fetch the MCU. */
  168904. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168905. /* Suspension forced; update state counters and exit */
  168906. coef->MCU_vert_offset = yoffset;
  168907. coef->MCU_ctr = MCU_col_num;
  168908. return JPEG_SUSPENDED;
  168909. }
  168910. }
  168911. /* Completed an MCU row, but perhaps not an iMCU row */
  168912. coef->MCU_ctr = 0;
  168913. }
  168914. /* Completed the iMCU row, advance counters for next one */
  168915. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168916. start_iMCU_row3(cinfo);
  168917. return JPEG_ROW_COMPLETED;
  168918. }
  168919. /* Completed the scan */
  168920. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168921. return JPEG_SCAN_COMPLETED;
  168922. }
  168923. /*
  168924. * Decompress and return some data in the multi-pass case.
  168925. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168926. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168927. *
  168928. * NB: output_buf contains a plane for each component in image.
  168929. */
  168930. METHODDEF(int)
  168931. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168932. {
  168933. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168934. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168935. JDIMENSION block_num;
  168936. int ci, block_row, block_rows;
  168937. JBLOCKARRAY buffer;
  168938. JBLOCKROW buffer_ptr;
  168939. JSAMPARRAY output_ptr;
  168940. JDIMENSION output_col;
  168941. jpeg_component_info *compptr;
  168942. inverse_DCT_method_ptr inverse_DCT;
  168943. /* Force some input to be done if we are getting ahead of the input. */
  168944. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168945. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168946. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168947. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168948. return JPEG_SUSPENDED;
  168949. }
  168950. /* OK, output from the virtual arrays. */
  168951. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168952. ci++, compptr++) {
  168953. /* Don't bother to IDCT an uninteresting component. */
  168954. if (! compptr->component_needed)
  168955. continue;
  168956. /* Align the virtual buffer for this component. */
  168957. buffer = (*cinfo->mem->access_virt_barray)
  168958. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168959. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168960. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168961. /* Count non-dummy DCT block rows in this iMCU row. */
  168962. if (cinfo->output_iMCU_row < last_iMCU_row)
  168963. block_rows = compptr->v_samp_factor;
  168964. else {
  168965. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168966. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168967. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168968. }
  168969. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168970. output_ptr = output_buf[ci];
  168971. /* Loop over all DCT blocks to be processed. */
  168972. for (block_row = 0; block_row < block_rows; block_row++) {
  168973. buffer_ptr = buffer[block_row];
  168974. output_col = 0;
  168975. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168976. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168977. output_ptr, output_col);
  168978. buffer_ptr++;
  168979. output_col += compptr->DCT_scaled_size;
  168980. }
  168981. output_ptr += compptr->DCT_scaled_size;
  168982. }
  168983. }
  168984. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168985. return JPEG_ROW_COMPLETED;
  168986. return JPEG_SCAN_COMPLETED;
  168987. }
  168988. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168989. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168990. /*
  168991. * This code applies interblock smoothing as described by section K.8
  168992. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168993. * the DC values of a DCT block and its 8 neighboring blocks.
  168994. * We apply smoothing only for progressive JPEG decoding, and only if
  168995. * the coefficients it can estimate are not yet known to full precision.
  168996. */
  168997. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168998. #define Q01_POS 1
  168999. #define Q10_POS 8
  169000. #define Q20_POS 16
  169001. #define Q11_POS 9
  169002. #define Q02_POS 2
  169003. /*
  169004. * Determine whether block smoothing is applicable and safe.
  169005. * We also latch the current states of the coef_bits[] entries for the
  169006. * AC coefficients; otherwise, if the input side of the decompressor
  169007. * advances into a new scan, we might think the coefficients are known
  169008. * more accurately than they really are.
  169009. */
  169010. LOCAL(boolean)
  169011. smoothing_ok (j_decompress_ptr cinfo)
  169012. {
  169013. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169014. boolean smoothing_useful = FALSE;
  169015. int ci, coefi;
  169016. jpeg_component_info *compptr;
  169017. JQUANT_TBL * qtable;
  169018. int * coef_bits;
  169019. int * coef_bits_latch;
  169020. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  169021. return FALSE;
  169022. /* Allocate latch area if not already done */
  169023. if (coef->coef_bits_latch == NULL)
  169024. coef->coef_bits_latch = (int *)
  169025. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169026. cinfo->num_components *
  169027. (SAVED_COEFS * SIZEOF(int)));
  169028. coef_bits_latch = coef->coef_bits_latch;
  169029. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169030. ci++, compptr++) {
  169031. /* All components' quantization values must already be latched. */
  169032. if ((qtable = compptr->quant_table) == NULL)
  169033. return FALSE;
  169034. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  169035. if (qtable->quantval[0] == 0 ||
  169036. qtable->quantval[Q01_POS] == 0 ||
  169037. qtable->quantval[Q10_POS] == 0 ||
  169038. qtable->quantval[Q20_POS] == 0 ||
  169039. qtable->quantval[Q11_POS] == 0 ||
  169040. qtable->quantval[Q02_POS] == 0)
  169041. return FALSE;
  169042. /* DC values must be at least partly known for all components. */
  169043. coef_bits = cinfo->coef_bits[ci];
  169044. if (coef_bits[0] < 0)
  169045. return FALSE;
  169046. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  169047. for (coefi = 1; coefi <= 5; coefi++) {
  169048. coef_bits_latch[coefi] = coef_bits[coefi];
  169049. if (coef_bits[coefi] != 0)
  169050. smoothing_useful = TRUE;
  169051. }
  169052. coef_bits_latch += SAVED_COEFS;
  169053. }
  169054. return smoothing_useful;
  169055. }
  169056. /*
  169057. * Variant of decompress_data for use when doing block smoothing.
  169058. */
  169059. METHODDEF(int)
  169060. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  169061. {
  169062. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169063. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  169064. JDIMENSION block_num, last_block_column;
  169065. int ci, block_row, block_rows, access_rows;
  169066. JBLOCKARRAY buffer;
  169067. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  169068. JSAMPARRAY output_ptr;
  169069. JDIMENSION output_col;
  169070. jpeg_component_info *compptr;
  169071. inverse_DCT_method_ptr inverse_DCT;
  169072. boolean first_row, last_row;
  169073. JBLOCK workspace;
  169074. int *coef_bits;
  169075. JQUANT_TBL *quanttbl;
  169076. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  169077. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  169078. int Al, pred;
  169079. /* Force some input to be done if we are getting ahead of the input. */
  169080. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  169081. ! cinfo->inputctl->eoi_reached) {
  169082. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  169083. /* If input is working on current scan, we ordinarily want it to
  169084. * have completed the current row. But if input scan is DC,
  169085. * we want it to keep one row ahead so that next block row's DC
  169086. * values are up to date.
  169087. */
  169088. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  169089. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  169090. break;
  169091. }
  169092. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  169093. return JPEG_SUSPENDED;
  169094. }
  169095. /* OK, output from the virtual arrays. */
  169096. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169097. ci++, compptr++) {
  169098. /* Don't bother to IDCT an uninteresting component. */
  169099. if (! compptr->component_needed)
  169100. continue;
  169101. /* Count non-dummy DCT block rows in this iMCU row. */
  169102. if (cinfo->output_iMCU_row < last_iMCU_row) {
  169103. block_rows = compptr->v_samp_factor;
  169104. access_rows = block_rows * 2; /* this and next iMCU row */
  169105. last_row = FALSE;
  169106. } else {
  169107. /* NB: can't use last_row_height here; it is input-side-dependent! */
  169108. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169109. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  169110. access_rows = block_rows; /* this iMCU row only */
  169111. last_row = TRUE;
  169112. }
  169113. /* Align the virtual buffer for this component. */
  169114. if (cinfo->output_iMCU_row > 0) {
  169115. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  169116. buffer = (*cinfo->mem->access_virt_barray)
  169117. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169118. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  169119. (JDIMENSION) access_rows, FALSE);
  169120. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  169121. first_row = FALSE;
  169122. } else {
  169123. buffer = (*cinfo->mem->access_virt_barray)
  169124. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169125. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  169126. first_row = TRUE;
  169127. }
  169128. /* Fetch component-dependent info */
  169129. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  169130. quanttbl = compptr->quant_table;
  169131. Q00 = quanttbl->quantval[0];
  169132. Q01 = quanttbl->quantval[Q01_POS];
  169133. Q10 = quanttbl->quantval[Q10_POS];
  169134. Q20 = quanttbl->quantval[Q20_POS];
  169135. Q11 = quanttbl->quantval[Q11_POS];
  169136. Q02 = quanttbl->quantval[Q02_POS];
  169137. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169138. output_ptr = output_buf[ci];
  169139. /* Loop over all DCT blocks to be processed. */
  169140. for (block_row = 0; block_row < block_rows; block_row++) {
  169141. buffer_ptr = buffer[block_row];
  169142. if (first_row && block_row == 0)
  169143. prev_block_row = buffer_ptr;
  169144. else
  169145. prev_block_row = buffer[block_row-1];
  169146. if (last_row && block_row == block_rows-1)
  169147. next_block_row = buffer_ptr;
  169148. else
  169149. next_block_row = buffer[block_row+1];
  169150. /* We fetch the surrounding DC values using a sliding-register approach.
  169151. * Initialize all nine here so as to do the right thing on narrow pics.
  169152. */
  169153. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  169154. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  169155. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  169156. output_col = 0;
  169157. last_block_column = compptr->width_in_blocks - 1;
  169158. for (block_num = 0; block_num <= last_block_column; block_num++) {
  169159. /* Fetch current DCT block into workspace so we can modify it. */
  169160. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  169161. /* Update DC values */
  169162. if (block_num < last_block_column) {
  169163. DC3 = (int) prev_block_row[1][0];
  169164. DC6 = (int) buffer_ptr[1][0];
  169165. DC9 = (int) next_block_row[1][0];
  169166. }
  169167. /* Compute coefficient estimates per K.8.
  169168. * An estimate is applied only if coefficient is still zero,
  169169. * and is not known to be fully accurate.
  169170. */
  169171. /* AC01 */
  169172. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  169173. num = 36 * Q00 * (DC4 - DC6);
  169174. if (num >= 0) {
  169175. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  169176. if (Al > 0 && pred >= (1<<Al))
  169177. pred = (1<<Al)-1;
  169178. } else {
  169179. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  169180. if (Al > 0 && pred >= (1<<Al))
  169181. pred = (1<<Al)-1;
  169182. pred = -pred;
  169183. }
  169184. workspace[1] = (JCOEF) pred;
  169185. }
  169186. /* AC10 */
  169187. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  169188. num = 36 * Q00 * (DC2 - DC8);
  169189. if (num >= 0) {
  169190. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  169191. if (Al > 0 && pred >= (1<<Al))
  169192. pred = (1<<Al)-1;
  169193. } else {
  169194. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169195. if (Al > 0 && pred >= (1<<Al))
  169196. pred = (1<<Al)-1;
  169197. pred = -pred;
  169198. }
  169199. workspace[8] = (JCOEF) pred;
  169200. }
  169201. /* AC20 */
  169202. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169203. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169204. if (num >= 0) {
  169205. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169206. if (Al > 0 && pred >= (1<<Al))
  169207. pred = (1<<Al)-1;
  169208. } else {
  169209. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169210. if (Al > 0 && pred >= (1<<Al))
  169211. pred = (1<<Al)-1;
  169212. pred = -pred;
  169213. }
  169214. workspace[16] = (JCOEF) pred;
  169215. }
  169216. /* AC11 */
  169217. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169218. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169219. if (num >= 0) {
  169220. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169221. if (Al > 0 && pred >= (1<<Al))
  169222. pred = (1<<Al)-1;
  169223. } else {
  169224. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169225. if (Al > 0 && pred >= (1<<Al))
  169226. pred = (1<<Al)-1;
  169227. pred = -pred;
  169228. }
  169229. workspace[9] = (JCOEF) pred;
  169230. }
  169231. /* AC02 */
  169232. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169233. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169234. if (num >= 0) {
  169235. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169236. if (Al > 0 && pred >= (1<<Al))
  169237. pred = (1<<Al)-1;
  169238. } else {
  169239. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169240. if (Al > 0 && pred >= (1<<Al))
  169241. pred = (1<<Al)-1;
  169242. pred = -pred;
  169243. }
  169244. workspace[2] = (JCOEF) pred;
  169245. }
  169246. /* OK, do the IDCT */
  169247. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169248. output_ptr, output_col);
  169249. /* Advance for next column */
  169250. DC1 = DC2; DC2 = DC3;
  169251. DC4 = DC5; DC5 = DC6;
  169252. DC7 = DC8; DC8 = DC9;
  169253. buffer_ptr++, prev_block_row++, next_block_row++;
  169254. output_col += compptr->DCT_scaled_size;
  169255. }
  169256. output_ptr += compptr->DCT_scaled_size;
  169257. }
  169258. }
  169259. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169260. return JPEG_ROW_COMPLETED;
  169261. return JPEG_SCAN_COMPLETED;
  169262. }
  169263. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169264. /*
  169265. * Initialize coefficient buffer controller.
  169266. */
  169267. GLOBAL(void)
  169268. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169269. {
  169270. my_coef_ptr3 coef;
  169271. coef = (my_coef_ptr3)
  169272. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169273. SIZEOF(my_coef_controller3));
  169274. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169275. coef->pub.start_input_pass = start_input_pass;
  169276. coef->pub.start_output_pass = start_output_pass;
  169277. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169278. coef->coef_bits_latch = NULL;
  169279. #endif
  169280. /* Create the coefficient buffer. */
  169281. if (need_full_buffer) {
  169282. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169283. /* Allocate a full-image virtual array for each component, */
  169284. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169285. /* Note we ask for a pre-zeroed array. */
  169286. int ci, access_rows;
  169287. jpeg_component_info *compptr;
  169288. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169289. ci++, compptr++) {
  169290. access_rows = compptr->v_samp_factor;
  169291. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169292. /* If block smoothing could be used, need a bigger window */
  169293. if (cinfo->progressive_mode)
  169294. access_rows *= 3;
  169295. #endif
  169296. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169297. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169298. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169299. (long) compptr->h_samp_factor),
  169300. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169301. (long) compptr->v_samp_factor),
  169302. (JDIMENSION) access_rows);
  169303. }
  169304. coef->pub.consume_data = consume_data;
  169305. coef->pub.decompress_data = decompress_data;
  169306. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169307. #else
  169308. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169309. #endif
  169310. } else {
  169311. /* We only need a single-MCU buffer. */
  169312. JBLOCKROW buffer;
  169313. int i;
  169314. buffer = (JBLOCKROW)
  169315. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169316. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169317. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169318. coef->MCU_buffer[i] = buffer + i;
  169319. }
  169320. coef->pub.consume_data = dummy_consume_data;
  169321. coef->pub.decompress_data = decompress_onepass;
  169322. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169323. }
  169324. }
  169325. /*** End of inlined file: jdcoefct.c ***/
  169326. #undef FIX
  169327. /*** Start of inlined file: jdcolor.c ***/
  169328. #define JPEG_INTERNALS
  169329. /* Private subobject */
  169330. typedef struct {
  169331. struct jpeg_color_deconverter pub; /* public fields */
  169332. /* Private state for YCC->RGB conversion */
  169333. int * Cr_r_tab; /* => table for Cr to R conversion */
  169334. int * Cb_b_tab; /* => table for Cb to B conversion */
  169335. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169336. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169337. } my_color_deconverter2;
  169338. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169339. /**************** YCbCr -> RGB conversion: most common case **************/
  169340. /*
  169341. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169342. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169343. * The conversion equations to be implemented are therefore
  169344. * R = Y + 1.40200 * Cr
  169345. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169346. * B = Y + 1.77200 * Cb
  169347. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169348. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169349. *
  169350. * To avoid floating-point arithmetic, we represent the fractional constants
  169351. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169352. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169353. * Notice that Y, being an integral input, does not contribute any fraction
  169354. * so it need not participate in the rounding.
  169355. *
  169356. * For even more speed, we avoid doing any multiplications in the inner loop
  169357. * by precalculating the constants times Cb and Cr for all possible values.
  169358. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169359. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169360. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169361. * colorspace anyway.
  169362. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169363. * values for the G calculation are left scaled up, since we must add them
  169364. * together before rounding.
  169365. */
  169366. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169367. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169368. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169369. /*
  169370. * Initialize tables for YCC->RGB colorspace conversion.
  169371. */
  169372. LOCAL(void)
  169373. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169374. {
  169375. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169376. int i;
  169377. INT32 x;
  169378. SHIFT_TEMPS
  169379. cconvert->Cr_r_tab = (int *)
  169380. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169381. (MAXJSAMPLE+1) * SIZEOF(int));
  169382. cconvert->Cb_b_tab = (int *)
  169383. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169384. (MAXJSAMPLE+1) * SIZEOF(int));
  169385. cconvert->Cr_g_tab = (INT32 *)
  169386. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169387. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169388. cconvert->Cb_g_tab = (INT32 *)
  169389. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169390. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169391. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169392. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169393. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169394. /* Cr=>R value is nearest int to 1.40200 * x */
  169395. cconvert->Cr_r_tab[i] = (int)
  169396. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169397. /* Cb=>B value is nearest int to 1.77200 * x */
  169398. cconvert->Cb_b_tab[i] = (int)
  169399. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169400. /* Cr=>G value is scaled-up -0.71414 * x */
  169401. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169402. /* Cb=>G value is scaled-up -0.34414 * x */
  169403. /* We also add in ONE_HALF so that need not do it in inner loop */
  169404. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169405. }
  169406. }
  169407. /*
  169408. * Convert some rows of samples to the output colorspace.
  169409. *
  169410. * Note that we change from noninterleaved, one-plane-per-component format
  169411. * to interleaved-pixel format. The output buffer is therefore three times
  169412. * as wide as the input buffer.
  169413. * A starting row offset is provided only for the input buffer. The caller
  169414. * can easily adjust the passed output_buf value to accommodate any row
  169415. * offset required on that side.
  169416. */
  169417. METHODDEF(void)
  169418. ycc_rgb_convert (j_decompress_ptr cinfo,
  169419. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169420. JSAMPARRAY output_buf, int num_rows)
  169421. {
  169422. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169423. register int y, cb, cr;
  169424. register JSAMPROW outptr;
  169425. register JSAMPROW inptr0, inptr1, inptr2;
  169426. register JDIMENSION col;
  169427. JDIMENSION num_cols = cinfo->output_width;
  169428. /* copy these pointers into registers if possible */
  169429. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169430. register int * Crrtab = cconvert->Cr_r_tab;
  169431. register int * Cbbtab = cconvert->Cb_b_tab;
  169432. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169433. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169434. SHIFT_TEMPS
  169435. while (--num_rows >= 0) {
  169436. inptr0 = input_buf[0][input_row];
  169437. inptr1 = input_buf[1][input_row];
  169438. inptr2 = input_buf[2][input_row];
  169439. input_row++;
  169440. outptr = *output_buf++;
  169441. for (col = 0; col < num_cols; col++) {
  169442. y = GETJSAMPLE(inptr0[col]);
  169443. cb = GETJSAMPLE(inptr1[col]);
  169444. cr = GETJSAMPLE(inptr2[col]);
  169445. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169446. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169447. outptr[RGB_GREEN] = range_limit[y +
  169448. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169449. SCALEBITS))];
  169450. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169451. outptr += RGB_PIXELSIZE;
  169452. }
  169453. }
  169454. }
  169455. /**************** Cases other than YCbCr -> RGB **************/
  169456. /*
  169457. * Color conversion for no colorspace change: just copy the data,
  169458. * converting from separate-planes to interleaved representation.
  169459. */
  169460. METHODDEF(void)
  169461. null_convert2 (j_decompress_ptr cinfo,
  169462. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169463. JSAMPARRAY output_buf, int num_rows)
  169464. {
  169465. register JSAMPROW inptr, outptr;
  169466. register JDIMENSION count;
  169467. register int num_components = cinfo->num_components;
  169468. JDIMENSION num_cols = cinfo->output_width;
  169469. int ci;
  169470. while (--num_rows >= 0) {
  169471. for (ci = 0; ci < num_components; ci++) {
  169472. inptr = input_buf[ci][input_row];
  169473. outptr = output_buf[0] + ci;
  169474. for (count = num_cols; count > 0; count--) {
  169475. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169476. outptr += num_components;
  169477. }
  169478. }
  169479. input_row++;
  169480. output_buf++;
  169481. }
  169482. }
  169483. /*
  169484. * Color conversion for grayscale: just copy the data.
  169485. * This also works for YCbCr -> grayscale conversion, in which
  169486. * we just copy the Y (luminance) component and ignore chrominance.
  169487. */
  169488. METHODDEF(void)
  169489. grayscale_convert2 (j_decompress_ptr cinfo,
  169490. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169491. JSAMPARRAY output_buf, int num_rows)
  169492. {
  169493. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169494. num_rows, cinfo->output_width);
  169495. }
  169496. /*
  169497. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169498. * This is provided to support applications that don't want to cope
  169499. * with grayscale as a separate case.
  169500. */
  169501. METHODDEF(void)
  169502. gray_rgb_convert (j_decompress_ptr cinfo,
  169503. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169504. JSAMPARRAY output_buf, int num_rows)
  169505. {
  169506. register JSAMPROW inptr, outptr;
  169507. register JDIMENSION col;
  169508. JDIMENSION num_cols = cinfo->output_width;
  169509. while (--num_rows >= 0) {
  169510. inptr = input_buf[0][input_row++];
  169511. outptr = *output_buf++;
  169512. for (col = 0; col < num_cols; col++) {
  169513. /* We can dispense with GETJSAMPLE() here */
  169514. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169515. outptr += RGB_PIXELSIZE;
  169516. }
  169517. }
  169518. }
  169519. /*
  169520. * Adobe-style YCCK->CMYK conversion.
  169521. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169522. * conversion as above, while passing K (black) unchanged.
  169523. * We assume build_ycc_rgb_table has been called.
  169524. */
  169525. METHODDEF(void)
  169526. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169527. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169528. JSAMPARRAY output_buf, int num_rows)
  169529. {
  169530. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169531. register int y, cb, cr;
  169532. register JSAMPROW outptr;
  169533. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169534. register JDIMENSION col;
  169535. JDIMENSION num_cols = cinfo->output_width;
  169536. /* copy these pointers into registers if possible */
  169537. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169538. register int * Crrtab = cconvert->Cr_r_tab;
  169539. register int * Cbbtab = cconvert->Cb_b_tab;
  169540. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169541. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169542. SHIFT_TEMPS
  169543. while (--num_rows >= 0) {
  169544. inptr0 = input_buf[0][input_row];
  169545. inptr1 = input_buf[1][input_row];
  169546. inptr2 = input_buf[2][input_row];
  169547. inptr3 = input_buf[3][input_row];
  169548. input_row++;
  169549. outptr = *output_buf++;
  169550. for (col = 0; col < num_cols; col++) {
  169551. y = GETJSAMPLE(inptr0[col]);
  169552. cb = GETJSAMPLE(inptr1[col]);
  169553. cr = GETJSAMPLE(inptr2[col]);
  169554. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169555. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169556. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169557. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169558. SCALEBITS)))];
  169559. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169560. /* K passes through unchanged */
  169561. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169562. outptr += 4;
  169563. }
  169564. }
  169565. }
  169566. /*
  169567. * Empty method for start_pass.
  169568. */
  169569. METHODDEF(void)
  169570. start_pass_dcolor (j_decompress_ptr)
  169571. {
  169572. /* no work needed */
  169573. }
  169574. /*
  169575. * Module initialization routine for output colorspace conversion.
  169576. */
  169577. GLOBAL(void)
  169578. jinit_color_deconverter (j_decompress_ptr cinfo)
  169579. {
  169580. my_cconvert_ptr2 cconvert;
  169581. int ci;
  169582. cconvert = (my_cconvert_ptr2)
  169583. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169584. SIZEOF(my_color_deconverter2));
  169585. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169586. cconvert->pub.start_pass = start_pass_dcolor;
  169587. /* Make sure num_components agrees with jpeg_color_space */
  169588. switch (cinfo->jpeg_color_space) {
  169589. case JCS_GRAYSCALE:
  169590. if (cinfo->num_components != 1)
  169591. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169592. break;
  169593. case JCS_RGB:
  169594. case JCS_YCbCr:
  169595. if (cinfo->num_components != 3)
  169596. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169597. break;
  169598. case JCS_CMYK:
  169599. case JCS_YCCK:
  169600. if (cinfo->num_components != 4)
  169601. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169602. break;
  169603. default: /* JCS_UNKNOWN can be anything */
  169604. if (cinfo->num_components < 1)
  169605. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169606. break;
  169607. }
  169608. /* Set out_color_components and conversion method based on requested space.
  169609. * Also clear the component_needed flags for any unused components,
  169610. * so that earlier pipeline stages can avoid useless computation.
  169611. */
  169612. switch (cinfo->out_color_space) {
  169613. case JCS_GRAYSCALE:
  169614. cinfo->out_color_components = 1;
  169615. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169616. cinfo->jpeg_color_space == JCS_YCbCr) {
  169617. cconvert->pub.color_convert = grayscale_convert2;
  169618. /* For color->grayscale conversion, only the Y (0) component is needed */
  169619. for (ci = 1; ci < cinfo->num_components; ci++)
  169620. cinfo->comp_info[ci].component_needed = FALSE;
  169621. } else
  169622. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169623. break;
  169624. case JCS_RGB:
  169625. cinfo->out_color_components = RGB_PIXELSIZE;
  169626. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169627. cconvert->pub.color_convert = ycc_rgb_convert;
  169628. build_ycc_rgb_table(cinfo);
  169629. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169630. cconvert->pub.color_convert = gray_rgb_convert;
  169631. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169632. cconvert->pub.color_convert = null_convert2;
  169633. } else
  169634. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169635. break;
  169636. case JCS_CMYK:
  169637. cinfo->out_color_components = 4;
  169638. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169639. cconvert->pub.color_convert = ycck_cmyk_convert;
  169640. build_ycc_rgb_table(cinfo);
  169641. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169642. cconvert->pub.color_convert = null_convert2;
  169643. } else
  169644. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169645. break;
  169646. default:
  169647. /* Permit null conversion to same output space */
  169648. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169649. cinfo->out_color_components = cinfo->num_components;
  169650. cconvert->pub.color_convert = null_convert2;
  169651. } else /* unsupported non-null conversion */
  169652. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169653. break;
  169654. }
  169655. if (cinfo->quantize_colors)
  169656. cinfo->output_components = 1; /* single colormapped output component */
  169657. else
  169658. cinfo->output_components = cinfo->out_color_components;
  169659. }
  169660. /*** End of inlined file: jdcolor.c ***/
  169661. #undef FIX
  169662. /*** Start of inlined file: jddctmgr.c ***/
  169663. #define JPEG_INTERNALS
  169664. /*
  169665. * The decompressor input side (jdinput.c) saves away the appropriate
  169666. * quantization table for each component at the start of the first scan
  169667. * involving that component. (This is necessary in order to correctly
  169668. * decode files that reuse Q-table slots.)
  169669. * When we are ready to make an output pass, the saved Q-table is converted
  169670. * to a multiplier table that will actually be used by the IDCT routine.
  169671. * The multiplier table contents are IDCT-method-dependent. To support
  169672. * application changes in IDCT method between scans, we can remake the
  169673. * multiplier tables if necessary.
  169674. * In buffered-image mode, the first output pass may occur before any data
  169675. * has been seen for some components, and thus before their Q-tables have
  169676. * been saved away. To handle this case, multiplier tables are preset
  169677. * to zeroes; the result of the IDCT will be a neutral gray level.
  169678. */
  169679. /* Private subobject for this module */
  169680. typedef struct {
  169681. struct jpeg_inverse_dct pub; /* public fields */
  169682. /* This array contains the IDCT method code that each multiplier table
  169683. * is currently set up for, or -1 if it's not yet set up.
  169684. * The actual multiplier tables are pointed to by dct_table in the
  169685. * per-component comp_info structures.
  169686. */
  169687. int cur_method[MAX_COMPONENTS];
  169688. } my_idct_controller;
  169689. typedef my_idct_controller * my_idct_ptr;
  169690. /* Allocated multiplier tables: big enough for any supported variant */
  169691. typedef union {
  169692. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169693. #ifdef DCT_IFAST_SUPPORTED
  169694. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169695. #endif
  169696. #ifdef DCT_FLOAT_SUPPORTED
  169697. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169698. #endif
  169699. } multiplier_table;
  169700. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169701. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169702. */
  169703. #ifdef DCT_ISLOW_SUPPORTED
  169704. #define PROVIDE_ISLOW_TABLES
  169705. #else
  169706. #ifdef IDCT_SCALING_SUPPORTED
  169707. #define PROVIDE_ISLOW_TABLES
  169708. #endif
  169709. #endif
  169710. /*
  169711. * Prepare for an output pass.
  169712. * Here we select the proper IDCT routine for each component and build
  169713. * a matching multiplier table.
  169714. */
  169715. METHODDEF(void)
  169716. start_pass (j_decompress_ptr cinfo)
  169717. {
  169718. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169719. int ci, i;
  169720. jpeg_component_info *compptr;
  169721. int method = 0;
  169722. inverse_DCT_method_ptr method_ptr = NULL;
  169723. JQUANT_TBL * qtbl;
  169724. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169725. ci++, compptr++) {
  169726. /* Select the proper IDCT routine for this component's scaling */
  169727. switch (compptr->DCT_scaled_size) {
  169728. #ifdef IDCT_SCALING_SUPPORTED
  169729. case 1:
  169730. method_ptr = jpeg_idct_1x1;
  169731. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169732. break;
  169733. case 2:
  169734. method_ptr = jpeg_idct_2x2;
  169735. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169736. break;
  169737. case 4:
  169738. method_ptr = jpeg_idct_4x4;
  169739. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169740. break;
  169741. #endif
  169742. case DCTSIZE:
  169743. switch (cinfo->dct_method) {
  169744. #ifdef DCT_ISLOW_SUPPORTED
  169745. case JDCT_ISLOW:
  169746. method_ptr = jpeg_idct_islow;
  169747. method = JDCT_ISLOW;
  169748. break;
  169749. #endif
  169750. #ifdef DCT_IFAST_SUPPORTED
  169751. case JDCT_IFAST:
  169752. method_ptr = jpeg_idct_ifast;
  169753. method = JDCT_IFAST;
  169754. break;
  169755. #endif
  169756. #ifdef DCT_FLOAT_SUPPORTED
  169757. case JDCT_FLOAT:
  169758. method_ptr = jpeg_idct_float;
  169759. method = JDCT_FLOAT;
  169760. break;
  169761. #endif
  169762. default:
  169763. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169764. break;
  169765. }
  169766. break;
  169767. default:
  169768. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169769. break;
  169770. }
  169771. idct->pub.inverse_DCT[ci] = method_ptr;
  169772. /* Create multiplier table from quant table.
  169773. * However, we can skip this if the component is uninteresting
  169774. * or if we already built the table. Also, if no quant table
  169775. * has yet been saved for the component, we leave the
  169776. * multiplier table all-zero; we'll be reading zeroes from the
  169777. * coefficient controller's buffer anyway.
  169778. */
  169779. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169780. continue;
  169781. qtbl = compptr->quant_table;
  169782. if (qtbl == NULL) /* happens if no data yet for component */
  169783. continue;
  169784. idct->cur_method[ci] = method;
  169785. switch (method) {
  169786. #ifdef PROVIDE_ISLOW_TABLES
  169787. case JDCT_ISLOW:
  169788. {
  169789. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169790. * coefficients, but are stored as ints to ensure access efficiency.
  169791. */
  169792. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169793. for (i = 0; i < DCTSIZE2; i++) {
  169794. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169795. }
  169796. }
  169797. break;
  169798. #endif
  169799. #ifdef DCT_IFAST_SUPPORTED
  169800. case JDCT_IFAST:
  169801. {
  169802. /* For AA&N IDCT method, multipliers are equal to quantization
  169803. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169804. * scalefactor[0] = 1
  169805. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169806. * For integer operation, the multiplier table is to be scaled by
  169807. * IFAST_SCALE_BITS.
  169808. */
  169809. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169810. #define CONST_BITS 14
  169811. static const INT16 aanscales[DCTSIZE2] = {
  169812. /* precomputed values scaled up by 14 bits */
  169813. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169814. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169815. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169816. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169817. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169818. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169819. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169820. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169821. };
  169822. SHIFT_TEMPS
  169823. for (i = 0; i < DCTSIZE2; i++) {
  169824. ifmtbl[i] = (IFAST_MULT_TYPE)
  169825. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169826. (INT32) aanscales[i]),
  169827. CONST_BITS-IFAST_SCALE_BITS);
  169828. }
  169829. }
  169830. break;
  169831. #endif
  169832. #ifdef DCT_FLOAT_SUPPORTED
  169833. case JDCT_FLOAT:
  169834. {
  169835. /* For float AA&N IDCT method, multipliers are equal to quantization
  169836. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169837. * scalefactor[0] = 1
  169838. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169839. */
  169840. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169841. int row, col;
  169842. static const double aanscalefactor[DCTSIZE] = {
  169843. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169844. 1.0, 0.785694958, 0.541196100, 0.275899379
  169845. };
  169846. i = 0;
  169847. for (row = 0; row < DCTSIZE; row++) {
  169848. for (col = 0; col < DCTSIZE; col++) {
  169849. fmtbl[i] = (FLOAT_MULT_TYPE)
  169850. ((double) qtbl->quantval[i] *
  169851. aanscalefactor[row] * aanscalefactor[col]);
  169852. i++;
  169853. }
  169854. }
  169855. }
  169856. break;
  169857. #endif
  169858. default:
  169859. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169860. break;
  169861. }
  169862. }
  169863. }
  169864. /*
  169865. * Initialize IDCT manager.
  169866. */
  169867. GLOBAL(void)
  169868. jinit_inverse_dct (j_decompress_ptr cinfo)
  169869. {
  169870. my_idct_ptr idct;
  169871. int ci;
  169872. jpeg_component_info *compptr;
  169873. idct = (my_idct_ptr)
  169874. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169875. SIZEOF(my_idct_controller));
  169876. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169877. idct->pub.start_pass = start_pass;
  169878. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169879. ci++, compptr++) {
  169880. /* Allocate and pre-zero a multiplier table for each component */
  169881. compptr->dct_table =
  169882. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169883. SIZEOF(multiplier_table));
  169884. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169885. /* Mark multiplier table not yet set up for any method */
  169886. idct->cur_method[ci] = -1;
  169887. }
  169888. }
  169889. /*** End of inlined file: jddctmgr.c ***/
  169890. #undef CONST_BITS
  169891. #undef ASSIGN_STATE
  169892. /*** Start of inlined file: jdhuff.c ***/
  169893. #define JPEG_INTERNALS
  169894. /*** Start of inlined file: jdhuff.h ***/
  169895. /* Short forms of external names for systems with brain-damaged linkers. */
  169896. #ifndef __jdhuff_h__
  169897. #define __jdhuff_h__
  169898. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169899. #define jpeg_make_d_derived_tbl jMkDDerived
  169900. #define jpeg_fill_bit_buffer jFilBitBuf
  169901. #define jpeg_huff_decode jHufDecode
  169902. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169903. /* Derived data constructed for each Huffman table */
  169904. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169905. typedef struct {
  169906. /* Basic tables: (element [0] of each array is unused) */
  169907. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169908. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169909. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169910. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169911. * the smallest code of length k; so given a code of length k, the
  169912. * corresponding symbol is huffval[code + valoffset[k]]
  169913. */
  169914. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169915. JHUFF_TBL *pub;
  169916. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169917. * the input data stream. If the next Huffman code is no more
  169918. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169919. * the corresponding symbol directly from these tables.
  169920. */
  169921. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169922. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169923. } d_derived_tbl;
  169924. /* Expand a Huffman table definition into the derived format */
  169925. EXTERN(void) jpeg_make_d_derived_tbl
  169926. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169927. d_derived_tbl ** pdtbl));
  169928. /*
  169929. * Fetching the next N bits from the input stream is a time-critical operation
  169930. * for the Huffman decoders. We implement it with a combination of inline
  169931. * macros and out-of-line subroutines. Note that N (the number of bits
  169932. * demanded at one time) never exceeds 15 for JPEG use.
  169933. *
  169934. * We read source bytes into get_buffer and dole out bits as needed.
  169935. * If get_buffer already contains enough bits, they are fetched in-line
  169936. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169937. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169938. * as full as possible (not just to the number of bits needed; this
  169939. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169940. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169941. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169942. * at least the requested number of bits --- dummy zeroes are inserted if
  169943. * necessary.
  169944. */
  169945. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169946. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169947. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169948. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169949. * appropriately should be a win. Unfortunately we can't define the size
  169950. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169951. * because not all machines measure sizeof in 8-bit bytes.
  169952. */
  169953. typedef struct { /* Bitreading state saved across MCUs */
  169954. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169955. int bits_left; /* # of unused bits in it */
  169956. } bitread_perm_state;
  169957. typedef struct { /* Bitreading working state within an MCU */
  169958. /* Current data source location */
  169959. /* We need a copy, rather than munging the original, in case of suspension */
  169960. const JOCTET * next_input_byte; /* => next byte to read from source */
  169961. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169962. /* Bit input buffer --- note these values are kept in register variables,
  169963. * not in this struct, inside the inner loops.
  169964. */
  169965. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169966. int bits_left; /* # of unused bits in it */
  169967. /* Pointer needed by jpeg_fill_bit_buffer. */
  169968. j_decompress_ptr cinfo; /* back link to decompress master record */
  169969. } bitread_working_state;
  169970. /* Macros to declare and load/save bitread local variables. */
  169971. #define BITREAD_STATE_VARS \
  169972. register bit_buf_type get_buffer; \
  169973. register int bits_left; \
  169974. bitread_working_state br_state
  169975. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169976. br_state.cinfo = cinfop; \
  169977. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169978. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169979. get_buffer = permstate.get_buffer; \
  169980. bits_left = permstate.bits_left;
  169981. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169982. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169983. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169984. permstate.get_buffer = get_buffer; \
  169985. permstate.bits_left = bits_left
  169986. /*
  169987. * These macros provide the in-line portion of bit fetching.
  169988. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169989. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169990. * The variables get_buffer and bits_left are assumed to be locals,
  169991. * but the state struct might not be (jpeg_huff_decode needs this).
  169992. * CHECK_BIT_BUFFER(state,n,action);
  169993. * Ensure there are N bits in get_buffer; if suspend, take action.
  169994. * val = GET_BITS(n);
  169995. * Fetch next N bits.
  169996. * val = PEEK_BITS(n);
  169997. * Fetch next N bits without removing them from the buffer.
  169998. * DROP_BITS(n);
  169999. * Discard next N bits.
  170000. * The value N should be a simple variable, not an expression, because it
  170001. * is evaluated multiple times.
  170002. */
  170003. #define CHECK_BIT_BUFFER(state,nbits,action) \
  170004. { if (bits_left < (nbits)) { \
  170005. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  170006. { action; } \
  170007. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  170008. #define GET_BITS(nbits) \
  170009. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  170010. #define PEEK_BITS(nbits) \
  170011. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  170012. #define DROP_BITS(nbits) \
  170013. (bits_left -= (nbits))
  170014. /* Load up the bit buffer to a depth of at least nbits */
  170015. EXTERN(boolean) jpeg_fill_bit_buffer
  170016. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170017. register int bits_left, int nbits));
  170018. /*
  170019. * Code for extracting next Huffman-coded symbol from input bit stream.
  170020. * Again, this is time-critical and we make the main paths be macros.
  170021. *
  170022. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  170023. * without looping. Usually, more than 95% of the Huffman codes will be 8
  170024. * or fewer bits long. The few overlength codes are handled with a loop,
  170025. * which need not be inline code.
  170026. *
  170027. * Notes about the HUFF_DECODE macro:
  170028. * 1. Near the end of the data segment, we may fail to get enough bits
  170029. * for a lookahead. In that case, we do it the hard way.
  170030. * 2. If the lookahead table contains no entry, the next code must be
  170031. * more than HUFF_LOOKAHEAD bits long.
  170032. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  170033. */
  170034. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  170035. { register int nb, look; \
  170036. if (bits_left < HUFF_LOOKAHEAD) { \
  170037. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  170038. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170039. if (bits_left < HUFF_LOOKAHEAD) { \
  170040. nb = 1; goto slowlabel; \
  170041. } \
  170042. } \
  170043. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  170044. if ((nb = htbl->look_nbits[look]) != 0) { \
  170045. DROP_BITS(nb); \
  170046. result = htbl->look_sym[look]; \
  170047. } else { \
  170048. nb = HUFF_LOOKAHEAD+1; \
  170049. slowlabel: \
  170050. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  170051. { failaction; } \
  170052. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170053. } \
  170054. }
  170055. /* Out-of-line case for Huffman code fetching */
  170056. EXTERN(int) jpeg_huff_decode
  170057. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170058. register int bits_left, d_derived_tbl * htbl, int min_bits));
  170059. #endif
  170060. /*** End of inlined file: jdhuff.h ***/
  170061. /* Declarations shared with jdphuff.c */
  170062. /*
  170063. * Expanded entropy decoder object for Huffman decoding.
  170064. *
  170065. * The savable_state subrecord contains fields that change within an MCU,
  170066. * but must not be updated permanently until we complete the MCU.
  170067. */
  170068. typedef struct {
  170069. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  170070. } savable_state2;
  170071. /* This macro is to work around compilers with missing or broken
  170072. * structure assignment. You'll need to fix this code if you have
  170073. * such a compiler and you change MAX_COMPS_IN_SCAN.
  170074. */
  170075. #ifndef NO_STRUCT_ASSIGN
  170076. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  170077. #else
  170078. #if MAX_COMPS_IN_SCAN == 4
  170079. #define ASSIGN_STATE(dest,src) \
  170080. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  170081. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  170082. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  170083. (dest).last_dc_val[3] = (src).last_dc_val[3])
  170084. #endif
  170085. #endif
  170086. typedef struct {
  170087. struct jpeg_entropy_decoder pub; /* public fields */
  170088. /* These fields are loaded into local variables at start of each MCU.
  170089. * In case of suspension, we exit WITHOUT updating them.
  170090. */
  170091. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  170092. savable_state2 saved; /* Other state at start of MCU */
  170093. /* These fields are NOT loaded into local working state. */
  170094. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  170095. /* Pointers to derived tables (these workspaces have image lifespan) */
  170096. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  170097. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  170098. /* Precalculated info set up by start_pass for use in decode_mcu: */
  170099. /* Pointers to derived tables to be used for each block within an MCU */
  170100. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170101. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170102. /* Whether we care about the DC and AC coefficient values for each block */
  170103. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  170104. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  170105. } huff_entropy_decoder2;
  170106. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  170107. /*
  170108. * Initialize for a Huffman-compressed scan.
  170109. */
  170110. METHODDEF(void)
  170111. start_pass_huff_decoder (j_decompress_ptr cinfo)
  170112. {
  170113. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170114. int ci, blkn, dctbl, actbl;
  170115. jpeg_component_info * compptr;
  170116. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  170117. * This ought to be an error condition, but we make it a warning because
  170118. * there are some baseline files out there with all zeroes in these bytes.
  170119. */
  170120. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  170121. cinfo->Ah != 0 || cinfo->Al != 0)
  170122. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  170123. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170124. compptr = cinfo->cur_comp_info[ci];
  170125. dctbl = compptr->dc_tbl_no;
  170126. actbl = compptr->ac_tbl_no;
  170127. /* Compute derived values for Huffman tables */
  170128. /* We may do this more than once for a table, but it's not expensive */
  170129. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  170130. & entropy->dc_derived_tbls[dctbl]);
  170131. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  170132. & entropy->ac_derived_tbls[actbl]);
  170133. /* Initialize DC predictions to 0 */
  170134. entropy->saved.last_dc_val[ci] = 0;
  170135. }
  170136. /* Precalculate decoding info for each block in an MCU of this scan */
  170137. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170138. ci = cinfo->MCU_membership[blkn];
  170139. compptr = cinfo->cur_comp_info[ci];
  170140. /* Precalculate which table to use for each block */
  170141. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  170142. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  170143. /* Decide whether we really care about the coefficient values */
  170144. if (compptr->component_needed) {
  170145. entropy->dc_needed[blkn] = TRUE;
  170146. /* we don't need the ACs if producing a 1/8th-size image */
  170147. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  170148. } else {
  170149. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  170150. }
  170151. }
  170152. /* Initialize bitread state variables */
  170153. entropy->bitstate.bits_left = 0;
  170154. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170155. entropy->pub.insufficient_data = FALSE;
  170156. /* Initialize restart counter */
  170157. entropy->restarts_to_go = cinfo->restart_interval;
  170158. }
  170159. /*
  170160. * Compute the derived values for a Huffman table.
  170161. * This routine also performs some validation checks on the table.
  170162. *
  170163. * Note this is also used by jdphuff.c.
  170164. */
  170165. GLOBAL(void)
  170166. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  170167. d_derived_tbl ** pdtbl)
  170168. {
  170169. JHUFF_TBL *htbl;
  170170. d_derived_tbl *dtbl;
  170171. int p, i, l, si, numsymbols;
  170172. int lookbits, ctr;
  170173. char huffsize[257];
  170174. unsigned int huffcode[257];
  170175. unsigned int code;
  170176. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170177. * paralleling the order of the symbols themselves in htbl->huffval[].
  170178. */
  170179. /* Find the input Huffman table */
  170180. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  170181. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170182. htbl =
  170183. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  170184. if (htbl == NULL)
  170185. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170186. /* Allocate a workspace if we haven't already done so. */
  170187. if (*pdtbl == NULL)
  170188. *pdtbl = (d_derived_tbl *)
  170189. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170190. SIZEOF(d_derived_tbl));
  170191. dtbl = *pdtbl;
  170192. dtbl->pub = htbl; /* fill in back link */
  170193. /* Figure C.1: make table of Huffman code length for each symbol */
  170194. p = 0;
  170195. for (l = 1; l <= 16; l++) {
  170196. i = (int) htbl->bits[l];
  170197. if (i < 0 || p + i > 256) /* protect against table overrun */
  170198. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170199. while (i--)
  170200. huffsize[p++] = (char) l;
  170201. }
  170202. huffsize[p] = 0;
  170203. numsymbols = p;
  170204. /* Figure C.2: generate the codes themselves */
  170205. /* We also validate that the counts represent a legal Huffman code tree. */
  170206. code = 0;
  170207. si = huffsize[0];
  170208. p = 0;
  170209. while (huffsize[p]) {
  170210. while (((int) huffsize[p]) == si) {
  170211. huffcode[p++] = code;
  170212. code++;
  170213. }
  170214. /* code is now 1 more than the last code used for codelength si; but
  170215. * it must still fit in si bits, since no code is allowed to be all ones.
  170216. */
  170217. if (((INT32) code) >= (((INT32) 1) << si))
  170218. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170219. code <<= 1;
  170220. si++;
  170221. }
  170222. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170223. p = 0;
  170224. for (l = 1; l <= 16; l++) {
  170225. if (htbl->bits[l]) {
  170226. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170227. * minus the minimum code of length l
  170228. */
  170229. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170230. p += htbl->bits[l];
  170231. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170232. } else {
  170233. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170234. }
  170235. }
  170236. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170237. /* Compute lookahead tables to speed up decoding.
  170238. * First we set all the table entries to 0, indicating "too long";
  170239. * then we iterate through the Huffman codes that are short enough and
  170240. * fill in all the entries that correspond to bit sequences starting
  170241. * with that code.
  170242. */
  170243. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170244. p = 0;
  170245. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170246. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170247. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170248. /* Generate left-justified code followed by all possible bit sequences */
  170249. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170250. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170251. dtbl->look_nbits[lookbits] = l;
  170252. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170253. lookbits++;
  170254. }
  170255. }
  170256. }
  170257. /* Validate symbols as being reasonable.
  170258. * For AC tables, we make no check, but accept all byte values 0..255.
  170259. * For DC tables, we require the symbols to be in range 0..15.
  170260. * (Tighter bounds could be applied depending on the data depth and mode,
  170261. * but this is sufficient to ensure safe decoding.)
  170262. */
  170263. if (isDC) {
  170264. for (i = 0; i < numsymbols; i++) {
  170265. int sym = htbl->huffval[i];
  170266. if (sym < 0 || sym > 15)
  170267. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170268. }
  170269. }
  170270. }
  170271. /*
  170272. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170273. * See jdhuff.h for info about usage.
  170274. * Note: current values of get_buffer and bits_left are passed as parameters,
  170275. * but are returned in the corresponding fields of the state struct.
  170276. *
  170277. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170278. * of get_buffer to be used. (On machines with wider words, an even larger
  170279. * buffer could be used.) However, on some machines 32-bit shifts are
  170280. * quite slow and take time proportional to the number of places shifted.
  170281. * (This is true with most PC compilers, for instance.) In this case it may
  170282. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170283. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170284. */
  170285. #ifdef SLOW_SHIFT_32
  170286. #define MIN_GET_BITS 15 /* minimum allowable value */
  170287. #else
  170288. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170289. #endif
  170290. GLOBAL(boolean)
  170291. jpeg_fill_bit_buffer (bitread_working_state * state,
  170292. register bit_buf_type get_buffer, register int bits_left,
  170293. int nbits)
  170294. /* Load up the bit buffer to a depth of at least nbits */
  170295. {
  170296. /* Copy heavily used state fields into locals (hopefully registers) */
  170297. register const JOCTET * next_input_byte = state->next_input_byte;
  170298. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170299. j_decompress_ptr cinfo = state->cinfo;
  170300. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170301. /* (It is assumed that no request will be for more than that many bits.) */
  170302. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170303. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170304. while (bits_left < MIN_GET_BITS) {
  170305. register int c;
  170306. /* Attempt to read a byte */
  170307. if (bytes_in_buffer == 0) {
  170308. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170309. return FALSE;
  170310. next_input_byte = cinfo->src->next_input_byte;
  170311. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170312. }
  170313. bytes_in_buffer--;
  170314. c = GETJOCTET(*next_input_byte++);
  170315. /* If it's 0xFF, check and discard stuffed zero byte */
  170316. if (c == 0xFF) {
  170317. /* Loop here to discard any padding FF's on terminating marker,
  170318. * so that we can save a valid unread_marker value. NOTE: we will
  170319. * accept multiple FF's followed by a 0 as meaning a single FF data
  170320. * byte. This data pattern is not valid according to the standard.
  170321. */
  170322. do {
  170323. if (bytes_in_buffer == 0) {
  170324. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170325. return FALSE;
  170326. next_input_byte = cinfo->src->next_input_byte;
  170327. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170328. }
  170329. bytes_in_buffer--;
  170330. c = GETJOCTET(*next_input_byte++);
  170331. } while (c == 0xFF);
  170332. if (c == 0) {
  170333. /* Found FF/00, which represents an FF data byte */
  170334. c = 0xFF;
  170335. } else {
  170336. /* Oops, it's actually a marker indicating end of compressed data.
  170337. * Save the marker code for later use.
  170338. * Fine point: it might appear that we should save the marker into
  170339. * bitread working state, not straight into permanent state. But
  170340. * once we have hit a marker, we cannot need to suspend within the
  170341. * current MCU, because we will read no more bytes from the data
  170342. * source. So it is OK to update permanent state right away.
  170343. */
  170344. cinfo->unread_marker = c;
  170345. /* See if we need to insert some fake zero bits. */
  170346. goto no_more_bytes;
  170347. }
  170348. }
  170349. /* OK, load c into get_buffer */
  170350. get_buffer = (get_buffer << 8) | c;
  170351. bits_left += 8;
  170352. } /* end while */
  170353. } else {
  170354. no_more_bytes:
  170355. /* We get here if we've read the marker that terminates the compressed
  170356. * data segment. There should be enough bits in the buffer register
  170357. * to satisfy the request; if so, no problem.
  170358. */
  170359. if (nbits > bits_left) {
  170360. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170361. * the data stream, so that we can produce some kind of image.
  170362. * We use a nonvolatile flag to ensure that only one warning message
  170363. * appears per data segment.
  170364. */
  170365. if (! cinfo->entropy->insufficient_data) {
  170366. WARNMS(cinfo, JWRN_HIT_MARKER);
  170367. cinfo->entropy->insufficient_data = TRUE;
  170368. }
  170369. /* Fill the buffer with zero bits */
  170370. get_buffer <<= MIN_GET_BITS - bits_left;
  170371. bits_left = MIN_GET_BITS;
  170372. }
  170373. }
  170374. /* Unload the local registers */
  170375. state->next_input_byte = next_input_byte;
  170376. state->bytes_in_buffer = bytes_in_buffer;
  170377. state->get_buffer = get_buffer;
  170378. state->bits_left = bits_left;
  170379. return TRUE;
  170380. }
  170381. /*
  170382. * Out-of-line code for Huffman code decoding.
  170383. * See jdhuff.h for info about usage.
  170384. */
  170385. GLOBAL(int)
  170386. jpeg_huff_decode (bitread_working_state * state,
  170387. register bit_buf_type get_buffer, register int bits_left,
  170388. d_derived_tbl * htbl, int min_bits)
  170389. {
  170390. register int l = min_bits;
  170391. register INT32 code;
  170392. /* HUFF_DECODE has determined that the code is at least min_bits */
  170393. /* bits long, so fetch that many bits in one swoop. */
  170394. CHECK_BIT_BUFFER(*state, l, return -1);
  170395. code = GET_BITS(l);
  170396. /* Collect the rest of the Huffman code one bit at a time. */
  170397. /* This is per Figure F.16 in the JPEG spec. */
  170398. while (code > htbl->maxcode[l]) {
  170399. code <<= 1;
  170400. CHECK_BIT_BUFFER(*state, 1, return -1);
  170401. code |= GET_BITS(1);
  170402. l++;
  170403. }
  170404. /* Unload the local registers */
  170405. state->get_buffer = get_buffer;
  170406. state->bits_left = bits_left;
  170407. /* With garbage input we may reach the sentinel value l = 17. */
  170408. if (l > 16) {
  170409. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170410. return 0; /* fake a zero as the safest result */
  170411. }
  170412. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170413. }
  170414. /*
  170415. * Check for a restart marker & resynchronize decoder.
  170416. * Returns FALSE if must suspend.
  170417. */
  170418. LOCAL(boolean)
  170419. process_restart (j_decompress_ptr cinfo)
  170420. {
  170421. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170422. int ci;
  170423. /* Throw away any unused bits remaining in bit buffer; */
  170424. /* include any full bytes in next_marker's count of discarded bytes */
  170425. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170426. entropy->bitstate.bits_left = 0;
  170427. /* Advance past the RSTn marker */
  170428. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170429. return FALSE;
  170430. /* Re-initialize DC predictions to 0 */
  170431. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170432. entropy->saved.last_dc_val[ci] = 0;
  170433. /* Reset restart counter */
  170434. entropy->restarts_to_go = cinfo->restart_interval;
  170435. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170436. * against a marker. In that case we will end up treating the next data
  170437. * segment as empty, and we can avoid producing bogus output pixels by
  170438. * leaving the flag set.
  170439. */
  170440. if (cinfo->unread_marker == 0)
  170441. entropy->pub.insufficient_data = FALSE;
  170442. return TRUE;
  170443. }
  170444. /*
  170445. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170446. * The coefficients are reordered from zigzag order into natural array order,
  170447. * but are not dequantized.
  170448. *
  170449. * The i'th block of the MCU is stored into the block pointed to by
  170450. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170451. * (Wholesale zeroing is usually a little faster than retail...)
  170452. *
  170453. * Returns FALSE if data source requested suspension. In that case no
  170454. * changes have been made to permanent state. (Exception: some output
  170455. * coefficients may already have been assigned. This is harmless for
  170456. * this module, since we'll just re-assign them on the next call.)
  170457. */
  170458. METHODDEF(boolean)
  170459. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170460. {
  170461. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170462. int blkn;
  170463. BITREAD_STATE_VARS;
  170464. savable_state2 state;
  170465. /* Process restart marker if needed; may have to suspend */
  170466. if (cinfo->restart_interval) {
  170467. if (entropy->restarts_to_go == 0)
  170468. if (! process_restart(cinfo))
  170469. return FALSE;
  170470. }
  170471. /* If we've run out of data, just leave the MCU set to zeroes.
  170472. * This way, we return uniform gray for the remainder of the segment.
  170473. */
  170474. if (! entropy->pub.insufficient_data) {
  170475. /* Load up working state */
  170476. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170477. ASSIGN_STATE(state, entropy->saved);
  170478. /* Outer loop handles each block in the MCU */
  170479. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170480. JBLOCKROW block = MCU_data[blkn];
  170481. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170482. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170483. register int s, k, r;
  170484. /* Decode a single block's worth of coefficients */
  170485. /* Section F.2.2.1: decode the DC coefficient difference */
  170486. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170487. if (s) {
  170488. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170489. r = GET_BITS(s);
  170490. s = HUFF_EXTEND(r, s);
  170491. }
  170492. if (entropy->dc_needed[blkn]) {
  170493. /* Convert DC difference to actual value, update last_dc_val */
  170494. int ci = cinfo->MCU_membership[blkn];
  170495. s += state.last_dc_val[ci];
  170496. state.last_dc_val[ci] = s;
  170497. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170498. (*block)[0] = (JCOEF) s;
  170499. }
  170500. if (entropy->ac_needed[blkn]) {
  170501. /* Section F.2.2.2: decode the AC coefficients */
  170502. /* Since zeroes are skipped, output area must be cleared beforehand */
  170503. for (k = 1; k < DCTSIZE2; k++) {
  170504. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170505. r = s >> 4;
  170506. s &= 15;
  170507. if (s) {
  170508. k += r;
  170509. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170510. r = GET_BITS(s);
  170511. s = HUFF_EXTEND(r, s);
  170512. /* Output coefficient in natural (dezigzagged) order.
  170513. * Note: the extra entries in jpeg_natural_order[] will save us
  170514. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170515. */
  170516. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170517. } else {
  170518. if (r != 15)
  170519. break;
  170520. k += 15;
  170521. }
  170522. }
  170523. } else {
  170524. /* Section F.2.2.2: decode the AC coefficients */
  170525. /* In this path we just discard the values */
  170526. for (k = 1; k < DCTSIZE2; k++) {
  170527. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170528. r = s >> 4;
  170529. s &= 15;
  170530. if (s) {
  170531. k += r;
  170532. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170533. DROP_BITS(s);
  170534. } else {
  170535. if (r != 15)
  170536. break;
  170537. k += 15;
  170538. }
  170539. }
  170540. }
  170541. }
  170542. /* Completed MCU, so update state */
  170543. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170544. ASSIGN_STATE(entropy->saved, state);
  170545. }
  170546. /* Account for restart interval (no-op if not using restarts) */
  170547. entropy->restarts_to_go--;
  170548. return TRUE;
  170549. }
  170550. /*
  170551. * Module initialization routine for Huffman entropy decoding.
  170552. */
  170553. GLOBAL(void)
  170554. jinit_huff_decoder (j_decompress_ptr cinfo)
  170555. {
  170556. huff_entropy_ptr2 entropy;
  170557. int i;
  170558. entropy = (huff_entropy_ptr2)
  170559. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170560. SIZEOF(huff_entropy_decoder2));
  170561. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170562. entropy->pub.start_pass = start_pass_huff_decoder;
  170563. entropy->pub.decode_mcu = decode_mcu;
  170564. /* Mark tables unallocated */
  170565. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170566. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170567. }
  170568. }
  170569. /*** End of inlined file: jdhuff.c ***/
  170570. /*** Start of inlined file: jdinput.c ***/
  170571. #define JPEG_INTERNALS
  170572. /* Private state */
  170573. typedef struct {
  170574. struct jpeg_input_controller pub; /* public fields */
  170575. boolean inheaders; /* TRUE until first SOS is reached */
  170576. } my_input_controller;
  170577. typedef my_input_controller * my_inputctl_ptr;
  170578. /* Forward declarations */
  170579. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170580. /*
  170581. * Routines to calculate various quantities related to the size of the image.
  170582. */
  170583. LOCAL(void)
  170584. initial_setup2 (j_decompress_ptr cinfo)
  170585. /* Called once, when first SOS marker is reached */
  170586. {
  170587. int ci;
  170588. jpeg_component_info *compptr;
  170589. /* Make sure image isn't bigger than I can handle */
  170590. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170591. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170592. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170593. /* For now, precision must match compiled-in value... */
  170594. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170595. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170596. /* Check that number of components won't exceed internal array sizes */
  170597. if (cinfo->num_components > MAX_COMPONENTS)
  170598. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170599. MAX_COMPONENTS);
  170600. /* Compute maximum sampling factors; check factor validity */
  170601. cinfo->max_h_samp_factor = 1;
  170602. cinfo->max_v_samp_factor = 1;
  170603. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170604. ci++, compptr++) {
  170605. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170606. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170607. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170608. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170609. compptr->h_samp_factor);
  170610. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170611. compptr->v_samp_factor);
  170612. }
  170613. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170614. * In the full decompressor, this will be overridden by jdmaster.c;
  170615. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170616. */
  170617. cinfo->min_DCT_scaled_size = DCTSIZE;
  170618. /* Compute dimensions of components */
  170619. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170620. ci++, compptr++) {
  170621. compptr->DCT_scaled_size = DCTSIZE;
  170622. /* Size in DCT blocks */
  170623. compptr->width_in_blocks = (JDIMENSION)
  170624. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170625. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170626. compptr->height_in_blocks = (JDIMENSION)
  170627. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170628. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170629. /* downsampled_width and downsampled_height will also be overridden by
  170630. * jdmaster.c if we are doing full decompression. The transcoder library
  170631. * doesn't use these values, but the calling application might.
  170632. */
  170633. /* Size in samples */
  170634. compptr->downsampled_width = (JDIMENSION)
  170635. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170636. (long) cinfo->max_h_samp_factor);
  170637. compptr->downsampled_height = (JDIMENSION)
  170638. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170639. (long) cinfo->max_v_samp_factor);
  170640. /* Mark component needed, until color conversion says otherwise */
  170641. compptr->component_needed = TRUE;
  170642. /* Mark no quantization table yet saved for component */
  170643. compptr->quant_table = NULL;
  170644. }
  170645. /* Compute number of fully interleaved MCU rows. */
  170646. cinfo->total_iMCU_rows = (JDIMENSION)
  170647. jdiv_round_up((long) cinfo->image_height,
  170648. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170649. /* Decide whether file contains multiple scans */
  170650. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170651. cinfo->inputctl->has_multiple_scans = TRUE;
  170652. else
  170653. cinfo->inputctl->has_multiple_scans = FALSE;
  170654. }
  170655. LOCAL(void)
  170656. per_scan_setup2 (j_decompress_ptr cinfo)
  170657. /* Do computations that are needed before processing a JPEG scan */
  170658. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170659. {
  170660. int ci, mcublks, tmp;
  170661. jpeg_component_info *compptr;
  170662. if (cinfo->comps_in_scan == 1) {
  170663. /* Noninterleaved (single-component) scan */
  170664. compptr = cinfo->cur_comp_info[0];
  170665. /* Overall image size in MCUs */
  170666. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170667. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170668. /* For noninterleaved scan, always one block per MCU */
  170669. compptr->MCU_width = 1;
  170670. compptr->MCU_height = 1;
  170671. compptr->MCU_blocks = 1;
  170672. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170673. compptr->last_col_width = 1;
  170674. /* For noninterleaved scans, it is convenient to define last_row_height
  170675. * as the number of block rows present in the last iMCU row.
  170676. */
  170677. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170678. if (tmp == 0) tmp = compptr->v_samp_factor;
  170679. compptr->last_row_height = tmp;
  170680. /* Prepare array describing MCU composition */
  170681. cinfo->blocks_in_MCU = 1;
  170682. cinfo->MCU_membership[0] = 0;
  170683. } else {
  170684. /* Interleaved (multi-component) scan */
  170685. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170686. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170687. MAX_COMPS_IN_SCAN);
  170688. /* Overall image size in MCUs */
  170689. cinfo->MCUs_per_row = (JDIMENSION)
  170690. jdiv_round_up((long) cinfo->image_width,
  170691. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170692. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170693. jdiv_round_up((long) cinfo->image_height,
  170694. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170695. cinfo->blocks_in_MCU = 0;
  170696. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170697. compptr = cinfo->cur_comp_info[ci];
  170698. /* Sampling factors give # of blocks of component in each MCU */
  170699. compptr->MCU_width = compptr->h_samp_factor;
  170700. compptr->MCU_height = compptr->v_samp_factor;
  170701. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170702. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170703. /* Figure number of non-dummy blocks in last MCU column & row */
  170704. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170705. if (tmp == 0) tmp = compptr->MCU_width;
  170706. compptr->last_col_width = tmp;
  170707. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170708. if (tmp == 0) tmp = compptr->MCU_height;
  170709. compptr->last_row_height = tmp;
  170710. /* Prepare array describing MCU composition */
  170711. mcublks = compptr->MCU_blocks;
  170712. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170713. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170714. while (mcublks-- > 0) {
  170715. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170716. }
  170717. }
  170718. }
  170719. }
  170720. /*
  170721. * Save away a copy of the Q-table referenced by each component present
  170722. * in the current scan, unless already saved during a prior scan.
  170723. *
  170724. * In a multiple-scan JPEG file, the encoder could assign different components
  170725. * the same Q-table slot number, but change table definitions between scans
  170726. * so that each component uses a different Q-table. (The IJG encoder is not
  170727. * currently capable of doing this, but other encoders might.) Since we want
  170728. * to be able to dequantize all the components at the end of the file, this
  170729. * means that we have to save away the table actually used for each component.
  170730. * We do this by copying the table at the start of the first scan containing
  170731. * the component.
  170732. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170733. * slot between scans of a component using that slot. If the encoder does so
  170734. * anyway, this decoder will simply use the Q-table values that were current
  170735. * at the start of the first scan for the component.
  170736. *
  170737. * The decompressor output side looks only at the saved quant tables,
  170738. * not at the current Q-table slots.
  170739. */
  170740. LOCAL(void)
  170741. latch_quant_tables (j_decompress_ptr cinfo)
  170742. {
  170743. int ci, qtblno;
  170744. jpeg_component_info *compptr;
  170745. JQUANT_TBL * qtbl;
  170746. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170747. compptr = cinfo->cur_comp_info[ci];
  170748. /* No work if we already saved Q-table for this component */
  170749. if (compptr->quant_table != NULL)
  170750. continue;
  170751. /* Make sure specified quantization table is present */
  170752. qtblno = compptr->quant_tbl_no;
  170753. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170754. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170755. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170756. /* OK, save away the quantization table */
  170757. qtbl = (JQUANT_TBL *)
  170758. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170759. SIZEOF(JQUANT_TBL));
  170760. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170761. compptr->quant_table = qtbl;
  170762. }
  170763. }
  170764. /*
  170765. * Initialize the input modules to read a scan of compressed data.
  170766. * The first call to this is done by jdmaster.c after initializing
  170767. * the entire decompressor (during jpeg_start_decompress).
  170768. * Subsequent calls come from consume_markers, below.
  170769. */
  170770. METHODDEF(void)
  170771. start_input_pass2 (j_decompress_ptr cinfo)
  170772. {
  170773. per_scan_setup2(cinfo);
  170774. latch_quant_tables(cinfo);
  170775. (*cinfo->entropy->start_pass) (cinfo);
  170776. (*cinfo->coef->start_input_pass) (cinfo);
  170777. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170778. }
  170779. /*
  170780. * Finish up after inputting a compressed-data scan.
  170781. * This is called by the coefficient controller after it's read all
  170782. * the expected data of the scan.
  170783. */
  170784. METHODDEF(void)
  170785. finish_input_pass (j_decompress_ptr cinfo)
  170786. {
  170787. cinfo->inputctl->consume_input = consume_markers;
  170788. }
  170789. /*
  170790. * Read JPEG markers before, between, or after compressed-data scans.
  170791. * Change state as necessary when a new scan is reached.
  170792. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170793. *
  170794. * The consume_input method pointer points either here or to the
  170795. * coefficient controller's consume_data routine, depending on whether
  170796. * we are reading a compressed data segment or inter-segment markers.
  170797. */
  170798. METHODDEF(int)
  170799. consume_markers (j_decompress_ptr cinfo)
  170800. {
  170801. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170802. int val;
  170803. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170804. return JPEG_REACHED_EOI;
  170805. val = (*cinfo->marker->read_markers) (cinfo);
  170806. switch (val) {
  170807. case JPEG_REACHED_SOS: /* Found SOS */
  170808. if (inputctl->inheaders) { /* 1st SOS */
  170809. initial_setup2(cinfo);
  170810. inputctl->inheaders = FALSE;
  170811. /* Note: start_input_pass must be called by jdmaster.c
  170812. * before any more input can be consumed. jdapimin.c is
  170813. * responsible for enforcing this sequencing.
  170814. */
  170815. } else { /* 2nd or later SOS marker */
  170816. if (! inputctl->pub.has_multiple_scans)
  170817. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170818. start_input_pass2(cinfo);
  170819. }
  170820. break;
  170821. case JPEG_REACHED_EOI: /* Found EOI */
  170822. inputctl->pub.eoi_reached = TRUE;
  170823. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170824. if (cinfo->marker->saw_SOF)
  170825. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170826. } else {
  170827. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170828. * if user set output_scan_number larger than number of scans.
  170829. */
  170830. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170831. cinfo->output_scan_number = cinfo->input_scan_number;
  170832. }
  170833. break;
  170834. case JPEG_SUSPENDED:
  170835. break;
  170836. }
  170837. return val;
  170838. }
  170839. /*
  170840. * Reset state to begin a fresh datastream.
  170841. */
  170842. METHODDEF(void)
  170843. reset_input_controller (j_decompress_ptr cinfo)
  170844. {
  170845. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170846. inputctl->pub.consume_input = consume_markers;
  170847. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170848. inputctl->pub.eoi_reached = FALSE;
  170849. inputctl->inheaders = TRUE;
  170850. /* Reset other modules */
  170851. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170852. (*cinfo->marker->reset_marker_reader) (cinfo);
  170853. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170854. cinfo->coef_bits = NULL;
  170855. }
  170856. /*
  170857. * Initialize the input controller module.
  170858. * This is called only once, when the decompression object is created.
  170859. */
  170860. GLOBAL(void)
  170861. jinit_input_controller (j_decompress_ptr cinfo)
  170862. {
  170863. my_inputctl_ptr inputctl;
  170864. /* Create subobject in permanent pool */
  170865. inputctl = (my_inputctl_ptr)
  170866. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170867. SIZEOF(my_input_controller));
  170868. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170869. /* Initialize method pointers */
  170870. inputctl->pub.consume_input = consume_markers;
  170871. inputctl->pub.reset_input_controller = reset_input_controller;
  170872. inputctl->pub.start_input_pass = start_input_pass2;
  170873. inputctl->pub.finish_input_pass = finish_input_pass;
  170874. /* Initialize state: can't use reset_input_controller since we don't
  170875. * want to try to reset other modules yet.
  170876. */
  170877. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170878. inputctl->pub.eoi_reached = FALSE;
  170879. inputctl->inheaders = TRUE;
  170880. }
  170881. /*** End of inlined file: jdinput.c ***/
  170882. /*** Start of inlined file: jdmainct.c ***/
  170883. #define JPEG_INTERNALS
  170884. /*
  170885. * In the current system design, the main buffer need never be a full-image
  170886. * buffer; any full-height buffers will be found inside the coefficient or
  170887. * postprocessing controllers. Nonetheless, the main controller is not
  170888. * trivial. Its responsibility is to provide context rows for upsampling/
  170889. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170890. *
  170891. * Postprocessor input data is counted in "row groups". A row group
  170892. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170893. * sample rows of each component. (We require DCT_scaled_size values to be
  170894. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170895. * values will likely be powers of two, so we actually have the stronger
  170896. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170897. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170898. * row group (times any additional scale factor that the upsampler is
  170899. * applying).
  170900. *
  170901. * The coefficient controller will deliver data to us one iMCU row at a time;
  170902. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170903. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170904. * to one row of MCUs when the image is fully interleaved.) Note that the
  170905. * number of sample rows varies across components, but the number of row
  170906. * groups does not. Some garbage sample rows may be included in the last iMCU
  170907. * row at the bottom of the image.
  170908. *
  170909. * Depending on the vertical scaling algorithm used, the upsampler may need
  170910. * access to the sample row(s) above and below its current input row group.
  170911. * The upsampler is required to set need_context_rows TRUE at global selection
  170912. * time if so. When need_context_rows is FALSE, this controller can simply
  170913. * obtain one iMCU row at a time from the coefficient controller and dole it
  170914. * out as row groups to the postprocessor.
  170915. *
  170916. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170917. * passed to postprocessing contains at least one row group's worth of samples
  170918. * above and below the row group(s) being processed. Note that the context
  170919. * rows "above" the first passed row group appear at negative row offsets in
  170920. * the passed buffer. At the top and bottom of the image, the required
  170921. * context rows are manufactured by duplicating the first or last real sample
  170922. * row; this avoids having special cases in the upsampling inner loops.
  170923. *
  170924. * The amount of context is fixed at one row group just because that's a
  170925. * convenient number for this controller to work with. The existing
  170926. * upsamplers really only need one sample row of context. An upsampler
  170927. * supporting arbitrary output rescaling might wish for more than one row
  170928. * group of context when shrinking the image; tough, we don't handle that.
  170929. * (This is justified by the assumption that downsizing will be handled mostly
  170930. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170931. * the upsample step needn't be much less than one.)
  170932. *
  170933. * To provide the desired context, we have to retain the last two row groups
  170934. * of one iMCU row while reading in the next iMCU row. (The last row group
  170935. * can't be processed until we have another row group for its below-context,
  170936. * and so we have to save the next-to-last group too for its above-context.)
  170937. * We could do this most simply by copying data around in our buffer, but
  170938. * that'd be very slow. We can avoid copying any data by creating a rather
  170939. * strange pointer structure. Here's how it works. We allocate a workspace
  170940. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170941. * of row groups per iMCU row). We create two sets of redundant pointers to
  170942. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170943. * pointer lists look like this:
  170944. * M+1 M-1
  170945. * master pointer --> 0 master pointer --> 0
  170946. * 1 1
  170947. * ... ...
  170948. * M-3 M-3
  170949. * M-2 M
  170950. * M-1 M+1
  170951. * M M-2
  170952. * M+1 M-1
  170953. * 0 0
  170954. * We read alternate iMCU rows using each master pointer; thus the last two
  170955. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170956. * The pointer lists are set up so that the required context rows appear to
  170957. * be adjacent to the proper places when we pass the pointer lists to the
  170958. * upsampler.
  170959. *
  170960. * The above pictures describe the normal state of the pointer lists.
  170961. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170962. * the first or last sample row as necessary (this is cheaper than copying
  170963. * sample rows around).
  170964. *
  170965. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170966. * situation each iMCU row provides only one row group so the buffering logic
  170967. * must be different (eg, we must read two iMCU rows before we can emit the
  170968. * first row group). For now, we simply do not support providing context
  170969. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170970. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170971. * want it quick and dirty, so a context-free upsampler is sufficient.
  170972. */
  170973. /* Private buffer controller object */
  170974. typedef struct {
  170975. struct jpeg_d_main_controller pub; /* public fields */
  170976. /* Pointer to allocated workspace (M or M+2 row groups). */
  170977. JSAMPARRAY buffer[MAX_COMPONENTS];
  170978. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170979. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170980. /* Remaining fields are only used in the context case. */
  170981. /* These are the master pointers to the funny-order pointer lists. */
  170982. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170983. int whichptr; /* indicates which pointer set is now in use */
  170984. int context_state; /* process_data state machine status */
  170985. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170986. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170987. } my_main_controller4;
  170988. typedef my_main_controller4 * my_main_ptr4;
  170989. /* context_state values: */
  170990. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170991. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170992. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170993. /* Forward declarations */
  170994. METHODDEF(void) process_data_simple_main2
  170995. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170996. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170997. METHODDEF(void) process_data_context_main
  170998. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170999. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171000. #ifdef QUANT_2PASS_SUPPORTED
  171001. METHODDEF(void) process_data_crank_post
  171002. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171003. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171004. #endif
  171005. LOCAL(void)
  171006. alloc_funny_pointers (j_decompress_ptr cinfo)
  171007. /* Allocate space for the funny pointer lists.
  171008. * This is done only once, not once per pass.
  171009. */
  171010. {
  171011. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171012. int ci, rgroup;
  171013. int M = cinfo->min_DCT_scaled_size;
  171014. jpeg_component_info *compptr;
  171015. JSAMPARRAY xbuf;
  171016. /* Get top-level space for component array pointers.
  171017. * We alloc both arrays with one call to save a few cycles.
  171018. */
  171019. main_->xbuffer[0] = (JSAMPIMAGE)
  171020. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171021. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  171022. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  171023. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171024. ci++, compptr++) {
  171025. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171026. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171027. /* Get space for pointer lists --- M+4 row groups in each list.
  171028. * We alloc both pointer lists with one call to save a few cycles.
  171029. */
  171030. xbuf = (JSAMPARRAY)
  171031. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171032. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  171033. xbuf += rgroup; /* want one row group at negative offsets */
  171034. main_->xbuffer[0][ci] = xbuf;
  171035. xbuf += rgroup * (M + 4);
  171036. main_->xbuffer[1][ci] = xbuf;
  171037. }
  171038. }
  171039. LOCAL(void)
  171040. make_funny_pointers (j_decompress_ptr cinfo)
  171041. /* Create the funny pointer lists discussed in the comments above.
  171042. * The actual workspace is already allocated (in main->buffer),
  171043. * and the space for the pointer lists is allocated too.
  171044. * This routine just fills in the curiously ordered lists.
  171045. * This will be repeated at the beginning of each pass.
  171046. */
  171047. {
  171048. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171049. int ci, i, rgroup;
  171050. int M = cinfo->min_DCT_scaled_size;
  171051. jpeg_component_info *compptr;
  171052. JSAMPARRAY buf, xbuf0, xbuf1;
  171053. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171054. ci++, compptr++) {
  171055. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171056. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171057. xbuf0 = main_->xbuffer[0][ci];
  171058. xbuf1 = main_->xbuffer[1][ci];
  171059. /* First copy the workspace pointers as-is */
  171060. buf = main_->buffer[ci];
  171061. for (i = 0; i < rgroup * (M + 2); i++) {
  171062. xbuf0[i] = xbuf1[i] = buf[i];
  171063. }
  171064. /* In the second list, put the last four row groups in swapped order */
  171065. for (i = 0; i < rgroup * 2; i++) {
  171066. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  171067. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  171068. }
  171069. /* The wraparound pointers at top and bottom will be filled later
  171070. * (see set_wraparound_pointers, below). Initially we want the "above"
  171071. * pointers to duplicate the first actual data line. This only needs
  171072. * to happen in xbuffer[0].
  171073. */
  171074. for (i = 0; i < rgroup; i++) {
  171075. xbuf0[i - rgroup] = xbuf0[0];
  171076. }
  171077. }
  171078. }
  171079. LOCAL(void)
  171080. set_wraparound_pointers (j_decompress_ptr cinfo)
  171081. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  171082. * This changes the pointer list state from top-of-image to the normal state.
  171083. */
  171084. {
  171085. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171086. int ci, i, rgroup;
  171087. int M = cinfo->min_DCT_scaled_size;
  171088. jpeg_component_info *compptr;
  171089. JSAMPARRAY xbuf0, xbuf1;
  171090. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171091. ci++, compptr++) {
  171092. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171093. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171094. xbuf0 = main_->xbuffer[0][ci];
  171095. xbuf1 = main_->xbuffer[1][ci];
  171096. for (i = 0; i < rgroup; i++) {
  171097. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  171098. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  171099. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  171100. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  171101. }
  171102. }
  171103. }
  171104. LOCAL(void)
  171105. set_bottom_pointers (j_decompress_ptr cinfo)
  171106. /* Change the pointer lists to duplicate the last sample row at the bottom
  171107. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  171108. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  171109. */
  171110. {
  171111. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171112. int ci, i, rgroup, iMCUheight, rows_left;
  171113. jpeg_component_info *compptr;
  171114. JSAMPARRAY xbuf;
  171115. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171116. ci++, compptr++) {
  171117. /* Count sample rows in one iMCU row and in one row group */
  171118. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  171119. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  171120. /* Count nondummy sample rows remaining for this component */
  171121. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  171122. if (rows_left == 0) rows_left = iMCUheight;
  171123. /* Count nondummy row groups. Should get same answer for each component,
  171124. * so we need only do it once.
  171125. */
  171126. if (ci == 0) {
  171127. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  171128. }
  171129. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  171130. * last partial rowgroup and ensures at least one full rowgroup of context.
  171131. */
  171132. xbuf = main_->xbuffer[main_->whichptr][ci];
  171133. for (i = 0; i < rgroup * 2; i++) {
  171134. xbuf[rows_left + i] = xbuf[rows_left-1];
  171135. }
  171136. }
  171137. }
  171138. /*
  171139. * Initialize for a processing pass.
  171140. */
  171141. METHODDEF(void)
  171142. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  171143. {
  171144. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171145. switch (pass_mode) {
  171146. case JBUF_PASS_THRU:
  171147. if (cinfo->upsample->need_context_rows) {
  171148. main_->pub.process_data = process_data_context_main;
  171149. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  171150. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  171151. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171152. main_->iMCU_row_ctr = 0;
  171153. } else {
  171154. /* Simple case with no context needed */
  171155. main_->pub.process_data = process_data_simple_main2;
  171156. }
  171157. main_->buffer_full = FALSE; /* Mark buffer empty */
  171158. main_->rowgroup_ctr = 0;
  171159. break;
  171160. #ifdef QUANT_2PASS_SUPPORTED
  171161. case JBUF_CRANK_DEST:
  171162. /* For last pass of 2-pass quantization, just crank the postprocessor */
  171163. main_->pub.process_data = process_data_crank_post;
  171164. break;
  171165. #endif
  171166. default:
  171167. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171168. break;
  171169. }
  171170. }
  171171. /*
  171172. * Process some data.
  171173. * This handles the simple case where no context is required.
  171174. */
  171175. METHODDEF(void)
  171176. process_data_simple_main2 (j_decompress_ptr cinfo,
  171177. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171178. JDIMENSION out_rows_avail)
  171179. {
  171180. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171181. JDIMENSION rowgroups_avail;
  171182. /* Read input data if we haven't filled the main buffer yet */
  171183. if (! main_->buffer_full) {
  171184. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  171185. return; /* suspension forced, can do nothing more */
  171186. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171187. }
  171188. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  171189. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  171190. /* Note: at the bottom of the image, we may pass extra garbage row groups
  171191. * to the postprocessor. The postprocessor has to check for bottom
  171192. * of image anyway (at row resolution), so no point in us doing it too.
  171193. */
  171194. /* Feed the postprocessor */
  171195. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  171196. &main_->rowgroup_ctr, rowgroups_avail,
  171197. output_buf, out_row_ctr, out_rows_avail);
  171198. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  171199. if (main_->rowgroup_ctr >= rowgroups_avail) {
  171200. main_->buffer_full = FALSE;
  171201. main_->rowgroup_ctr = 0;
  171202. }
  171203. }
  171204. /*
  171205. * Process some data.
  171206. * This handles the case where context rows must be provided.
  171207. */
  171208. METHODDEF(void)
  171209. process_data_context_main (j_decompress_ptr cinfo,
  171210. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171211. JDIMENSION out_rows_avail)
  171212. {
  171213. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171214. /* Read input data if we haven't filled the main buffer yet */
  171215. if (! main_->buffer_full) {
  171216. if (! (*cinfo->coef->decompress_data) (cinfo,
  171217. main_->xbuffer[main_->whichptr]))
  171218. return; /* suspension forced, can do nothing more */
  171219. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171220. main_->iMCU_row_ctr++; /* count rows received */
  171221. }
  171222. /* Postprocessor typically will not swallow all the input data it is handed
  171223. * in one call (due to filling the output buffer first). Must be prepared
  171224. * to exit and restart. This switch lets us keep track of how far we got.
  171225. * Note that each case falls through to the next on successful completion.
  171226. */
  171227. switch (main_->context_state) {
  171228. case CTX_POSTPONED_ROW:
  171229. /* Call postprocessor using previously set pointers for postponed row */
  171230. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171231. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171232. output_buf, out_row_ctr, out_rows_avail);
  171233. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171234. return; /* Need to suspend */
  171235. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171236. if (*out_row_ctr >= out_rows_avail)
  171237. return; /* Postprocessor exactly filled output buf */
  171238. /*FALLTHROUGH*/
  171239. case CTX_PREPARE_FOR_IMCU:
  171240. /* Prepare to process first M-1 row groups of this iMCU row */
  171241. main_->rowgroup_ctr = 0;
  171242. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171243. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171244. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171245. */
  171246. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171247. set_bottom_pointers(cinfo);
  171248. main_->context_state = CTX_PROCESS_IMCU;
  171249. /*FALLTHROUGH*/
  171250. case CTX_PROCESS_IMCU:
  171251. /* Call postprocessor using previously set pointers */
  171252. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171253. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171254. output_buf, out_row_ctr, out_rows_avail);
  171255. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171256. return; /* Need to suspend */
  171257. /* After the first iMCU, change wraparound pointers to normal state */
  171258. if (main_->iMCU_row_ctr == 1)
  171259. set_wraparound_pointers(cinfo);
  171260. /* Prepare to load new iMCU row using other xbuffer list */
  171261. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171262. main_->buffer_full = FALSE;
  171263. /* Still need to process last row group of this iMCU row, */
  171264. /* which is saved at index M+1 of the other xbuffer */
  171265. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171266. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171267. main_->context_state = CTX_POSTPONED_ROW;
  171268. }
  171269. }
  171270. /*
  171271. * Process some data.
  171272. * Final pass of two-pass quantization: just call the postprocessor.
  171273. * Source data will be the postprocessor controller's internal buffer.
  171274. */
  171275. #ifdef QUANT_2PASS_SUPPORTED
  171276. METHODDEF(void)
  171277. process_data_crank_post (j_decompress_ptr cinfo,
  171278. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171279. JDIMENSION out_rows_avail)
  171280. {
  171281. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171282. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171283. output_buf, out_row_ctr, out_rows_avail);
  171284. }
  171285. #endif /* QUANT_2PASS_SUPPORTED */
  171286. /*
  171287. * Initialize main buffer controller.
  171288. */
  171289. GLOBAL(void)
  171290. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171291. {
  171292. my_main_ptr4 main_;
  171293. int ci, rgroup, ngroups;
  171294. jpeg_component_info *compptr;
  171295. main_ = (my_main_ptr4)
  171296. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171297. SIZEOF(my_main_controller4));
  171298. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171299. main_->pub.start_pass = start_pass_main2;
  171300. if (need_full_buffer) /* shouldn't happen */
  171301. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171302. /* Allocate the workspace.
  171303. * ngroups is the number of row groups we need.
  171304. */
  171305. if (cinfo->upsample->need_context_rows) {
  171306. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171307. ERREXIT(cinfo, JERR_NOTIMPL);
  171308. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171309. ngroups = cinfo->min_DCT_scaled_size + 2;
  171310. } else {
  171311. ngroups = cinfo->min_DCT_scaled_size;
  171312. }
  171313. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171314. ci++, compptr++) {
  171315. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171316. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171317. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171318. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171319. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171320. (JDIMENSION) (rgroup * ngroups));
  171321. }
  171322. }
  171323. /*** End of inlined file: jdmainct.c ***/
  171324. /*** Start of inlined file: jdmarker.c ***/
  171325. #define JPEG_INTERNALS
  171326. /* Private state */
  171327. typedef struct {
  171328. struct jpeg_marker_reader pub; /* public fields */
  171329. /* Application-overridable marker processing methods */
  171330. jpeg_marker_parser_method process_COM;
  171331. jpeg_marker_parser_method process_APPn[16];
  171332. /* Limit on marker data length to save for each marker type */
  171333. unsigned int length_limit_COM;
  171334. unsigned int length_limit_APPn[16];
  171335. /* Status of COM/APPn marker saving */
  171336. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171337. unsigned int bytes_read; /* data bytes read so far in marker */
  171338. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171339. } my_marker_reader;
  171340. typedef my_marker_reader * my_marker_ptr2;
  171341. /*
  171342. * Macros for fetching data from the data source module.
  171343. *
  171344. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171345. * the current restart point; we update them only when we have reached a
  171346. * suitable place to restart if a suspension occurs.
  171347. */
  171348. /* Declare and initialize local copies of input pointer/count */
  171349. #define INPUT_VARS(cinfo) \
  171350. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171351. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171352. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171353. /* Unload the local copies --- do this only at a restart boundary */
  171354. #define INPUT_SYNC(cinfo) \
  171355. ( datasrc->next_input_byte = next_input_byte, \
  171356. datasrc->bytes_in_buffer = bytes_in_buffer )
  171357. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171358. #define INPUT_RELOAD(cinfo) \
  171359. ( next_input_byte = datasrc->next_input_byte, \
  171360. bytes_in_buffer = datasrc->bytes_in_buffer )
  171361. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171362. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171363. * but we must reload the local copies after a successful fill.
  171364. */
  171365. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171366. if (bytes_in_buffer == 0) { \
  171367. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171368. { action; } \
  171369. INPUT_RELOAD(cinfo); \
  171370. }
  171371. /* Read a byte into variable V.
  171372. * If must suspend, take the specified action (typically "return FALSE").
  171373. */
  171374. #define INPUT_BYTE(cinfo,V,action) \
  171375. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171376. bytes_in_buffer--; \
  171377. V = GETJOCTET(*next_input_byte++); )
  171378. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171379. * V should be declared unsigned int or perhaps INT32.
  171380. */
  171381. #define INPUT_2BYTES(cinfo,V,action) \
  171382. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171383. bytes_in_buffer--; \
  171384. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171385. MAKE_BYTE_AVAIL(cinfo,action); \
  171386. bytes_in_buffer--; \
  171387. V += GETJOCTET(*next_input_byte++); )
  171388. /*
  171389. * Routines to process JPEG markers.
  171390. *
  171391. * Entry condition: JPEG marker itself has been read and its code saved
  171392. * in cinfo->unread_marker; input restart point is just after the marker.
  171393. *
  171394. * Exit: if return TRUE, have read and processed any parameters, and have
  171395. * updated the restart point to point after the parameters.
  171396. * If return FALSE, was forced to suspend before reaching end of
  171397. * marker parameters; restart point has not been moved. Same routine
  171398. * will be called again after application supplies more input data.
  171399. *
  171400. * This approach to suspension assumes that all of a marker's parameters
  171401. * can fit into a single input bufferload. This should hold for "normal"
  171402. * markers. Some COM/APPn markers might have large parameter segments
  171403. * that might not fit. If we are simply dropping such a marker, we use
  171404. * skip_input_data to get past it, and thereby put the problem on the
  171405. * source manager's shoulders. If we are saving the marker's contents
  171406. * into memory, we use a slightly different convention: when forced to
  171407. * suspend, the marker processor updates the restart point to the end of
  171408. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171409. * On resumption, cinfo->unread_marker still contains the marker code,
  171410. * but the data source will point to the next chunk of marker data.
  171411. * The marker processor must retain internal state to deal with this.
  171412. *
  171413. * Note that we don't bother to avoid duplicate trace messages if a
  171414. * suspension occurs within marker parameters. Other side effects
  171415. * require more care.
  171416. */
  171417. LOCAL(boolean)
  171418. get_soi (j_decompress_ptr cinfo)
  171419. /* Process an SOI marker */
  171420. {
  171421. int i;
  171422. TRACEMS(cinfo, 1, JTRC_SOI);
  171423. if (cinfo->marker->saw_SOI)
  171424. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171425. /* Reset all parameters that are defined to be reset by SOI */
  171426. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171427. cinfo->arith_dc_L[i] = 0;
  171428. cinfo->arith_dc_U[i] = 1;
  171429. cinfo->arith_ac_K[i] = 5;
  171430. }
  171431. cinfo->restart_interval = 0;
  171432. /* Set initial assumptions for colorspace etc */
  171433. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171434. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171435. cinfo->saw_JFIF_marker = FALSE;
  171436. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171437. cinfo->JFIF_minor_version = 1;
  171438. cinfo->density_unit = 0;
  171439. cinfo->X_density = 1;
  171440. cinfo->Y_density = 1;
  171441. cinfo->saw_Adobe_marker = FALSE;
  171442. cinfo->Adobe_transform = 0;
  171443. cinfo->marker->saw_SOI = TRUE;
  171444. return TRUE;
  171445. }
  171446. LOCAL(boolean)
  171447. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171448. /* Process a SOFn marker */
  171449. {
  171450. INT32 length;
  171451. int c, ci;
  171452. jpeg_component_info * compptr;
  171453. INPUT_VARS(cinfo);
  171454. cinfo->progressive_mode = is_prog;
  171455. cinfo->arith_code = is_arith;
  171456. INPUT_2BYTES(cinfo, length, return FALSE);
  171457. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171458. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171459. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171460. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171461. length -= 8;
  171462. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171463. (int) cinfo->image_width, (int) cinfo->image_height,
  171464. cinfo->num_components);
  171465. if (cinfo->marker->saw_SOF)
  171466. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171467. /* We don't support files in which the image height is initially specified */
  171468. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171469. /* might as well have a general sanity check. */
  171470. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171471. || cinfo->num_components <= 0)
  171472. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171473. if (length != (cinfo->num_components * 3))
  171474. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171475. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171476. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171477. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171478. cinfo->num_components * SIZEOF(jpeg_component_info));
  171479. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171480. ci++, compptr++) {
  171481. compptr->component_index = ci;
  171482. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171483. INPUT_BYTE(cinfo, c, return FALSE);
  171484. compptr->h_samp_factor = (c >> 4) & 15;
  171485. compptr->v_samp_factor = (c ) & 15;
  171486. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171487. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171488. compptr->component_id, compptr->h_samp_factor,
  171489. compptr->v_samp_factor, compptr->quant_tbl_no);
  171490. }
  171491. cinfo->marker->saw_SOF = TRUE;
  171492. INPUT_SYNC(cinfo);
  171493. return TRUE;
  171494. }
  171495. LOCAL(boolean)
  171496. get_sos (j_decompress_ptr cinfo)
  171497. /* Process a SOS marker */
  171498. {
  171499. INT32 length;
  171500. int i, ci, n, c, cc;
  171501. jpeg_component_info * compptr;
  171502. INPUT_VARS(cinfo);
  171503. if (! cinfo->marker->saw_SOF)
  171504. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171505. INPUT_2BYTES(cinfo, length, return FALSE);
  171506. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171507. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171508. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171509. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171510. cinfo->comps_in_scan = n;
  171511. /* Collect the component-spec parameters */
  171512. for (i = 0; i < n; i++) {
  171513. INPUT_BYTE(cinfo, cc, return FALSE);
  171514. INPUT_BYTE(cinfo, c, return FALSE);
  171515. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171516. ci++, compptr++) {
  171517. if (cc == compptr->component_id)
  171518. goto id_found;
  171519. }
  171520. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171521. id_found:
  171522. cinfo->cur_comp_info[i] = compptr;
  171523. compptr->dc_tbl_no = (c >> 4) & 15;
  171524. compptr->ac_tbl_no = (c ) & 15;
  171525. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171526. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171527. }
  171528. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171529. INPUT_BYTE(cinfo, c, return FALSE);
  171530. cinfo->Ss = c;
  171531. INPUT_BYTE(cinfo, c, return FALSE);
  171532. cinfo->Se = c;
  171533. INPUT_BYTE(cinfo, c, return FALSE);
  171534. cinfo->Ah = (c >> 4) & 15;
  171535. cinfo->Al = (c ) & 15;
  171536. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171537. cinfo->Ah, cinfo->Al);
  171538. /* Prepare to scan data & restart markers */
  171539. cinfo->marker->next_restart_num = 0;
  171540. /* Count another SOS marker */
  171541. cinfo->input_scan_number++;
  171542. INPUT_SYNC(cinfo);
  171543. return TRUE;
  171544. }
  171545. #ifdef D_ARITH_CODING_SUPPORTED
  171546. LOCAL(boolean)
  171547. get_dac (j_decompress_ptr cinfo)
  171548. /* Process a DAC marker */
  171549. {
  171550. INT32 length;
  171551. int index, val;
  171552. INPUT_VARS(cinfo);
  171553. INPUT_2BYTES(cinfo, length, return FALSE);
  171554. length -= 2;
  171555. while (length > 0) {
  171556. INPUT_BYTE(cinfo, index, return FALSE);
  171557. INPUT_BYTE(cinfo, val, return FALSE);
  171558. length -= 2;
  171559. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171560. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171561. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171562. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171563. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171564. } else { /* define DC table */
  171565. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171566. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171567. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171568. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171569. }
  171570. }
  171571. if (length != 0)
  171572. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171573. INPUT_SYNC(cinfo);
  171574. return TRUE;
  171575. }
  171576. #else /* ! D_ARITH_CODING_SUPPORTED */
  171577. #define get_dac(cinfo) skip_variable(cinfo)
  171578. #endif /* D_ARITH_CODING_SUPPORTED */
  171579. LOCAL(boolean)
  171580. get_dht (j_decompress_ptr cinfo)
  171581. /* Process a DHT marker */
  171582. {
  171583. INT32 length;
  171584. UINT8 bits[17];
  171585. UINT8 huffval[256];
  171586. int i, index, count;
  171587. JHUFF_TBL **htblptr;
  171588. INPUT_VARS(cinfo);
  171589. INPUT_2BYTES(cinfo, length, return FALSE);
  171590. length -= 2;
  171591. while (length > 16) {
  171592. INPUT_BYTE(cinfo, index, return FALSE);
  171593. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171594. bits[0] = 0;
  171595. count = 0;
  171596. for (i = 1; i <= 16; i++) {
  171597. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171598. count += bits[i];
  171599. }
  171600. length -= 1 + 16;
  171601. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171602. bits[1], bits[2], bits[3], bits[4],
  171603. bits[5], bits[6], bits[7], bits[8]);
  171604. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171605. bits[9], bits[10], bits[11], bits[12],
  171606. bits[13], bits[14], bits[15], bits[16]);
  171607. /* Here we just do minimal validation of the counts to avoid walking
  171608. * off the end of our table space. jdhuff.c will check more carefully.
  171609. */
  171610. if (count > 256 || ((INT32) count) > length)
  171611. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171612. for (i = 0; i < count; i++)
  171613. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171614. length -= count;
  171615. if (index & 0x10) { /* AC table definition */
  171616. index -= 0x10;
  171617. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171618. } else { /* DC table definition */
  171619. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171620. }
  171621. if (index < 0 || index >= NUM_HUFF_TBLS)
  171622. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171623. if (*htblptr == NULL)
  171624. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171625. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171626. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171627. }
  171628. if (length != 0)
  171629. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171630. INPUT_SYNC(cinfo);
  171631. return TRUE;
  171632. }
  171633. LOCAL(boolean)
  171634. get_dqt (j_decompress_ptr cinfo)
  171635. /* Process a DQT marker */
  171636. {
  171637. INT32 length;
  171638. int n, i, prec;
  171639. unsigned int tmp;
  171640. JQUANT_TBL *quant_ptr;
  171641. INPUT_VARS(cinfo);
  171642. INPUT_2BYTES(cinfo, length, return FALSE);
  171643. length -= 2;
  171644. while (length > 0) {
  171645. INPUT_BYTE(cinfo, n, return FALSE);
  171646. prec = n >> 4;
  171647. n &= 0x0F;
  171648. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171649. if (n >= NUM_QUANT_TBLS)
  171650. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171651. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171652. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171653. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171654. for (i = 0; i < DCTSIZE2; i++) {
  171655. if (prec)
  171656. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171657. else
  171658. INPUT_BYTE(cinfo, tmp, return FALSE);
  171659. /* We convert the zigzag-order table to natural array order. */
  171660. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171661. }
  171662. if (cinfo->err->trace_level >= 2) {
  171663. for (i = 0; i < DCTSIZE2; i += 8) {
  171664. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171665. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171666. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171667. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171668. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171669. }
  171670. }
  171671. length -= DCTSIZE2+1;
  171672. if (prec) length -= DCTSIZE2;
  171673. }
  171674. if (length != 0)
  171675. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171676. INPUT_SYNC(cinfo);
  171677. return TRUE;
  171678. }
  171679. LOCAL(boolean)
  171680. get_dri (j_decompress_ptr cinfo)
  171681. /* Process a DRI marker */
  171682. {
  171683. INT32 length;
  171684. unsigned int tmp;
  171685. INPUT_VARS(cinfo);
  171686. INPUT_2BYTES(cinfo, length, return FALSE);
  171687. if (length != 4)
  171688. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171689. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171690. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171691. cinfo->restart_interval = tmp;
  171692. INPUT_SYNC(cinfo);
  171693. return TRUE;
  171694. }
  171695. /*
  171696. * Routines for processing APPn and COM markers.
  171697. * These are either saved in memory or discarded, per application request.
  171698. * APP0 and APP14 are specially checked to see if they are
  171699. * JFIF and Adobe markers, respectively.
  171700. */
  171701. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171702. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171703. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171704. LOCAL(void)
  171705. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171706. unsigned int datalen, INT32 remaining)
  171707. /* Examine first few bytes from an APP0.
  171708. * Take appropriate action if it is a JFIF marker.
  171709. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171710. */
  171711. {
  171712. INT32 totallen = (INT32) datalen + remaining;
  171713. if (datalen >= APP0_DATA_LEN &&
  171714. GETJOCTET(data[0]) == 0x4A &&
  171715. GETJOCTET(data[1]) == 0x46 &&
  171716. GETJOCTET(data[2]) == 0x49 &&
  171717. GETJOCTET(data[3]) == 0x46 &&
  171718. GETJOCTET(data[4]) == 0) {
  171719. /* Found JFIF APP0 marker: save info */
  171720. cinfo->saw_JFIF_marker = TRUE;
  171721. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171722. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171723. cinfo->density_unit = GETJOCTET(data[7]);
  171724. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171725. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171726. /* Check version.
  171727. * Major version must be 1, anything else signals an incompatible change.
  171728. * (We used to treat this as an error, but now it's a nonfatal warning,
  171729. * because some bozo at Hijaak couldn't read the spec.)
  171730. * Minor version should be 0..2, but process anyway if newer.
  171731. */
  171732. if (cinfo->JFIF_major_version != 1)
  171733. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171734. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171735. /* Generate trace messages */
  171736. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171737. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171738. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171739. /* Validate thumbnail dimensions and issue appropriate messages */
  171740. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171741. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171742. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171743. totallen -= APP0_DATA_LEN;
  171744. if (totallen !=
  171745. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171746. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171747. } else if (datalen >= 6 &&
  171748. GETJOCTET(data[0]) == 0x4A &&
  171749. GETJOCTET(data[1]) == 0x46 &&
  171750. GETJOCTET(data[2]) == 0x58 &&
  171751. GETJOCTET(data[3]) == 0x58 &&
  171752. GETJOCTET(data[4]) == 0) {
  171753. /* Found JFIF "JFXX" extension APP0 marker */
  171754. /* The library doesn't actually do anything with these,
  171755. * but we try to produce a helpful trace message.
  171756. */
  171757. switch (GETJOCTET(data[5])) {
  171758. case 0x10:
  171759. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171760. break;
  171761. case 0x11:
  171762. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171763. break;
  171764. case 0x13:
  171765. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171766. break;
  171767. default:
  171768. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171769. GETJOCTET(data[5]), (int) totallen);
  171770. break;
  171771. }
  171772. } else {
  171773. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171774. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171775. }
  171776. }
  171777. LOCAL(void)
  171778. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171779. unsigned int datalen, INT32 remaining)
  171780. /* Examine first few bytes from an APP14.
  171781. * Take appropriate action if it is an Adobe marker.
  171782. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171783. */
  171784. {
  171785. unsigned int version, flags0, flags1, transform;
  171786. if (datalen >= APP14_DATA_LEN &&
  171787. GETJOCTET(data[0]) == 0x41 &&
  171788. GETJOCTET(data[1]) == 0x64 &&
  171789. GETJOCTET(data[2]) == 0x6F &&
  171790. GETJOCTET(data[3]) == 0x62 &&
  171791. GETJOCTET(data[4]) == 0x65) {
  171792. /* Found Adobe APP14 marker */
  171793. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171794. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171795. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171796. transform = GETJOCTET(data[11]);
  171797. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171798. cinfo->saw_Adobe_marker = TRUE;
  171799. cinfo->Adobe_transform = (UINT8) transform;
  171800. } else {
  171801. /* Start of APP14 does not match "Adobe", or too short */
  171802. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171803. }
  171804. }
  171805. METHODDEF(boolean)
  171806. get_interesting_appn (j_decompress_ptr cinfo)
  171807. /* Process an APP0 or APP14 marker without saving it */
  171808. {
  171809. INT32 length;
  171810. JOCTET b[APPN_DATA_LEN];
  171811. unsigned int i, numtoread;
  171812. INPUT_VARS(cinfo);
  171813. INPUT_2BYTES(cinfo, length, return FALSE);
  171814. length -= 2;
  171815. /* get the interesting part of the marker data */
  171816. if (length >= APPN_DATA_LEN)
  171817. numtoread = APPN_DATA_LEN;
  171818. else if (length > 0)
  171819. numtoread = (unsigned int) length;
  171820. else
  171821. numtoread = 0;
  171822. for (i = 0; i < numtoread; i++)
  171823. INPUT_BYTE(cinfo, b[i], return FALSE);
  171824. length -= numtoread;
  171825. /* process it */
  171826. switch (cinfo->unread_marker) {
  171827. case M_APP0:
  171828. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171829. break;
  171830. case M_APP14:
  171831. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171832. break;
  171833. default:
  171834. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171835. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171836. break;
  171837. }
  171838. /* skip any remaining data -- could be lots */
  171839. INPUT_SYNC(cinfo);
  171840. if (length > 0)
  171841. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171842. return TRUE;
  171843. }
  171844. #ifdef SAVE_MARKERS_SUPPORTED
  171845. METHODDEF(boolean)
  171846. save_marker (j_decompress_ptr cinfo)
  171847. /* Save an APPn or COM marker into the marker list */
  171848. {
  171849. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171850. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171851. unsigned int bytes_read, data_length;
  171852. JOCTET FAR * data;
  171853. INT32 length = 0;
  171854. INPUT_VARS(cinfo);
  171855. if (cur_marker == NULL) {
  171856. /* begin reading a marker */
  171857. INPUT_2BYTES(cinfo, length, return FALSE);
  171858. length -= 2;
  171859. if (length >= 0) { /* watch out for bogus length word */
  171860. /* figure out how much we want to save */
  171861. unsigned int limit;
  171862. if (cinfo->unread_marker == (int) M_COM)
  171863. limit = marker->length_limit_COM;
  171864. else
  171865. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171866. if ((unsigned int) length < limit)
  171867. limit = (unsigned int) length;
  171868. /* allocate and initialize the marker item */
  171869. cur_marker = (jpeg_saved_marker_ptr)
  171870. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171871. SIZEOF(struct jpeg_marker_struct) + limit);
  171872. cur_marker->next = NULL;
  171873. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171874. cur_marker->original_length = (unsigned int) length;
  171875. cur_marker->data_length = limit;
  171876. /* data area is just beyond the jpeg_marker_struct */
  171877. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171878. marker->cur_marker = cur_marker;
  171879. marker->bytes_read = 0;
  171880. bytes_read = 0;
  171881. data_length = limit;
  171882. } else {
  171883. /* deal with bogus length word */
  171884. bytes_read = data_length = 0;
  171885. data = NULL;
  171886. }
  171887. } else {
  171888. /* resume reading a marker */
  171889. bytes_read = marker->bytes_read;
  171890. data_length = cur_marker->data_length;
  171891. data = cur_marker->data + bytes_read;
  171892. }
  171893. while (bytes_read < data_length) {
  171894. INPUT_SYNC(cinfo); /* move the restart point to here */
  171895. marker->bytes_read = bytes_read;
  171896. /* If there's not at least one byte in buffer, suspend */
  171897. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171898. /* Copy bytes with reasonable rapidity */
  171899. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171900. *data++ = *next_input_byte++;
  171901. bytes_in_buffer--;
  171902. bytes_read++;
  171903. }
  171904. }
  171905. /* Done reading what we want to read */
  171906. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171907. /* Add new marker to end of list */
  171908. if (cinfo->marker_list == NULL) {
  171909. cinfo->marker_list = cur_marker;
  171910. } else {
  171911. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171912. while (prev->next != NULL)
  171913. prev = prev->next;
  171914. prev->next = cur_marker;
  171915. }
  171916. /* Reset pointer & calc remaining data length */
  171917. data = cur_marker->data;
  171918. length = cur_marker->original_length - data_length;
  171919. }
  171920. /* Reset to initial state for next marker */
  171921. marker->cur_marker = NULL;
  171922. /* Process the marker if interesting; else just make a generic trace msg */
  171923. switch (cinfo->unread_marker) {
  171924. case M_APP0:
  171925. examine_app0(cinfo, data, data_length, length);
  171926. break;
  171927. case M_APP14:
  171928. examine_app14(cinfo, data, data_length, length);
  171929. break;
  171930. default:
  171931. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171932. (int) (data_length + length));
  171933. break;
  171934. }
  171935. /* skip any remaining data -- could be lots */
  171936. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171937. if (length > 0)
  171938. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171939. return TRUE;
  171940. }
  171941. #endif /* SAVE_MARKERS_SUPPORTED */
  171942. METHODDEF(boolean)
  171943. skip_variable (j_decompress_ptr cinfo)
  171944. /* Skip over an unknown or uninteresting variable-length marker */
  171945. {
  171946. INT32 length;
  171947. INPUT_VARS(cinfo);
  171948. INPUT_2BYTES(cinfo, length, return FALSE);
  171949. length -= 2;
  171950. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171951. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171952. if (length > 0)
  171953. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171954. return TRUE;
  171955. }
  171956. /*
  171957. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171958. * Returns FALSE if had to suspend before reaching a marker;
  171959. * in that case cinfo->unread_marker is unchanged.
  171960. *
  171961. * Note that the result might not be a valid marker code,
  171962. * but it will never be 0 or FF.
  171963. */
  171964. LOCAL(boolean)
  171965. next_marker (j_decompress_ptr cinfo)
  171966. {
  171967. int c;
  171968. INPUT_VARS(cinfo);
  171969. for (;;) {
  171970. INPUT_BYTE(cinfo, c, return FALSE);
  171971. /* Skip any non-FF bytes.
  171972. * This may look a bit inefficient, but it will not occur in a valid file.
  171973. * We sync after each discarded byte so that a suspending data source
  171974. * can discard the byte from its buffer.
  171975. */
  171976. while (c != 0xFF) {
  171977. cinfo->marker->discarded_bytes++;
  171978. INPUT_SYNC(cinfo);
  171979. INPUT_BYTE(cinfo, c, return FALSE);
  171980. }
  171981. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171982. * pad bytes, so don't count them in discarded_bytes. We assume there
  171983. * will not be so many consecutive FF bytes as to overflow a suspending
  171984. * data source's input buffer.
  171985. */
  171986. do {
  171987. INPUT_BYTE(cinfo, c, return FALSE);
  171988. } while (c == 0xFF);
  171989. if (c != 0)
  171990. break; /* found a valid marker, exit loop */
  171991. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171992. * Discard it and loop back to try again.
  171993. */
  171994. cinfo->marker->discarded_bytes += 2;
  171995. INPUT_SYNC(cinfo);
  171996. }
  171997. if (cinfo->marker->discarded_bytes != 0) {
  171998. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171999. cinfo->marker->discarded_bytes = 0;
  172000. }
  172001. cinfo->unread_marker = c;
  172002. INPUT_SYNC(cinfo);
  172003. return TRUE;
  172004. }
  172005. LOCAL(boolean)
  172006. first_marker (j_decompress_ptr cinfo)
  172007. /* Like next_marker, but used to obtain the initial SOI marker. */
  172008. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  172009. * we might well scan an entire input file before realizing it ain't JPEG.
  172010. * If an application wants to process non-JFIF files, it must seek to the
  172011. * SOI before calling the JPEG library.
  172012. */
  172013. {
  172014. int c, c2;
  172015. INPUT_VARS(cinfo);
  172016. INPUT_BYTE(cinfo, c, return FALSE);
  172017. INPUT_BYTE(cinfo, c2, return FALSE);
  172018. if (c != 0xFF || c2 != (int) M_SOI)
  172019. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  172020. cinfo->unread_marker = c2;
  172021. INPUT_SYNC(cinfo);
  172022. return TRUE;
  172023. }
  172024. /*
  172025. * Read markers until SOS or EOI.
  172026. *
  172027. * Returns same codes as are defined for jpeg_consume_input:
  172028. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  172029. */
  172030. METHODDEF(int)
  172031. read_markers (j_decompress_ptr cinfo)
  172032. {
  172033. /* Outer loop repeats once for each marker. */
  172034. for (;;) {
  172035. /* Collect the marker proper, unless we already did. */
  172036. /* NB: first_marker() enforces the requirement that SOI appear first. */
  172037. if (cinfo->unread_marker == 0) {
  172038. if (! cinfo->marker->saw_SOI) {
  172039. if (! first_marker(cinfo))
  172040. return JPEG_SUSPENDED;
  172041. } else {
  172042. if (! next_marker(cinfo))
  172043. return JPEG_SUSPENDED;
  172044. }
  172045. }
  172046. /* At this point cinfo->unread_marker contains the marker code and the
  172047. * input point is just past the marker proper, but before any parameters.
  172048. * A suspension will cause us to return with this state still true.
  172049. */
  172050. switch (cinfo->unread_marker) {
  172051. case M_SOI:
  172052. if (! get_soi(cinfo))
  172053. return JPEG_SUSPENDED;
  172054. break;
  172055. case M_SOF0: /* Baseline */
  172056. case M_SOF1: /* Extended sequential, Huffman */
  172057. if (! get_sof(cinfo, FALSE, FALSE))
  172058. return JPEG_SUSPENDED;
  172059. break;
  172060. case M_SOF2: /* Progressive, Huffman */
  172061. if (! get_sof(cinfo, TRUE, FALSE))
  172062. return JPEG_SUSPENDED;
  172063. break;
  172064. case M_SOF9: /* Extended sequential, arithmetic */
  172065. if (! get_sof(cinfo, FALSE, TRUE))
  172066. return JPEG_SUSPENDED;
  172067. break;
  172068. case M_SOF10: /* Progressive, arithmetic */
  172069. if (! get_sof(cinfo, TRUE, TRUE))
  172070. return JPEG_SUSPENDED;
  172071. break;
  172072. /* Currently unsupported SOFn types */
  172073. case M_SOF3: /* Lossless, Huffman */
  172074. case M_SOF5: /* Differential sequential, Huffman */
  172075. case M_SOF6: /* Differential progressive, Huffman */
  172076. case M_SOF7: /* Differential lossless, Huffman */
  172077. case M_JPG: /* Reserved for JPEG extensions */
  172078. case M_SOF11: /* Lossless, arithmetic */
  172079. case M_SOF13: /* Differential sequential, arithmetic */
  172080. case M_SOF14: /* Differential progressive, arithmetic */
  172081. case M_SOF15: /* Differential lossless, arithmetic */
  172082. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  172083. break;
  172084. case M_SOS:
  172085. if (! get_sos(cinfo))
  172086. return JPEG_SUSPENDED;
  172087. cinfo->unread_marker = 0; /* processed the marker */
  172088. return JPEG_REACHED_SOS;
  172089. case M_EOI:
  172090. TRACEMS(cinfo, 1, JTRC_EOI);
  172091. cinfo->unread_marker = 0; /* processed the marker */
  172092. return JPEG_REACHED_EOI;
  172093. case M_DAC:
  172094. if (! get_dac(cinfo))
  172095. return JPEG_SUSPENDED;
  172096. break;
  172097. case M_DHT:
  172098. if (! get_dht(cinfo))
  172099. return JPEG_SUSPENDED;
  172100. break;
  172101. case M_DQT:
  172102. if (! get_dqt(cinfo))
  172103. return JPEG_SUSPENDED;
  172104. break;
  172105. case M_DRI:
  172106. if (! get_dri(cinfo))
  172107. return JPEG_SUSPENDED;
  172108. break;
  172109. case M_APP0:
  172110. case M_APP1:
  172111. case M_APP2:
  172112. case M_APP3:
  172113. case M_APP4:
  172114. case M_APP5:
  172115. case M_APP6:
  172116. case M_APP7:
  172117. case M_APP8:
  172118. case M_APP9:
  172119. case M_APP10:
  172120. case M_APP11:
  172121. case M_APP12:
  172122. case M_APP13:
  172123. case M_APP14:
  172124. case M_APP15:
  172125. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  172126. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  172127. return JPEG_SUSPENDED;
  172128. break;
  172129. case M_COM:
  172130. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  172131. return JPEG_SUSPENDED;
  172132. break;
  172133. case M_RST0: /* these are all parameterless */
  172134. case M_RST1:
  172135. case M_RST2:
  172136. case M_RST3:
  172137. case M_RST4:
  172138. case M_RST5:
  172139. case M_RST6:
  172140. case M_RST7:
  172141. case M_TEM:
  172142. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  172143. break;
  172144. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  172145. if (! skip_variable(cinfo))
  172146. return JPEG_SUSPENDED;
  172147. break;
  172148. default: /* must be DHP, EXP, JPGn, or RESn */
  172149. /* For now, we treat the reserved markers as fatal errors since they are
  172150. * likely to be used to signal incompatible JPEG Part 3 extensions.
  172151. * Once the JPEG 3 version-number marker is well defined, this code
  172152. * ought to change!
  172153. */
  172154. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  172155. break;
  172156. }
  172157. /* Successfully processed marker, so reset state variable */
  172158. cinfo->unread_marker = 0;
  172159. } /* end loop */
  172160. }
  172161. /*
  172162. * Read a restart marker, which is expected to appear next in the datastream;
  172163. * if the marker is not there, take appropriate recovery action.
  172164. * Returns FALSE if suspension is required.
  172165. *
  172166. * This is called by the entropy decoder after it has read an appropriate
  172167. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  172168. * has already read a marker from the data source. Under normal conditions
  172169. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  172170. * it holds a marker which the decoder will be unable to read past.
  172171. */
  172172. METHODDEF(boolean)
  172173. read_restart_marker (j_decompress_ptr cinfo)
  172174. {
  172175. /* Obtain a marker unless we already did. */
  172176. /* Note that next_marker will complain if it skips any data. */
  172177. if (cinfo->unread_marker == 0) {
  172178. if (! next_marker(cinfo))
  172179. return FALSE;
  172180. }
  172181. if (cinfo->unread_marker ==
  172182. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  172183. /* Normal case --- swallow the marker and let entropy decoder continue */
  172184. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  172185. cinfo->unread_marker = 0;
  172186. } else {
  172187. /* Uh-oh, the restart markers have been messed up. */
  172188. /* Let the data source manager determine how to resync. */
  172189. if (! (*cinfo->src->resync_to_restart) (cinfo,
  172190. cinfo->marker->next_restart_num))
  172191. return FALSE;
  172192. }
  172193. /* Update next-restart state */
  172194. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172195. return TRUE;
  172196. }
  172197. /*
  172198. * This is the default resync_to_restart method for data source managers
  172199. * to use if they don't have any better approach. Some data source managers
  172200. * may be able to back up, or may have additional knowledge about the data
  172201. * which permits a more intelligent recovery strategy; such managers would
  172202. * presumably supply their own resync method.
  172203. *
  172204. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172205. * the restart marker it was expecting. (This code is *not* used unless
  172206. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172207. * the marker code actually found (might be anything, except 0 or FF).
  172208. * The desired restart marker number (0..7) is passed as a parameter.
  172209. * This routine is supposed to apply whatever error recovery strategy seems
  172210. * appropriate in order to position the input stream to the next data segment.
  172211. * Note that cinfo->unread_marker is treated as a marker appearing before
  172212. * the current data-source input point; usually it should be reset to zero
  172213. * before returning.
  172214. * Returns FALSE if suspension is required.
  172215. *
  172216. * This implementation is substantially constrained by wanting to treat the
  172217. * input as a data stream; this means we can't back up. Therefore, we have
  172218. * only the following actions to work with:
  172219. * 1. Simply discard the marker and let the entropy decoder resume at next
  172220. * byte of file.
  172221. * 2. Read forward until we find another marker, discarding intervening
  172222. * data. (In theory we could look ahead within the current bufferload,
  172223. * without having to discard data if we don't find the desired marker.
  172224. * This idea is not implemented here, in part because it makes behavior
  172225. * dependent on buffer size and chance buffer-boundary positions.)
  172226. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172227. * This will cause the entropy decoder to process an empty data segment,
  172228. * inserting dummy zeroes, and then we will reprocess the marker.
  172229. *
  172230. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172231. * appropriate if the found marker is a future restart marker (indicating
  172232. * that we have missed the desired restart marker, probably because it got
  172233. * corrupted).
  172234. * We apply #2 or #3 if the found marker is a restart marker no more than
  172235. * two counts behind or ahead of the expected one. We also apply #2 if the
  172236. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172237. * If the found marker is a restart marker more than 2 counts away, we do #1
  172238. * (too much risk that the marker is erroneous; with luck we will be able to
  172239. * resync at some future point).
  172240. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172241. * overrunning the end of a scan. An implementation limited to single-scan
  172242. * files might find it better to apply #2 for markers other than EOI, since
  172243. * any other marker would have to be bogus data in that case.
  172244. */
  172245. GLOBAL(boolean)
  172246. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172247. {
  172248. int marker = cinfo->unread_marker;
  172249. int action = 1;
  172250. /* Always put up a warning. */
  172251. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172252. /* Outer loop handles repeated decision after scanning forward. */
  172253. for (;;) {
  172254. if (marker < (int) M_SOF0)
  172255. action = 2; /* invalid marker */
  172256. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172257. action = 3; /* valid non-restart marker */
  172258. else {
  172259. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172260. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172261. action = 3; /* one of the next two expected restarts */
  172262. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172263. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172264. action = 2; /* a prior restart, so advance */
  172265. else
  172266. action = 1; /* desired restart or too far away */
  172267. }
  172268. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172269. switch (action) {
  172270. case 1:
  172271. /* Discard marker and let entropy decoder resume processing. */
  172272. cinfo->unread_marker = 0;
  172273. return TRUE;
  172274. case 2:
  172275. /* Scan to the next marker, and repeat the decision loop. */
  172276. if (! next_marker(cinfo))
  172277. return FALSE;
  172278. marker = cinfo->unread_marker;
  172279. break;
  172280. case 3:
  172281. /* Return without advancing past this marker. */
  172282. /* Entropy decoder will be forced to process an empty segment. */
  172283. return TRUE;
  172284. }
  172285. } /* end loop */
  172286. }
  172287. /*
  172288. * Reset marker processing state to begin a fresh datastream.
  172289. */
  172290. METHODDEF(void)
  172291. reset_marker_reader (j_decompress_ptr cinfo)
  172292. {
  172293. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172294. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172295. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172296. cinfo->unread_marker = 0; /* no pending marker */
  172297. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172298. marker->pub.saw_SOF = FALSE;
  172299. marker->pub.discarded_bytes = 0;
  172300. marker->cur_marker = NULL;
  172301. }
  172302. /*
  172303. * Initialize the marker reader module.
  172304. * This is called only once, when the decompression object is created.
  172305. */
  172306. GLOBAL(void)
  172307. jinit_marker_reader (j_decompress_ptr cinfo)
  172308. {
  172309. my_marker_ptr2 marker;
  172310. int i;
  172311. /* Create subobject in permanent pool */
  172312. marker = (my_marker_ptr2)
  172313. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172314. SIZEOF(my_marker_reader));
  172315. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172316. /* Initialize public method pointers */
  172317. marker->pub.reset_marker_reader = reset_marker_reader;
  172318. marker->pub.read_markers = read_markers;
  172319. marker->pub.read_restart_marker = read_restart_marker;
  172320. /* Initialize COM/APPn processing.
  172321. * By default, we examine and then discard APP0 and APP14,
  172322. * but simply discard COM and all other APPn.
  172323. */
  172324. marker->process_COM = skip_variable;
  172325. marker->length_limit_COM = 0;
  172326. for (i = 0; i < 16; i++) {
  172327. marker->process_APPn[i] = skip_variable;
  172328. marker->length_limit_APPn[i] = 0;
  172329. }
  172330. marker->process_APPn[0] = get_interesting_appn;
  172331. marker->process_APPn[14] = get_interesting_appn;
  172332. /* Reset marker processing state */
  172333. reset_marker_reader(cinfo);
  172334. }
  172335. /*
  172336. * Control saving of COM and APPn markers into marker_list.
  172337. */
  172338. #ifdef SAVE_MARKERS_SUPPORTED
  172339. GLOBAL(void)
  172340. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172341. unsigned int length_limit)
  172342. {
  172343. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172344. long maxlength;
  172345. jpeg_marker_parser_method processor;
  172346. /* Length limit mustn't be larger than what we can allocate
  172347. * (should only be a concern in a 16-bit environment).
  172348. */
  172349. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172350. if (((long) length_limit) > maxlength)
  172351. length_limit = (unsigned int) maxlength;
  172352. /* Choose processor routine to use.
  172353. * APP0/APP14 have special requirements.
  172354. */
  172355. if (length_limit) {
  172356. processor = save_marker;
  172357. /* If saving APP0/APP14, save at least enough for our internal use. */
  172358. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172359. length_limit = APP0_DATA_LEN;
  172360. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172361. length_limit = APP14_DATA_LEN;
  172362. } else {
  172363. processor = skip_variable;
  172364. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172365. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172366. processor = get_interesting_appn;
  172367. }
  172368. if (marker_code == (int) M_COM) {
  172369. marker->process_COM = processor;
  172370. marker->length_limit_COM = length_limit;
  172371. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172372. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172373. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172374. } else
  172375. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172376. }
  172377. #endif /* SAVE_MARKERS_SUPPORTED */
  172378. /*
  172379. * Install a special processing method for COM or APPn markers.
  172380. */
  172381. GLOBAL(void)
  172382. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172383. jpeg_marker_parser_method routine)
  172384. {
  172385. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172386. if (marker_code == (int) M_COM)
  172387. marker->process_COM = routine;
  172388. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172389. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172390. else
  172391. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172392. }
  172393. /*** End of inlined file: jdmarker.c ***/
  172394. /*** Start of inlined file: jdmaster.c ***/
  172395. #define JPEG_INTERNALS
  172396. /* Private state */
  172397. typedef struct {
  172398. struct jpeg_decomp_master pub; /* public fields */
  172399. int pass_number; /* # of passes completed */
  172400. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172401. /* Saved references to initialized quantizer modules,
  172402. * in case we need to switch modes.
  172403. */
  172404. struct jpeg_color_quantizer * quantizer_1pass;
  172405. struct jpeg_color_quantizer * quantizer_2pass;
  172406. } my_decomp_master;
  172407. typedef my_decomp_master * my_master_ptr6;
  172408. /*
  172409. * Determine whether merged upsample/color conversion should be used.
  172410. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172411. */
  172412. LOCAL(boolean)
  172413. use_merged_upsample (j_decompress_ptr cinfo)
  172414. {
  172415. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172416. /* Merging is the equivalent of plain box-filter upsampling */
  172417. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172418. return FALSE;
  172419. /* jdmerge.c only supports YCC=>RGB color conversion */
  172420. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172421. cinfo->out_color_space != JCS_RGB ||
  172422. cinfo->out_color_components != RGB_PIXELSIZE)
  172423. return FALSE;
  172424. /* and it only handles 2h1v or 2h2v sampling ratios */
  172425. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172426. cinfo->comp_info[1].h_samp_factor != 1 ||
  172427. cinfo->comp_info[2].h_samp_factor != 1 ||
  172428. cinfo->comp_info[0].v_samp_factor > 2 ||
  172429. cinfo->comp_info[1].v_samp_factor != 1 ||
  172430. cinfo->comp_info[2].v_samp_factor != 1)
  172431. return FALSE;
  172432. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172433. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172434. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172435. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172436. return FALSE;
  172437. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172438. return TRUE; /* by golly, it'll work... */
  172439. #else
  172440. return FALSE;
  172441. #endif
  172442. }
  172443. /*
  172444. * Compute output image dimensions and related values.
  172445. * NOTE: this is exported for possible use by application.
  172446. * Hence it mustn't do anything that can't be done twice.
  172447. * Also note that it may be called before the master module is initialized!
  172448. */
  172449. GLOBAL(void)
  172450. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172451. /* Do computations that are needed before master selection phase */
  172452. {
  172453. #ifdef IDCT_SCALING_SUPPORTED
  172454. int ci;
  172455. jpeg_component_info *compptr;
  172456. #endif
  172457. /* Prevent application from calling me at wrong times */
  172458. if (cinfo->global_state != DSTATE_READY)
  172459. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172460. #ifdef IDCT_SCALING_SUPPORTED
  172461. /* Compute actual output image dimensions and DCT scaling choices. */
  172462. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172463. /* Provide 1/8 scaling */
  172464. cinfo->output_width = (JDIMENSION)
  172465. jdiv_round_up((long) cinfo->image_width, 8L);
  172466. cinfo->output_height = (JDIMENSION)
  172467. jdiv_round_up((long) cinfo->image_height, 8L);
  172468. cinfo->min_DCT_scaled_size = 1;
  172469. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172470. /* Provide 1/4 scaling */
  172471. cinfo->output_width = (JDIMENSION)
  172472. jdiv_round_up((long) cinfo->image_width, 4L);
  172473. cinfo->output_height = (JDIMENSION)
  172474. jdiv_round_up((long) cinfo->image_height, 4L);
  172475. cinfo->min_DCT_scaled_size = 2;
  172476. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172477. /* Provide 1/2 scaling */
  172478. cinfo->output_width = (JDIMENSION)
  172479. jdiv_round_up((long) cinfo->image_width, 2L);
  172480. cinfo->output_height = (JDIMENSION)
  172481. jdiv_round_up((long) cinfo->image_height, 2L);
  172482. cinfo->min_DCT_scaled_size = 4;
  172483. } else {
  172484. /* Provide 1/1 scaling */
  172485. cinfo->output_width = cinfo->image_width;
  172486. cinfo->output_height = cinfo->image_height;
  172487. cinfo->min_DCT_scaled_size = DCTSIZE;
  172488. }
  172489. /* In selecting the actual DCT scaling for each component, we try to
  172490. * scale up the chroma components via IDCT scaling rather than upsampling.
  172491. * This saves time if the upsampler gets to use 1:1 scaling.
  172492. * Note this code assumes that the supported DCT scalings are powers of 2.
  172493. */
  172494. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172495. ci++, compptr++) {
  172496. int ssize = cinfo->min_DCT_scaled_size;
  172497. while (ssize < DCTSIZE &&
  172498. (compptr->h_samp_factor * ssize * 2 <=
  172499. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172500. (compptr->v_samp_factor * ssize * 2 <=
  172501. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172502. ssize = ssize * 2;
  172503. }
  172504. compptr->DCT_scaled_size = ssize;
  172505. }
  172506. /* Recompute downsampled dimensions of components;
  172507. * application needs to know these if using raw downsampled data.
  172508. */
  172509. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172510. ci++, compptr++) {
  172511. /* Size in samples, after IDCT scaling */
  172512. compptr->downsampled_width = (JDIMENSION)
  172513. jdiv_round_up((long) cinfo->image_width *
  172514. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172515. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172516. compptr->downsampled_height = (JDIMENSION)
  172517. jdiv_round_up((long) cinfo->image_height *
  172518. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172519. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172520. }
  172521. #else /* !IDCT_SCALING_SUPPORTED */
  172522. /* Hardwire it to "no scaling" */
  172523. cinfo->output_width = cinfo->image_width;
  172524. cinfo->output_height = cinfo->image_height;
  172525. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172526. * and has computed unscaled downsampled_width and downsampled_height.
  172527. */
  172528. #endif /* IDCT_SCALING_SUPPORTED */
  172529. /* Report number of components in selected colorspace. */
  172530. /* Probably this should be in the color conversion module... */
  172531. switch (cinfo->out_color_space) {
  172532. case JCS_GRAYSCALE:
  172533. cinfo->out_color_components = 1;
  172534. break;
  172535. case JCS_RGB:
  172536. #if RGB_PIXELSIZE != 3
  172537. cinfo->out_color_components = RGB_PIXELSIZE;
  172538. break;
  172539. #endif /* else share code with YCbCr */
  172540. case JCS_YCbCr:
  172541. cinfo->out_color_components = 3;
  172542. break;
  172543. case JCS_CMYK:
  172544. case JCS_YCCK:
  172545. cinfo->out_color_components = 4;
  172546. break;
  172547. default: /* else must be same colorspace as in file */
  172548. cinfo->out_color_components = cinfo->num_components;
  172549. break;
  172550. }
  172551. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172552. cinfo->out_color_components);
  172553. /* See if upsampler will want to emit more than one row at a time */
  172554. if (use_merged_upsample(cinfo))
  172555. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172556. else
  172557. cinfo->rec_outbuf_height = 1;
  172558. }
  172559. /*
  172560. * Several decompression processes need to range-limit values to the range
  172561. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172562. * due to noise introduced by quantization, roundoff error, etc. These
  172563. * processes are inner loops and need to be as fast as possible. On most
  172564. * machines, particularly CPUs with pipelines or instruction prefetch,
  172565. * a (subscript-check-less) C table lookup
  172566. * x = sample_range_limit[x];
  172567. * is faster than explicit tests
  172568. * if (x < 0) x = 0;
  172569. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172570. * These processes all use a common table prepared by the routine below.
  172571. *
  172572. * For most steps we can mathematically guarantee that the initial value
  172573. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172574. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172575. * limiting step (just after the IDCT), a wildly out-of-range value is
  172576. * possible if the input data is corrupt. To avoid any chance of indexing
  172577. * off the end of memory and getting a bad-pointer trap, we perform the
  172578. * post-IDCT limiting thus:
  172579. * x = range_limit[x & MASK];
  172580. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172581. * samples. Under normal circumstances this is more than enough range and
  172582. * a correct output will be generated; with bogus input data the mask will
  172583. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172584. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172585. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172586. * So the post-IDCT limiting table ends up looking like this:
  172587. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172588. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172589. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172590. * 0,1,...,CENTERJSAMPLE-1
  172591. * Negative inputs select values from the upper half of the table after
  172592. * masking.
  172593. *
  172594. * We can save some space by overlapping the start of the post-IDCT table
  172595. * with the simpler range limiting table. The post-IDCT table begins at
  172596. * sample_range_limit + CENTERJSAMPLE.
  172597. *
  172598. * Note that the table is allocated in near data space on PCs; it's small
  172599. * enough and used often enough to justify this.
  172600. */
  172601. LOCAL(void)
  172602. prepare_range_limit_table (j_decompress_ptr cinfo)
  172603. /* Allocate and fill in the sample_range_limit table */
  172604. {
  172605. JSAMPLE * table;
  172606. int i;
  172607. table = (JSAMPLE *)
  172608. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172609. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172610. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172611. cinfo->sample_range_limit = table;
  172612. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172613. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172614. /* Main part of "simple" table: limit[x] = x */
  172615. for (i = 0; i <= MAXJSAMPLE; i++)
  172616. table[i] = (JSAMPLE) i;
  172617. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172618. /* End of simple table, rest of first half of post-IDCT table */
  172619. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172620. table[i] = MAXJSAMPLE;
  172621. /* Second half of post-IDCT table */
  172622. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172623. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172624. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172625. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172626. }
  172627. /*
  172628. * Master selection of decompression modules.
  172629. * This is done once at jpeg_start_decompress time. We determine
  172630. * which modules will be used and give them appropriate initialization calls.
  172631. * We also initialize the decompressor input side to begin consuming data.
  172632. *
  172633. * Since jpeg_read_header has finished, we know what is in the SOF
  172634. * and (first) SOS markers. We also have all the application parameter
  172635. * settings.
  172636. */
  172637. LOCAL(void)
  172638. master_selection (j_decompress_ptr cinfo)
  172639. {
  172640. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172641. boolean use_c_buffer;
  172642. long samplesperrow;
  172643. JDIMENSION jd_samplesperrow;
  172644. /* Initialize dimensions and other stuff */
  172645. jpeg_calc_output_dimensions(cinfo);
  172646. prepare_range_limit_table(cinfo);
  172647. /* Width of an output scanline must be representable as JDIMENSION. */
  172648. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172649. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172650. if ((long) jd_samplesperrow != samplesperrow)
  172651. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172652. /* Initialize my private state */
  172653. master->pass_number = 0;
  172654. master->using_merged_upsample = use_merged_upsample(cinfo);
  172655. /* Color quantizer selection */
  172656. master->quantizer_1pass = NULL;
  172657. master->quantizer_2pass = NULL;
  172658. /* No mode changes if not using buffered-image mode. */
  172659. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172660. cinfo->enable_1pass_quant = FALSE;
  172661. cinfo->enable_external_quant = FALSE;
  172662. cinfo->enable_2pass_quant = FALSE;
  172663. }
  172664. if (cinfo->quantize_colors) {
  172665. if (cinfo->raw_data_out)
  172666. ERREXIT(cinfo, JERR_NOTIMPL);
  172667. /* 2-pass quantizer only works in 3-component color space. */
  172668. if (cinfo->out_color_components != 3) {
  172669. cinfo->enable_1pass_quant = TRUE;
  172670. cinfo->enable_external_quant = FALSE;
  172671. cinfo->enable_2pass_quant = FALSE;
  172672. cinfo->colormap = NULL;
  172673. } else if (cinfo->colormap != NULL) {
  172674. cinfo->enable_external_quant = TRUE;
  172675. } else if (cinfo->two_pass_quantize) {
  172676. cinfo->enable_2pass_quant = TRUE;
  172677. } else {
  172678. cinfo->enable_1pass_quant = TRUE;
  172679. }
  172680. if (cinfo->enable_1pass_quant) {
  172681. #ifdef QUANT_1PASS_SUPPORTED
  172682. jinit_1pass_quantizer(cinfo);
  172683. master->quantizer_1pass = cinfo->cquantize;
  172684. #else
  172685. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172686. #endif
  172687. }
  172688. /* We use the 2-pass code to map to external colormaps. */
  172689. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172690. #ifdef QUANT_2PASS_SUPPORTED
  172691. jinit_2pass_quantizer(cinfo);
  172692. master->quantizer_2pass = cinfo->cquantize;
  172693. #else
  172694. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172695. #endif
  172696. }
  172697. /* If both quantizers are initialized, the 2-pass one is left active;
  172698. * this is necessary for starting with quantization to an external map.
  172699. */
  172700. }
  172701. /* Post-processing: in particular, color conversion first */
  172702. if (! cinfo->raw_data_out) {
  172703. if (master->using_merged_upsample) {
  172704. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172705. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172706. #else
  172707. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172708. #endif
  172709. } else {
  172710. jinit_color_deconverter(cinfo);
  172711. jinit_upsampler(cinfo);
  172712. }
  172713. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172714. }
  172715. /* Inverse DCT */
  172716. jinit_inverse_dct(cinfo);
  172717. /* Entropy decoding: either Huffman or arithmetic coding. */
  172718. if (cinfo->arith_code) {
  172719. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172720. } else {
  172721. if (cinfo->progressive_mode) {
  172722. #ifdef D_PROGRESSIVE_SUPPORTED
  172723. jinit_phuff_decoder(cinfo);
  172724. #else
  172725. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172726. #endif
  172727. } else
  172728. jinit_huff_decoder(cinfo);
  172729. }
  172730. /* Initialize principal buffer controllers. */
  172731. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172732. jinit_d_coef_controller(cinfo, use_c_buffer);
  172733. if (! cinfo->raw_data_out)
  172734. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172735. /* We can now tell the memory manager to allocate virtual arrays. */
  172736. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172737. /* Initialize input side of decompressor to consume first scan. */
  172738. (*cinfo->inputctl->start_input_pass) (cinfo);
  172739. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172740. /* If jpeg_start_decompress will read the whole file, initialize
  172741. * progress monitoring appropriately. The input step is counted
  172742. * as one pass.
  172743. */
  172744. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172745. cinfo->inputctl->has_multiple_scans) {
  172746. int nscans;
  172747. /* Estimate number of scans to set pass_limit. */
  172748. if (cinfo->progressive_mode) {
  172749. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172750. nscans = 2 + 3 * cinfo->num_components;
  172751. } else {
  172752. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172753. nscans = cinfo->num_components;
  172754. }
  172755. cinfo->progress->pass_counter = 0L;
  172756. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172757. cinfo->progress->completed_passes = 0;
  172758. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172759. /* Count the input pass as done */
  172760. master->pass_number++;
  172761. }
  172762. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172763. }
  172764. /*
  172765. * Per-pass setup.
  172766. * This is called at the beginning of each output pass. We determine which
  172767. * modules will be active during this pass and give them appropriate
  172768. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172769. * is a "real" output pass or a dummy pass for color quantization.
  172770. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172771. */
  172772. METHODDEF(void)
  172773. prepare_for_output_pass (j_decompress_ptr cinfo)
  172774. {
  172775. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172776. if (master->pub.is_dummy_pass) {
  172777. #ifdef QUANT_2PASS_SUPPORTED
  172778. /* Final pass of 2-pass quantization */
  172779. master->pub.is_dummy_pass = FALSE;
  172780. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172781. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172782. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172783. #else
  172784. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172785. #endif /* QUANT_2PASS_SUPPORTED */
  172786. } else {
  172787. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172788. /* Select new quantization method */
  172789. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172790. cinfo->cquantize = master->quantizer_2pass;
  172791. master->pub.is_dummy_pass = TRUE;
  172792. } else if (cinfo->enable_1pass_quant) {
  172793. cinfo->cquantize = master->quantizer_1pass;
  172794. } else {
  172795. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172796. }
  172797. }
  172798. (*cinfo->idct->start_pass) (cinfo);
  172799. (*cinfo->coef->start_output_pass) (cinfo);
  172800. if (! cinfo->raw_data_out) {
  172801. if (! master->using_merged_upsample)
  172802. (*cinfo->cconvert->start_pass) (cinfo);
  172803. (*cinfo->upsample->start_pass) (cinfo);
  172804. if (cinfo->quantize_colors)
  172805. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172806. (*cinfo->post->start_pass) (cinfo,
  172807. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172808. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172809. }
  172810. }
  172811. /* Set up progress monitor's pass info if present */
  172812. if (cinfo->progress != NULL) {
  172813. cinfo->progress->completed_passes = master->pass_number;
  172814. cinfo->progress->total_passes = master->pass_number +
  172815. (master->pub.is_dummy_pass ? 2 : 1);
  172816. /* In buffered-image mode, we assume one more output pass if EOI not
  172817. * yet reached, but no more passes if EOI has been reached.
  172818. */
  172819. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172820. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172821. }
  172822. }
  172823. }
  172824. /*
  172825. * Finish up at end of an output pass.
  172826. */
  172827. METHODDEF(void)
  172828. finish_output_pass (j_decompress_ptr cinfo)
  172829. {
  172830. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172831. if (cinfo->quantize_colors)
  172832. (*cinfo->cquantize->finish_pass) (cinfo);
  172833. master->pass_number++;
  172834. }
  172835. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172836. /*
  172837. * Switch to a new external colormap between output passes.
  172838. */
  172839. GLOBAL(void)
  172840. jpeg_new_colormap (j_decompress_ptr cinfo)
  172841. {
  172842. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172843. /* Prevent application from calling me at wrong times */
  172844. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172845. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172846. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172847. cinfo->colormap != NULL) {
  172848. /* Select 2-pass quantizer for external colormap use */
  172849. cinfo->cquantize = master->quantizer_2pass;
  172850. /* Notify quantizer of colormap change */
  172851. (*cinfo->cquantize->new_color_map) (cinfo);
  172852. master->pub.is_dummy_pass = FALSE; /* just in case */
  172853. } else
  172854. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172855. }
  172856. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172857. /*
  172858. * Initialize master decompression control and select active modules.
  172859. * This is performed at the start of jpeg_start_decompress.
  172860. */
  172861. GLOBAL(void)
  172862. jinit_master_decompress (j_decompress_ptr cinfo)
  172863. {
  172864. my_master_ptr6 master;
  172865. master = (my_master_ptr6)
  172866. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172867. SIZEOF(my_decomp_master));
  172868. cinfo->master = (struct jpeg_decomp_master *) master;
  172869. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172870. master->pub.finish_output_pass = finish_output_pass;
  172871. master->pub.is_dummy_pass = FALSE;
  172872. master_selection(cinfo);
  172873. }
  172874. /*** End of inlined file: jdmaster.c ***/
  172875. #undef FIX
  172876. /*** Start of inlined file: jdmerge.c ***/
  172877. #define JPEG_INTERNALS
  172878. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172879. /* Private subobject */
  172880. typedef struct {
  172881. struct jpeg_upsampler pub; /* public fields */
  172882. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172883. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172884. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172885. JSAMPARRAY output_buf));
  172886. /* Private state for YCC->RGB conversion */
  172887. int * Cr_r_tab; /* => table for Cr to R conversion */
  172888. int * Cb_b_tab; /* => table for Cb to B conversion */
  172889. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172890. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172891. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172892. * We need a "spare" row buffer to hold the second output row if the
  172893. * application provides just a one-row buffer; we also use the spare
  172894. * to discard the dummy last row if the image height is odd.
  172895. */
  172896. JSAMPROW spare_row;
  172897. boolean spare_full; /* T if spare buffer is occupied */
  172898. JDIMENSION out_row_width; /* samples per output row */
  172899. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172900. } my_upsampler;
  172901. typedef my_upsampler * my_upsample_ptr;
  172902. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172903. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172904. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172905. /*
  172906. * Initialize tables for YCC->RGB colorspace conversion.
  172907. * This is taken directly from jdcolor.c; see that file for more info.
  172908. */
  172909. LOCAL(void)
  172910. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172911. {
  172912. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172913. int i;
  172914. INT32 x;
  172915. SHIFT_TEMPS
  172916. upsample->Cr_r_tab = (int *)
  172917. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172918. (MAXJSAMPLE+1) * SIZEOF(int));
  172919. upsample->Cb_b_tab = (int *)
  172920. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172921. (MAXJSAMPLE+1) * SIZEOF(int));
  172922. upsample->Cr_g_tab = (INT32 *)
  172923. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172924. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172925. upsample->Cb_g_tab = (INT32 *)
  172926. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172927. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172928. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172929. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172930. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172931. /* Cr=>R value is nearest int to 1.40200 * x */
  172932. upsample->Cr_r_tab[i] = (int)
  172933. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172934. /* Cb=>B value is nearest int to 1.77200 * x */
  172935. upsample->Cb_b_tab[i] = (int)
  172936. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172937. /* Cr=>G value is scaled-up -0.71414 * x */
  172938. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172939. /* Cb=>G value is scaled-up -0.34414 * x */
  172940. /* We also add in ONE_HALF so that need not do it in inner loop */
  172941. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172942. }
  172943. }
  172944. /*
  172945. * Initialize for an upsampling pass.
  172946. */
  172947. METHODDEF(void)
  172948. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172949. {
  172950. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172951. /* Mark the spare buffer empty */
  172952. upsample->spare_full = FALSE;
  172953. /* Initialize total-height counter for detecting bottom of image */
  172954. upsample->rows_to_go = cinfo->output_height;
  172955. }
  172956. /*
  172957. * Control routine to do upsampling (and color conversion).
  172958. *
  172959. * The control routine just handles the row buffering considerations.
  172960. */
  172961. METHODDEF(void)
  172962. merged_2v_upsample (j_decompress_ptr cinfo,
  172963. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172964. JDIMENSION,
  172965. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172966. JDIMENSION out_rows_avail)
  172967. /* 2:1 vertical sampling case: may need a spare row. */
  172968. {
  172969. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172970. JSAMPROW work_ptrs[2];
  172971. JDIMENSION num_rows; /* number of rows returned to caller */
  172972. if (upsample->spare_full) {
  172973. /* If we have a spare row saved from a previous cycle, just return it. */
  172974. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172975. 1, upsample->out_row_width);
  172976. num_rows = 1;
  172977. upsample->spare_full = FALSE;
  172978. } else {
  172979. /* Figure number of rows to return to caller. */
  172980. num_rows = 2;
  172981. /* Not more than the distance to the end of the image. */
  172982. if (num_rows > upsample->rows_to_go)
  172983. num_rows = upsample->rows_to_go;
  172984. /* And not more than what the client can accept: */
  172985. out_rows_avail -= *out_row_ctr;
  172986. if (num_rows > out_rows_avail)
  172987. num_rows = out_rows_avail;
  172988. /* Create output pointer array for upsampler. */
  172989. work_ptrs[0] = output_buf[*out_row_ctr];
  172990. if (num_rows > 1) {
  172991. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172992. } else {
  172993. work_ptrs[1] = upsample->spare_row;
  172994. upsample->spare_full = TRUE;
  172995. }
  172996. /* Now do the upsampling. */
  172997. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172998. }
  172999. /* Adjust counts */
  173000. *out_row_ctr += num_rows;
  173001. upsample->rows_to_go -= num_rows;
  173002. /* When the buffer is emptied, declare this input row group consumed */
  173003. if (! upsample->spare_full)
  173004. (*in_row_group_ctr)++;
  173005. }
  173006. METHODDEF(void)
  173007. merged_1v_upsample (j_decompress_ptr cinfo,
  173008. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173009. JDIMENSION,
  173010. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173011. JDIMENSION)
  173012. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  173013. {
  173014. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173015. /* Just do the upsampling. */
  173016. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  173017. output_buf + *out_row_ctr);
  173018. /* Adjust counts */
  173019. (*out_row_ctr)++;
  173020. (*in_row_group_ctr)++;
  173021. }
  173022. /*
  173023. * These are the routines invoked by the control routines to do
  173024. * the actual upsampling/conversion. One row group is processed per call.
  173025. *
  173026. * Note: since we may be writing directly into application-supplied buffers,
  173027. * we have to be honest about the output width; we can't assume the buffer
  173028. * has been rounded up to an even width.
  173029. */
  173030. /*
  173031. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  173032. */
  173033. METHODDEF(void)
  173034. h2v1_merged_upsample (j_decompress_ptr cinfo,
  173035. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173036. JSAMPARRAY output_buf)
  173037. {
  173038. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173039. register int y, cred, cgreen, cblue;
  173040. int cb, cr;
  173041. register JSAMPROW outptr;
  173042. JSAMPROW inptr0, inptr1, inptr2;
  173043. JDIMENSION col;
  173044. /* copy these pointers into registers if possible */
  173045. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173046. int * Crrtab = upsample->Cr_r_tab;
  173047. int * Cbbtab = upsample->Cb_b_tab;
  173048. INT32 * Crgtab = upsample->Cr_g_tab;
  173049. INT32 * Cbgtab = upsample->Cb_g_tab;
  173050. SHIFT_TEMPS
  173051. inptr0 = input_buf[0][in_row_group_ctr];
  173052. inptr1 = input_buf[1][in_row_group_ctr];
  173053. inptr2 = input_buf[2][in_row_group_ctr];
  173054. outptr = output_buf[0];
  173055. /* Loop for each pair of output pixels */
  173056. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173057. /* Do the chroma part of the calculation */
  173058. cb = GETJSAMPLE(*inptr1++);
  173059. cr = GETJSAMPLE(*inptr2++);
  173060. cred = Crrtab[cr];
  173061. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173062. cblue = Cbbtab[cb];
  173063. /* Fetch 2 Y values and emit 2 pixels */
  173064. y = GETJSAMPLE(*inptr0++);
  173065. outptr[RGB_RED] = range_limit[y + cred];
  173066. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173067. outptr[RGB_BLUE] = range_limit[y + cblue];
  173068. outptr += RGB_PIXELSIZE;
  173069. y = GETJSAMPLE(*inptr0++);
  173070. outptr[RGB_RED] = range_limit[y + cred];
  173071. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173072. outptr[RGB_BLUE] = range_limit[y + cblue];
  173073. outptr += RGB_PIXELSIZE;
  173074. }
  173075. /* If image width is odd, do the last output column separately */
  173076. if (cinfo->output_width & 1) {
  173077. cb = GETJSAMPLE(*inptr1);
  173078. cr = GETJSAMPLE(*inptr2);
  173079. cred = Crrtab[cr];
  173080. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173081. cblue = Cbbtab[cb];
  173082. y = GETJSAMPLE(*inptr0);
  173083. outptr[RGB_RED] = range_limit[y + cred];
  173084. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173085. outptr[RGB_BLUE] = range_limit[y + cblue];
  173086. }
  173087. }
  173088. /*
  173089. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  173090. */
  173091. METHODDEF(void)
  173092. h2v2_merged_upsample (j_decompress_ptr cinfo,
  173093. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173094. JSAMPARRAY output_buf)
  173095. {
  173096. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173097. register int y, cred, cgreen, cblue;
  173098. int cb, cr;
  173099. register JSAMPROW outptr0, outptr1;
  173100. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  173101. JDIMENSION col;
  173102. /* copy these pointers into registers if possible */
  173103. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173104. int * Crrtab = upsample->Cr_r_tab;
  173105. int * Cbbtab = upsample->Cb_b_tab;
  173106. INT32 * Crgtab = upsample->Cr_g_tab;
  173107. INT32 * Cbgtab = upsample->Cb_g_tab;
  173108. SHIFT_TEMPS
  173109. inptr00 = input_buf[0][in_row_group_ctr*2];
  173110. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  173111. inptr1 = input_buf[1][in_row_group_ctr];
  173112. inptr2 = input_buf[2][in_row_group_ctr];
  173113. outptr0 = output_buf[0];
  173114. outptr1 = output_buf[1];
  173115. /* Loop for each group of output pixels */
  173116. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173117. /* Do the chroma part of the calculation */
  173118. cb = GETJSAMPLE(*inptr1++);
  173119. cr = GETJSAMPLE(*inptr2++);
  173120. cred = Crrtab[cr];
  173121. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173122. cblue = Cbbtab[cb];
  173123. /* Fetch 4 Y values and emit 4 pixels */
  173124. y = GETJSAMPLE(*inptr00++);
  173125. outptr0[RGB_RED] = range_limit[y + cred];
  173126. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173127. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173128. outptr0 += RGB_PIXELSIZE;
  173129. y = GETJSAMPLE(*inptr00++);
  173130. outptr0[RGB_RED] = range_limit[y + cred];
  173131. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173132. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173133. outptr0 += RGB_PIXELSIZE;
  173134. y = GETJSAMPLE(*inptr01++);
  173135. outptr1[RGB_RED] = range_limit[y + cred];
  173136. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173137. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173138. outptr1 += RGB_PIXELSIZE;
  173139. y = GETJSAMPLE(*inptr01++);
  173140. outptr1[RGB_RED] = range_limit[y + cred];
  173141. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173142. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173143. outptr1 += RGB_PIXELSIZE;
  173144. }
  173145. /* If image width is odd, do the last output column separately */
  173146. if (cinfo->output_width & 1) {
  173147. cb = GETJSAMPLE(*inptr1);
  173148. cr = GETJSAMPLE(*inptr2);
  173149. cred = Crrtab[cr];
  173150. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173151. cblue = Cbbtab[cb];
  173152. y = GETJSAMPLE(*inptr00);
  173153. outptr0[RGB_RED] = range_limit[y + cred];
  173154. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173155. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173156. y = GETJSAMPLE(*inptr01);
  173157. outptr1[RGB_RED] = range_limit[y + cred];
  173158. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173159. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173160. }
  173161. }
  173162. /*
  173163. * Module initialization routine for merged upsampling/color conversion.
  173164. *
  173165. * NB: this is called under the conditions determined by use_merged_upsample()
  173166. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  173167. * of this module; no safety checks are made here.
  173168. */
  173169. GLOBAL(void)
  173170. jinit_merged_upsampler (j_decompress_ptr cinfo)
  173171. {
  173172. my_upsample_ptr upsample;
  173173. upsample = (my_upsample_ptr)
  173174. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173175. SIZEOF(my_upsampler));
  173176. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173177. upsample->pub.start_pass = start_pass_merged_upsample;
  173178. upsample->pub.need_context_rows = FALSE;
  173179. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  173180. if (cinfo->max_v_samp_factor == 2) {
  173181. upsample->pub.upsample = merged_2v_upsample;
  173182. upsample->upmethod = h2v2_merged_upsample;
  173183. /* Allocate a spare row buffer */
  173184. upsample->spare_row = (JSAMPROW)
  173185. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173186. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  173187. } else {
  173188. upsample->pub.upsample = merged_1v_upsample;
  173189. upsample->upmethod = h2v1_merged_upsample;
  173190. /* No spare row needed */
  173191. upsample->spare_row = NULL;
  173192. }
  173193. build_ycc_rgb_table2(cinfo);
  173194. }
  173195. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  173196. /*** End of inlined file: jdmerge.c ***/
  173197. #undef ASSIGN_STATE
  173198. /*** Start of inlined file: jdphuff.c ***/
  173199. #define JPEG_INTERNALS
  173200. #ifdef D_PROGRESSIVE_SUPPORTED
  173201. /*
  173202. * Expanded entropy decoder object for progressive Huffman decoding.
  173203. *
  173204. * The savable_state subrecord contains fields that change within an MCU,
  173205. * but must not be updated permanently until we complete the MCU.
  173206. */
  173207. typedef struct {
  173208. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173209. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173210. } savable_state3;
  173211. /* This macro is to work around compilers with missing or broken
  173212. * structure assignment. You'll need to fix this code if you have
  173213. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173214. */
  173215. #ifndef NO_STRUCT_ASSIGN
  173216. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173217. #else
  173218. #if MAX_COMPS_IN_SCAN == 4
  173219. #define ASSIGN_STATE(dest,src) \
  173220. ((dest).EOBRUN = (src).EOBRUN, \
  173221. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173222. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173223. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173224. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173225. #endif
  173226. #endif
  173227. typedef struct {
  173228. struct jpeg_entropy_decoder pub; /* public fields */
  173229. /* These fields are loaded into local variables at start of each MCU.
  173230. * In case of suspension, we exit WITHOUT updating them.
  173231. */
  173232. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173233. savable_state3 saved; /* Other state at start of MCU */
  173234. /* These fields are NOT loaded into local working state. */
  173235. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173236. /* Pointers to derived tables (these workspaces have image lifespan) */
  173237. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173238. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173239. } phuff_entropy_decoder;
  173240. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173241. /* Forward declarations */
  173242. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173243. JBLOCKROW *MCU_data));
  173244. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173245. JBLOCKROW *MCU_data));
  173246. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173247. JBLOCKROW *MCU_data));
  173248. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173249. JBLOCKROW *MCU_data));
  173250. /*
  173251. * Initialize for a Huffman-compressed scan.
  173252. */
  173253. METHODDEF(void)
  173254. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173255. {
  173256. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173257. boolean is_DC_band, bad;
  173258. int ci, coefi, tbl;
  173259. int *coef_bit_ptr;
  173260. jpeg_component_info * compptr;
  173261. is_DC_band = (cinfo->Ss == 0);
  173262. /* Validate scan parameters */
  173263. bad = FALSE;
  173264. if (is_DC_band) {
  173265. if (cinfo->Se != 0)
  173266. bad = TRUE;
  173267. } else {
  173268. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173269. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173270. bad = TRUE;
  173271. /* AC scans may have only one component */
  173272. if (cinfo->comps_in_scan != 1)
  173273. bad = TRUE;
  173274. }
  173275. if (cinfo->Ah != 0) {
  173276. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173277. if (cinfo->Al != cinfo->Ah-1)
  173278. bad = TRUE;
  173279. }
  173280. if (cinfo->Al > 13) /* need not check for < 0 */
  173281. bad = TRUE;
  173282. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173283. * but the spec doesn't say so, and we try to be liberal about what we
  173284. * accept. Note: large Al values could result in out-of-range DC
  173285. * coefficients during early scans, leading to bizarre displays due to
  173286. * overflows in the IDCT math. But we won't crash.
  173287. */
  173288. if (bad)
  173289. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173290. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173291. /* Update progression status, and verify that scan order is legal.
  173292. * Note that inter-scan inconsistencies are treated as warnings
  173293. * not fatal errors ... not clear if this is right way to behave.
  173294. */
  173295. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173296. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173297. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173298. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173299. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173300. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173301. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173302. if (cinfo->Ah != expected)
  173303. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173304. coef_bit_ptr[coefi] = cinfo->Al;
  173305. }
  173306. }
  173307. /* Select MCU decoding routine */
  173308. if (cinfo->Ah == 0) {
  173309. if (is_DC_band)
  173310. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173311. else
  173312. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173313. } else {
  173314. if (is_DC_band)
  173315. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173316. else
  173317. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173318. }
  173319. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173320. compptr = cinfo->cur_comp_info[ci];
  173321. /* Make sure requested tables are present, and compute derived tables.
  173322. * We may build same derived table more than once, but it's not expensive.
  173323. */
  173324. if (is_DC_band) {
  173325. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173326. tbl = compptr->dc_tbl_no;
  173327. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173328. & entropy->derived_tbls[tbl]);
  173329. }
  173330. } else {
  173331. tbl = compptr->ac_tbl_no;
  173332. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173333. & entropy->derived_tbls[tbl]);
  173334. /* remember the single active table */
  173335. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173336. }
  173337. /* Initialize DC predictions to 0 */
  173338. entropy->saved.last_dc_val[ci] = 0;
  173339. }
  173340. /* Initialize bitread state variables */
  173341. entropy->bitstate.bits_left = 0;
  173342. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173343. entropy->pub.insufficient_data = FALSE;
  173344. /* Initialize private state variables */
  173345. entropy->saved.EOBRUN = 0;
  173346. /* Initialize restart counter */
  173347. entropy->restarts_to_go = cinfo->restart_interval;
  173348. }
  173349. /*
  173350. * Check for a restart marker & resynchronize decoder.
  173351. * Returns FALSE if must suspend.
  173352. */
  173353. LOCAL(boolean)
  173354. process_restartp (j_decompress_ptr cinfo)
  173355. {
  173356. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173357. int ci;
  173358. /* Throw away any unused bits remaining in bit buffer; */
  173359. /* include any full bytes in next_marker's count of discarded bytes */
  173360. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173361. entropy->bitstate.bits_left = 0;
  173362. /* Advance past the RSTn marker */
  173363. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173364. return FALSE;
  173365. /* Re-initialize DC predictions to 0 */
  173366. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173367. entropy->saved.last_dc_val[ci] = 0;
  173368. /* Re-init EOB run count, too */
  173369. entropy->saved.EOBRUN = 0;
  173370. /* Reset restart counter */
  173371. entropy->restarts_to_go = cinfo->restart_interval;
  173372. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173373. * against a marker. In that case we will end up treating the next data
  173374. * segment as empty, and we can avoid producing bogus output pixels by
  173375. * leaving the flag set.
  173376. */
  173377. if (cinfo->unread_marker == 0)
  173378. entropy->pub.insufficient_data = FALSE;
  173379. return TRUE;
  173380. }
  173381. /*
  173382. * Huffman MCU decoding.
  173383. * Each of these routines decodes and returns one MCU's worth of
  173384. * Huffman-compressed coefficients.
  173385. * The coefficients are reordered from zigzag order into natural array order,
  173386. * but are not dequantized.
  173387. *
  173388. * The i'th block of the MCU is stored into the block pointed to by
  173389. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173390. *
  173391. * We return FALSE if data source requested suspension. In that case no
  173392. * changes have been made to permanent state. (Exception: some output
  173393. * coefficients may already have been assigned. This is harmless for
  173394. * spectral selection, since we'll just re-assign them on the next call.
  173395. * Successive approximation AC refinement has to be more careful, however.)
  173396. */
  173397. /*
  173398. * MCU decoding for DC initial scan (either spectral selection,
  173399. * or first pass of successive approximation).
  173400. */
  173401. METHODDEF(boolean)
  173402. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173403. {
  173404. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173405. int Al = cinfo->Al;
  173406. register int s, r;
  173407. int blkn, ci;
  173408. JBLOCKROW block;
  173409. BITREAD_STATE_VARS;
  173410. savable_state3 state;
  173411. d_derived_tbl * tbl;
  173412. jpeg_component_info * compptr;
  173413. /* Process restart marker if needed; may have to suspend */
  173414. if (cinfo->restart_interval) {
  173415. if (entropy->restarts_to_go == 0)
  173416. if (! process_restartp(cinfo))
  173417. return FALSE;
  173418. }
  173419. /* If we've run out of data, just leave the MCU set to zeroes.
  173420. * This way, we return uniform gray for the remainder of the segment.
  173421. */
  173422. if (! entropy->pub.insufficient_data) {
  173423. /* Load up working state */
  173424. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173425. ASSIGN_STATE(state, entropy->saved);
  173426. /* Outer loop handles each block in the MCU */
  173427. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173428. block = MCU_data[blkn];
  173429. ci = cinfo->MCU_membership[blkn];
  173430. compptr = cinfo->cur_comp_info[ci];
  173431. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173432. /* Decode a single block's worth of coefficients */
  173433. /* Section F.2.2.1: decode the DC coefficient difference */
  173434. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173435. if (s) {
  173436. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173437. r = GET_BITS(s);
  173438. s = HUFF_EXTEND(r, s);
  173439. }
  173440. /* Convert DC difference to actual value, update last_dc_val */
  173441. s += state.last_dc_val[ci];
  173442. state.last_dc_val[ci] = s;
  173443. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173444. (*block)[0] = (JCOEF) (s << Al);
  173445. }
  173446. /* Completed MCU, so update state */
  173447. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173448. ASSIGN_STATE(entropy->saved, state);
  173449. }
  173450. /* Account for restart interval (no-op if not using restarts) */
  173451. entropy->restarts_to_go--;
  173452. return TRUE;
  173453. }
  173454. /*
  173455. * MCU decoding for AC initial scan (either spectral selection,
  173456. * or first pass of successive approximation).
  173457. */
  173458. METHODDEF(boolean)
  173459. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173460. {
  173461. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173462. int Se = cinfo->Se;
  173463. int Al = cinfo->Al;
  173464. register int s, k, r;
  173465. unsigned int EOBRUN;
  173466. JBLOCKROW block;
  173467. BITREAD_STATE_VARS;
  173468. d_derived_tbl * tbl;
  173469. /* Process restart marker if needed; may have to suspend */
  173470. if (cinfo->restart_interval) {
  173471. if (entropy->restarts_to_go == 0)
  173472. if (! process_restartp(cinfo))
  173473. return FALSE;
  173474. }
  173475. /* If we've run out of data, just leave the MCU set to zeroes.
  173476. * This way, we return uniform gray for the remainder of the segment.
  173477. */
  173478. if (! entropy->pub.insufficient_data) {
  173479. /* Load up working state.
  173480. * We can avoid loading/saving bitread state if in an EOB run.
  173481. */
  173482. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173483. /* There is always only one block per MCU */
  173484. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173485. EOBRUN--; /* ...process it now (we do nothing) */
  173486. else {
  173487. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173488. block = MCU_data[0];
  173489. tbl = entropy->ac_derived_tbl;
  173490. for (k = cinfo->Ss; k <= Se; k++) {
  173491. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173492. r = s >> 4;
  173493. s &= 15;
  173494. if (s) {
  173495. k += r;
  173496. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173497. r = GET_BITS(s);
  173498. s = HUFF_EXTEND(r, s);
  173499. /* Scale and output coefficient in natural (dezigzagged) order */
  173500. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173501. } else {
  173502. if (r == 15) { /* ZRL */
  173503. k += 15; /* skip 15 zeroes in band */
  173504. } else { /* EOBr, run length is 2^r + appended bits */
  173505. EOBRUN = 1 << r;
  173506. if (r) { /* EOBr, r > 0 */
  173507. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173508. r = GET_BITS(r);
  173509. EOBRUN += r;
  173510. }
  173511. EOBRUN--; /* this band is processed at this moment */
  173512. break; /* force end-of-band */
  173513. }
  173514. }
  173515. }
  173516. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173517. }
  173518. /* Completed MCU, so update state */
  173519. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173520. }
  173521. /* Account for restart interval (no-op if not using restarts) */
  173522. entropy->restarts_to_go--;
  173523. return TRUE;
  173524. }
  173525. /*
  173526. * MCU decoding for DC successive approximation refinement scan.
  173527. * Note: we assume such scans can be multi-component, although the spec
  173528. * is not very clear on the point.
  173529. */
  173530. METHODDEF(boolean)
  173531. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173532. {
  173533. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173534. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173535. int blkn;
  173536. JBLOCKROW block;
  173537. BITREAD_STATE_VARS;
  173538. /* Process restart marker if needed; may have to suspend */
  173539. if (cinfo->restart_interval) {
  173540. if (entropy->restarts_to_go == 0)
  173541. if (! process_restartp(cinfo))
  173542. return FALSE;
  173543. }
  173544. /* Not worth the cycles to check insufficient_data here,
  173545. * since we will not change the data anyway if we read zeroes.
  173546. */
  173547. /* Load up working state */
  173548. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173549. /* Outer loop handles each block in the MCU */
  173550. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173551. block = MCU_data[blkn];
  173552. /* Encoded data is simply the next bit of the two's-complement DC value */
  173553. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173554. if (GET_BITS(1))
  173555. (*block)[0] |= p1;
  173556. /* Note: since we use |=, repeating the assignment later is safe */
  173557. }
  173558. /* Completed MCU, so update state */
  173559. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173560. /* Account for restart interval (no-op if not using restarts) */
  173561. entropy->restarts_to_go--;
  173562. return TRUE;
  173563. }
  173564. /*
  173565. * MCU decoding for AC successive approximation refinement scan.
  173566. */
  173567. METHODDEF(boolean)
  173568. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173569. {
  173570. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173571. int Se = cinfo->Se;
  173572. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173573. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173574. register int s, k, r;
  173575. unsigned int EOBRUN;
  173576. JBLOCKROW block;
  173577. JCOEFPTR thiscoef;
  173578. BITREAD_STATE_VARS;
  173579. d_derived_tbl * tbl;
  173580. int num_newnz;
  173581. int newnz_pos[DCTSIZE2];
  173582. /* Process restart marker if needed; may have to suspend */
  173583. if (cinfo->restart_interval) {
  173584. if (entropy->restarts_to_go == 0)
  173585. if (! process_restartp(cinfo))
  173586. return FALSE;
  173587. }
  173588. /* If we've run out of data, don't modify the MCU.
  173589. */
  173590. if (! entropy->pub.insufficient_data) {
  173591. /* Load up working state */
  173592. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173593. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173594. /* There is always only one block per MCU */
  173595. block = MCU_data[0];
  173596. tbl = entropy->ac_derived_tbl;
  173597. /* If we are forced to suspend, we must undo the assignments to any newly
  173598. * nonzero coefficients in the block, because otherwise we'd get confused
  173599. * next time about which coefficients were already nonzero.
  173600. * But we need not undo addition of bits to already-nonzero coefficients;
  173601. * instead, we can test the current bit to see if we already did it.
  173602. */
  173603. num_newnz = 0;
  173604. /* initialize coefficient loop counter to start of band */
  173605. k = cinfo->Ss;
  173606. if (EOBRUN == 0) {
  173607. for (; k <= Se; k++) {
  173608. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173609. r = s >> 4;
  173610. s &= 15;
  173611. if (s) {
  173612. if (s != 1) /* size of new coef should always be 1 */
  173613. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173614. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173615. if (GET_BITS(1))
  173616. s = p1; /* newly nonzero coef is positive */
  173617. else
  173618. s = m1; /* newly nonzero coef is negative */
  173619. } else {
  173620. if (r != 15) {
  173621. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173622. if (r) {
  173623. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173624. r = GET_BITS(r);
  173625. EOBRUN += r;
  173626. }
  173627. break; /* rest of block is handled by EOB logic */
  173628. }
  173629. /* note s = 0 for processing ZRL */
  173630. }
  173631. /* Advance over already-nonzero coefs and r still-zero coefs,
  173632. * appending correction bits to the nonzeroes. A correction bit is 1
  173633. * if the absolute value of the coefficient must be increased.
  173634. */
  173635. do {
  173636. thiscoef = *block + jpeg_natural_order[k];
  173637. if (*thiscoef != 0) {
  173638. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173639. if (GET_BITS(1)) {
  173640. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173641. if (*thiscoef >= 0)
  173642. *thiscoef += p1;
  173643. else
  173644. *thiscoef += m1;
  173645. }
  173646. }
  173647. } else {
  173648. if (--r < 0)
  173649. break; /* reached target zero coefficient */
  173650. }
  173651. k++;
  173652. } while (k <= Se);
  173653. if (s) {
  173654. int pos = jpeg_natural_order[k];
  173655. /* Output newly nonzero coefficient */
  173656. (*block)[pos] = (JCOEF) s;
  173657. /* Remember its position in case we have to suspend */
  173658. newnz_pos[num_newnz++] = pos;
  173659. }
  173660. }
  173661. }
  173662. if (EOBRUN > 0) {
  173663. /* Scan any remaining coefficient positions after the end-of-band
  173664. * (the last newly nonzero coefficient, if any). Append a correction
  173665. * bit to each already-nonzero coefficient. A correction bit is 1
  173666. * if the absolute value of the coefficient must be increased.
  173667. */
  173668. for (; k <= Se; k++) {
  173669. thiscoef = *block + jpeg_natural_order[k];
  173670. if (*thiscoef != 0) {
  173671. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173672. if (GET_BITS(1)) {
  173673. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173674. if (*thiscoef >= 0)
  173675. *thiscoef += p1;
  173676. else
  173677. *thiscoef += m1;
  173678. }
  173679. }
  173680. }
  173681. }
  173682. /* Count one block completed in EOB run */
  173683. EOBRUN--;
  173684. }
  173685. /* Completed MCU, so update state */
  173686. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173687. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173688. }
  173689. /* Account for restart interval (no-op if not using restarts) */
  173690. entropy->restarts_to_go--;
  173691. return TRUE;
  173692. undoit:
  173693. /* Re-zero any output coefficients that we made newly nonzero */
  173694. while (num_newnz > 0)
  173695. (*block)[newnz_pos[--num_newnz]] = 0;
  173696. return FALSE;
  173697. }
  173698. /*
  173699. * Module initialization routine for progressive Huffman entropy decoding.
  173700. */
  173701. GLOBAL(void)
  173702. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173703. {
  173704. phuff_entropy_ptr2 entropy;
  173705. int *coef_bit_ptr;
  173706. int ci, i;
  173707. entropy = (phuff_entropy_ptr2)
  173708. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173709. SIZEOF(phuff_entropy_decoder));
  173710. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173711. entropy->pub.start_pass = start_pass_phuff_decoder;
  173712. /* Mark derived tables unallocated */
  173713. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173714. entropy->derived_tbls[i] = NULL;
  173715. }
  173716. /* Create progression status table */
  173717. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173718. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173719. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173720. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173721. for (ci = 0; ci < cinfo->num_components; ci++)
  173722. for (i = 0; i < DCTSIZE2; i++)
  173723. *coef_bit_ptr++ = -1;
  173724. }
  173725. #endif /* D_PROGRESSIVE_SUPPORTED */
  173726. /*** End of inlined file: jdphuff.c ***/
  173727. /*** Start of inlined file: jdpostct.c ***/
  173728. #define JPEG_INTERNALS
  173729. /* Private buffer controller object */
  173730. typedef struct {
  173731. struct jpeg_d_post_controller pub; /* public fields */
  173732. /* Color quantization source buffer: this holds output data from
  173733. * the upsample/color conversion step to be passed to the quantizer.
  173734. * For two-pass color quantization, we need a full-image buffer;
  173735. * for one-pass operation, a strip buffer is sufficient.
  173736. */
  173737. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173738. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173739. JDIMENSION strip_height; /* buffer size in rows */
  173740. /* for two-pass mode only: */
  173741. JDIMENSION starting_row; /* row # of first row in current strip */
  173742. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173743. } my_post_controller;
  173744. typedef my_post_controller * my_post_ptr;
  173745. /* Forward declarations */
  173746. METHODDEF(void) post_process_1pass
  173747. JPP((j_decompress_ptr cinfo,
  173748. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173749. JDIMENSION in_row_groups_avail,
  173750. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173751. JDIMENSION out_rows_avail));
  173752. #ifdef QUANT_2PASS_SUPPORTED
  173753. METHODDEF(void) post_process_prepass
  173754. JPP((j_decompress_ptr cinfo,
  173755. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173756. JDIMENSION in_row_groups_avail,
  173757. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173758. JDIMENSION out_rows_avail));
  173759. METHODDEF(void) post_process_2pass
  173760. JPP((j_decompress_ptr cinfo,
  173761. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173762. JDIMENSION in_row_groups_avail,
  173763. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173764. JDIMENSION out_rows_avail));
  173765. #endif
  173766. /*
  173767. * Initialize for a processing pass.
  173768. */
  173769. METHODDEF(void)
  173770. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173771. {
  173772. my_post_ptr post = (my_post_ptr) cinfo->post;
  173773. switch (pass_mode) {
  173774. case JBUF_PASS_THRU:
  173775. if (cinfo->quantize_colors) {
  173776. /* Single-pass processing with color quantization. */
  173777. post->pub.post_process_data = post_process_1pass;
  173778. /* We could be doing buffered-image output before starting a 2-pass
  173779. * color quantization; in that case, jinit_d_post_controller did not
  173780. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173781. */
  173782. if (post->buffer == NULL) {
  173783. post->buffer = (*cinfo->mem->access_virt_sarray)
  173784. ((j_common_ptr) cinfo, post->whole_image,
  173785. (JDIMENSION) 0, post->strip_height, TRUE);
  173786. }
  173787. } else {
  173788. /* For single-pass processing without color quantization,
  173789. * I have no work to do; just call the upsampler directly.
  173790. */
  173791. post->pub.post_process_data = cinfo->upsample->upsample;
  173792. }
  173793. break;
  173794. #ifdef QUANT_2PASS_SUPPORTED
  173795. case JBUF_SAVE_AND_PASS:
  173796. /* First pass of 2-pass quantization */
  173797. if (post->whole_image == NULL)
  173798. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173799. post->pub.post_process_data = post_process_prepass;
  173800. break;
  173801. case JBUF_CRANK_DEST:
  173802. /* Second pass of 2-pass quantization */
  173803. if (post->whole_image == NULL)
  173804. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173805. post->pub.post_process_data = post_process_2pass;
  173806. break;
  173807. #endif /* QUANT_2PASS_SUPPORTED */
  173808. default:
  173809. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173810. break;
  173811. }
  173812. post->starting_row = post->next_row = 0;
  173813. }
  173814. /*
  173815. * Process some data in the one-pass (strip buffer) case.
  173816. * This is used for color precision reduction as well as one-pass quantization.
  173817. */
  173818. METHODDEF(void)
  173819. post_process_1pass (j_decompress_ptr cinfo,
  173820. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173821. JDIMENSION in_row_groups_avail,
  173822. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173823. JDIMENSION out_rows_avail)
  173824. {
  173825. my_post_ptr post = (my_post_ptr) cinfo->post;
  173826. JDIMENSION num_rows, max_rows;
  173827. /* Fill the buffer, but not more than what we can dump out in one go. */
  173828. /* Note we rely on the upsampler to detect bottom of image. */
  173829. max_rows = out_rows_avail - *out_row_ctr;
  173830. if (max_rows > post->strip_height)
  173831. max_rows = post->strip_height;
  173832. num_rows = 0;
  173833. (*cinfo->upsample->upsample) (cinfo,
  173834. input_buf, in_row_group_ctr, in_row_groups_avail,
  173835. post->buffer, &num_rows, max_rows);
  173836. /* Quantize and emit data. */
  173837. (*cinfo->cquantize->color_quantize) (cinfo,
  173838. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173839. *out_row_ctr += num_rows;
  173840. }
  173841. #ifdef QUANT_2PASS_SUPPORTED
  173842. /*
  173843. * Process some data in the first pass of 2-pass quantization.
  173844. */
  173845. METHODDEF(void)
  173846. post_process_prepass (j_decompress_ptr cinfo,
  173847. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173848. JDIMENSION in_row_groups_avail,
  173849. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173850. JDIMENSION)
  173851. {
  173852. my_post_ptr post = (my_post_ptr) cinfo->post;
  173853. JDIMENSION old_next_row, num_rows;
  173854. /* Reposition virtual buffer if at start of strip. */
  173855. if (post->next_row == 0) {
  173856. post->buffer = (*cinfo->mem->access_virt_sarray)
  173857. ((j_common_ptr) cinfo, post->whole_image,
  173858. post->starting_row, post->strip_height, TRUE);
  173859. }
  173860. /* Upsample some data (up to a strip height's worth). */
  173861. old_next_row = post->next_row;
  173862. (*cinfo->upsample->upsample) (cinfo,
  173863. input_buf, in_row_group_ctr, in_row_groups_avail,
  173864. post->buffer, &post->next_row, post->strip_height);
  173865. /* Allow quantizer to scan new data. No data is emitted, */
  173866. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173867. if (post->next_row > old_next_row) {
  173868. num_rows = post->next_row - old_next_row;
  173869. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173870. (JSAMPARRAY) NULL, (int) num_rows);
  173871. *out_row_ctr += num_rows;
  173872. }
  173873. /* Advance if we filled the strip. */
  173874. if (post->next_row >= post->strip_height) {
  173875. post->starting_row += post->strip_height;
  173876. post->next_row = 0;
  173877. }
  173878. }
  173879. /*
  173880. * Process some data in the second pass of 2-pass quantization.
  173881. */
  173882. METHODDEF(void)
  173883. post_process_2pass (j_decompress_ptr cinfo,
  173884. JSAMPIMAGE, JDIMENSION *,
  173885. JDIMENSION,
  173886. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173887. JDIMENSION out_rows_avail)
  173888. {
  173889. my_post_ptr post = (my_post_ptr) cinfo->post;
  173890. JDIMENSION num_rows, max_rows;
  173891. /* Reposition virtual buffer if at start of strip. */
  173892. if (post->next_row == 0) {
  173893. post->buffer = (*cinfo->mem->access_virt_sarray)
  173894. ((j_common_ptr) cinfo, post->whole_image,
  173895. post->starting_row, post->strip_height, FALSE);
  173896. }
  173897. /* Determine number of rows to emit. */
  173898. num_rows = post->strip_height - post->next_row; /* available in strip */
  173899. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173900. if (num_rows > max_rows)
  173901. num_rows = max_rows;
  173902. /* We have to check bottom of image here, can't depend on upsampler. */
  173903. max_rows = cinfo->output_height - post->starting_row;
  173904. if (num_rows > max_rows)
  173905. num_rows = max_rows;
  173906. /* Quantize and emit data. */
  173907. (*cinfo->cquantize->color_quantize) (cinfo,
  173908. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173909. (int) num_rows);
  173910. *out_row_ctr += num_rows;
  173911. /* Advance if we filled the strip. */
  173912. post->next_row += num_rows;
  173913. if (post->next_row >= post->strip_height) {
  173914. post->starting_row += post->strip_height;
  173915. post->next_row = 0;
  173916. }
  173917. }
  173918. #endif /* QUANT_2PASS_SUPPORTED */
  173919. /*
  173920. * Initialize postprocessing controller.
  173921. */
  173922. GLOBAL(void)
  173923. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173924. {
  173925. my_post_ptr post;
  173926. post = (my_post_ptr)
  173927. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173928. SIZEOF(my_post_controller));
  173929. cinfo->post = (struct jpeg_d_post_controller *) post;
  173930. post->pub.start_pass = start_pass_dpost;
  173931. post->whole_image = NULL; /* flag for no virtual arrays */
  173932. post->buffer = NULL; /* flag for no strip buffer */
  173933. /* Create the quantization buffer, if needed */
  173934. if (cinfo->quantize_colors) {
  173935. /* The buffer strip height is max_v_samp_factor, which is typically
  173936. * an efficient number of rows for upsampling to return.
  173937. * (In the presence of output rescaling, we might want to be smarter?)
  173938. */
  173939. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173940. if (need_full_buffer) {
  173941. /* Two-pass color quantization: need full-image storage. */
  173942. /* We round up the number of rows to a multiple of the strip height. */
  173943. #ifdef QUANT_2PASS_SUPPORTED
  173944. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173945. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173946. cinfo->output_width * cinfo->out_color_components,
  173947. (JDIMENSION) jround_up((long) cinfo->output_height,
  173948. (long) post->strip_height),
  173949. post->strip_height);
  173950. #else
  173951. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173952. #endif /* QUANT_2PASS_SUPPORTED */
  173953. } else {
  173954. /* One-pass color quantization: just make a strip buffer. */
  173955. post->buffer = (*cinfo->mem->alloc_sarray)
  173956. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173957. cinfo->output_width * cinfo->out_color_components,
  173958. post->strip_height);
  173959. }
  173960. }
  173961. }
  173962. /*** End of inlined file: jdpostct.c ***/
  173963. #undef FIX
  173964. /*** Start of inlined file: jdsample.c ***/
  173965. #define JPEG_INTERNALS
  173966. /* Pointer to routine to upsample a single component */
  173967. typedef JMETHOD(void, upsample1_ptr,
  173968. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173969. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173970. /* Private subobject */
  173971. typedef struct {
  173972. struct jpeg_upsampler pub; /* public fields */
  173973. /* Color conversion buffer. When using separate upsampling and color
  173974. * conversion steps, this buffer holds one upsampled row group until it
  173975. * has been color converted and output.
  173976. * Note: we do not allocate any storage for component(s) which are full-size,
  173977. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173978. * simply set to point to the input data array, thereby avoiding copying.
  173979. */
  173980. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173981. /* Per-component upsampling method pointers */
  173982. upsample1_ptr methods[MAX_COMPONENTS];
  173983. int next_row_out; /* counts rows emitted from color_buf */
  173984. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173985. /* Height of an input row group for each component. */
  173986. int rowgroup_height[MAX_COMPONENTS];
  173987. /* These arrays save pixel expansion factors so that int_expand need not
  173988. * recompute them each time. They are unused for other upsampling methods.
  173989. */
  173990. UINT8 h_expand[MAX_COMPONENTS];
  173991. UINT8 v_expand[MAX_COMPONENTS];
  173992. } my_upsampler2;
  173993. typedef my_upsampler2 * my_upsample_ptr2;
  173994. /*
  173995. * Initialize for an upsampling pass.
  173996. */
  173997. METHODDEF(void)
  173998. start_pass_upsample (j_decompress_ptr cinfo)
  173999. {
  174000. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174001. /* Mark the conversion buffer empty */
  174002. upsample->next_row_out = cinfo->max_v_samp_factor;
  174003. /* Initialize total-height counter for detecting bottom of image */
  174004. upsample->rows_to_go = cinfo->output_height;
  174005. }
  174006. /*
  174007. * Control routine to do upsampling (and color conversion).
  174008. *
  174009. * In this version we upsample each component independently.
  174010. * We upsample one row group into the conversion buffer, then apply
  174011. * color conversion a row at a time.
  174012. */
  174013. METHODDEF(void)
  174014. sep_upsample (j_decompress_ptr cinfo,
  174015. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174016. JDIMENSION,
  174017. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174018. JDIMENSION out_rows_avail)
  174019. {
  174020. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174021. int ci;
  174022. jpeg_component_info * compptr;
  174023. JDIMENSION num_rows;
  174024. /* Fill the conversion buffer, if it's empty */
  174025. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  174026. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174027. ci++, compptr++) {
  174028. /* Invoke per-component upsample method. Notice we pass a POINTER
  174029. * to color_buf[ci], so that fullsize_upsample can change it.
  174030. */
  174031. (*upsample->methods[ci]) (cinfo, compptr,
  174032. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  174033. upsample->color_buf + ci);
  174034. }
  174035. upsample->next_row_out = 0;
  174036. }
  174037. /* Color-convert and emit rows */
  174038. /* How many we have in the buffer: */
  174039. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  174040. /* Not more than the distance to the end of the image. Need this test
  174041. * in case the image height is not a multiple of max_v_samp_factor:
  174042. */
  174043. if (num_rows > upsample->rows_to_go)
  174044. num_rows = upsample->rows_to_go;
  174045. /* And not more than what the client can accept: */
  174046. out_rows_avail -= *out_row_ctr;
  174047. if (num_rows > out_rows_avail)
  174048. num_rows = out_rows_avail;
  174049. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  174050. (JDIMENSION) upsample->next_row_out,
  174051. output_buf + *out_row_ctr,
  174052. (int) num_rows);
  174053. /* Adjust counts */
  174054. *out_row_ctr += num_rows;
  174055. upsample->rows_to_go -= num_rows;
  174056. upsample->next_row_out += num_rows;
  174057. /* When the buffer is emptied, declare this input row group consumed */
  174058. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  174059. (*in_row_group_ctr)++;
  174060. }
  174061. /*
  174062. * These are the routines invoked by sep_upsample to upsample pixel values
  174063. * of a single component. One row group is processed per call.
  174064. */
  174065. /*
  174066. * For full-size components, we just make color_buf[ci] point at the
  174067. * input buffer, and thus avoid copying any data. Note that this is
  174068. * safe only because sep_upsample doesn't declare the input row group
  174069. * "consumed" until we are done color converting and emitting it.
  174070. */
  174071. METHODDEF(void)
  174072. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  174073. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174074. {
  174075. *output_data_ptr = input_data;
  174076. }
  174077. /*
  174078. * This is a no-op version used for "uninteresting" components.
  174079. * These components will not be referenced by color conversion.
  174080. */
  174081. METHODDEF(void)
  174082. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  174083. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  174084. {
  174085. *output_data_ptr = NULL; /* safety check */
  174086. }
  174087. /*
  174088. * This version handles any integral sampling ratios.
  174089. * This is not used for typical JPEG files, so it need not be fast.
  174090. * Nor, for that matter, is it particularly accurate: the algorithm is
  174091. * simple replication of the input pixel onto the corresponding output
  174092. * pixels. The hi-falutin sampling literature refers to this as a
  174093. * "box filter". A box filter tends to introduce visible artifacts,
  174094. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  174095. * you would be well advised to improve this code.
  174096. */
  174097. METHODDEF(void)
  174098. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174099. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174100. {
  174101. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174102. JSAMPARRAY output_data = *output_data_ptr;
  174103. register JSAMPROW inptr, outptr;
  174104. register JSAMPLE invalue;
  174105. register int h;
  174106. JSAMPROW outend;
  174107. int h_expand, v_expand;
  174108. int inrow, outrow;
  174109. h_expand = upsample->h_expand[compptr->component_index];
  174110. v_expand = upsample->v_expand[compptr->component_index];
  174111. inrow = outrow = 0;
  174112. while (outrow < cinfo->max_v_samp_factor) {
  174113. /* Generate one output row with proper horizontal expansion */
  174114. inptr = input_data[inrow];
  174115. outptr = output_data[outrow];
  174116. outend = outptr + cinfo->output_width;
  174117. while (outptr < outend) {
  174118. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174119. for (h = h_expand; h > 0; h--) {
  174120. *outptr++ = invalue;
  174121. }
  174122. }
  174123. /* Generate any additional output rows by duplicating the first one */
  174124. if (v_expand > 1) {
  174125. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174126. v_expand-1, cinfo->output_width);
  174127. }
  174128. inrow++;
  174129. outrow += v_expand;
  174130. }
  174131. }
  174132. /*
  174133. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  174134. * It's still a box filter.
  174135. */
  174136. METHODDEF(void)
  174137. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174138. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174139. {
  174140. JSAMPARRAY output_data = *output_data_ptr;
  174141. register JSAMPROW inptr, outptr;
  174142. register JSAMPLE invalue;
  174143. JSAMPROW outend;
  174144. int inrow;
  174145. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174146. inptr = input_data[inrow];
  174147. outptr = output_data[inrow];
  174148. outend = outptr + cinfo->output_width;
  174149. while (outptr < outend) {
  174150. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174151. *outptr++ = invalue;
  174152. *outptr++ = invalue;
  174153. }
  174154. }
  174155. }
  174156. /*
  174157. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  174158. * It's still a box filter.
  174159. */
  174160. METHODDEF(void)
  174161. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174162. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174163. {
  174164. JSAMPARRAY output_data = *output_data_ptr;
  174165. register JSAMPROW inptr, outptr;
  174166. register JSAMPLE invalue;
  174167. JSAMPROW outend;
  174168. int inrow, outrow;
  174169. inrow = outrow = 0;
  174170. while (outrow < cinfo->max_v_samp_factor) {
  174171. inptr = input_data[inrow];
  174172. outptr = output_data[outrow];
  174173. outend = outptr + cinfo->output_width;
  174174. while (outptr < outend) {
  174175. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174176. *outptr++ = invalue;
  174177. *outptr++ = invalue;
  174178. }
  174179. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174180. 1, cinfo->output_width);
  174181. inrow++;
  174182. outrow += 2;
  174183. }
  174184. }
  174185. /*
  174186. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  174187. *
  174188. * The upsampling algorithm is linear interpolation between pixel centers,
  174189. * also known as a "triangle filter". This is a good compromise between
  174190. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  174191. * of the way between input pixel centers.
  174192. *
  174193. * A note about the "bias" calculations: when rounding fractional values to
  174194. * integer, we do not want to always round 0.5 up to the next integer.
  174195. * If we did that, we'd introduce a noticeable bias towards larger values.
  174196. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  174197. * alternate pixel locations (a simple ordered dither pattern).
  174198. */
  174199. METHODDEF(void)
  174200. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174201. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174202. {
  174203. JSAMPARRAY output_data = *output_data_ptr;
  174204. register JSAMPROW inptr, outptr;
  174205. register int invalue;
  174206. register JDIMENSION colctr;
  174207. int inrow;
  174208. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174209. inptr = input_data[inrow];
  174210. outptr = output_data[inrow];
  174211. /* Special case for first column */
  174212. invalue = GETJSAMPLE(*inptr++);
  174213. *outptr++ = (JSAMPLE) invalue;
  174214. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174215. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174216. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174217. invalue = GETJSAMPLE(*inptr++) * 3;
  174218. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174219. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174220. }
  174221. /* Special case for last column */
  174222. invalue = GETJSAMPLE(*inptr);
  174223. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174224. *outptr++ = (JSAMPLE) invalue;
  174225. }
  174226. }
  174227. /*
  174228. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174229. * Again a triangle filter; see comments for h2v1 case, above.
  174230. *
  174231. * It is OK for us to reference the adjacent input rows because we demanded
  174232. * context from the main buffer controller (see initialization code).
  174233. */
  174234. METHODDEF(void)
  174235. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174236. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174237. {
  174238. JSAMPARRAY output_data = *output_data_ptr;
  174239. register JSAMPROW inptr0, inptr1, outptr;
  174240. #if BITS_IN_JSAMPLE == 8
  174241. register int thiscolsum, lastcolsum, nextcolsum;
  174242. #else
  174243. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174244. #endif
  174245. register JDIMENSION colctr;
  174246. int inrow, outrow, v;
  174247. inrow = outrow = 0;
  174248. while (outrow < cinfo->max_v_samp_factor) {
  174249. for (v = 0; v < 2; v++) {
  174250. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174251. inptr0 = input_data[inrow];
  174252. if (v == 0) /* next nearest is row above */
  174253. inptr1 = input_data[inrow-1];
  174254. else /* next nearest is row below */
  174255. inptr1 = input_data[inrow+1];
  174256. outptr = output_data[outrow++];
  174257. /* Special case for first column */
  174258. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174259. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174260. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174261. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174262. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174263. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174264. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174265. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174266. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174267. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174268. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174269. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174270. }
  174271. /* Special case for last column */
  174272. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174273. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174274. }
  174275. inrow++;
  174276. }
  174277. }
  174278. /*
  174279. * Module initialization routine for upsampling.
  174280. */
  174281. GLOBAL(void)
  174282. jinit_upsampler (j_decompress_ptr cinfo)
  174283. {
  174284. my_upsample_ptr2 upsample;
  174285. int ci;
  174286. jpeg_component_info * compptr;
  174287. boolean need_buffer, do_fancy;
  174288. int h_in_group, v_in_group, h_out_group, v_out_group;
  174289. upsample = (my_upsample_ptr2)
  174290. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174291. SIZEOF(my_upsampler2));
  174292. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174293. upsample->pub.start_pass = start_pass_upsample;
  174294. upsample->pub.upsample = sep_upsample;
  174295. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174296. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174297. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174298. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174299. * so don't ask for it.
  174300. */
  174301. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174302. /* Verify we can handle the sampling factors, select per-component methods,
  174303. * and create storage as needed.
  174304. */
  174305. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174306. ci++, compptr++) {
  174307. /* Compute size of an "input group" after IDCT scaling. This many samples
  174308. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174309. */
  174310. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174311. cinfo->min_DCT_scaled_size;
  174312. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174313. cinfo->min_DCT_scaled_size;
  174314. h_out_group = cinfo->max_h_samp_factor;
  174315. v_out_group = cinfo->max_v_samp_factor;
  174316. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174317. need_buffer = TRUE;
  174318. if (! compptr->component_needed) {
  174319. /* Don't bother to upsample an uninteresting component. */
  174320. upsample->methods[ci] = noop_upsample;
  174321. need_buffer = FALSE;
  174322. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174323. /* Fullsize components can be processed without any work. */
  174324. upsample->methods[ci] = fullsize_upsample;
  174325. need_buffer = FALSE;
  174326. } else if (h_in_group * 2 == h_out_group &&
  174327. v_in_group == v_out_group) {
  174328. /* Special cases for 2h1v upsampling */
  174329. if (do_fancy && compptr->downsampled_width > 2)
  174330. upsample->methods[ci] = h2v1_fancy_upsample;
  174331. else
  174332. upsample->methods[ci] = h2v1_upsample;
  174333. } else if (h_in_group * 2 == h_out_group &&
  174334. v_in_group * 2 == v_out_group) {
  174335. /* Special cases for 2h2v upsampling */
  174336. if (do_fancy && compptr->downsampled_width > 2) {
  174337. upsample->methods[ci] = h2v2_fancy_upsample;
  174338. upsample->pub.need_context_rows = TRUE;
  174339. } else
  174340. upsample->methods[ci] = h2v2_upsample;
  174341. } else if ((h_out_group % h_in_group) == 0 &&
  174342. (v_out_group % v_in_group) == 0) {
  174343. /* Generic integral-factors upsampling method */
  174344. upsample->methods[ci] = int_upsample;
  174345. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174346. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174347. } else
  174348. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174349. if (need_buffer) {
  174350. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174351. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174352. (JDIMENSION) jround_up((long) cinfo->output_width,
  174353. (long) cinfo->max_h_samp_factor),
  174354. (JDIMENSION) cinfo->max_v_samp_factor);
  174355. }
  174356. }
  174357. }
  174358. /*** End of inlined file: jdsample.c ***/
  174359. /*** Start of inlined file: jdtrans.c ***/
  174360. #define JPEG_INTERNALS
  174361. /* Forward declarations */
  174362. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174363. /*
  174364. * Read the coefficient arrays from a JPEG file.
  174365. * jpeg_read_header must be completed before calling this.
  174366. *
  174367. * The entire image is read into a set of virtual coefficient-block arrays,
  174368. * one per component. The return value is a pointer to the array of
  174369. * virtual-array descriptors. These can be manipulated directly via the
  174370. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174371. * To release the memory occupied by the virtual arrays, call
  174372. * jpeg_finish_decompress() when done with the data.
  174373. *
  174374. * An alternative usage is to simply obtain access to the coefficient arrays
  174375. * during a buffered-image-mode decompression operation. This is allowed
  174376. * after any jpeg_finish_output() call. The arrays can be accessed until
  174377. * jpeg_finish_decompress() is called. (Note that any call to the library
  174378. * may reposition the arrays, so don't rely on access_virt_barray() results
  174379. * to stay valid across library calls.)
  174380. *
  174381. * Returns NULL if suspended. This case need be checked only if
  174382. * a suspending data source is used.
  174383. */
  174384. GLOBAL(jvirt_barray_ptr *)
  174385. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174386. {
  174387. if (cinfo->global_state == DSTATE_READY) {
  174388. /* First call: initialize active modules */
  174389. transdecode_master_selection(cinfo);
  174390. cinfo->global_state = DSTATE_RDCOEFS;
  174391. }
  174392. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174393. /* Absorb whole file into the coef buffer */
  174394. for (;;) {
  174395. int retcode;
  174396. /* Call progress monitor hook if present */
  174397. if (cinfo->progress != NULL)
  174398. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174399. /* Absorb some more input */
  174400. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174401. if (retcode == JPEG_SUSPENDED)
  174402. return NULL;
  174403. if (retcode == JPEG_REACHED_EOI)
  174404. break;
  174405. /* Advance progress counter if appropriate */
  174406. if (cinfo->progress != NULL &&
  174407. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174408. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174409. /* startup underestimated number of scans; ratchet up one scan */
  174410. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174411. }
  174412. }
  174413. }
  174414. /* Set state so that jpeg_finish_decompress does the right thing */
  174415. cinfo->global_state = DSTATE_STOPPING;
  174416. }
  174417. /* At this point we should be in state DSTATE_STOPPING if being used
  174418. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174419. * to the coefficients during a full buffered-image-mode decompression.
  174420. */
  174421. if ((cinfo->global_state == DSTATE_STOPPING ||
  174422. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174423. return cinfo->coef->coef_arrays;
  174424. }
  174425. /* Oops, improper usage */
  174426. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174427. return NULL; /* keep compiler happy */
  174428. }
  174429. /*
  174430. * Master selection of decompression modules for transcoding.
  174431. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174432. */
  174433. LOCAL(void)
  174434. transdecode_master_selection (j_decompress_ptr cinfo)
  174435. {
  174436. /* This is effectively a buffered-image operation. */
  174437. cinfo->buffered_image = TRUE;
  174438. /* Entropy decoding: either Huffman or arithmetic coding. */
  174439. if (cinfo->arith_code) {
  174440. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174441. } else {
  174442. if (cinfo->progressive_mode) {
  174443. #ifdef D_PROGRESSIVE_SUPPORTED
  174444. jinit_phuff_decoder(cinfo);
  174445. #else
  174446. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174447. #endif
  174448. } else
  174449. jinit_huff_decoder(cinfo);
  174450. }
  174451. /* Always get a full-image coefficient buffer. */
  174452. jinit_d_coef_controller(cinfo, TRUE);
  174453. /* We can now tell the memory manager to allocate virtual arrays. */
  174454. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174455. /* Initialize input side of decompressor to consume first scan. */
  174456. (*cinfo->inputctl->start_input_pass) (cinfo);
  174457. /* Initialize progress monitoring. */
  174458. if (cinfo->progress != NULL) {
  174459. int nscans;
  174460. /* Estimate number of scans to set pass_limit. */
  174461. if (cinfo->progressive_mode) {
  174462. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174463. nscans = 2 + 3 * cinfo->num_components;
  174464. } else if (cinfo->inputctl->has_multiple_scans) {
  174465. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174466. nscans = cinfo->num_components;
  174467. } else {
  174468. nscans = 1;
  174469. }
  174470. cinfo->progress->pass_counter = 0L;
  174471. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174472. cinfo->progress->completed_passes = 0;
  174473. cinfo->progress->total_passes = 1;
  174474. }
  174475. }
  174476. /*** End of inlined file: jdtrans.c ***/
  174477. /*** Start of inlined file: jfdctflt.c ***/
  174478. #define JPEG_INTERNALS
  174479. #ifdef DCT_FLOAT_SUPPORTED
  174480. /*
  174481. * This module is specialized to the case DCTSIZE = 8.
  174482. */
  174483. #if DCTSIZE != 8
  174484. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174485. #endif
  174486. /*
  174487. * Perform the forward DCT on one block of samples.
  174488. */
  174489. GLOBAL(void)
  174490. jpeg_fdct_float (FAST_FLOAT * data)
  174491. {
  174492. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174493. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174494. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174495. FAST_FLOAT *dataptr;
  174496. int ctr;
  174497. /* Pass 1: process rows. */
  174498. dataptr = data;
  174499. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174500. tmp0 = dataptr[0] + dataptr[7];
  174501. tmp7 = dataptr[0] - dataptr[7];
  174502. tmp1 = dataptr[1] + dataptr[6];
  174503. tmp6 = dataptr[1] - dataptr[6];
  174504. tmp2 = dataptr[2] + dataptr[5];
  174505. tmp5 = dataptr[2] - dataptr[5];
  174506. tmp3 = dataptr[3] + dataptr[4];
  174507. tmp4 = dataptr[3] - dataptr[4];
  174508. /* Even part */
  174509. tmp10 = tmp0 + tmp3; /* phase 2 */
  174510. tmp13 = tmp0 - tmp3;
  174511. tmp11 = tmp1 + tmp2;
  174512. tmp12 = tmp1 - tmp2;
  174513. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174514. dataptr[4] = tmp10 - tmp11;
  174515. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174516. dataptr[2] = tmp13 + z1; /* phase 5 */
  174517. dataptr[6] = tmp13 - z1;
  174518. /* Odd part */
  174519. tmp10 = tmp4 + tmp5; /* phase 2 */
  174520. tmp11 = tmp5 + tmp6;
  174521. tmp12 = tmp6 + tmp7;
  174522. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174523. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174524. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174525. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174526. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174527. z11 = tmp7 + z3; /* phase 5 */
  174528. z13 = tmp7 - z3;
  174529. dataptr[5] = z13 + z2; /* phase 6 */
  174530. dataptr[3] = z13 - z2;
  174531. dataptr[1] = z11 + z4;
  174532. dataptr[7] = z11 - z4;
  174533. dataptr += DCTSIZE; /* advance pointer to next row */
  174534. }
  174535. /* Pass 2: process columns. */
  174536. dataptr = data;
  174537. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174538. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174539. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174540. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174541. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174542. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174543. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174544. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174545. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174546. /* Even part */
  174547. tmp10 = tmp0 + tmp3; /* phase 2 */
  174548. tmp13 = tmp0 - tmp3;
  174549. tmp11 = tmp1 + tmp2;
  174550. tmp12 = tmp1 - tmp2;
  174551. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174552. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174553. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174554. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174555. dataptr[DCTSIZE*6] = tmp13 - z1;
  174556. /* Odd part */
  174557. tmp10 = tmp4 + tmp5; /* phase 2 */
  174558. tmp11 = tmp5 + tmp6;
  174559. tmp12 = tmp6 + tmp7;
  174560. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174561. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174562. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174563. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174564. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174565. z11 = tmp7 + z3; /* phase 5 */
  174566. z13 = tmp7 - z3;
  174567. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174568. dataptr[DCTSIZE*3] = z13 - z2;
  174569. dataptr[DCTSIZE*1] = z11 + z4;
  174570. dataptr[DCTSIZE*7] = z11 - z4;
  174571. dataptr++; /* advance pointer to next column */
  174572. }
  174573. }
  174574. #endif /* DCT_FLOAT_SUPPORTED */
  174575. /*** End of inlined file: jfdctflt.c ***/
  174576. /*** Start of inlined file: jfdctint.c ***/
  174577. #define JPEG_INTERNALS
  174578. #ifdef DCT_ISLOW_SUPPORTED
  174579. /*
  174580. * This module is specialized to the case DCTSIZE = 8.
  174581. */
  174582. #if DCTSIZE != 8
  174583. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174584. #endif
  174585. /*
  174586. * The poop on this scaling stuff is as follows:
  174587. *
  174588. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174589. * larger than the true DCT outputs. The final outputs are therefore
  174590. * a factor of N larger than desired; since N=8 this can be cured by
  174591. * a simple right shift at the end of the algorithm. The advantage of
  174592. * this arrangement is that we save two multiplications per 1-D DCT,
  174593. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174594. * In the IJG code, this factor of 8 is removed by the quantization step
  174595. * (in jcdctmgr.c), NOT in this module.
  174596. *
  174597. * We have to do addition and subtraction of the integer inputs, which
  174598. * is no problem, and multiplication by fractional constants, which is
  174599. * a problem to do in integer arithmetic. We multiply all the constants
  174600. * by CONST_SCALE and convert them to integer constants (thus retaining
  174601. * CONST_BITS bits of precision in the constants). After doing a
  174602. * multiplication we have to divide the product by CONST_SCALE, with proper
  174603. * rounding, to produce the correct output. This division can be done
  174604. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174605. * as long as possible so that partial sums can be added together with
  174606. * full fractional precision.
  174607. *
  174608. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174609. * they are represented to better-than-integral precision. These outputs
  174610. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174611. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174612. * array is INT32 anyway.)
  174613. *
  174614. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174615. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174616. * shows that the values given below are the most effective.
  174617. */
  174618. #if BITS_IN_JSAMPLE == 8
  174619. #define CONST_BITS 13
  174620. #define PASS1_BITS 2
  174621. #else
  174622. #define CONST_BITS 13
  174623. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174624. #endif
  174625. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174626. * causing a lot of useless floating-point operations at run time.
  174627. * To get around this we use the following pre-calculated constants.
  174628. * If you change CONST_BITS you may want to add appropriate values.
  174629. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174630. */
  174631. #if CONST_BITS == 13
  174632. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174633. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174634. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174635. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174636. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174637. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174638. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174639. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174640. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174641. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174642. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174643. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174644. #else
  174645. #define FIX_0_298631336 FIX(0.298631336)
  174646. #define FIX_0_390180644 FIX(0.390180644)
  174647. #define FIX_0_541196100 FIX(0.541196100)
  174648. #define FIX_0_765366865 FIX(0.765366865)
  174649. #define FIX_0_899976223 FIX(0.899976223)
  174650. #define FIX_1_175875602 FIX(1.175875602)
  174651. #define FIX_1_501321110 FIX(1.501321110)
  174652. #define FIX_1_847759065 FIX(1.847759065)
  174653. #define FIX_1_961570560 FIX(1.961570560)
  174654. #define FIX_2_053119869 FIX(2.053119869)
  174655. #define FIX_2_562915447 FIX(2.562915447)
  174656. #define FIX_3_072711026 FIX(3.072711026)
  174657. #endif
  174658. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174659. * For 8-bit samples with the recommended scaling, all the variable
  174660. * and constant values involved are no more than 16 bits wide, so a
  174661. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174662. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174663. */
  174664. #if BITS_IN_JSAMPLE == 8
  174665. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174666. #else
  174667. #define MULTIPLY(var,const) ((var) * (const))
  174668. #endif
  174669. /*
  174670. * Perform the forward DCT on one block of samples.
  174671. */
  174672. GLOBAL(void)
  174673. jpeg_fdct_islow (DCTELEM * data)
  174674. {
  174675. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174676. INT32 tmp10, tmp11, tmp12, tmp13;
  174677. INT32 z1, z2, z3, z4, z5;
  174678. DCTELEM *dataptr;
  174679. int ctr;
  174680. SHIFT_TEMPS
  174681. /* Pass 1: process rows. */
  174682. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174683. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174684. dataptr = data;
  174685. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174686. tmp0 = dataptr[0] + dataptr[7];
  174687. tmp7 = dataptr[0] - dataptr[7];
  174688. tmp1 = dataptr[1] + dataptr[6];
  174689. tmp6 = dataptr[1] - dataptr[6];
  174690. tmp2 = dataptr[2] + dataptr[5];
  174691. tmp5 = dataptr[2] - dataptr[5];
  174692. tmp3 = dataptr[3] + dataptr[4];
  174693. tmp4 = dataptr[3] - dataptr[4];
  174694. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174695. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174696. */
  174697. tmp10 = tmp0 + tmp3;
  174698. tmp13 = tmp0 - tmp3;
  174699. tmp11 = tmp1 + tmp2;
  174700. tmp12 = tmp1 - tmp2;
  174701. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174702. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174703. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174704. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174705. CONST_BITS-PASS1_BITS);
  174706. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174707. CONST_BITS-PASS1_BITS);
  174708. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174709. * cK represents cos(K*pi/16).
  174710. * i0..i3 in the paper are tmp4..tmp7 here.
  174711. */
  174712. z1 = tmp4 + tmp7;
  174713. z2 = tmp5 + tmp6;
  174714. z3 = tmp4 + tmp6;
  174715. z4 = tmp5 + tmp7;
  174716. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174717. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174718. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174719. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174720. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174721. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174722. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174723. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174724. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174725. z3 += z5;
  174726. z4 += z5;
  174727. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174728. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174729. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174730. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174731. dataptr += DCTSIZE; /* advance pointer to next row */
  174732. }
  174733. /* Pass 2: process columns.
  174734. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174735. * by an overall factor of 8.
  174736. */
  174737. dataptr = data;
  174738. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174739. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174740. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174741. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174742. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174743. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174744. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174745. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174746. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174747. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174748. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174749. */
  174750. tmp10 = tmp0 + tmp3;
  174751. tmp13 = tmp0 - tmp3;
  174752. tmp11 = tmp1 + tmp2;
  174753. tmp12 = tmp1 - tmp2;
  174754. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174755. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174756. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174757. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174758. CONST_BITS+PASS1_BITS);
  174759. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174760. CONST_BITS+PASS1_BITS);
  174761. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174762. * cK represents cos(K*pi/16).
  174763. * i0..i3 in the paper are tmp4..tmp7 here.
  174764. */
  174765. z1 = tmp4 + tmp7;
  174766. z2 = tmp5 + tmp6;
  174767. z3 = tmp4 + tmp6;
  174768. z4 = tmp5 + tmp7;
  174769. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174770. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174771. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174772. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174773. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174774. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174775. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174776. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174777. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174778. z3 += z5;
  174779. z4 += z5;
  174780. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174781. CONST_BITS+PASS1_BITS);
  174782. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174783. CONST_BITS+PASS1_BITS);
  174784. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174785. CONST_BITS+PASS1_BITS);
  174786. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174787. CONST_BITS+PASS1_BITS);
  174788. dataptr++; /* advance pointer to next column */
  174789. }
  174790. }
  174791. #endif /* DCT_ISLOW_SUPPORTED */
  174792. /*** End of inlined file: jfdctint.c ***/
  174793. #undef CONST_BITS
  174794. #undef MULTIPLY
  174795. #undef FIX_0_541196100
  174796. /*** Start of inlined file: jfdctfst.c ***/
  174797. #define JPEG_INTERNALS
  174798. #ifdef DCT_IFAST_SUPPORTED
  174799. /*
  174800. * This module is specialized to the case DCTSIZE = 8.
  174801. */
  174802. #if DCTSIZE != 8
  174803. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174804. #endif
  174805. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174806. * see jfdctint.c for more details. However, we choose to descale
  174807. * (right shift) multiplication products as soon as they are formed,
  174808. * rather than carrying additional fractional bits into subsequent additions.
  174809. * This compromises accuracy slightly, but it lets us save a few shifts.
  174810. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174811. * everywhere except in the multiplications proper; this saves a good deal
  174812. * of work on 16-bit-int machines.
  174813. *
  174814. * Again to save a few shifts, the intermediate results between pass 1 and
  174815. * pass 2 are not upscaled, but are represented only to integral precision.
  174816. *
  174817. * A final compromise is to represent the multiplicative constants to only
  174818. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174819. * machines, and may also reduce the cost of multiplication (since there
  174820. * are fewer one-bits in the constants).
  174821. */
  174822. #define CONST_BITS 8
  174823. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174824. * causing a lot of useless floating-point operations at run time.
  174825. * To get around this we use the following pre-calculated constants.
  174826. * If you change CONST_BITS you may want to add appropriate values.
  174827. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174828. */
  174829. #if CONST_BITS == 8
  174830. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174831. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174832. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174833. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174834. #else
  174835. #define FIX_0_382683433 FIX(0.382683433)
  174836. #define FIX_0_541196100 FIX(0.541196100)
  174837. #define FIX_0_707106781 FIX(0.707106781)
  174838. #define FIX_1_306562965 FIX(1.306562965)
  174839. #endif
  174840. /* We can gain a little more speed, with a further compromise in accuracy,
  174841. * by omitting the addition in a descaling shift. This yields an incorrectly
  174842. * rounded result half the time...
  174843. */
  174844. #ifndef USE_ACCURATE_ROUNDING
  174845. #undef DESCALE
  174846. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174847. #endif
  174848. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174849. * descale to yield a DCTELEM result.
  174850. */
  174851. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174852. /*
  174853. * Perform the forward DCT on one block of samples.
  174854. */
  174855. GLOBAL(void)
  174856. jpeg_fdct_ifast (DCTELEM * data)
  174857. {
  174858. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174859. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174860. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174861. DCTELEM *dataptr;
  174862. int ctr;
  174863. SHIFT_TEMPS
  174864. /* Pass 1: process rows. */
  174865. dataptr = data;
  174866. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174867. tmp0 = dataptr[0] + dataptr[7];
  174868. tmp7 = dataptr[0] - dataptr[7];
  174869. tmp1 = dataptr[1] + dataptr[6];
  174870. tmp6 = dataptr[1] - dataptr[6];
  174871. tmp2 = dataptr[2] + dataptr[5];
  174872. tmp5 = dataptr[2] - dataptr[5];
  174873. tmp3 = dataptr[3] + dataptr[4];
  174874. tmp4 = dataptr[3] - dataptr[4];
  174875. /* Even part */
  174876. tmp10 = tmp0 + tmp3; /* phase 2 */
  174877. tmp13 = tmp0 - tmp3;
  174878. tmp11 = tmp1 + tmp2;
  174879. tmp12 = tmp1 - tmp2;
  174880. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174881. dataptr[4] = tmp10 - tmp11;
  174882. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174883. dataptr[2] = tmp13 + z1; /* phase 5 */
  174884. dataptr[6] = tmp13 - z1;
  174885. /* Odd part */
  174886. tmp10 = tmp4 + tmp5; /* phase 2 */
  174887. tmp11 = tmp5 + tmp6;
  174888. tmp12 = tmp6 + tmp7;
  174889. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174890. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174891. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174892. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174893. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174894. z11 = tmp7 + z3; /* phase 5 */
  174895. z13 = tmp7 - z3;
  174896. dataptr[5] = z13 + z2; /* phase 6 */
  174897. dataptr[3] = z13 - z2;
  174898. dataptr[1] = z11 + z4;
  174899. dataptr[7] = z11 - z4;
  174900. dataptr += DCTSIZE; /* advance pointer to next row */
  174901. }
  174902. /* Pass 2: process columns. */
  174903. dataptr = data;
  174904. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174905. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174906. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174907. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174908. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174909. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174910. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174911. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174912. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174913. /* Even part */
  174914. tmp10 = tmp0 + tmp3; /* phase 2 */
  174915. tmp13 = tmp0 - tmp3;
  174916. tmp11 = tmp1 + tmp2;
  174917. tmp12 = tmp1 - tmp2;
  174918. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174919. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174920. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174921. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174922. dataptr[DCTSIZE*6] = tmp13 - z1;
  174923. /* Odd part */
  174924. tmp10 = tmp4 + tmp5; /* phase 2 */
  174925. tmp11 = tmp5 + tmp6;
  174926. tmp12 = tmp6 + tmp7;
  174927. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174928. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174929. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174930. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174931. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174932. z11 = tmp7 + z3; /* phase 5 */
  174933. z13 = tmp7 - z3;
  174934. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174935. dataptr[DCTSIZE*3] = z13 - z2;
  174936. dataptr[DCTSIZE*1] = z11 + z4;
  174937. dataptr[DCTSIZE*7] = z11 - z4;
  174938. dataptr++; /* advance pointer to next column */
  174939. }
  174940. }
  174941. #endif /* DCT_IFAST_SUPPORTED */
  174942. /*** End of inlined file: jfdctfst.c ***/
  174943. #undef FIX_0_541196100
  174944. /*** Start of inlined file: jidctflt.c ***/
  174945. #define JPEG_INTERNALS
  174946. #ifdef DCT_FLOAT_SUPPORTED
  174947. /*
  174948. * This module is specialized to the case DCTSIZE = 8.
  174949. */
  174950. #if DCTSIZE != 8
  174951. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174952. #endif
  174953. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174954. * entry; produce a float result.
  174955. */
  174956. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174957. /*
  174958. * Perform dequantization and inverse DCT on one block of coefficients.
  174959. */
  174960. GLOBAL(void)
  174961. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174962. JCOEFPTR coef_block,
  174963. JSAMPARRAY output_buf, JDIMENSION output_col)
  174964. {
  174965. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174966. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174967. FAST_FLOAT z5, z10, z11, z12, z13;
  174968. JCOEFPTR inptr;
  174969. FLOAT_MULT_TYPE * quantptr;
  174970. FAST_FLOAT * wsptr;
  174971. JSAMPROW outptr;
  174972. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174973. int ctr;
  174974. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174975. SHIFT_TEMPS
  174976. /* Pass 1: process columns from input, store into work array. */
  174977. inptr = coef_block;
  174978. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174979. wsptr = workspace;
  174980. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174981. /* Due to quantization, we will usually find that many of the input
  174982. * coefficients are zero, especially the AC terms. We can exploit this
  174983. * by short-circuiting the IDCT calculation for any column in which all
  174984. * the AC terms are zero. In that case each output is equal to the
  174985. * DC coefficient (with scale factor as needed).
  174986. * With typical images and quantization tables, half or more of the
  174987. * column DCT calculations can be simplified this way.
  174988. */
  174989. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174990. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174991. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174992. inptr[DCTSIZE*7] == 0) {
  174993. /* AC terms all zero */
  174994. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174995. wsptr[DCTSIZE*0] = dcval;
  174996. wsptr[DCTSIZE*1] = dcval;
  174997. wsptr[DCTSIZE*2] = dcval;
  174998. wsptr[DCTSIZE*3] = dcval;
  174999. wsptr[DCTSIZE*4] = dcval;
  175000. wsptr[DCTSIZE*5] = dcval;
  175001. wsptr[DCTSIZE*6] = dcval;
  175002. wsptr[DCTSIZE*7] = dcval;
  175003. inptr++; /* advance pointers to next column */
  175004. quantptr++;
  175005. wsptr++;
  175006. continue;
  175007. }
  175008. /* Even part */
  175009. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175010. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175011. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175012. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175013. tmp10 = tmp0 + tmp2; /* phase 3 */
  175014. tmp11 = tmp0 - tmp2;
  175015. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175016. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  175017. tmp0 = tmp10 + tmp13; /* phase 2 */
  175018. tmp3 = tmp10 - tmp13;
  175019. tmp1 = tmp11 + tmp12;
  175020. tmp2 = tmp11 - tmp12;
  175021. /* Odd part */
  175022. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175023. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175024. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175025. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175026. z13 = tmp6 + tmp5; /* phase 6 */
  175027. z10 = tmp6 - tmp5;
  175028. z11 = tmp4 + tmp7;
  175029. z12 = tmp4 - tmp7;
  175030. tmp7 = z11 + z13; /* phase 5 */
  175031. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  175032. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175033. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175034. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175035. tmp6 = tmp12 - tmp7; /* phase 2 */
  175036. tmp5 = tmp11 - tmp6;
  175037. tmp4 = tmp10 + tmp5;
  175038. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  175039. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  175040. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  175041. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  175042. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  175043. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  175044. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  175045. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  175046. inptr++; /* advance pointers to next column */
  175047. quantptr++;
  175048. wsptr++;
  175049. }
  175050. /* Pass 2: process rows from work array, store into output array. */
  175051. /* Note that we must descale the results by a factor of 8 == 2**3. */
  175052. wsptr = workspace;
  175053. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175054. outptr = output_buf[ctr] + output_col;
  175055. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175056. * However, the column calculation has created many nonzero AC terms, so
  175057. * the simplification applies less often (typically 5% to 10% of the time).
  175058. * And testing floats for zero is relatively expensive, so we don't bother.
  175059. */
  175060. /* Even part */
  175061. tmp10 = wsptr[0] + wsptr[4];
  175062. tmp11 = wsptr[0] - wsptr[4];
  175063. tmp13 = wsptr[2] + wsptr[6];
  175064. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  175065. tmp0 = tmp10 + tmp13;
  175066. tmp3 = tmp10 - tmp13;
  175067. tmp1 = tmp11 + tmp12;
  175068. tmp2 = tmp11 - tmp12;
  175069. /* Odd part */
  175070. z13 = wsptr[5] + wsptr[3];
  175071. z10 = wsptr[5] - wsptr[3];
  175072. z11 = wsptr[1] + wsptr[7];
  175073. z12 = wsptr[1] - wsptr[7];
  175074. tmp7 = z11 + z13;
  175075. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  175076. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175077. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175078. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175079. tmp6 = tmp12 - tmp7;
  175080. tmp5 = tmp11 - tmp6;
  175081. tmp4 = tmp10 + tmp5;
  175082. /* Final output stage: scale down by a factor of 8 and range-limit */
  175083. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  175084. & RANGE_MASK];
  175085. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  175086. & RANGE_MASK];
  175087. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  175088. & RANGE_MASK];
  175089. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  175090. & RANGE_MASK];
  175091. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  175092. & RANGE_MASK];
  175093. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  175094. & RANGE_MASK];
  175095. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  175096. & RANGE_MASK];
  175097. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  175098. & RANGE_MASK];
  175099. wsptr += DCTSIZE; /* advance pointer to next row */
  175100. }
  175101. }
  175102. #endif /* DCT_FLOAT_SUPPORTED */
  175103. /*** End of inlined file: jidctflt.c ***/
  175104. #undef CONST_BITS
  175105. #undef FIX_1_847759065
  175106. #undef MULTIPLY
  175107. #undef DEQUANTIZE
  175108. #undef DESCALE
  175109. /*** Start of inlined file: jidctfst.c ***/
  175110. #define JPEG_INTERNALS
  175111. #ifdef DCT_IFAST_SUPPORTED
  175112. /*
  175113. * This module is specialized to the case DCTSIZE = 8.
  175114. */
  175115. #if DCTSIZE != 8
  175116. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175117. #endif
  175118. /* Scaling decisions are generally the same as in the LL&M algorithm;
  175119. * see jidctint.c for more details. However, we choose to descale
  175120. * (right shift) multiplication products as soon as they are formed,
  175121. * rather than carrying additional fractional bits into subsequent additions.
  175122. * This compromises accuracy slightly, but it lets us save a few shifts.
  175123. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  175124. * everywhere except in the multiplications proper; this saves a good deal
  175125. * of work on 16-bit-int machines.
  175126. *
  175127. * The dequantized coefficients are not integers because the AA&N scaling
  175128. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  175129. * so that the first and second IDCT rounds have the same input scaling.
  175130. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  175131. * avoid a descaling shift; this compromises accuracy rather drastically
  175132. * for small quantization table entries, but it saves a lot of shifts.
  175133. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  175134. * so we use a much larger scaling factor to preserve accuracy.
  175135. *
  175136. * A final compromise is to represent the multiplicative constants to only
  175137. * 8 fractional bits, rather than 13. This saves some shifting work on some
  175138. * machines, and may also reduce the cost of multiplication (since there
  175139. * are fewer one-bits in the constants).
  175140. */
  175141. #if BITS_IN_JSAMPLE == 8
  175142. #define CONST_BITS 8
  175143. #define PASS1_BITS 2
  175144. #else
  175145. #define CONST_BITS 8
  175146. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175147. #endif
  175148. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175149. * causing a lot of useless floating-point operations at run time.
  175150. * To get around this we use the following pre-calculated constants.
  175151. * If you change CONST_BITS you may want to add appropriate values.
  175152. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175153. */
  175154. #if CONST_BITS == 8
  175155. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  175156. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  175157. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  175158. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  175159. #else
  175160. #define FIX_1_082392200 FIX(1.082392200)
  175161. #define FIX_1_414213562 FIX(1.414213562)
  175162. #define FIX_1_847759065 FIX(1.847759065)
  175163. #define FIX_2_613125930 FIX(2.613125930)
  175164. #endif
  175165. /* We can gain a little more speed, with a further compromise in accuracy,
  175166. * by omitting the addition in a descaling shift. This yields an incorrectly
  175167. * rounded result half the time...
  175168. */
  175169. #ifndef USE_ACCURATE_ROUNDING
  175170. #undef DESCALE
  175171. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175172. #endif
  175173. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175174. * descale to yield a DCTELEM result.
  175175. */
  175176. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175177. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175178. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  175179. * multiplication will do. For 12-bit data, the multiplier table is
  175180. * declared INT32, so a 32-bit multiply will be used.
  175181. */
  175182. #if BITS_IN_JSAMPLE == 8
  175183. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  175184. #else
  175185. #define DEQUANTIZE(coef,quantval) \
  175186. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  175187. #endif
  175188. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  175189. * We assume that int right shift is unsigned if INT32 right shift is.
  175190. */
  175191. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  175192. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  175193. #if BITS_IN_JSAMPLE == 8
  175194. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175195. #else
  175196. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  175197. #endif
  175198. #define IRIGHT_SHIFT(x,shft) \
  175199. ((ishift_temp = (x)) < 0 ? \
  175200. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175201. (ishift_temp >> (shft)))
  175202. #else
  175203. #define ISHIFT_TEMPS
  175204. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175205. #endif
  175206. #ifdef USE_ACCURATE_ROUNDING
  175207. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175208. #else
  175209. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175210. #endif
  175211. /*
  175212. * Perform dequantization and inverse DCT on one block of coefficients.
  175213. */
  175214. GLOBAL(void)
  175215. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175216. JCOEFPTR coef_block,
  175217. JSAMPARRAY output_buf, JDIMENSION output_col)
  175218. {
  175219. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175220. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175221. DCTELEM z5, z10, z11, z12, z13;
  175222. JCOEFPTR inptr;
  175223. IFAST_MULT_TYPE * quantptr;
  175224. int * wsptr;
  175225. JSAMPROW outptr;
  175226. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175227. int ctr;
  175228. int workspace[DCTSIZE2]; /* buffers data between passes */
  175229. SHIFT_TEMPS /* for DESCALE */
  175230. ISHIFT_TEMPS /* for IDESCALE */
  175231. /* Pass 1: process columns from input, store into work array. */
  175232. inptr = coef_block;
  175233. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175234. wsptr = workspace;
  175235. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175236. /* Due to quantization, we will usually find that many of the input
  175237. * coefficients are zero, especially the AC terms. We can exploit this
  175238. * by short-circuiting the IDCT calculation for any column in which all
  175239. * the AC terms are zero. In that case each output is equal to the
  175240. * DC coefficient (with scale factor as needed).
  175241. * With typical images and quantization tables, half or more of the
  175242. * column DCT calculations can be simplified this way.
  175243. */
  175244. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175245. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175246. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175247. inptr[DCTSIZE*7] == 0) {
  175248. /* AC terms all zero */
  175249. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175250. wsptr[DCTSIZE*0] = dcval;
  175251. wsptr[DCTSIZE*1] = dcval;
  175252. wsptr[DCTSIZE*2] = dcval;
  175253. wsptr[DCTSIZE*3] = dcval;
  175254. wsptr[DCTSIZE*4] = dcval;
  175255. wsptr[DCTSIZE*5] = dcval;
  175256. wsptr[DCTSIZE*6] = dcval;
  175257. wsptr[DCTSIZE*7] = dcval;
  175258. inptr++; /* advance pointers to next column */
  175259. quantptr++;
  175260. wsptr++;
  175261. continue;
  175262. }
  175263. /* Even part */
  175264. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175265. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175266. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175267. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175268. tmp10 = tmp0 + tmp2; /* phase 3 */
  175269. tmp11 = tmp0 - tmp2;
  175270. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175271. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175272. tmp0 = tmp10 + tmp13; /* phase 2 */
  175273. tmp3 = tmp10 - tmp13;
  175274. tmp1 = tmp11 + tmp12;
  175275. tmp2 = tmp11 - tmp12;
  175276. /* Odd part */
  175277. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175278. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175279. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175280. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175281. z13 = tmp6 + tmp5; /* phase 6 */
  175282. z10 = tmp6 - tmp5;
  175283. z11 = tmp4 + tmp7;
  175284. z12 = tmp4 - tmp7;
  175285. tmp7 = z11 + z13; /* phase 5 */
  175286. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175287. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175288. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175289. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175290. tmp6 = tmp12 - tmp7; /* phase 2 */
  175291. tmp5 = tmp11 - tmp6;
  175292. tmp4 = tmp10 + tmp5;
  175293. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175294. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175295. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175296. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175297. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175298. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175299. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175300. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175301. inptr++; /* advance pointers to next column */
  175302. quantptr++;
  175303. wsptr++;
  175304. }
  175305. /* Pass 2: process rows from work array, store into output array. */
  175306. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175307. /* and also undo the PASS1_BITS scaling. */
  175308. wsptr = workspace;
  175309. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175310. outptr = output_buf[ctr] + output_col;
  175311. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175312. * However, the column calculation has created many nonzero AC terms, so
  175313. * the simplification applies less often (typically 5% to 10% of the time).
  175314. * On machines with very fast multiplication, it's possible that the
  175315. * test takes more time than it's worth. In that case this section
  175316. * may be commented out.
  175317. */
  175318. #ifndef NO_ZERO_ROW_TEST
  175319. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175320. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175321. /* AC terms all zero */
  175322. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175323. & RANGE_MASK];
  175324. outptr[0] = dcval;
  175325. outptr[1] = dcval;
  175326. outptr[2] = dcval;
  175327. outptr[3] = dcval;
  175328. outptr[4] = dcval;
  175329. outptr[5] = dcval;
  175330. outptr[6] = dcval;
  175331. outptr[7] = dcval;
  175332. wsptr += DCTSIZE; /* advance pointer to next row */
  175333. continue;
  175334. }
  175335. #endif
  175336. /* Even part */
  175337. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175338. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175339. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175340. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175341. - tmp13;
  175342. tmp0 = tmp10 + tmp13;
  175343. tmp3 = tmp10 - tmp13;
  175344. tmp1 = tmp11 + tmp12;
  175345. tmp2 = tmp11 - tmp12;
  175346. /* Odd part */
  175347. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175348. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175349. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175350. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175351. tmp7 = z11 + z13; /* phase 5 */
  175352. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175353. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175354. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175355. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175356. tmp6 = tmp12 - tmp7; /* phase 2 */
  175357. tmp5 = tmp11 - tmp6;
  175358. tmp4 = tmp10 + tmp5;
  175359. /* Final output stage: scale down by a factor of 8 and range-limit */
  175360. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175361. & RANGE_MASK];
  175362. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175363. & RANGE_MASK];
  175364. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175365. & RANGE_MASK];
  175366. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175367. & RANGE_MASK];
  175368. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175369. & RANGE_MASK];
  175370. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175371. & RANGE_MASK];
  175372. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175373. & RANGE_MASK];
  175374. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175375. & RANGE_MASK];
  175376. wsptr += DCTSIZE; /* advance pointer to next row */
  175377. }
  175378. }
  175379. #endif /* DCT_IFAST_SUPPORTED */
  175380. /*** End of inlined file: jidctfst.c ***/
  175381. #undef CONST_BITS
  175382. #undef FIX_1_847759065
  175383. #undef MULTIPLY
  175384. #undef DEQUANTIZE
  175385. /*** Start of inlined file: jidctint.c ***/
  175386. #define JPEG_INTERNALS
  175387. #ifdef DCT_ISLOW_SUPPORTED
  175388. /*
  175389. * This module is specialized to the case DCTSIZE = 8.
  175390. */
  175391. #if DCTSIZE != 8
  175392. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175393. #endif
  175394. /*
  175395. * The poop on this scaling stuff is as follows:
  175396. *
  175397. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175398. * larger than the true IDCT outputs. The final outputs are therefore
  175399. * a factor of N larger than desired; since N=8 this can be cured by
  175400. * a simple right shift at the end of the algorithm. The advantage of
  175401. * this arrangement is that we save two multiplications per 1-D IDCT,
  175402. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175403. *
  175404. * We have to do addition and subtraction of the integer inputs, which
  175405. * is no problem, and multiplication by fractional constants, which is
  175406. * a problem to do in integer arithmetic. We multiply all the constants
  175407. * by CONST_SCALE and convert them to integer constants (thus retaining
  175408. * CONST_BITS bits of precision in the constants). After doing a
  175409. * multiplication we have to divide the product by CONST_SCALE, with proper
  175410. * rounding, to produce the correct output. This division can be done
  175411. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175412. * as long as possible so that partial sums can be added together with
  175413. * full fractional precision.
  175414. *
  175415. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175416. * they are represented to better-than-integral precision. These outputs
  175417. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175418. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175419. * intermediate INT32 array would be needed.)
  175420. *
  175421. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175422. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175423. * shows that the values given below are the most effective.
  175424. */
  175425. #if BITS_IN_JSAMPLE == 8
  175426. #define CONST_BITS 13
  175427. #define PASS1_BITS 2
  175428. #else
  175429. #define CONST_BITS 13
  175430. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175431. #endif
  175432. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175433. * causing a lot of useless floating-point operations at run time.
  175434. * To get around this we use the following pre-calculated constants.
  175435. * If you change CONST_BITS you may want to add appropriate values.
  175436. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175437. */
  175438. #if CONST_BITS == 13
  175439. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175440. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175441. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175442. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175443. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175444. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175445. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175446. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175447. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175448. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175449. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175450. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175451. #else
  175452. #define FIX_0_298631336 FIX(0.298631336)
  175453. #define FIX_0_390180644 FIX(0.390180644)
  175454. #define FIX_0_541196100 FIX(0.541196100)
  175455. #define FIX_0_765366865 FIX(0.765366865)
  175456. #define FIX_0_899976223 FIX(0.899976223)
  175457. #define FIX_1_175875602 FIX(1.175875602)
  175458. #define FIX_1_501321110 FIX(1.501321110)
  175459. #define FIX_1_847759065 FIX(1.847759065)
  175460. #define FIX_1_961570560 FIX(1.961570560)
  175461. #define FIX_2_053119869 FIX(2.053119869)
  175462. #define FIX_2_562915447 FIX(2.562915447)
  175463. #define FIX_3_072711026 FIX(3.072711026)
  175464. #endif
  175465. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175466. * For 8-bit samples with the recommended scaling, all the variable
  175467. * and constant values involved are no more than 16 bits wide, so a
  175468. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175469. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175470. */
  175471. #if BITS_IN_JSAMPLE == 8
  175472. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175473. #else
  175474. #define MULTIPLY(var,const) ((var) * (const))
  175475. #endif
  175476. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175477. * entry; produce an int result. In this module, both inputs and result
  175478. * are 16 bits or less, so either int or short multiply will work.
  175479. */
  175480. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175481. /*
  175482. * Perform dequantization and inverse DCT on one block of coefficients.
  175483. */
  175484. GLOBAL(void)
  175485. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175486. JCOEFPTR coef_block,
  175487. JSAMPARRAY output_buf, JDIMENSION output_col)
  175488. {
  175489. INT32 tmp0, tmp1, tmp2, tmp3;
  175490. INT32 tmp10, tmp11, tmp12, tmp13;
  175491. INT32 z1, z2, z3, z4, z5;
  175492. JCOEFPTR inptr;
  175493. ISLOW_MULT_TYPE * quantptr;
  175494. int * wsptr;
  175495. JSAMPROW outptr;
  175496. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175497. int ctr;
  175498. int workspace[DCTSIZE2]; /* buffers data between passes */
  175499. SHIFT_TEMPS
  175500. /* Pass 1: process columns from input, store into work array. */
  175501. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175502. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175503. inptr = coef_block;
  175504. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175505. wsptr = workspace;
  175506. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175507. /* Due to quantization, we will usually find that many of the input
  175508. * coefficients are zero, especially the AC terms. We can exploit this
  175509. * by short-circuiting the IDCT calculation for any column in which all
  175510. * the AC terms are zero. In that case each output is equal to the
  175511. * DC coefficient (with scale factor as needed).
  175512. * With typical images and quantization tables, half or more of the
  175513. * column DCT calculations can be simplified this way.
  175514. */
  175515. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175516. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175517. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175518. inptr[DCTSIZE*7] == 0) {
  175519. /* AC terms all zero */
  175520. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175521. wsptr[DCTSIZE*0] = dcval;
  175522. wsptr[DCTSIZE*1] = dcval;
  175523. wsptr[DCTSIZE*2] = dcval;
  175524. wsptr[DCTSIZE*3] = dcval;
  175525. wsptr[DCTSIZE*4] = dcval;
  175526. wsptr[DCTSIZE*5] = dcval;
  175527. wsptr[DCTSIZE*6] = dcval;
  175528. wsptr[DCTSIZE*7] = dcval;
  175529. inptr++; /* advance pointers to next column */
  175530. quantptr++;
  175531. wsptr++;
  175532. continue;
  175533. }
  175534. /* Even part: reverse the even part of the forward DCT. */
  175535. /* The rotator is sqrt(2)*c(-6). */
  175536. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175537. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175538. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175539. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175540. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175541. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175542. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175543. tmp0 = (z2 + z3) << CONST_BITS;
  175544. tmp1 = (z2 - z3) << CONST_BITS;
  175545. tmp10 = tmp0 + tmp3;
  175546. tmp13 = tmp0 - tmp3;
  175547. tmp11 = tmp1 + tmp2;
  175548. tmp12 = tmp1 - tmp2;
  175549. /* Odd part per figure 8; the matrix is unitary and hence its
  175550. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175551. */
  175552. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175553. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175554. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175555. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175556. z1 = tmp0 + tmp3;
  175557. z2 = tmp1 + tmp2;
  175558. z3 = tmp0 + tmp2;
  175559. z4 = tmp1 + tmp3;
  175560. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175561. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175562. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175563. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175564. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175565. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175566. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175567. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175568. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175569. z3 += z5;
  175570. z4 += z5;
  175571. tmp0 += z1 + z3;
  175572. tmp1 += z2 + z4;
  175573. tmp2 += z2 + z3;
  175574. tmp3 += z1 + z4;
  175575. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175576. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175577. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175578. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175579. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175580. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175581. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175582. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175583. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175584. inptr++; /* advance pointers to next column */
  175585. quantptr++;
  175586. wsptr++;
  175587. }
  175588. /* Pass 2: process rows from work array, store into output array. */
  175589. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175590. /* and also undo the PASS1_BITS scaling. */
  175591. wsptr = workspace;
  175592. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175593. outptr = output_buf[ctr] + output_col;
  175594. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175595. * However, the column calculation has created many nonzero AC terms, so
  175596. * the simplification applies less often (typically 5% to 10% of the time).
  175597. * On machines with very fast multiplication, it's possible that the
  175598. * test takes more time than it's worth. In that case this section
  175599. * may be commented out.
  175600. */
  175601. #ifndef NO_ZERO_ROW_TEST
  175602. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175603. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175604. /* AC terms all zero */
  175605. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175606. & RANGE_MASK];
  175607. outptr[0] = dcval;
  175608. outptr[1] = dcval;
  175609. outptr[2] = dcval;
  175610. outptr[3] = dcval;
  175611. outptr[4] = dcval;
  175612. outptr[5] = dcval;
  175613. outptr[6] = dcval;
  175614. outptr[7] = dcval;
  175615. wsptr += DCTSIZE; /* advance pointer to next row */
  175616. continue;
  175617. }
  175618. #endif
  175619. /* Even part: reverse the even part of the forward DCT. */
  175620. /* The rotator is sqrt(2)*c(-6). */
  175621. z2 = (INT32) wsptr[2];
  175622. z3 = (INT32) wsptr[6];
  175623. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175624. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175625. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175626. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175627. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175628. tmp10 = tmp0 + tmp3;
  175629. tmp13 = tmp0 - tmp3;
  175630. tmp11 = tmp1 + tmp2;
  175631. tmp12 = tmp1 - tmp2;
  175632. /* Odd part per figure 8; the matrix is unitary and hence its
  175633. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175634. */
  175635. tmp0 = (INT32) wsptr[7];
  175636. tmp1 = (INT32) wsptr[5];
  175637. tmp2 = (INT32) wsptr[3];
  175638. tmp3 = (INT32) wsptr[1];
  175639. z1 = tmp0 + tmp3;
  175640. z2 = tmp1 + tmp2;
  175641. z3 = tmp0 + tmp2;
  175642. z4 = tmp1 + tmp3;
  175643. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175644. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175645. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175646. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175647. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175648. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175649. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175650. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175651. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175652. z3 += z5;
  175653. z4 += z5;
  175654. tmp0 += z1 + z3;
  175655. tmp1 += z2 + z4;
  175656. tmp2 += z2 + z3;
  175657. tmp3 += z1 + z4;
  175658. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175659. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175660. CONST_BITS+PASS1_BITS+3)
  175661. & RANGE_MASK];
  175662. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175663. CONST_BITS+PASS1_BITS+3)
  175664. & RANGE_MASK];
  175665. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175666. CONST_BITS+PASS1_BITS+3)
  175667. & RANGE_MASK];
  175668. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175669. CONST_BITS+PASS1_BITS+3)
  175670. & RANGE_MASK];
  175671. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175672. CONST_BITS+PASS1_BITS+3)
  175673. & RANGE_MASK];
  175674. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175675. CONST_BITS+PASS1_BITS+3)
  175676. & RANGE_MASK];
  175677. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175678. CONST_BITS+PASS1_BITS+3)
  175679. & RANGE_MASK];
  175680. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175681. CONST_BITS+PASS1_BITS+3)
  175682. & RANGE_MASK];
  175683. wsptr += DCTSIZE; /* advance pointer to next row */
  175684. }
  175685. }
  175686. #endif /* DCT_ISLOW_SUPPORTED */
  175687. /*** End of inlined file: jidctint.c ***/
  175688. /*** Start of inlined file: jidctred.c ***/
  175689. #define JPEG_INTERNALS
  175690. #ifdef IDCT_SCALING_SUPPORTED
  175691. /*
  175692. * This module is specialized to the case DCTSIZE = 8.
  175693. */
  175694. #if DCTSIZE != 8
  175695. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175696. #endif
  175697. /* Scaling is the same as in jidctint.c. */
  175698. #if BITS_IN_JSAMPLE == 8
  175699. #define CONST_BITS 13
  175700. #define PASS1_BITS 2
  175701. #else
  175702. #define CONST_BITS 13
  175703. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175704. #endif
  175705. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175706. * causing a lot of useless floating-point operations at run time.
  175707. * To get around this we use the following pre-calculated constants.
  175708. * If you change CONST_BITS you may want to add appropriate values.
  175709. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175710. */
  175711. #if CONST_BITS == 13
  175712. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175713. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175714. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175715. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175716. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175717. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175718. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175719. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175720. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175721. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175722. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175723. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175724. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175725. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175726. #else
  175727. #define FIX_0_211164243 FIX(0.211164243)
  175728. #define FIX_0_509795579 FIX(0.509795579)
  175729. #define FIX_0_601344887 FIX(0.601344887)
  175730. #define FIX_0_720959822 FIX(0.720959822)
  175731. #define FIX_0_765366865 FIX(0.765366865)
  175732. #define FIX_0_850430095 FIX(0.850430095)
  175733. #define FIX_0_899976223 FIX(0.899976223)
  175734. #define FIX_1_061594337 FIX(1.061594337)
  175735. #define FIX_1_272758580 FIX(1.272758580)
  175736. #define FIX_1_451774981 FIX(1.451774981)
  175737. #define FIX_1_847759065 FIX(1.847759065)
  175738. #define FIX_2_172734803 FIX(2.172734803)
  175739. #define FIX_2_562915447 FIX(2.562915447)
  175740. #define FIX_3_624509785 FIX(3.624509785)
  175741. #endif
  175742. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175743. * For 8-bit samples with the recommended scaling, all the variable
  175744. * and constant values involved are no more than 16 bits wide, so a
  175745. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175746. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175747. */
  175748. #if BITS_IN_JSAMPLE == 8
  175749. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175750. #else
  175751. #define MULTIPLY(var,const) ((var) * (const))
  175752. #endif
  175753. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175754. * entry; produce an int result. In this module, both inputs and result
  175755. * are 16 bits or less, so either int or short multiply will work.
  175756. */
  175757. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175758. /*
  175759. * Perform dequantization and inverse DCT on one block of coefficients,
  175760. * producing a reduced-size 4x4 output block.
  175761. */
  175762. GLOBAL(void)
  175763. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175764. JCOEFPTR coef_block,
  175765. JSAMPARRAY output_buf, JDIMENSION output_col)
  175766. {
  175767. INT32 tmp0, tmp2, tmp10, tmp12;
  175768. INT32 z1, z2, z3, z4;
  175769. JCOEFPTR inptr;
  175770. ISLOW_MULT_TYPE * quantptr;
  175771. int * wsptr;
  175772. JSAMPROW outptr;
  175773. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175774. int ctr;
  175775. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175776. SHIFT_TEMPS
  175777. /* Pass 1: process columns from input, store into work array. */
  175778. inptr = coef_block;
  175779. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175780. wsptr = workspace;
  175781. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175782. /* Don't bother to process column 4, because second pass won't use it */
  175783. if (ctr == DCTSIZE-4)
  175784. continue;
  175785. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175786. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175787. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175788. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175789. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175790. wsptr[DCTSIZE*0] = dcval;
  175791. wsptr[DCTSIZE*1] = dcval;
  175792. wsptr[DCTSIZE*2] = dcval;
  175793. wsptr[DCTSIZE*3] = dcval;
  175794. continue;
  175795. }
  175796. /* Even part */
  175797. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175798. tmp0 <<= (CONST_BITS+1);
  175799. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175800. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175801. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175802. tmp10 = tmp0 + tmp2;
  175803. tmp12 = tmp0 - tmp2;
  175804. /* Odd part */
  175805. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175806. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175807. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175808. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175809. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175810. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175811. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175812. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175813. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175814. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175815. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175816. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175817. /* Final output stage */
  175818. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175819. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175820. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175821. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175822. }
  175823. /* Pass 2: process 4 rows from work array, store into output array. */
  175824. wsptr = workspace;
  175825. for (ctr = 0; ctr < 4; ctr++) {
  175826. outptr = output_buf[ctr] + output_col;
  175827. /* It's not clear whether a zero row test is worthwhile here ... */
  175828. #ifndef NO_ZERO_ROW_TEST
  175829. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175830. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175831. /* AC terms all zero */
  175832. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175833. & RANGE_MASK];
  175834. outptr[0] = dcval;
  175835. outptr[1] = dcval;
  175836. outptr[2] = dcval;
  175837. outptr[3] = dcval;
  175838. wsptr += DCTSIZE; /* advance pointer to next row */
  175839. continue;
  175840. }
  175841. #endif
  175842. /* Even part */
  175843. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175844. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175845. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175846. tmp10 = tmp0 + tmp2;
  175847. tmp12 = tmp0 - tmp2;
  175848. /* Odd part */
  175849. z1 = (INT32) wsptr[7];
  175850. z2 = (INT32) wsptr[5];
  175851. z3 = (INT32) wsptr[3];
  175852. z4 = (INT32) wsptr[1];
  175853. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175854. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175855. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175856. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175857. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175858. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175859. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175860. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175861. /* Final output stage */
  175862. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175863. CONST_BITS+PASS1_BITS+3+1)
  175864. & RANGE_MASK];
  175865. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175866. CONST_BITS+PASS1_BITS+3+1)
  175867. & RANGE_MASK];
  175868. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175869. CONST_BITS+PASS1_BITS+3+1)
  175870. & RANGE_MASK];
  175871. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175872. CONST_BITS+PASS1_BITS+3+1)
  175873. & RANGE_MASK];
  175874. wsptr += DCTSIZE; /* advance pointer to next row */
  175875. }
  175876. }
  175877. /*
  175878. * Perform dequantization and inverse DCT on one block of coefficients,
  175879. * producing a reduced-size 2x2 output block.
  175880. */
  175881. GLOBAL(void)
  175882. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175883. JCOEFPTR coef_block,
  175884. JSAMPARRAY output_buf, JDIMENSION output_col)
  175885. {
  175886. INT32 tmp0, tmp10, z1;
  175887. JCOEFPTR inptr;
  175888. ISLOW_MULT_TYPE * quantptr;
  175889. int * wsptr;
  175890. JSAMPROW outptr;
  175891. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175892. int ctr;
  175893. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175894. SHIFT_TEMPS
  175895. /* Pass 1: process columns from input, store into work array. */
  175896. inptr = coef_block;
  175897. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175898. wsptr = workspace;
  175899. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175900. /* Don't bother to process columns 2,4,6 */
  175901. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175902. continue;
  175903. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175904. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175905. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175906. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175907. wsptr[DCTSIZE*0] = dcval;
  175908. wsptr[DCTSIZE*1] = dcval;
  175909. continue;
  175910. }
  175911. /* Even part */
  175912. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175913. tmp10 = z1 << (CONST_BITS+2);
  175914. /* Odd part */
  175915. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175916. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175917. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175918. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175919. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175920. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175921. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175922. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175923. /* Final output stage */
  175924. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175925. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175926. }
  175927. /* Pass 2: process 2 rows from work array, store into output array. */
  175928. wsptr = workspace;
  175929. for (ctr = 0; ctr < 2; ctr++) {
  175930. outptr = output_buf[ctr] + output_col;
  175931. /* It's not clear whether a zero row test is worthwhile here ... */
  175932. #ifndef NO_ZERO_ROW_TEST
  175933. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175934. /* AC terms all zero */
  175935. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175936. & RANGE_MASK];
  175937. outptr[0] = dcval;
  175938. outptr[1] = dcval;
  175939. wsptr += DCTSIZE; /* advance pointer to next row */
  175940. continue;
  175941. }
  175942. #endif
  175943. /* Even part */
  175944. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175945. /* Odd part */
  175946. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175947. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175948. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175949. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175950. /* Final output stage */
  175951. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175952. CONST_BITS+PASS1_BITS+3+2)
  175953. & RANGE_MASK];
  175954. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175955. CONST_BITS+PASS1_BITS+3+2)
  175956. & RANGE_MASK];
  175957. wsptr += DCTSIZE; /* advance pointer to next row */
  175958. }
  175959. }
  175960. /*
  175961. * Perform dequantization and inverse DCT on one block of coefficients,
  175962. * producing a reduced-size 1x1 output block.
  175963. */
  175964. GLOBAL(void)
  175965. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175966. JCOEFPTR coef_block,
  175967. JSAMPARRAY output_buf, JDIMENSION output_col)
  175968. {
  175969. int dcval;
  175970. ISLOW_MULT_TYPE * quantptr;
  175971. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175972. SHIFT_TEMPS
  175973. /* We hardly need an inverse DCT routine for this: just take the
  175974. * average pixel value, which is one-eighth of the DC coefficient.
  175975. */
  175976. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175977. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175978. dcval = (int) DESCALE((INT32) dcval, 3);
  175979. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175980. }
  175981. #endif /* IDCT_SCALING_SUPPORTED */
  175982. /*** End of inlined file: jidctred.c ***/
  175983. /*** Start of inlined file: jmemmgr.c ***/
  175984. #define JPEG_INTERNALS
  175985. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175986. /*** Start of inlined file: jmemsys.h ***/
  175987. #ifndef __jmemsys_h__
  175988. #define __jmemsys_h__
  175989. /* Short forms of external names for systems with brain-damaged linkers. */
  175990. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175991. #define jpeg_get_small jGetSmall
  175992. #define jpeg_free_small jFreeSmall
  175993. #define jpeg_get_large jGetLarge
  175994. #define jpeg_free_large jFreeLarge
  175995. #define jpeg_mem_available jMemAvail
  175996. #define jpeg_open_backing_store jOpenBackStore
  175997. #define jpeg_mem_init jMemInit
  175998. #define jpeg_mem_term jMemTerm
  175999. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  176000. /*
  176001. * These two functions are used to allocate and release small chunks of
  176002. * memory. (Typically the total amount requested through jpeg_get_small is
  176003. * no more than 20K or so; this will be requested in chunks of a few K each.)
  176004. * Behavior should be the same as for the standard library functions malloc
  176005. * and free; in particular, jpeg_get_small must return NULL on failure.
  176006. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  176007. * size of the object being freed, just in case it's needed.
  176008. * On an 80x86 machine using small-data memory model, these manage near heap.
  176009. */
  176010. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  176011. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  176012. size_t sizeofobject));
  176013. /*
  176014. * These two functions are used to allocate and release large chunks of
  176015. * memory (up to the total free space designated by jpeg_mem_available).
  176016. * The interface is the same as above, except that on an 80x86 machine,
  176017. * far pointers are used. On most other machines these are identical to
  176018. * the jpeg_get/free_small routines; but we keep them separate anyway,
  176019. * in case a different allocation strategy is desirable for large chunks.
  176020. */
  176021. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  176022. size_t sizeofobject));
  176023. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  176024. size_t sizeofobject));
  176025. /*
  176026. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  176027. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  176028. * matter, but that case should never come into play). This macro is needed
  176029. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  176030. * On those machines, we expect that jconfig.h will provide a proper value.
  176031. * On machines with 32-bit flat address spaces, any large constant may be used.
  176032. *
  176033. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  176034. * size_t and will be a multiple of sizeof(align_type).
  176035. */
  176036. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  176037. #define MAX_ALLOC_CHUNK 1000000000L
  176038. #endif
  176039. /*
  176040. * This routine computes the total space still available for allocation by
  176041. * jpeg_get_large. If more space than this is needed, backing store will be
  176042. * used. NOTE: any memory already allocated must not be counted.
  176043. *
  176044. * There is a minimum space requirement, corresponding to the minimum
  176045. * feasible buffer sizes; jmemmgr.c will request that much space even if
  176046. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  176047. * all working storage in memory, is also passed in case it is useful.
  176048. * Finally, the total space already allocated is passed. If no better
  176049. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  176050. * is often a suitable calculation.
  176051. *
  176052. * It is OK for jpeg_mem_available to underestimate the space available
  176053. * (that'll just lead to more backing-store access than is really necessary).
  176054. * However, an overestimate will lead to failure. Hence it's wise to subtract
  176055. * a slop factor from the true available space. 5% should be enough.
  176056. *
  176057. * On machines with lots of virtual memory, any large constant may be returned.
  176058. * Conversely, zero may be returned to always use the minimum amount of memory.
  176059. */
  176060. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  176061. long min_bytes_needed,
  176062. long max_bytes_needed,
  176063. long already_allocated));
  176064. /*
  176065. * This structure holds whatever state is needed to access a single
  176066. * backing-store object. The read/write/close method pointers are called
  176067. * by jmemmgr.c to manipulate the backing-store object; all other fields
  176068. * are private to the system-dependent backing store routines.
  176069. */
  176070. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  176071. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  176072. typedef unsigned short XMSH; /* type of extended-memory handles */
  176073. typedef unsigned short EMSH; /* type of expanded-memory handles */
  176074. typedef union {
  176075. short file_handle; /* DOS file handle if it's a temp file */
  176076. XMSH xms_handle; /* handle if it's a chunk of XMS */
  176077. EMSH ems_handle; /* handle if it's a chunk of EMS */
  176078. } handle_union;
  176079. #endif /* USE_MSDOS_MEMMGR */
  176080. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  176081. #include <Files.h>
  176082. #endif /* USE_MAC_MEMMGR */
  176083. //typedef struct backing_store_struct * backing_store_ptr;
  176084. typedef struct backing_store_struct {
  176085. /* Methods for reading/writing/closing this backing-store object */
  176086. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  176087. struct backing_store_struct *info,
  176088. void FAR * buffer_address,
  176089. long file_offset, long byte_count));
  176090. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  176091. struct backing_store_struct *info,
  176092. void FAR * buffer_address,
  176093. long file_offset, long byte_count));
  176094. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  176095. struct backing_store_struct *info));
  176096. /* Private fields for system-dependent backing-store management */
  176097. #ifdef USE_MSDOS_MEMMGR
  176098. /* For the MS-DOS manager (jmemdos.c), we need: */
  176099. handle_union handle; /* reference to backing-store storage object */
  176100. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176101. #else
  176102. #ifdef USE_MAC_MEMMGR
  176103. /* For the Mac manager (jmemmac.c), we need: */
  176104. short temp_file; /* file reference number to temp file */
  176105. FSSpec tempSpec; /* the FSSpec for the temp file */
  176106. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176107. #else
  176108. /* For a typical implementation with temp files, we need: */
  176109. FILE * temp_file; /* stdio reference to temp file */
  176110. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  176111. #endif
  176112. #endif
  176113. } backing_store_info;
  176114. /*
  176115. * Initial opening of a backing-store object. This must fill in the
  176116. * read/write/close pointers in the object. The read/write routines
  176117. * may take an error exit if the specified maximum file size is exceeded.
  176118. * (If jpeg_mem_available always returns a large value, this routine can
  176119. * just take an error exit.)
  176120. */
  176121. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  176122. struct backing_store_struct *info,
  176123. long total_bytes_needed));
  176124. /*
  176125. * These routines take care of any system-dependent initialization and
  176126. * cleanup required. jpeg_mem_init will be called before anything is
  176127. * allocated (and, therefore, nothing in cinfo is of use except the error
  176128. * manager pointer). It should return a suitable default value for
  176129. * max_memory_to_use; this may subsequently be overridden by the surrounding
  176130. * application. (Note that max_memory_to_use is only important if
  176131. * jpeg_mem_available chooses to consult it ... no one else will.)
  176132. * jpeg_mem_term may assume that all requested memory has been freed and that
  176133. * all opened backing-store objects have been closed.
  176134. */
  176135. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  176136. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  176137. #endif
  176138. /*** End of inlined file: jmemsys.h ***/
  176139. /* import the system-dependent declarations */
  176140. #ifndef NO_GETENV
  176141. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  176142. extern char * getenv JPP((const char * name));
  176143. #endif
  176144. #endif
  176145. /*
  176146. * Some important notes:
  176147. * The allocation routines provided here must never return NULL.
  176148. * They should exit to error_exit if unsuccessful.
  176149. *
  176150. * It's not a good idea to try to merge the sarray and barray routines,
  176151. * even though they are textually almost the same, because samples are
  176152. * usually stored as bytes while coefficients are shorts or ints. Thus,
  176153. * in machines where byte pointers have a different representation from
  176154. * word pointers, the resulting machine code could not be the same.
  176155. */
  176156. /*
  176157. * Many machines require storage alignment: longs must start on 4-byte
  176158. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  176159. * always returns pointers that are multiples of the worst-case alignment
  176160. * requirement, and we had better do so too.
  176161. * There isn't any really portable way to determine the worst-case alignment
  176162. * requirement. This module assumes that the alignment requirement is
  176163. * multiples of sizeof(ALIGN_TYPE).
  176164. * By default, we define ALIGN_TYPE as double. This is necessary on some
  176165. * workstations (where doubles really do need 8-byte alignment) and will work
  176166. * fine on nearly everything. If your machine has lesser alignment needs,
  176167. * you can save a few bytes by making ALIGN_TYPE smaller.
  176168. * The only place I know of where this will NOT work is certain Macintosh
  176169. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  176170. * Doing 10-byte alignment is counterproductive because longwords won't be
  176171. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  176172. * such a compiler.
  176173. */
  176174. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  176175. #define ALIGN_TYPE double
  176176. #endif
  176177. /*
  176178. * We allocate objects from "pools", where each pool is gotten with a single
  176179. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  176180. * overhead within a pool, except for alignment padding. Each pool has a
  176181. * header with a link to the next pool of the same class.
  176182. * Small and large pool headers are identical except that the latter's
  176183. * link pointer must be FAR on 80x86 machines.
  176184. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  176185. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  176186. * of the alignment requirement of ALIGN_TYPE.
  176187. */
  176188. typedef union small_pool_struct * small_pool_ptr;
  176189. typedef union small_pool_struct {
  176190. struct {
  176191. small_pool_ptr next; /* next in list of pools */
  176192. size_t bytes_used; /* how many bytes already used within pool */
  176193. size_t bytes_left; /* bytes still available in this pool */
  176194. } hdr;
  176195. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176196. } small_pool_hdr;
  176197. typedef union large_pool_struct FAR * large_pool_ptr;
  176198. typedef union large_pool_struct {
  176199. struct {
  176200. large_pool_ptr next; /* next in list of pools */
  176201. size_t bytes_used; /* how many bytes already used within pool */
  176202. size_t bytes_left; /* bytes still available in this pool */
  176203. } hdr;
  176204. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176205. } large_pool_hdr;
  176206. /*
  176207. * Here is the full definition of a memory manager object.
  176208. */
  176209. typedef struct {
  176210. struct jpeg_memory_mgr pub; /* public fields */
  176211. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176212. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176213. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176214. /* Since we only have one lifetime class of virtual arrays, only one
  176215. * linked list is necessary (for each datatype). Note that the virtual
  176216. * array control blocks being linked together are actually stored somewhere
  176217. * in the small-pool list.
  176218. */
  176219. jvirt_sarray_ptr virt_sarray_list;
  176220. jvirt_barray_ptr virt_barray_list;
  176221. /* This counts total space obtained from jpeg_get_small/large */
  176222. long total_space_allocated;
  176223. /* alloc_sarray and alloc_barray set this value for use by virtual
  176224. * array routines.
  176225. */
  176226. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176227. } my_memory_mgr;
  176228. typedef my_memory_mgr * my_mem_ptr;
  176229. /*
  176230. * The control blocks for virtual arrays.
  176231. * Note that these blocks are allocated in the "small" pool area.
  176232. * System-dependent info for the associated backing store (if any) is hidden
  176233. * inside the backing_store_info struct.
  176234. */
  176235. struct jvirt_sarray_control {
  176236. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176237. JDIMENSION rows_in_array; /* total virtual array height */
  176238. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176239. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176240. JDIMENSION rows_in_mem; /* height of memory buffer */
  176241. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176242. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176243. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176244. boolean pre_zero; /* pre-zero mode requested? */
  176245. boolean dirty; /* do current buffer contents need written? */
  176246. boolean b_s_open; /* is backing-store data valid? */
  176247. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176248. backing_store_info b_s_info; /* System-dependent control info */
  176249. };
  176250. struct jvirt_barray_control {
  176251. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176252. JDIMENSION rows_in_array; /* total virtual array height */
  176253. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176254. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176255. JDIMENSION rows_in_mem; /* height of memory buffer */
  176256. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176257. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176258. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176259. boolean pre_zero; /* pre-zero mode requested? */
  176260. boolean dirty; /* do current buffer contents need written? */
  176261. boolean b_s_open; /* is backing-store data valid? */
  176262. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176263. backing_store_info b_s_info; /* System-dependent control info */
  176264. };
  176265. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176266. LOCAL(void)
  176267. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176268. {
  176269. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176270. small_pool_ptr shdr_ptr;
  176271. large_pool_ptr lhdr_ptr;
  176272. /* Since this is only a debugging stub, we can cheat a little by using
  176273. * fprintf directly rather than going through the trace message code.
  176274. * This is helpful because message parm array can't handle longs.
  176275. */
  176276. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176277. pool_id, mem->total_space_allocated);
  176278. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176279. lhdr_ptr = lhdr_ptr->hdr.next) {
  176280. fprintf(stderr, " Large chunk used %ld\n",
  176281. (long) lhdr_ptr->hdr.bytes_used);
  176282. }
  176283. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176284. shdr_ptr = shdr_ptr->hdr.next) {
  176285. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176286. (long) shdr_ptr->hdr.bytes_used,
  176287. (long) shdr_ptr->hdr.bytes_left);
  176288. }
  176289. }
  176290. #endif /* MEM_STATS */
  176291. LOCAL(void)
  176292. out_of_memory (j_common_ptr cinfo, int which)
  176293. /* Report an out-of-memory error and stop execution */
  176294. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176295. {
  176296. #ifdef MEM_STATS
  176297. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176298. #endif
  176299. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176300. }
  176301. /*
  176302. * Allocation of "small" objects.
  176303. *
  176304. * For these, we use pooled storage. When a new pool must be created,
  176305. * we try to get enough space for the current request plus a "slop" factor,
  176306. * where the slop will be the amount of leftover space in the new pool.
  176307. * The speed vs. space tradeoff is largely determined by the slop values.
  176308. * A different slop value is provided for each pool class (lifetime),
  176309. * and we also distinguish the first pool of a class from later ones.
  176310. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176311. * machines, but may be too small if longs are 64 bits or more.
  176312. */
  176313. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176314. {
  176315. 1600, /* first PERMANENT pool */
  176316. 16000 /* first IMAGE pool */
  176317. };
  176318. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176319. {
  176320. 0, /* additional PERMANENT pools */
  176321. 5000 /* additional IMAGE pools */
  176322. };
  176323. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176324. METHODDEF(void *)
  176325. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176326. /* Allocate a "small" object */
  176327. {
  176328. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176329. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176330. char * data_ptr;
  176331. size_t odd_bytes, min_request, slop;
  176332. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176333. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176334. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176335. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176336. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176337. if (odd_bytes > 0)
  176338. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176339. /* See if space is available in any existing pool */
  176340. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176341. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176342. prev_hdr_ptr = NULL;
  176343. hdr_ptr = mem->small_list[pool_id];
  176344. while (hdr_ptr != NULL) {
  176345. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176346. break; /* found pool with enough space */
  176347. prev_hdr_ptr = hdr_ptr;
  176348. hdr_ptr = hdr_ptr->hdr.next;
  176349. }
  176350. /* Time to make a new pool? */
  176351. if (hdr_ptr == NULL) {
  176352. /* min_request is what we need now, slop is what will be leftover */
  176353. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176354. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176355. slop = first_pool_slop[pool_id];
  176356. else
  176357. slop = extra_pool_slop[pool_id];
  176358. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176359. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176360. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176361. /* Try to get space, if fail reduce slop and try again */
  176362. for (;;) {
  176363. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176364. if (hdr_ptr != NULL)
  176365. break;
  176366. slop /= 2;
  176367. if (slop < MIN_SLOP) /* give up when it gets real small */
  176368. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176369. }
  176370. mem->total_space_allocated += min_request + slop;
  176371. /* Success, initialize the new pool header and add to end of list */
  176372. hdr_ptr->hdr.next = NULL;
  176373. hdr_ptr->hdr.bytes_used = 0;
  176374. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176375. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176376. mem->small_list[pool_id] = hdr_ptr;
  176377. else
  176378. prev_hdr_ptr->hdr.next = hdr_ptr;
  176379. }
  176380. /* OK, allocate the object from the current pool */
  176381. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176382. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176383. hdr_ptr->hdr.bytes_used += sizeofobject;
  176384. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176385. return (void *) data_ptr;
  176386. }
  176387. /*
  176388. * Allocation of "large" objects.
  176389. *
  176390. * The external semantics of these are the same as "small" objects,
  176391. * except that FAR pointers are used on 80x86. However the pool
  176392. * management heuristics are quite different. We assume that each
  176393. * request is large enough that it may as well be passed directly to
  176394. * jpeg_get_large; the pool management just links everything together
  176395. * so that we can free it all on demand.
  176396. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176397. * structures. The routines that create these structures (see below)
  176398. * deliberately bunch rows together to ensure a large request size.
  176399. */
  176400. METHODDEF(void FAR *)
  176401. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176402. /* Allocate a "large" object */
  176403. {
  176404. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176405. large_pool_ptr hdr_ptr;
  176406. size_t odd_bytes;
  176407. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176408. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176409. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176410. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176411. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176412. if (odd_bytes > 0)
  176413. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176414. /* Always make a new pool */
  176415. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176416. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176417. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176418. SIZEOF(large_pool_hdr));
  176419. if (hdr_ptr == NULL)
  176420. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176421. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176422. /* Success, initialize the new pool header and add to list */
  176423. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176424. /* We maintain space counts in each pool header for statistical purposes,
  176425. * even though they are not needed for allocation.
  176426. */
  176427. hdr_ptr->hdr.bytes_used = sizeofobject;
  176428. hdr_ptr->hdr.bytes_left = 0;
  176429. mem->large_list[pool_id] = hdr_ptr;
  176430. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176431. }
  176432. /*
  176433. * Creation of 2-D sample arrays.
  176434. * The pointers are in near heap, the samples themselves in FAR heap.
  176435. *
  176436. * To minimize allocation overhead and to allow I/O of large contiguous
  176437. * blocks, we allocate the sample rows in groups of as many rows as possible
  176438. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176439. * NB: the virtual array control routines, later in this file, know about
  176440. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176441. * object so that it can be saved away if this sarray is the workspace for
  176442. * a virtual array.
  176443. */
  176444. METHODDEF(JSAMPARRAY)
  176445. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176446. JDIMENSION samplesperrow, JDIMENSION numrows)
  176447. /* Allocate a 2-D sample array */
  176448. {
  176449. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176450. JSAMPARRAY result;
  176451. JSAMPROW workspace;
  176452. JDIMENSION rowsperchunk, currow, i;
  176453. long ltemp;
  176454. /* Calculate max # of rows allowed in one allocation chunk */
  176455. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176456. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176457. if (ltemp <= 0)
  176458. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176459. if (ltemp < (long) numrows)
  176460. rowsperchunk = (JDIMENSION) ltemp;
  176461. else
  176462. rowsperchunk = numrows;
  176463. mem->last_rowsperchunk = rowsperchunk;
  176464. /* Get space for row pointers (small object) */
  176465. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176466. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176467. /* Get the rows themselves (large objects) */
  176468. currow = 0;
  176469. while (currow < numrows) {
  176470. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176471. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176472. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176473. * SIZEOF(JSAMPLE)));
  176474. for (i = rowsperchunk; i > 0; i--) {
  176475. result[currow++] = workspace;
  176476. workspace += samplesperrow;
  176477. }
  176478. }
  176479. return result;
  176480. }
  176481. /*
  176482. * Creation of 2-D coefficient-block arrays.
  176483. * This is essentially the same as the code for sample arrays, above.
  176484. */
  176485. METHODDEF(JBLOCKARRAY)
  176486. alloc_barray (j_common_ptr cinfo, int pool_id,
  176487. JDIMENSION blocksperrow, JDIMENSION numrows)
  176488. /* Allocate a 2-D coefficient-block array */
  176489. {
  176490. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176491. JBLOCKARRAY result;
  176492. JBLOCKROW workspace;
  176493. JDIMENSION rowsperchunk, currow, i;
  176494. long ltemp;
  176495. /* Calculate max # of rows allowed in one allocation chunk */
  176496. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176497. ((long) blocksperrow * SIZEOF(JBLOCK));
  176498. if (ltemp <= 0)
  176499. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176500. if (ltemp < (long) numrows)
  176501. rowsperchunk = (JDIMENSION) ltemp;
  176502. else
  176503. rowsperchunk = numrows;
  176504. mem->last_rowsperchunk = rowsperchunk;
  176505. /* Get space for row pointers (small object) */
  176506. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176507. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176508. /* Get the rows themselves (large objects) */
  176509. currow = 0;
  176510. while (currow < numrows) {
  176511. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176512. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176513. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176514. * SIZEOF(JBLOCK)));
  176515. for (i = rowsperchunk; i > 0; i--) {
  176516. result[currow++] = workspace;
  176517. workspace += blocksperrow;
  176518. }
  176519. }
  176520. return result;
  176521. }
  176522. /*
  176523. * About virtual array management:
  176524. *
  176525. * The above "normal" array routines are only used to allocate strip buffers
  176526. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176527. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176528. * time, but the memory manager must save the whole array for repeated
  176529. * accesses. The intended implementation is that there is a strip buffer in
  176530. * memory (as high as is possible given the desired memory limit), plus a
  176531. * backing file that holds the rest of the array.
  176532. *
  176533. * The request_virt_array routines are told the total size of the image and
  176534. * the maximum number of rows that will be accessed at once. The in-memory
  176535. * buffer must be at least as large as the maxaccess value.
  176536. *
  176537. * The request routines create control blocks but not the in-memory buffers.
  176538. * That is postponed until realize_virt_arrays is called. At that time the
  176539. * total amount of space needed is known (approximately, anyway), so free
  176540. * memory can be divided up fairly.
  176541. *
  176542. * The access_virt_array routines are responsible for making a specific strip
  176543. * area accessible (after reading or writing the backing file, if necessary).
  176544. * Note that the access routines are told whether the caller intends to modify
  176545. * the accessed strip; during a read-only pass this saves having to rewrite
  176546. * data to disk. The access routines are also responsible for pre-zeroing
  176547. * any newly accessed rows, if pre-zeroing was requested.
  176548. *
  176549. * In current usage, the access requests are usually for nonoverlapping
  176550. * strips; that is, successive access start_row numbers differ by exactly
  176551. * num_rows = maxaccess. This means we can get good performance with simple
  176552. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176553. * of the access height; then there will never be accesses across bufferload
  176554. * boundaries. The code will still work with overlapping access requests,
  176555. * but it doesn't handle bufferload overlaps very efficiently.
  176556. */
  176557. METHODDEF(jvirt_sarray_ptr)
  176558. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176559. JDIMENSION samplesperrow, JDIMENSION numrows,
  176560. JDIMENSION maxaccess)
  176561. /* Request a virtual 2-D sample array */
  176562. {
  176563. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176564. jvirt_sarray_ptr result;
  176565. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176566. if (pool_id != JPOOL_IMAGE)
  176567. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176568. /* get control block */
  176569. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176570. SIZEOF(struct jvirt_sarray_control));
  176571. result->mem_buffer = NULL; /* marks array not yet realized */
  176572. result->rows_in_array = numrows;
  176573. result->samplesperrow = samplesperrow;
  176574. result->maxaccess = maxaccess;
  176575. result->pre_zero = pre_zero;
  176576. result->b_s_open = FALSE; /* no associated backing-store object */
  176577. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176578. mem->virt_sarray_list = result;
  176579. return result;
  176580. }
  176581. METHODDEF(jvirt_barray_ptr)
  176582. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176583. JDIMENSION blocksperrow, JDIMENSION numrows,
  176584. JDIMENSION maxaccess)
  176585. /* Request a virtual 2-D coefficient-block array */
  176586. {
  176587. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176588. jvirt_barray_ptr result;
  176589. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176590. if (pool_id != JPOOL_IMAGE)
  176591. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176592. /* get control block */
  176593. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176594. SIZEOF(struct jvirt_barray_control));
  176595. result->mem_buffer = NULL; /* marks array not yet realized */
  176596. result->rows_in_array = numrows;
  176597. result->blocksperrow = blocksperrow;
  176598. result->maxaccess = maxaccess;
  176599. result->pre_zero = pre_zero;
  176600. result->b_s_open = FALSE; /* no associated backing-store object */
  176601. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176602. mem->virt_barray_list = result;
  176603. return result;
  176604. }
  176605. METHODDEF(void)
  176606. realize_virt_arrays (j_common_ptr cinfo)
  176607. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176608. {
  176609. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176610. long space_per_minheight, maximum_space, avail_mem;
  176611. long minheights, max_minheights;
  176612. jvirt_sarray_ptr sptr;
  176613. jvirt_barray_ptr bptr;
  176614. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176615. * and the maximum space needed (full image height in each buffer).
  176616. * These may be of use to the system-dependent jpeg_mem_available routine.
  176617. */
  176618. space_per_minheight = 0;
  176619. maximum_space = 0;
  176620. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176621. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176622. space_per_minheight += (long) sptr->maxaccess *
  176623. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176624. maximum_space += (long) sptr->rows_in_array *
  176625. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176626. }
  176627. }
  176628. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176629. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176630. space_per_minheight += (long) bptr->maxaccess *
  176631. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176632. maximum_space += (long) bptr->rows_in_array *
  176633. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176634. }
  176635. }
  176636. if (space_per_minheight <= 0)
  176637. return; /* no unrealized arrays, no work */
  176638. /* Determine amount of memory to actually use; this is system-dependent. */
  176639. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176640. mem->total_space_allocated);
  176641. /* If the maximum space needed is available, make all the buffers full
  176642. * height; otherwise parcel it out with the same number of minheights
  176643. * in each buffer.
  176644. */
  176645. if (avail_mem >= maximum_space)
  176646. max_minheights = 1000000000L;
  176647. else {
  176648. max_minheights = avail_mem / space_per_minheight;
  176649. /* If there doesn't seem to be enough space, try to get the minimum
  176650. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176651. */
  176652. if (max_minheights <= 0)
  176653. max_minheights = 1;
  176654. }
  176655. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176656. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176657. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176658. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176659. if (minheights <= max_minheights) {
  176660. /* This buffer fits in memory */
  176661. sptr->rows_in_mem = sptr->rows_in_array;
  176662. } else {
  176663. /* It doesn't fit in memory, create backing store. */
  176664. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176665. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176666. (long) sptr->rows_in_array *
  176667. (long) sptr->samplesperrow *
  176668. (long) SIZEOF(JSAMPLE));
  176669. sptr->b_s_open = TRUE;
  176670. }
  176671. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176672. sptr->samplesperrow, sptr->rows_in_mem);
  176673. sptr->rowsperchunk = mem->last_rowsperchunk;
  176674. sptr->cur_start_row = 0;
  176675. sptr->first_undef_row = 0;
  176676. sptr->dirty = FALSE;
  176677. }
  176678. }
  176679. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176680. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176681. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176682. if (minheights <= max_minheights) {
  176683. /* This buffer fits in memory */
  176684. bptr->rows_in_mem = bptr->rows_in_array;
  176685. } else {
  176686. /* It doesn't fit in memory, create backing store. */
  176687. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176688. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176689. (long) bptr->rows_in_array *
  176690. (long) bptr->blocksperrow *
  176691. (long) SIZEOF(JBLOCK));
  176692. bptr->b_s_open = TRUE;
  176693. }
  176694. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176695. bptr->blocksperrow, bptr->rows_in_mem);
  176696. bptr->rowsperchunk = mem->last_rowsperchunk;
  176697. bptr->cur_start_row = 0;
  176698. bptr->first_undef_row = 0;
  176699. bptr->dirty = FALSE;
  176700. }
  176701. }
  176702. }
  176703. LOCAL(void)
  176704. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176705. /* Do backing store read or write of a virtual sample array */
  176706. {
  176707. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176708. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176709. file_offset = ptr->cur_start_row * bytesperrow;
  176710. /* Loop to read or write each allocation chunk in mem_buffer */
  176711. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176712. /* One chunk, but check for short chunk at end of buffer */
  176713. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176714. /* Transfer no more than is currently defined */
  176715. thisrow = (long) ptr->cur_start_row + i;
  176716. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176717. /* Transfer no more than fits in file */
  176718. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176719. if (rows <= 0) /* this chunk might be past end of file! */
  176720. break;
  176721. byte_count = rows * bytesperrow;
  176722. if (writing)
  176723. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176724. (void FAR *) ptr->mem_buffer[i],
  176725. file_offset, byte_count);
  176726. else
  176727. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176728. (void FAR *) ptr->mem_buffer[i],
  176729. file_offset, byte_count);
  176730. file_offset += byte_count;
  176731. }
  176732. }
  176733. LOCAL(void)
  176734. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176735. /* Do backing store read or write of a virtual coefficient-block array */
  176736. {
  176737. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176738. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176739. file_offset = ptr->cur_start_row * bytesperrow;
  176740. /* Loop to read or write each allocation chunk in mem_buffer */
  176741. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176742. /* One chunk, but check for short chunk at end of buffer */
  176743. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176744. /* Transfer no more than is currently defined */
  176745. thisrow = (long) ptr->cur_start_row + i;
  176746. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176747. /* Transfer no more than fits in file */
  176748. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176749. if (rows <= 0) /* this chunk might be past end of file! */
  176750. break;
  176751. byte_count = rows * bytesperrow;
  176752. if (writing)
  176753. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176754. (void FAR *) ptr->mem_buffer[i],
  176755. file_offset, byte_count);
  176756. else
  176757. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176758. (void FAR *) ptr->mem_buffer[i],
  176759. file_offset, byte_count);
  176760. file_offset += byte_count;
  176761. }
  176762. }
  176763. METHODDEF(JSAMPARRAY)
  176764. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176765. JDIMENSION start_row, JDIMENSION num_rows,
  176766. boolean writable)
  176767. /* Access the part of a virtual sample array starting at start_row */
  176768. /* and extending for num_rows rows. writable is true if */
  176769. /* caller intends to modify the accessed area. */
  176770. {
  176771. JDIMENSION end_row = start_row + num_rows;
  176772. JDIMENSION undef_row;
  176773. /* debugging check */
  176774. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176775. ptr->mem_buffer == NULL)
  176776. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176777. /* Make the desired part of the virtual array accessible */
  176778. if (start_row < ptr->cur_start_row ||
  176779. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176780. if (! ptr->b_s_open)
  176781. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176782. /* Flush old buffer contents if necessary */
  176783. if (ptr->dirty) {
  176784. do_sarray_io(cinfo, ptr, TRUE);
  176785. ptr->dirty = FALSE;
  176786. }
  176787. /* Decide what part of virtual array to access.
  176788. * Algorithm: if target address > current window, assume forward scan,
  176789. * load starting at target address. If target address < current window,
  176790. * assume backward scan, load so that target area is top of window.
  176791. * Note that when switching from forward write to forward read, will have
  176792. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176793. */
  176794. if (start_row > ptr->cur_start_row) {
  176795. ptr->cur_start_row = start_row;
  176796. } else {
  176797. /* use long arithmetic here to avoid overflow & unsigned problems */
  176798. long ltemp;
  176799. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176800. if (ltemp < 0)
  176801. ltemp = 0; /* don't fall off front end of file */
  176802. ptr->cur_start_row = (JDIMENSION) ltemp;
  176803. }
  176804. /* Read in the selected part of the array.
  176805. * During the initial write pass, we will do no actual read
  176806. * because the selected part is all undefined.
  176807. */
  176808. do_sarray_io(cinfo, ptr, FALSE);
  176809. }
  176810. /* Ensure the accessed part of the array is defined; prezero if needed.
  176811. * To improve locality of access, we only prezero the part of the array
  176812. * that the caller is about to access, not the entire in-memory array.
  176813. */
  176814. if (ptr->first_undef_row < end_row) {
  176815. if (ptr->first_undef_row < start_row) {
  176816. if (writable) /* writer skipped over a section of array */
  176817. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176818. undef_row = start_row; /* but reader is allowed to read ahead */
  176819. } else {
  176820. undef_row = ptr->first_undef_row;
  176821. }
  176822. if (writable)
  176823. ptr->first_undef_row = end_row;
  176824. if (ptr->pre_zero) {
  176825. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176826. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176827. end_row -= ptr->cur_start_row;
  176828. while (undef_row < end_row) {
  176829. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176830. undef_row++;
  176831. }
  176832. } else {
  176833. if (! writable) /* reader looking at undefined data */
  176834. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176835. }
  176836. }
  176837. /* Flag the buffer dirty if caller will write in it */
  176838. if (writable)
  176839. ptr->dirty = TRUE;
  176840. /* Return address of proper part of the buffer */
  176841. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176842. }
  176843. METHODDEF(JBLOCKARRAY)
  176844. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176845. JDIMENSION start_row, JDIMENSION num_rows,
  176846. boolean writable)
  176847. /* Access the part of a virtual block array starting at start_row */
  176848. /* and extending for num_rows rows. writable is true if */
  176849. /* caller intends to modify the accessed area. */
  176850. {
  176851. JDIMENSION end_row = start_row + num_rows;
  176852. JDIMENSION undef_row;
  176853. /* debugging check */
  176854. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176855. ptr->mem_buffer == NULL)
  176856. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176857. /* Make the desired part of the virtual array accessible */
  176858. if (start_row < ptr->cur_start_row ||
  176859. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176860. if (! ptr->b_s_open)
  176861. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176862. /* Flush old buffer contents if necessary */
  176863. if (ptr->dirty) {
  176864. do_barray_io(cinfo, ptr, TRUE);
  176865. ptr->dirty = FALSE;
  176866. }
  176867. /* Decide what part of virtual array to access.
  176868. * Algorithm: if target address > current window, assume forward scan,
  176869. * load starting at target address. If target address < current window,
  176870. * assume backward scan, load so that target area is top of window.
  176871. * Note that when switching from forward write to forward read, will have
  176872. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176873. */
  176874. if (start_row > ptr->cur_start_row) {
  176875. ptr->cur_start_row = start_row;
  176876. } else {
  176877. /* use long arithmetic here to avoid overflow & unsigned problems */
  176878. long ltemp;
  176879. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176880. if (ltemp < 0)
  176881. ltemp = 0; /* don't fall off front end of file */
  176882. ptr->cur_start_row = (JDIMENSION) ltemp;
  176883. }
  176884. /* Read in the selected part of the array.
  176885. * During the initial write pass, we will do no actual read
  176886. * because the selected part is all undefined.
  176887. */
  176888. do_barray_io(cinfo, ptr, FALSE);
  176889. }
  176890. /* Ensure the accessed part of the array is defined; prezero if needed.
  176891. * To improve locality of access, we only prezero the part of the array
  176892. * that the caller is about to access, not the entire in-memory array.
  176893. */
  176894. if (ptr->first_undef_row < end_row) {
  176895. if (ptr->first_undef_row < start_row) {
  176896. if (writable) /* writer skipped over a section of array */
  176897. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176898. undef_row = start_row; /* but reader is allowed to read ahead */
  176899. } else {
  176900. undef_row = ptr->first_undef_row;
  176901. }
  176902. if (writable)
  176903. ptr->first_undef_row = end_row;
  176904. if (ptr->pre_zero) {
  176905. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176906. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176907. end_row -= ptr->cur_start_row;
  176908. while (undef_row < end_row) {
  176909. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176910. undef_row++;
  176911. }
  176912. } else {
  176913. if (! writable) /* reader looking at undefined data */
  176914. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176915. }
  176916. }
  176917. /* Flag the buffer dirty if caller will write in it */
  176918. if (writable)
  176919. ptr->dirty = TRUE;
  176920. /* Return address of proper part of the buffer */
  176921. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176922. }
  176923. /*
  176924. * Release all objects belonging to a specified pool.
  176925. */
  176926. METHODDEF(void)
  176927. free_pool (j_common_ptr cinfo, int pool_id)
  176928. {
  176929. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176930. small_pool_ptr shdr_ptr;
  176931. large_pool_ptr lhdr_ptr;
  176932. size_t space_freed;
  176933. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176934. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176935. #ifdef MEM_STATS
  176936. if (cinfo->err->trace_level > 1)
  176937. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176938. #endif
  176939. /* If freeing IMAGE pool, close any virtual arrays first */
  176940. if (pool_id == JPOOL_IMAGE) {
  176941. jvirt_sarray_ptr sptr;
  176942. jvirt_barray_ptr bptr;
  176943. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176944. if (sptr->b_s_open) { /* there may be no backing store */
  176945. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176946. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176947. }
  176948. }
  176949. mem->virt_sarray_list = NULL;
  176950. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176951. if (bptr->b_s_open) { /* there may be no backing store */
  176952. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176953. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176954. }
  176955. }
  176956. mem->virt_barray_list = NULL;
  176957. }
  176958. /* Release large objects */
  176959. lhdr_ptr = mem->large_list[pool_id];
  176960. mem->large_list[pool_id] = NULL;
  176961. while (lhdr_ptr != NULL) {
  176962. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176963. space_freed = lhdr_ptr->hdr.bytes_used +
  176964. lhdr_ptr->hdr.bytes_left +
  176965. SIZEOF(large_pool_hdr);
  176966. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176967. mem->total_space_allocated -= space_freed;
  176968. lhdr_ptr = next_lhdr_ptr;
  176969. }
  176970. /* Release small objects */
  176971. shdr_ptr = mem->small_list[pool_id];
  176972. mem->small_list[pool_id] = NULL;
  176973. while (shdr_ptr != NULL) {
  176974. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176975. space_freed = shdr_ptr->hdr.bytes_used +
  176976. shdr_ptr->hdr.bytes_left +
  176977. SIZEOF(small_pool_hdr);
  176978. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176979. mem->total_space_allocated -= space_freed;
  176980. shdr_ptr = next_shdr_ptr;
  176981. }
  176982. }
  176983. /*
  176984. * Close up shop entirely.
  176985. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176986. */
  176987. METHODDEF(void)
  176988. self_destruct (j_common_ptr cinfo)
  176989. {
  176990. int pool;
  176991. /* Close all backing store, release all memory.
  176992. * Releasing pools in reverse order might help avoid fragmentation
  176993. * with some (brain-damaged) malloc libraries.
  176994. */
  176995. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176996. free_pool(cinfo, pool);
  176997. }
  176998. /* Release the memory manager control block too. */
  176999. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  177000. cinfo->mem = NULL; /* ensures I will be called only once */
  177001. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177002. }
  177003. /*
  177004. * Memory manager initialization.
  177005. * When this is called, only the error manager pointer is valid in cinfo!
  177006. */
  177007. GLOBAL(void)
  177008. jinit_memory_mgr (j_common_ptr cinfo)
  177009. {
  177010. my_mem_ptr mem;
  177011. long max_to_use;
  177012. int pool;
  177013. size_t test_mac;
  177014. cinfo->mem = NULL; /* for safety if init fails */
  177015. /* Check for configuration errors.
  177016. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  177017. * doesn't reflect any real hardware alignment requirement.
  177018. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  177019. * in common if and only if X is a power of 2, ie has only one one-bit.
  177020. * Some compilers may give an "unreachable code" warning here; ignore it.
  177021. */
  177022. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  177023. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  177024. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  177025. * a multiple of SIZEOF(ALIGN_TYPE).
  177026. * Again, an "unreachable code" warning may be ignored here.
  177027. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  177028. */
  177029. test_mac = (size_t) MAX_ALLOC_CHUNK;
  177030. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  177031. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  177032. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  177033. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  177034. /* Attempt to allocate memory manager's control block */
  177035. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  177036. if (mem == NULL) {
  177037. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177038. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  177039. }
  177040. /* OK, fill in the method pointers */
  177041. mem->pub.alloc_small = alloc_small;
  177042. mem->pub.alloc_large = alloc_large;
  177043. mem->pub.alloc_sarray = alloc_sarray;
  177044. mem->pub.alloc_barray = alloc_barray;
  177045. mem->pub.request_virt_sarray = request_virt_sarray;
  177046. mem->pub.request_virt_barray = request_virt_barray;
  177047. mem->pub.realize_virt_arrays = realize_virt_arrays;
  177048. mem->pub.access_virt_sarray = access_virt_sarray;
  177049. mem->pub.access_virt_barray = access_virt_barray;
  177050. mem->pub.free_pool = free_pool;
  177051. mem->pub.self_destruct = self_destruct;
  177052. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  177053. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  177054. /* Initialize working state */
  177055. mem->pub.max_memory_to_use = max_to_use;
  177056. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177057. mem->small_list[pool] = NULL;
  177058. mem->large_list[pool] = NULL;
  177059. }
  177060. mem->virt_sarray_list = NULL;
  177061. mem->virt_barray_list = NULL;
  177062. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  177063. /* Declare ourselves open for business */
  177064. cinfo->mem = & mem->pub;
  177065. /* Check for an environment variable JPEGMEM; if found, override the
  177066. * default max_memory setting from jpeg_mem_init. Note that the
  177067. * surrounding application may again override this value.
  177068. * If your system doesn't support getenv(), define NO_GETENV to disable
  177069. * this feature.
  177070. */
  177071. #ifndef NO_GETENV
  177072. { char * memenv;
  177073. if ((memenv = getenv("JPEGMEM")) != NULL) {
  177074. char ch = 'x';
  177075. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  177076. if (ch == 'm' || ch == 'M')
  177077. max_to_use *= 1000L;
  177078. mem->pub.max_memory_to_use = max_to_use * 1000L;
  177079. }
  177080. }
  177081. }
  177082. #endif
  177083. }
  177084. /*** End of inlined file: jmemmgr.c ***/
  177085. /*** Start of inlined file: jmemnobs.c ***/
  177086. #define JPEG_INTERNALS
  177087. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  177088. extern void * malloc JPP((size_t size));
  177089. extern void free JPP((void *ptr));
  177090. #endif
  177091. /*
  177092. * Memory allocation and freeing are controlled by the regular library
  177093. * routines malloc() and free().
  177094. */
  177095. GLOBAL(void *)
  177096. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  177097. {
  177098. return (void *) malloc(sizeofobject);
  177099. }
  177100. GLOBAL(void)
  177101. jpeg_free_small (j_common_ptr , void * object, size_t)
  177102. {
  177103. free(object);
  177104. }
  177105. /*
  177106. * "Large" objects are treated the same as "small" ones.
  177107. * NB: although we include FAR keywords in the routine declarations,
  177108. * this file won't actually work in 80x86 small/medium model; at least,
  177109. * you probably won't be able to process useful-size images in only 64KB.
  177110. */
  177111. GLOBAL(void FAR *)
  177112. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  177113. {
  177114. return (void FAR *) malloc(sizeofobject);
  177115. }
  177116. GLOBAL(void)
  177117. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  177118. {
  177119. free(object);
  177120. }
  177121. /*
  177122. * This routine computes the total memory space available for allocation.
  177123. * Here we always say, "we got all you want bud!"
  177124. */
  177125. GLOBAL(long)
  177126. jpeg_mem_available (j_common_ptr, long,
  177127. long max_bytes_needed, long)
  177128. {
  177129. return max_bytes_needed;
  177130. }
  177131. /*
  177132. * Backing store (temporary file) management.
  177133. * Since jpeg_mem_available always promised the moon,
  177134. * this should never be called and we can just error out.
  177135. */
  177136. GLOBAL(void)
  177137. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  177138. long )
  177139. {
  177140. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  177141. }
  177142. /*
  177143. * These routines take care of any system-dependent initialization and
  177144. * cleanup required. Here, there isn't any.
  177145. */
  177146. GLOBAL(long)
  177147. jpeg_mem_init (j_common_ptr)
  177148. {
  177149. return 0; /* just set max_memory_to_use to 0 */
  177150. }
  177151. GLOBAL(void)
  177152. jpeg_mem_term (j_common_ptr)
  177153. {
  177154. /* no work */
  177155. }
  177156. /*** End of inlined file: jmemnobs.c ***/
  177157. /*** Start of inlined file: jquant1.c ***/
  177158. #define JPEG_INTERNALS
  177159. #ifdef QUANT_1PASS_SUPPORTED
  177160. /*
  177161. * The main purpose of 1-pass quantization is to provide a fast, if not very
  177162. * high quality, colormapped output capability. A 2-pass quantizer usually
  177163. * gives better visual quality; however, for quantized grayscale output this
  177164. * quantizer is perfectly adequate. Dithering is highly recommended with this
  177165. * quantizer, though you can turn it off if you really want to.
  177166. *
  177167. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  177168. * image. We use a map consisting of all combinations of Ncolors[i] color
  177169. * values for the i'th component. The Ncolors[] values are chosen so that
  177170. * their product, the total number of colors, is no more than that requested.
  177171. * (In most cases, the product will be somewhat less.)
  177172. *
  177173. * Since the colormap is orthogonal, the representative value for each color
  177174. * component can be determined without considering the other components;
  177175. * then these indexes can be combined into a colormap index by a standard
  177176. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  177177. * can be precalculated and stored in the lookup table colorindex[].
  177178. * colorindex[i][j] maps pixel value j in component i to the nearest
  177179. * representative value (grid plane) for that component; this index is
  177180. * multiplied by the array stride for component i, so that the
  177181. * index of the colormap entry closest to a given pixel value is just
  177182. * sum( colorindex[component-number][pixel-component-value] )
  177183. * Aside from being fast, this scheme allows for variable spacing between
  177184. * representative values with no additional lookup cost.
  177185. *
  177186. * If gamma correction has been applied in color conversion, it might be wise
  177187. * to adjust the color grid spacing so that the representative colors are
  177188. * equidistant in linear space. At this writing, gamma correction is not
  177189. * implemented by jdcolor, so nothing is done here.
  177190. */
  177191. /* Declarations for ordered dithering.
  177192. *
  177193. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  177194. * dithering is described in many references, for instance Dale Schumacher's
  177195. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  177196. * In place of Schumacher's comparisons against a "threshold" value, we add a
  177197. * "dither" value to the input pixel and then round the result to the nearest
  177198. * output value. The dither value is equivalent to (0.5 - threshold) times
  177199. * the distance between output values. For ordered dithering, we assume that
  177200. * the output colors are equally spaced; if not, results will probably be
  177201. * worse, since the dither may be too much or too little at a given point.
  177202. *
  177203. * The normal calculation would be to form pixel value + dither, range-limit
  177204. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177205. * We can skip the separate range-limiting step by extending the colorindex
  177206. * table in both directions.
  177207. */
  177208. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177209. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177210. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177211. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177212. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177213. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177214. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177215. /* Bayer's order-4 dither array. Generated by the code given in
  177216. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177217. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177218. */
  177219. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177220. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177221. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177222. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177223. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177224. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177225. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177226. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177227. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177228. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177229. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177230. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177231. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177232. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177233. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177234. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177235. };
  177236. /* Declarations for Floyd-Steinberg dithering.
  177237. *
  177238. * Errors are accumulated into the array fserrors[], at a resolution of
  177239. * 1/16th of a pixel count. The error at a given pixel is propagated
  177240. * to its not-yet-processed neighbors using the standard F-S fractions,
  177241. * ... (here) 7/16
  177242. * 3/16 5/16 1/16
  177243. * We work left-to-right on even rows, right-to-left on odd rows.
  177244. *
  177245. * We can get away with a single array (holding one row's worth of errors)
  177246. * by using it to store the current row's errors at pixel columns not yet
  177247. * processed, but the next row's errors at columns already processed. We
  177248. * need only a few extra variables to hold the errors immediately around the
  177249. * current column. (If we are lucky, those variables are in registers, but
  177250. * even if not, they're probably cheaper to access than array elements are.)
  177251. *
  177252. * The fserrors[] array is indexed [component#][position].
  177253. * We provide (#columns + 2) entries per component; the extra entry at each
  177254. * end saves us from special-casing the first and last pixels.
  177255. *
  177256. * Note: on a wide image, we might not have enough room in a PC's near data
  177257. * segment to hold the error array; so it is allocated with alloc_large.
  177258. */
  177259. #if BITS_IN_JSAMPLE == 8
  177260. typedef INT16 FSERROR; /* 16 bits should be enough */
  177261. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177262. #else
  177263. typedef INT32 FSERROR; /* may need more than 16 bits */
  177264. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177265. #endif
  177266. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177267. /* Private subobject */
  177268. #define MAX_Q_COMPS 4 /* max components I can handle */
  177269. typedef struct {
  177270. struct jpeg_color_quantizer pub; /* public fields */
  177271. /* Initially allocated colormap is saved here */
  177272. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177273. int sv_actual; /* number of entries in use */
  177274. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177275. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177276. * premultiplied as described above. Since colormap indexes must fit into
  177277. * JSAMPLEs, the entries of this array will too.
  177278. */
  177279. boolean is_padded; /* is the colorindex padded for odither? */
  177280. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177281. /* Variables for ordered dithering */
  177282. int row_index; /* cur row's vertical index in dither matrix */
  177283. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177284. /* Variables for Floyd-Steinberg dithering */
  177285. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177286. boolean on_odd_row; /* flag to remember which row we are on */
  177287. } my_cquantizer;
  177288. typedef my_cquantizer * my_cquantize_ptr;
  177289. /*
  177290. * Policy-making subroutines for create_colormap and create_colorindex.
  177291. * These routines determine the colormap to be used. The rest of the module
  177292. * only assumes that the colormap is orthogonal.
  177293. *
  177294. * * select_ncolors decides how to divvy up the available colors
  177295. * among the components.
  177296. * * output_value defines the set of representative values for a component.
  177297. * * largest_input_value defines the mapping from input values to
  177298. * representative values for a component.
  177299. * Note that the latter two routines may impose different policies for
  177300. * different components, though this is not currently done.
  177301. */
  177302. LOCAL(int)
  177303. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177304. /* Determine allocation of desired colors to components, */
  177305. /* and fill in Ncolors[] array to indicate choice. */
  177306. /* Return value is total number of colors (product of Ncolors[] values). */
  177307. {
  177308. int nc = cinfo->out_color_components; /* number of color components */
  177309. int max_colors = cinfo->desired_number_of_colors;
  177310. int total_colors, iroot, i, j;
  177311. boolean changed;
  177312. long temp;
  177313. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177314. /* We can allocate at least the nc'th root of max_colors per component. */
  177315. /* Compute floor(nc'th root of max_colors). */
  177316. iroot = 1;
  177317. do {
  177318. iroot++;
  177319. temp = iroot; /* set temp = iroot ** nc */
  177320. for (i = 1; i < nc; i++)
  177321. temp *= iroot;
  177322. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177323. iroot--; /* now iroot = floor(root) */
  177324. /* Must have at least 2 color values per component */
  177325. if (iroot < 2)
  177326. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177327. /* Initialize to iroot color values for each component */
  177328. total_colors = 1;
  177329. for (i = 0; i < nc; i++) {
  177330. Ncolors[i] = iroot;
  177331. total_colors *= iroot;
  177332. }
  177333. /* We may be able to increment the count for one or more components without
  177334. * exceeding max_colors, though we know not all can be incremented.
  177335. * Sometimes, the first component can be incremented more than once!
  177336. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177337. * In RGB colorspace, try to increment G first, then R, then B.
  177338. */
  177339. do {
  177340. changed = FALSE;
  177341. for (i = 0; i < nc; i++) {
  177342. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177343. /* calculate new total_colors if Ncolors[j] is incremented */
  177344. temp = total_colors / Ncolors[j];
  177345. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177346. if (temp > (long) max_colors)
  177347. break; /* won't fit, done with this pass */
  177348. Ncolors[j]++; /* OK, apply the increment */
  177349. total_colors = (int) temp;
  177350. changed = TRUE;
  177351. }
  177352. } while (changed);
  177353. return total_colors;
  177354. }
  177355. LOCAL(int)
  177356. output_value (j_decompress_ptr, int, int j, int maxj)
  177357. /* Return j'th output value, where j will range from 0 to maxj */
  177358. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177359. {
  177360. /* We always provide values 0 and MAXJSAMPLE for each component;
  177361. * any additional values are equally spaced between these limits.
  177362. * (Forcing the upper and lower values to the limits ensures that
  177363. * dithering can't produce a color outside the selected gamut.)
  177364. */
  177365. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177366. }
  177367. LOCAL(int)
  177368. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177369. /* Return largest input value that should map to j'th output value */
  177370. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177371. {
  177372. /* Breakpoints are halfway between values returned by output_value */
  177373. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177374. }
  177375. /*
  177376. * Create the colormap.
  177377. */
  177378. LOCAL(void)
  177379. create_colormap (j_decompress_ptr cinfo)
  177380. {
  177381. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177382. JSAMPARRAY colormap; /* Created colormap */
  177383. int total_colors; /* Number of distinct output colors */
  177384. int i,j,k, nci, blksize, blkdist, ptr, val;
  177385. /* Select number of colors for each component */
  177386. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177387. /* Report selected color counts */
  177388. if (cinfo->out_color_components == 3)
  177389. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177390. total_colors, cquantize->Ncolors[0],
  177391. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177392. else
  177393. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177394. /* Allocate and fill in the colormap. */
  177395. /* The colors are ordered in the map in standard row-major order, */
  177396. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177397. colormap = (*cinfo->mem->alloc_sarray)
  177398. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177399. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177400. /* blksize is number of adjacent repeated entries for a component */
  177401. /* blkdist is distance between groups of identical entries for a component */
  177402. blkdist = total_colors;
  177403. for (i = 0; i < cinfo->out_color_components; i++) {
  177404. /* fill in colormap entries for i'th color component */
  177405. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177406. blksize = blkdist / nci;
  177407. for (j = 0; j < nci; j++) {
  177408. /* Compute j'th output value (out of nci) for component */
  177409. val = output_value(cinfo, i, j, nci-1);
  177410. /* Fill in all colormap entries that have this value of this component */
  177411. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177412. /* fill in blksize entries beginning at ptr */
  177413. for (k = 0; k < blksize; k++)
  177414. colormap[i][ptr+k] = (JSAMPLE) val;
  177415. }
  177416. }
  177417. blkdist = blksize; /* blksize of this color is blkdist of next */
  177418. }
  177419. /* Save the colormap in private storage,
  177420. * where it will survive color quantization mode changes.
  177421. */
  177422. cquantize->sv_colormap = colormap;
  177423. cquantize->sv_actual = total_colors;
  177424. }
  177425. /*
  177426. * Create the color index table.
  177427. */
  177428. LOCAL(void)
  177429. create_colorindex (j_decompress_ptr cinfo)
  177430. {
  177431. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177432. JSAMPROW indexptr;
  177433. int i,j,k, nci, blksize, val, pad;
  177434. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177435. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177436. * This is not necessary in the other dithering modes. However, we
  177437. * flag whether it was done in case user changes dithering mode.
  177438. */
  177439. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177440. pad = MAXJSAMPLE*2;
  177441. cquantize->is_padded = TRUE;
  177442. } else {
  177443. pad = 0;
  177444. cquantize->is_padded = FALSE;
  177445. }
  177446. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177447. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177448. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177449. (JDIMENSION) cinfo->out_color_components);
  177450. /* blksize is number of adjacent repeated entries for a component */
  177451. blksize = cquantize->sv_actual;
  177452. for (i = 0; i < cinfo->out_color_components; i++) {
  177453. /* fill in colorindex entries for i'th color component */
  177454. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177455. blksize = blksize / nci;
  177456. /* adjust colorindex pointers to provide padding at negative indexes. */
  177457. if (pad)
  177458. cquantize->colorindex[i] += MAXJSAMPLE;
  177459. /* in loop, val = index of current output value, */
  177460. /* and k = largest j that maps to current val */
  177461. indexptr = cquantize->colorindex[i];
  177462. val = 0;
  177463. k = largest_input_value(cinfo, i, 0, nci-1);
  177464. for (j = 0; j <= MAXJSAMPLE; j++) {
  177465. while (j > k) /* advance val if past boundary */
  177466. k = largest_input_value(cinfo, i, ++val, nci-1);
  177467. /* premultiply so that no multiplication needed in main processing */
  177468. indexptr[j] = (JSAMPLE) (val * blksize);
  177469. }
  177470. /* Pad at both ends if necessary */
  177471. if (pad)
  177472. for (j = 1; j <= MAXJSAMPLE; j++) {
  177473. indexptr[-j] = indexptr[0];
  177474. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177475. }
  177476. }
  177477. }
  177478. /*
  177479. * Create an ordered-dither array for a component having ncolors
  177480. * distinct output values.
  177481. */
  177482. LOCAL(ODITHER_MATRIX_PTR)
  177483. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177484. {
  177485. ODITHER_MATRIX_PTR odither;
  177486. int j,k;
  177487. INT32 num,den;
  177488. odither = (ODITHER_MATRIX_PTR)
  177489. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177490. SIZEOF(ODITHER_MATRIX));
  177491. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177492. * Hence the dither value for the matrix cell with fill order f
  177493. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177494. * On 16-bit-int machine, be careful to avoid overflow.
  177495. */
  177496. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177497. for (j = 0; j < ODITHER_SIZE; j++) {
  177498. for (k = 0; k < ODITHER_SIZE; k++) {
  177499. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177500. * MAXJSAMPLE;
  177501. /* Ensure round towards zero despite C's lack of consistency
  177502. * about rounding negative values in integer division...
  177503. */
  177504. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177505. }
  177506. }
  177507. return odither;
  177508. }
  177509. /*
  177510. * Create the ordered-dither tables.
  177511. * Components having the same number of representative colors may
  177512. * share a dither table.
  177513. */
  177514. LOCAL(void)
  177515. create_odither_tables (j_decompress_ptr cinfo)
  177516. {
  177517. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177518. ODITHER_MATRIX_PTR odither;
  177519. int i, j, nci;
  177520. for (i = 0; i < cinfo->out_color_components; i++) {
  177521. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177522. odither = NULL; /* search for matching prior component */
  177523. for (j = 0; j < i; j++) {
  177524. if (nci == cquantize->Ncolors[j]) {
  177525. odither = cquantize->odither[j];
  177526. break;
  177527. }
  177528. }
  177529. if (odither == NULL) /* need a new table? */
  177530. odither = make_odither_array(cinfo, nci);
  177531. cquantize->odither[i] = odither;
  177532. }
  177533. }
  177534. /*
  177535. * Map some rows of pixels to the output colormapped representation.
  177536. */
  177537. METHODDEF(void)
  177538. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177539. JSAMPARRAY output_buf, int num_rows)
  177540. /* General case, no dithering */
  177541. {
  177542. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177543. JSAMPARRAY colorindex = cquantize->colorindex;
  177544. register int pixcode, ci;
  177545. register JSAMPROW ptrin, ptrout;
  177546. int row;
  177547. JDIMENSION col;
  177548. JDIMENSION width = cinfo->output_width;
  177549. register int nc = cinfo->out_color_components;
  177550. for (row = 0; row < num_rows; row++) {
  177551. ptrin = input_buf[row];
  177552. ptrout = output_buf[row];
  177553. for (col = width; col > 0; col--) {
  177554. pixcode = 0;
  177555. for (ci = 0; ci < nc; ci++) {
  177556. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177557. }
  177558. *ptrout++ = (JSAMPLE) pixcode;
  177559. }
  177560. }
  177561. }
  177562. METHODDEF(void)
  177563. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177564. JSAMPARRAY output_buf, int num_rows)
  177565. /* Fast path for out_color_components==3, no dithering */
  177566. {
  177567. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177568. register int pixcode;
  177569. register JSAMPROW ptrin, ptrout;
  177570. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177571. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177572. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177573. int row;
  177574. JDIMENSION col;
  177575. JDIMENSION width = cinfo->output_width;
  177576. for (row = 0; row < num_rows; row++) {
  177577. ptrin = input_buf[row];
  177578. ptrout = output_buf[row];
  177579. for (col = width; col > 0; col--) {
  177580. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177581. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177582. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177583. *ptrout++ = (JSAMPLE) pixcode;
  177584. }
  177585. }
  177586. }
  177587. METHODDEF(void)
  177588. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177589. JSAMPARRAY output_buf, int num_rows)
  177590. /* General case, with ordered dithering */
  177591. {
  177592. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177593. register JSAMPROW input_ptr;
  177594. register JSAMPROW output_ptr;
  177595. JSAMPROW colorindex_ci;
  177596. int * dither; /* points to active row of dither matrix */
  177597. int row_index, col_index; /* current indexes into dither matrix */
  177598. int nc = cinfo->out_color_components;
  177599. int ci;
  177600. int row;
  177601. JDIMENSION col;
  177602. JDIMENSION width = cinfo->output_width;
  177603. for (row = 0; row < num_rows; row++) {
  177604. /* Initialize output values to 0 so can process components separately */
  177605. jzero_far((void FAR *) output_buf[row],
  177606. (size_t) (width * SIZEOF(JSAMPLE)));
  177607. row_index = cquantize->row_index;
  177608. for (ci = 0; ci < nc; ci++) {
  177609. input_ptr = input_buf[row] + ci;
  177610. output_ptr = output_buf[row];
  177611. colorindex_ci = cquantize->colorindex[ci];
  177612. dither = cquantize->odither[ci][row_index];
  177613. col_index = 0;
  177614. for (col = width; col > 0; col--) {
  177615. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177616. * select output value, accumulate into output code for this pixel.
  177617. * Range-limiting need not be done explicitly, as we have extended
  177618. * the colorindex table to produce the right answers for out-of-range
  177619. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177620. * required amount of padding.
  177621. */
  177622. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177623. input_ptr += nc;
  177624. output_ptr++;
  177625. col_index = (col_index + 1) & ODITHER_MASK;
  177626. }
  177627. }
  177628. /* Advance row index for next row */
  177629. row_index = (row_index + 1) & ODITHER_MASK;
  177630. cquantize->row_index = row_index;
  177631. }
  177632. }
  177633. METHODDEF(void)
  177634. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177635. JSAMPARRAY output_buf, int num_rows)
  177636. /* Fast path for out_color_components==3, with ordered dithering */
  177637. {
  177638. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177639. register int pixcode;
  177640. register JSAMPROW input_ptr;
  177641. register JSAMPROW output_ptr;
  177642. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177643. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177644. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177645. int * dither0; /* points to active row of dither matrix */
  177646. int * dither1;
  177647. int * dither2;
  177648. int row_index, col_index; /* current indexes into dither matrix */
  177649. int row;
  177650. JDIMENSION col;
  177651. JDIMENSION width = cinfo->output_width;
  177652. for (row = 0; row < num_rows; row++) {
  177653. row_index = cquantize->row_index;
  177654. input_ptr = input_buf[row];
  177655. output_ptr = output_buf[row];
  177656. dither0 = cquantize->odither[0][row_index];
  177657. dither1 = cquantize->odither[1][row_index];
  177658. dither2 = cquantize->odither[2][row_index];
  177659. col_index = 0;
  177660. for (col = width; col > 0; col--) {
  177661. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177662. dither0[col_index]]);
  177663. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177664. dither1[col_index]]);
  177665. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177666. dither2[col_index]]);
  177667. *output_ptr++ = (JSAMPLE) pixcode;
  177668. col_index = (col_index + 1) & ODITHER_MASK;
  177669. }
  177670. row_index = (row_index + 1) & ODITHER_MASK;
  177671. cquantize->row_index = row_index;
  177672. }
  177673. }
  177674. METHODDEF(void)
  177675. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177676. JSAMPARRAY output_buf, int num_rows)
  177677. /* General case, with Floyd-Steinberg dithering */
  177678. {
  177679. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177680. register LOCFSERROR cur; /* current error or pixel value */
  177681. LOCFSERROR belowerr; /* error for pixel below cur */
  177682. LOCFSERROR bpreverr; /* error for below/prev col */
  177683. LOCFSERROR bnexterr; /* error for below/next col */
  177684. LOCFSERROR delta;
  177685. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177686. register JSAMPROW input_ptr;
  177687. register JSAMPROW output_ptr;
  177688. JSAMPROW colorindex_ci;
  177689. JSAMPROW colormap_ci;
  177690. int pixcode;
  177691. int nc = cinfo->out_color_components;
  177692. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177693. int dirnc; /* dir * nc */
  177694. int ci;
  177695. int row;
  177696. JDIMENSION col;
  177697. JDIMENSION width = cinfo->output_width;
  177698. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177699. SHIFT_TEMPS
  177700. for (row = 0; row < num_rows; row++) {
  177701. /* Initialize output values to 0 so can process components separately */
  177702. jzero_far((void FAR *) output_buf[row],
  177703. (size_t) (width * SIZEOF(JSAMPLE)));
  177704. for (ci = 0; ci < nc; ci++) {
  177705. input_ptr = input_buf[row] + ci;
  177706. output_ptr = output_buf[row];
  177707. if (cquantize->on_odd_row) {
  177708. /* work right to left in this row */
  177709. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177710. output_ptr += width-1;
  177711. dir = -1;
  177712. dirnc = -nc;
  177713. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177714. } else {
  177715. /* work left to right in this row */
  177716. dir = 1;
  177717. dirnc = nc;
  177718. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177719. }
  177720. colorindex_ci = cquantize->colorindex[ci];
  177721. colormap_ci = cquantize->sv_colormap[ci];
  177722. /* Preset error values: no error propagated to first pixel from left */
  177723. cur = 0;
  177724. /* and no error propagated to row below yet */
  177725. belowerr = bpreverr = 0;
  177726. for (col = width; col > 0; col--) {
  177727. /* cur holds the error propagated from the previous pixel on the
  177728. * current line. Add the error propagated from the previous line
  177729. * to form the complete error correction term for this pixel, and
  177730. * round the error term (which is expressed * 16) to an integer.
  177731. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177732. * for either sign of the error value.
  177733. * Note: errorptr points to *previous* column's array entry.
  177734. */
  177735. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177736. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177737. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177738. * of the range_limit array.
  177739. */
  177740. cur += GETJSAMPLE(*input_ptr);
  177741. cur = GETJSAMPLE(range_limit[cur]);
  177742. /* Select output value, accumulate into output code for this pixel */
  177743. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177744. *output_ptr += (JSAMPLE) pixcode;
  177745. /* Compute actual representation error at this pixel */
  177746. /* Note: we can do this even though we don't have the final */
  177747. /* pixel code, because the colormap is orthogonal. */
  177748. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177749. /* Compute error fractions to be propagated to adjacent pixels.
  177750. * Add these into the running sums, and simultaneously shift the
  177751. * next-line error sums left by 1 column.
  177752. */
  177753. bnexterr = cur;
  177754. delta = cur * 2;
  177755. cur += delta; /* form error * 3 */
  177756. errorptr[0] = (FSERROR) (bpreverr + cur);
  177757. cur += delta; /* form error * 5 */
  177758. bpreverr = belowerr + cur;
  177759. belowerr = bnexterr;
  177760. cur += delta; /* form error * 7 */
  177761. /* At this point cur contains the 7/16 error value to be propagated
  177762. * to the next pixel on the current line, and all the errors for the
  177763. * next line have been shifted over. We are therefore ready to move on.
  177764. */
  177765. input_ptr += dirnc; /* advance input ptr to next column */
  177766. output_ptr += dir; /* advance output ptr to next column */
  177767. errorptr += dir; /* advance errorptr to current column */
  177768. }
  177769. /* Post-loop cleanup: we must unload the final error value into the
  177770. * final fserrors[] entry. Note we need not unload belowerr because
  177771. * it is for the dummy column before or after the actual array.
  177772. */
  177773. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177774. }
  177775. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177776. }
  177777. }
  177778. /*
  177779. * Allocate workspace for Floyd-Steinberg errors.
  177780. */
  177781. LOCAL(void)
  177782. alloc_fs_workspace (j_decompress_ptr cinfo)
  177783. {
  177784. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177785. size_t arraysize;
  177786. int i;
  177787. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177788. for (i = 0; i < cinfo->out_color_components; i++) {
  177789. cquantize->fserrors[i] = (FSERRPTR)
  177790. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177791. }
  177792. }
  177793. /*
  177794. * Initialize for one-pass color quantization.
  177795. */
  177796. METHODDEF(void)
  177797. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177798. {
  177799. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177800. size_t arraysize;
  177801. int i;
  177802. /* Install my colormap. */
  177803. cinfo->colormap = cquantize->sv_colormap;
  177804. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177805. /* Initialize for desired dithering mode. */
  177806. switch (cinfo->dither_mode) {
  177807. case JDITHER_NONE:
  177808. if (cinfo->out_color_components == 3)
  177809. cquantize->pub.color_quantize = color_quantize3;
  177810. else
  177811. cquantize->pub.color_quantize = color_quantize;
  177812. break;
  177813. case JDITHER_ORDERED:
  177814. if (cinfo->out_color_components == 3)
  177815. cquantize->pub.color_quantize = quantize3_ord_dither;
  177816. else
  177817. cquantize->pub.color_quantize = quantize_ord_dither;
  177818. cquantize->row_index = 0; /* initialize state for ordered dither */
  177819. /* If user changed to ordered dither from another mode,
  177820. * we must recreate the color index table with padding.
  177821. * This will cost extra space, but probably isn't very likely.
  177822. */
  177823. if (! cquantize->is_padded)
  177824. create_colorindex(cinfo);
  177825. /* Create ordered-dither tables if we didn't already. */
  177826. if (cquantize->odither[0] == NULL)
  177827. create_odither_tables(cinfo);
  177828. break;
  177829. case JDITHER_FS:
  177830. cquantize->pub.color_quantize = quantize_fs_dither;
  177831. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177832. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177833. if (cquantize->fserrors[0] == NULL)
  177834. alloc_fs_workspace(cinfo);
  177835. /* Initialize the propagated errors to zero. */
  177836. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177837. for (i = 0; i < cinfo->out_color_components; i++)
  177838. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177839. break;
  177840. default:
  177841. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177842. break;
  177843. }
  177844. }
  177845. /*
  177846. * Finish up at the end of the pass.
  177847. */
  177848. METHODDEF(void)
  177849. finish_pass_1_quant (j_decompress_ptr)
  177850. {
  177851. /* no work in 1-pass case */
  177852. }
  177853. /*
  177854. * Switch to a new external colormap between output passes.
  177855. * Shouldn't get to this module!
  177856. */
  177857. METHODDEF(void)
  177858. new_color_map_1_quant (j_decompress_ptr cinfo)
  177859. {
  177860. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177861. }
  177862. /*
  177863. * Module initialization routine for 1-pass color quantization.
  177864. */
  177865. GLOBAL(void)
  177866. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177867. {
  177868. my_cquantize_ptr cquantize;
  177869. cquantize = (my_cquantize_ptr)
  177870. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177871. SIZEOF(my_cquantizer));
  177872. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177873. cquantize->pub.start_pass = start_pass_1_quant;
  177874. cquantize->pub.finish_pass = finish_pass_1_quant;
  177875. cquantize->pub.new_color_map = new_color_map_1_quant;
  177876. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177877. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177878. /* Make sure my internal arrays won't overflow */
  177879. if (cinfo->out_color_components > MAX_Q_COMPS)
  177880. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177881. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177882. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177883. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177884. /* Create the colormap and color index table. */
  177885. create_colormap(cinfo);
  177886. create_colorindex(cinfo);
  177887. /* Allocate Floyd-Steinberg workspace now if requested.
  177888. * We do this now since it is FAR storage and may affect the memory
  177889. * manager's space calculations. If the user changes to FS dither
  177890. * mode in a later pass, we will allocate the space then, and will
  177891. * possibly overrun the max_memory_to_use setting.
  177892. */
  177893. if (cinfo->dither_mode == JDITHER_FS)
  177894. alloc_fs_workspace(cinfo);
  177895. }
  177896. #endif /* QUANT_1PASS_SUPPORTED */
  177897. /*** End of inlined file: jquant1.c ***/
  177898. /*** Start of inlined file: jquant2.c ***/
  177899. #define JPEG_INTERNALS
  177900. #ifdef QUANT_2PASS_SUPPORTED
  177901. /*
  177902. * This module implements the well-known Heckbert paradigm for color
  177903. * quantization. Most of the ideas used here can be traced back to
  177904. * Heckbert's seminal paper
  177905. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177906. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177907. *
  177908. * In the first pass over the image, we accumulate a histogram showing the
  177909. * usage count of each possible color. To keep the histogram to a reasonable
  177910. * size, we reduce the precision of the input; typical practice is to retain
  177911. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177912. * in the same histogram cell.
  177913. *
  177914. * Next, the color-selection step begins with a box representing the whole
  177915. * color space, and repeatedly splits the "largest" remaining box until we
  177916. * have as many boxes as desired colors. Then the mean color in each
  177917. * remaining box becomes one of the possible output colors.
  177918. *
  177919. * The second pass over the image maps each input pixel to the closest output
  177920. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177921. * This mapping is logically trivial, but making it go fast enough requires
  177922. * considerable care.
  177923. *
  177924. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177925. * the "largest" box and deciding where to cut it. The particular policies
  177926. * used here have proved out well in experimental comparisons, but better ones
  177927. * may yet be found.
  177928. *
  177929. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177930. * space, processing the raw upsampled data without a color conversion step.
  177931. * This allowed the color conversion math to be done only once per colormap
  177932. * entry, not once per pixel. However, that optimization precluded other
  177933. * useful optimizations (such as merging color conversion with upsampling)
  177934. * and it also interfered with desired capabilities such as quantizing to an
  177935. * externally-supplied colormap. We have therefore abandoned that approach.
  177936. * The present code works in the post-conversion color space, typically RGB.
  177937. *
  177938. * To improve the visual quality of the results, we actually work in scaled
  177939. * RGB space, giving G distances more weight than R, and R in turn more than
  177940. * B. To do everything in integer math, we must use integer scale factors.
  177941. * The 2/3/1 scale factors used here correspond loosely to the relative
  177942. * weights of the colors in the NTSC grayscale equation.
  177943. * If you want to use this code to quantize a non-RGB color space, you'll
  177944. * probably need to change these scale factors.
  177945. */
  177946. #define R_SCALE 2 /* scale R distances by this much */
  177947. #define G_SCALE 3 /* scale G distances by this much */
  177948. #define B_SCALE 1 /* and B by this much */
  177949. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177950. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177951. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177952. * you'll get compile errors until you extend this logic. In that case
  177953. * you'll probably want to tweak the histogram sizes too.
  177954. */
  177955. #if RGB_RED == 0
  177956. #define C0_SCALE R_SCALE
  177957. #endif
  177958. #if RGB_BLUE == 0
  177959. #define C0_SCALE B_SCALE
  177960. #endif
  177961. #if RGB_GREEN == 1
  177962. #define C1_SCALE G_SCALE
  177963. #endif
  177964. #if RGB_RED == 2
  177965. #define C2_SCALE R_SCALE
  177966. #endif
  177967. #if RGB_BLUE == 2
  177968. #define C2_SCALE B_SCALE
  177969. #endif
  177970. /*
  177971. * First we have the histogram data structure and routines for creating it.
  177972. *
  177973. * The number of bits of precision can be adjusted by changing these symbols.
  177974. * We recommend keeping 6 bits for G and 5 each for R and B.
  177975. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177976. * better results; if you are short of memory, 5 bits all around will save
  177977. * some space but degrade the results.
  177978. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177979. * (preferably unsigned long) for each cell. In practice this is overkill;
  177980. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177981. * and clamping those that do overflow to the maximum value will give close-
  177982. * enough results. This reduces the recommended histogram size from 256Kb
  177983. * to 128Kb, which is a useful savings on PC-class machines.
  177984. * (In the second pass the histogram space is re-used for pixel mapping data;
  177985. * in that capacity, each cell must be able to store zero to the number of
  177986. * desired colors. 16 bits/cell is plenty for that too.)
  177987. * Since the JPEG code is intended to run in small memory model on 80x86
  177988. * machines, we can't just allocate the histogram in one chunk. Instead
  177989. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177990. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177991. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177992. * on 80x86 machines, the pointer row is in near memory but the actual
  177993. * arrays are in far memory (same arrangement as we use for image arrays).
  177994. */
  177995. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177996. /* These will do the right thing for either R,G,B or B,G,R color order,
  177997. * but you may not like the results for other color orders.
  177998. */
  177999. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  178000. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  178001. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  178002. /* Number of elements along histogram axes. */
  178003. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  178004. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  178005. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  178006. /* These are the amounts to shift an input value to get a histogram index. */
  178007. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  178008. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  178009. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  178010. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  178011. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  178012. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  178013. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  178014. typedef hist2d * hist3d; /* type for top-level pointer */
  178015. /* Declarations for Floyd-Steinberg dithering.
  178016. *
  178017. * Errors are accumulated into the array fserrors[], at a resolution of
  178018. * 1/16th of a pixel count. The error at a given pixel is propagated
  178019. * to its not-yet-processed neighbors using the standard F-S fractions,
  178020. * ... (here) 7/16
  178021. * 3/16 5/16 1/16
  178022. * We work left-to-right on even rows, right-to-left on odd rows.
  178023. *
  178024. * We can get away with a single array (holding one row's worth of errors)
  178025. * by using it to store the current row's errors at pixel columns not yet
  178026. * processed, but the next row's errors at columns already processed. We
  178027. * need only a few extra variables to hold the errors immediately around the
  178028. * current column. (If we are lucky, those variables are in registers, but
  178029. * even if not, they're probably cheaper to access than array elements are.)
  178030. *
  178031. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  178032. * each end saves us from special-casing the first and last pixels.
  178033. * Each entry is three values long, one value for each color component.
  178034. *
  178035. * Note: on a wide image, we might not have enough room in a PC's near data
  178036. * segment to hold the error array; so it is allocated with alloc_large.
  178037. */
  178038. #if BITS_IN_JSAMPLE == 8
  178039. typedef INT16 FSERROR; /* 16 bits should be enough */
  178040. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  178041. #else
  178042. typedef INT32 FSERROR; /* may need more than 16 bits */
  178043. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  178044. #endif
  178045. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  178046. /* Private subobject */
  178047. typedef struct {
  178048. struct jpeg_color_quantizer pub; /* public fields */
  178049. /* Space for the eventually created colormap is stashed here */
  178050. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  178051. int desired; /* desired # of colors = size of colormap */
  178052. /* Variables for accumulating image statistics */
  178053. hist3d histogram; /* pointer to the histogram */
  178054. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  178055. /* Variables for Floyd-Steinberg dithering */
  178056. FSERRPTR fserrors; /* accumulated errors */
  178057. boolean on_odd_row; /* flag to remember which row we are on */
  178058. int * error_limiter; /* table for clamping the applied error */
  178059. } my_cquantizer2;
  178060. typedef my_cquantizer2 * my_cquantize_ptr2;
  178061. /*
  178062. * Prescan some rows of pixels.
  178063. * In this module the prescan simply updates the histogram, which has been
  178064. * initialized to zeroes by start_pass.
  178065. * An output_buf parameter is required by the method signature, but no data
  178066. * is actually output (in fact the buffer controller is probably passing a
  178067. * NULL pointer).
  178068. */
  178069. METHODDEF(void)
  178070. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178071. JSAMPARRAY, int num_rows)
  178072. {
  178073. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178074. register JSAMPROW ptr;
  178075. register histptr histp;
  178076. register hist3d histogram = cquantize->histogram;
  178077. int row;
  178078. JDIMENSION col;
  178079. JDIMENSION width = cinfo->output_width;
  178080. for (row = 0; row < num_rows; row++) {
  178081. ptr = input_buf[row];
  178082. for (col = width; col > 0; col--) {
  178083. /* get pixel value and index into the histogram */
  178084. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  178085. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  178086. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  178087. /* increment, check for overflow and undo increment if so. */
  178088. if (++(*histp) <= 0)
  178089. (*histp)--;
  178090. ptr += 3;
  178091. }
  178092. }
  178093. }
  178094. /*
  178095. * Next we have the really interesting routines: selection of a colormap
  178096. * given the completed histogram.
  178097. * These routines work with a list of "boxes", each representing a rectangular
  178098. * subset of the input color space (to histogram precision).
  178099. */
  178100. typedef struct {
  178101. /* The bounds of the box (inclusive); expressed as histogram indexes */
  178102. int c0min, c0max;
  178103. int c1min, c1max;
  178104. int c2min, c2max;
  178105. /* The volume (actually 2-norm) of the box */
  178106. INT32 volume;
  178107. /* The number of nonzero histogram cells within this box */
  178108. long colorcount;
  178109. } box;
  178110. typedef box * boxptr;
  178111. LOCAL(boxptr)
  178112. find_biggest_color_pop (boxptr boxlist, int numboxes)
  178113. /* Find the splittable box with the largest color population */
  178114. /* Returns NULL if no splittable boxes remain */
  178115. {
  178116. register boxptr boxp;
  178117. register int i;
  178118. register long maxc = 0;
  178119. boxptr which = NULL;
  178120. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178121. if (boxp->colorcount > maxc && boxp->volume > 0) {
  178122. which = boxp;
  178123. maxc = boxp->colorcount;
  178124. }
  178125. }
  178126. return which;
  178127. }
  178128. LOCAL(boxptr)
  178129. find_biggest_volume (boxptr boxlist, int numboxes)
  178130. /* Find the splittable box with the largest (scaled) volume */
  178131. /* Returns NULL if no splittable boxes remain */
  178132. {
  178133. register boxptr boxp;
  178134. register int i;
  178135. register INT32 maxv = 0;
  178136. boxptr which = NULL;
  178137. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178138. if (boxp->volume > maxv) {
  178139. which = boxp;
  178140. maxv = boxp->volume;
  178141. }
  178142. }
  178143. return which;
  178144. }
  178145. LOCAL(void)
  178146. update_box (j_decompress_ptr cinfo, boxptr boxp)
  178147. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  178148. /* and recompute its volume and population */
  178149. {
  178150. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178151. hist3d histogram = cquantize->histogram;
  178152. histptr histp;
  178153. int c0,c1,c2;
  178154. int c0min,c0max,c1min,c1max,c2min,c2max;
  178155. INT32 dist0,dist1,dist2;
  178156. long ccount;
  178157. c0min = boxp->c0min; c0max = boxp->c0max;
  178158. c1min = boxp->c1min; c1max = boxp->c1max;
  178159. c2min = boxp->c2min; c2max = boxp->c2max;
  178160. if (c0max > c0min)
  178161. for (c0 = c0min; c0 <= c0max; c0++)
  178162. for (c1 = c1min; c1 <= c1max; c1++) {
  178163. histp = & histogram[c0][c1][c2min];
  178164. for (c2 = c2min; c2 <= c2max; c2++)
  178165. if (*histp++ != 0) {
  178166. boxp->c0min = c0min = c0;
  178167. goto have_c0min;
  178168. }
  178169. }
  178170. have_c0min:
  178171. if (c0max > c0min)
  178172. for (c0 = c0max; c0 >= c0min; c0--)
  178173. for (c1 = c1min; c1 <= c1max; c1++) {
  178174. histp = & histogram[c0][c1][c2min];
  178175. for (c2 = c2min; c2 <= c2max; c2++)
  178176. if (*histp++ != 0) {
  178177. boxp->c0max = c0max = c0;
  178178. goto have_c0max;
  178179. }
  178180. }
  178181. have_c0max:
  178182. if (c1max > c1min)
  178183. for (c1 = c1min; c1 <= c1max; c1++)
  178184. for (c0 = c0min; c0 <= c0max; c0++) {
  178185. histp = & histogram[c0][c1][c2min];
  178186. for (c2 = c2min; c2 <= c2max; c2++)
  178187. if (*histp++ != 0) {
  178188. boxp->c1min = c1min = c1;
  178189. goto have_c1min;
  178190. }
  178191. }
  178192. have_c1min:
  178193. if (c1max > c1min)
  178194. for (c1 = c1max; c1 >= c1min; c1--)
  178195. for (c0 = c0min; c0 <= c0max; c0++) {
  178196. histp = & histogram[c0][c1][c2min];
  178197. for (c2 = c2min; c2 <= c2max; c2++)
  178198. if (*histp++ != 0) {
  178199. boxp->c1max = c1max = c1;
  178200. goto have_c1max;
  178201. }
  178202. }
  178203. have_c1max:
  178204. if (c2max > c2min)
  178205. for (c2 = c2min; c2 <= c2max; c2++)
  178206. for (c0 = c0min; c0 <= c0max; c0++) {
  178207. histp = & histogram[c0][c1min][c2];
  178208. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178209. if (*histp != 0) {
  178210. boxp->c2min = c2min = c2;
  178211. goto have_c2min;
  178212. }
  178213. }
  178214. have_c2min:
  178215. if (c2max > c2min)
  178216. for (c2 = c2max; c2 >= c2min; c2--)
  178217. for (c0 = c0min; c0 <= c0max; c0++) {
  178218. histp = & histogram[c0][c1min][c2];
  178219. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178220. if (*histp != 0) {
  178221. boxp->c2max = c2max = c2;
  178222. goto have_c2max;
  178223. }
  178224. }
  178225. have_c2max:
  178226. /* Update box volume.
  178227. * We use 2-norm rather than real volume here; this biases the method
  178228. * against making long narrow boxes, and it has the side benefit that
  178229. * a box is splittable iff norm > 0.
  178230. * Since the differences are expressed in histogram-cell units,
  178231. * we have to shift back to JSAMPLE units to get consistent distances;
  178232. * after which, we scale according to the selected distance scale factors.
  178233. */
  178234. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178235. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178236. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178237. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178238. /* Now scan remaining volume of box and compute population */
  178239. ccount = 0;
  178240. for (c0 = c0min; c0 <= c0max; c0++)
  178241. for (c1 = c1min; c1 <= c1max; c1++) {
  178242. histp = & histogram[c0][c1][c2min];
  178243. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178244. if (*histp != 0) {
  178245. ccount++;
  178246. }
  178247. }
  178248. boxp->colorcount = ccount;
  178249. }
  178250. LOCAL(int)
  178251. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178252. int desired_colors)
  178253. /* Repeatedly select and split the largest box until we have enough boxes */
  178254. {
  178255. int n,lb;
  178256. int c0,c1,c2,cmax;
  178257. register boxptr b1,b2;
  178258. while (numboxes < desired_colors) {
  178259. /* Select box to split.
  178260. * Current algorithm: by population for first half, then by volume.
  178261. */
  178262. if (numboxes*2 <= desired_colors) {
  178263. b1 = find_biggest_color_pop(boxlist, numboxes);
  178264. } else {
  178265. b1 = find_biggest_volume(boxlist, numboxes);
  178266. }
  178267. if (b1 == NULL) /* no splittable boxes left! */
  178268. break;
  178269. b2 = &boxlist[numboxes]; /* where new box will go */
  178270. /* Copy the color bounds to the new box. */
  178271. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178272. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178273. /* Choose which axis to split the box on.
  178274. * Current algorithm: longest scaled axis.
  178275. * See notes in update_box about scaling distances.
  178276. */
  178277. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178278. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178279. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178280. /* We want to break any ties in favor of green, then red, blue last.
  178281. * This code does the right thing for R,G,B or B,G,R color orders only.
  178282. */
  178283. #if RGB_RED == 0
  178284. cmax = c1; n = 1;
  178285. if (c0 > cmax) { cmax = c0; n = 0; }
  178286. if (c2 > cmax) { n = 2; }
  178287. #else
  178288. cmax = c1; n = 1;
  178289. if (c2 > cmax) { cmax = c2; n = 2; }
  178290. if (c0 > cmax) { n = 0; }
  178291. #endif
  178292. /* Choose split point along selected axis, and update box bounds.
  178293. * Current algorithm: split at halfway point.
  178294. * (Since the box has been shrunk to minimum volume,
  178295. * any split will produce two nonempty subboxes.)
  178296. * Note that lb value is max for lower box, so must be < old max.
  178297. */
  178298. switch (n) {
  178299. case 0:
  178300. lb = (b1->c0max + b1->c0min) / 2;
  178301. b1->c0max = lb;
  178302. b2->c0min = lb+1;
  178303. break;
  178304. case 1:
  178305. lb = (b1->c1max + b1->c1min) / 2;
  178306. b1->c1max = lb;
  178307. b2->c1min = lb+1;
  178308. break;
  178309. case 2:
  178310. lb = (b1->c2max + b1->c2min) / 2;
  178311. b1->c2max = lb;
  178312. b2->c2min = lb+1;
  178313. break;
  178314. }
  178315. /* Update stats for boxes */
  178316. update_box(cinfo, b1);
  178317. update_box(cinfo, b2);
  178318. numboxes++;
  178319. }
  178320. return numboxes;
  178321. }
  178322. LOCAL(void)
  178323. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178324. /* Compute representative color for a box, put it in colormap[icolor] */
  178325. {
  178326. /* Current algorithm: mean weighted by pixels (not colors) */
  178327. /* Note it is important to get the rounding correct! */
  178328. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178329. hist3d histogram = cquantize->histogram;
  178330. histptr histp;
  178331. int c0,c1,c2;
  178332. int c0min,c0max,c1min,c1max,c2min,c2max;
  178333. long count;
  178334. long total = 0;
  178335. long c0total = 0;
  178336. long c1total = 0;
  178337. long c2total = 0;
  178338. c0min = boxp->c0min; c0max = boxp->c0max;
  178339. c1min = boxp->c1min; c1max = boxp->c1max;
  178340. c2min = boxp->c2min; c2max = boxp->c2max;
  178341. for (c0 = c0min; c0 <= c0max; c0++)
  178342. for (c1 = c1min; c1 <= c1max; c1++) {
  178343. histp = & histogram[c0][c1][c2min];
  178344. for (c2 = c2min; c2 <= c2max; c2++) {
  178345. if ((count = *histp++) != 0) {
  178346. total += count;
  178347. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178348. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178349. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178350. }
  178351. }
  178352. }
  178353. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178354. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178355. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178356. }
  178357. LOCAL(void)
  178358. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178359. /* Master routine for color selection */
  178360. {
  178361. boxptr boxlist;
  178362. int numboxes;
  178363. int i;
  178364. /* Allocate workspace for box list */
  178365. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178366. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178367. /* Initialize one box containing whole space */
  178368. numboxes = 1;
  178369. boxlist[0].c0min = 0;
  178370. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178371. boxlist[0].c1min = 0;
  178372. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178373. boxlist[0].c2min = 0;
  178374. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178375. /* Shrink it to actually-used volume and set its statistics */
  178376. update_box(cinfo, & boxlist[0]);
  178377. /* Perform median-cut to produce final box list */
  178378. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178379. /* Compute the representative color for each box, fill colormap */
  178380. for (i = 0; i < numboxes; i++)
  178381. compute_color(cinfo, & boxlist[i], i);
  178382. cinfo->actual_number_of_colors = numboxes;
  178383. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178384. }
  178385. /*
  178386. * These routines are concerned with the time-critical task of mapping input
  178387. * colors to the nearest color in the selected colormap.
  178388. *
  178389. * We re-use the histogram space as an "inverse color map", essentially a
  178390. * cache for the results of nearest-color searches. All colors within a
  178391. * histogram cell will be mapped to the same colormap entry, namely the one
  178392. * closest to the cell's center. This may not be quite the closest entry to
  178393. * the actual input color, but it's almost as good. A zero in the cache
  178394. * indicates we haven't found the nearest color for that cell yet; the array
  178395. * is cleared to zeroes before starting the mapping pass. When we find the
  178396. * nearest color for a cell, its colormap index plus one is recorded in the
  178397. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178398. * when they need to use an unfilled entry in the cache.
  178399. *
  178400. * Our method of efficiently finding nearest colors is based on the "locally
  178401. * sorted search" idea described by Heckbert and on the incremental distance
  178402. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178403. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178404. * the distances from a given colormap entry to each cell of the histogram can
  178405. * be computed quickly using an incremental method: the differences between
  178406. * distances to adjacent cells themselves differ by a constant. This allows a
  178407. * fairly fast implementation of the "brute force" approach of computing the
  178408. * distance from every colormap entry to every histogram cell. Unfortunately,
  178409. * it needs a work array to hold the best-distance-so-far for each histogram
  178410. * cell (because the inner loop has to be over cells, not colormap entries).
  178411. * The work array elements have to be INT32s, so the work array would need
  178412. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178413. *
  178414. * To get around these problems, we apply Thomas' method to compute the
  178415. * nearest colors for only the cells within a small subbox of the histogram.
  178416. * The work array need be only as big as the subbox, so the memory usage
  178417. * problem is solved. Furthermore, we need not fill subboxes that are never
  178418. * referenced in pass2; many images use only part of the color gamut, so a
  178419. * fair amount of work is saved. An additional advantage of this
  178420. * approach is that we can apply Heckbert's locality criterion to quickly
  178421. * eliminate colormap entries that are far away from the subbox; typically
  178422. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178423. * and we need not compute their distances to individual cells in the subbox.
  178424. * The speed of this approach is heavily influenced by the subbox size: too
  178425. * small means too much overhead, too big loses because Heckbert's criterion
  178426. * can't eliminate as many colormap entries. Empirically the best subbox
  178427. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178428. *
  178429. * Thomas' article also describes a refined method which is asymptotically
  178430. * faster than the brute-force method, but it is also far more complex and
  178431. * cannot efficiently be applied to small subboxes. It is therefore not
  178432. * useful for programs intended to be portable to DOS machines. On machines
  178433. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178434. * refined method might be faster than the present code --- but then again,
  178435. * it might not be any faster, and it's certainly more complicated.
  178436. */
  178437. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178438. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178439. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178440. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178441. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178442. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178443. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178444. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178445. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178446. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178447. /*
  178448. * The next three routines implement inverse colormap filling. They could
  178449. * all be folded into one big routine, but splitting them up this way saves
  178450. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178451. * and may allow some compilers to produce better code by registerizing more
  178452. * inner-loop variables.
  178453. */
  178454. LOCAL(int)
  178455. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178456. JSAMPLE colorlist[])
  178457. /* Locate the colormap entries close enough to an update box to be candidates
  178458. * for the nearest entry to some cell(s) in the update box. The update box
  178459. * is specified by the center coordinates of its first cell. The number of
  178460. * candidate colormap entries is returned, and their colormap indexes are
  178461. * placed in colorlist[].
  178462. * This routine uses Heckbert's "locally sorted search" criterion to select
  178463. * the colors that need further consideration.
  178464. */
  178465. {
  178466. int numcolors = cinfo->actual_number_of_colors;
  178467. int maxc0, maxc1, maxc2;
  178468. int centerc0, centerc1, centerc2;
  178469. int i, x, ncolors;
  178470. INT32 minmaxdist, min_dist, max_dist, tdist;
  178471. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178472. /* Compute true coordinates of update box's upper corner and center.
  178473. * Actually we compute the coordinates of the center of the upper-corner
  178474. * histogram cell, which are the upper bounds of the volume we care about.
  178475. * Note that since ">>" rounds down, the "center" values may be closer to
  178476. * min than to max; hence comparisons to them must be "<=", not "<".
  178477. */
  178478. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178479. centerc0 = (minc0 + maxc0) >> 1;
  178480. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178481. centerc1 = (minc1 + maxc1) >> 1;
  178482. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178483. centerc2 = (minc2 + maxc2) >> 1;
  178484. /* For each color in colormap, find:
  178485. * 1. its minimum squared-distance to any point in the update box
  178486. * (zero if color is within update box);
  178487. * 2. its maximum squared-distance to any point in the update box.
  178488. * Both of these can be found by considering only the corners of the box.
  178489. * We save the minimum distance for each color in mindist[];
  178490. * only the smallest maximum distance is of interest.
  178491. */
  178492. minmaxdist = 0x7FFFFFFFL;
  178493. for (i = 0; i < numcolors; i++) {
  178494. /* We compute the squared-c0-distance term, then add in the other two. */
  178495. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178496. if (x < minc0) {
  178497. tdist = (x - minc0) * C0_SCALE;
  178498. min_dist = tdist*tdist;
  178499. tdist = (x - maxc0) * C0_SCALE;
  178500. max_dist = tdist*tdist;
  178501. } else if (x > maxc0) {
  178502. tdist = (x - maxc0) * C0_SCALE;
  178503. min_dist = tdist*tdist;
  178504. tdist = (x - minc0) * C0_SCALE;
  178505. max_dist = tdist*tdist;
  178506. } else {
  178507. /* within cell range so no contribution to min_dist */
  178508. min_dist = 0;
  178509. if (x <= centerc0) {
  178510. tdist = (x - maxc0) * C0_SCALE;
  178511. max_dist = tdist*tdist;
  178512. } else {
  178513. tdist = (x - minc0) * C0_SCALE;
  178514. max_dist = tdist*tdist;
  178515. }
  178516. }
  178517. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178518. if (x < minc1) {
  178519. tdist = (x - minc1) * C1_SCALE;
  178520. min_dist += tdist*tdist;
  178521. tdist = (x - maxc1) * C1_SCALE;
  178522. max_dist += tdist*tdist;
  178523. } else if (x > maxc1) {
  178524. tdist = (x - maxc1) * C1_SCALE;
  178525. min_dist += tdist*tdist;
  178526. tdist = (x - minc1) * C1_SCALE;
  178527. max_dist += tdist*tdist;
  178528. } else {
  178529. /* within cell range so no contribution to min_dist */
  178530. if (x <= centerc1) {
  178531. tdist = (x - maxc1) * C1_SCALE;
  178532. max_dist += tdist*tdist;
  178533. } else {
  178534. tdist = (x - minc1) * C1_SCALE;
  178535. max_dist += tdist*tdist;
  178536. }
  178537. }
  178538. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178539. if (x < minc2) {
  178540. tdist = (x - minc2) * C2_SCALE;
  178541. min_dist += tdist*tdist;
  178542. tdist = (x - maxc2) * C2_SCALE;
  178543. max_dist += tdist*tdist;
  178544. } else if (x > maxc2) {
  178545. tdist = (x - maxc2) * C2_SCALE;
  178546. min_dist += tdist*tdist;
  178547. tdist = (x - minc2) * C2_SCALE;
  178548. max_dist += tdist*tdist;
  178549. } else {
  178550. /* within cell range so no contribution to min_dist */
  178551. if (x <= centerc2) {
  178552. tdist = (x - maxc2) * C2_SCALE;
  178553. max_dist += tdist*tdist;
  178554. } else {
  178555. tdist = (x - minc2) * C2_SCALE;
  178556. max_dist += tdist*tdist;
  178557. }
  178558. }
  178559. mindist[i] = min_dist; /* save away the results */
  178560. if (max_dist < minmaxdist)
  178561. minmaxdist = max_dist;
  178562. }
  178563. /* Now we know that no cell in the update box is more than minmaxdist
  178564. * away from some colormap entry. Therefore, only colors that are
  178565. * within minmaxdist of some part of the box need be considered.
  178566. */
  178567. ncolors = 0;
  178568. for (i = 0; i < numcolors; i++) {
  178569. if (mindist[i] <= minmaxdist)
  178570. colorlist[ncolors++] = (JSAMPLE) i;
  178571. }
  178572. return ncolors;
  178573. }
  178574. LOCAL(void)
  178575. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178576. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178577. /* Find the closest colormap entry for each cell in the update box,
  178578. * given the list of candidate colors prepared by find_nearby_colors.
  178579. * Return the indexes of the closest entries in the bestcolor[] array.
  178580. * This routine uses Thomas' incremental distance calculation method to
  178581. * find the distance from a colormap entry to successive cells in the box.
  178582. */
  178583. {
  178584. int ic0, ic1, ic2;
  178585. int i, icolor;
  178586. register INT32 * bptr; /* pointer into bestdist[] array */
  178587. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178588. INT32 dist0, dist1; /* initial distance values */
  178589. register INT32 dist2; /* current distance in inner loop */
  178590. INT32 xx0, xx1; /* distance increments */
  178591. register INT32 xx2;
  178592. INT32 inc0, inc1, inc2; /* initial values for increments */
  178593. /* This array holds the distance to the nearest-so-far color for each cell */
  178594. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178595. /* Initialize best-distance for each cell of the update box */
  178596. bptr = bestdist;
  178597. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178598. *bptr++ = 0x7FFFFFFFL;
  178599. /* For each color selected by find_nearby_colors,
  178600. * compute its distance to the center of each cell in the box.
  178601. * If that's less than best-so-far, update best distance and color number.
  178602. */
  178603. /* Nominal steps between cell centers ("x" in Thomas article) */
  178604. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178605. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178606. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178607. for (i = 0; i < numcolors; i++) {
  178608. icolor = GETJSAMPLE(colorlist[i]);
  178609. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178610. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178611. dist0 = inc0*inc0;
  178612. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178613. dist0 += inc1*inc1;
  178614. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178615. dist0 += inc2*inc2;
  178616. /* Form the initial difference increments */
  178617. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178618. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178619. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178620. /* Now loop over all cells in box, updating distance per Thomas method */
  178621. bptr = bestdist;
  178622. cptr = bestcolor;
  178623. xx0 = inc0;
  178624. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178625. dist1 = dist0;
  178626. xx1 = inc1;
  178627. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178628. dist2 = dist1;
  178629. xx2 = inc2;
  178630. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178631. if (dist2 < *bptr) {
  178632. *bptr = dist2;
  178633. *cptr = (JSAMPLE) icolor;
  178634. }
  178635. dist2 += xx2;
  178636. xx2 += 2 * STEP_C2 * STEP_C2;
  178637. bptr++;
  178638. cptr++;
  178639. }
  178640. dist1 += xx1;
  178641. xx1 += 2 * STEP_C1 * STEP_C1;
  178642. }
  178643. dist0 += xx0;
  178644. xx0 += 2 * STEP_C0 * STEP_C0;
  178645. }
  178646. }
  178647. }
  178648. LOCAL(void)
  178649. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178650. /* Fill the inverse-colormap entries in the update box that contains */
  178651. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178652. /* we can fill as many others as we wish.) */
  178653. {
  178654. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178655. hist3d histogram = cquantize->histogram;
  178656. int minc0, minc1, minc2; /* lower left corner of update box */
  178657. int ic0, ic1, ic2;
  178658. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178659. register histptr cachep; /* pointer into main cache array */
  178660. /* This array lists the candidate colormap indexes. */
  178661. JSAMPLE colorlist[MAXNUMCOLORS];
  178662. int numcolors; /* number of candidate colors */
  178663. /* This array holds the actually closest colormap index for each cell. */
  178664. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178665. /* Convert cell coordinates to update box ID */
  178666. c0 >>= BOX_C0_LOG;
  178667. c1 >>= BOX_C1_LOG;
  178668. c2 >>= BOX_C2_LOG;
  178669. /* Compute true coordinates of update box's origin corner.
  178670. * Actually we compute the coordinates of the center of the corner
  178671. * histogram cell, which are the lower bounds of the volume we care about.
  178672. */
  178673. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178674. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178675. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178676. /* Determine which colormap entries are close enough to be candidates
  178677. * for the nearest entry to some cell in the update box.
  178678. */
  178679. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178680. /* Determine the actually nearest colors. */
  178681. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178682. bestcolor);
  178683. /* Save the best color numbers (plus 1) in the main cache array */
  178684. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178685. c1 <<= BOX_C1_LOG;
  178686. c2 <<= BOX_C2_LOG;
  178687. cptr = bestcolor;
  178688. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178689. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178690. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178691. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178692. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178693. }
  178694. }
  178695. }
  178696. }
  178697. /*
  178698. * Map some rows of pixels to the output colormapped representation.
  178699. */
  178700. METHODDEF(void)
  178701. pass2_no_dither (j_decompress_ptr cinfo,
  178702. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178703. /* This version performs no dithering */
  178704. {
  178705. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178706. hist3d histogram = cquantize->histogram;
  178707. register JSAMPROW inptr, outptr;
  178708. register histptr cachep;
  178709. register int c0, c1, c2;
  178710. int row;
  178711. JDIMENSION col;
  178712. JDIMENSION width = cinfo->output_width;
  178713. for (row = 0; row < num_rows; row++) {
  178714. inptr = input_buf[row];
  178715. outptr = output_buf[row];
  178716. for (col = width; col > 0; col--) {
  178717. /* get pixel value and index into the cache */
  178718. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178719. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178720. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178721. cachep = & histogram[c0][c1][c2];
  178722. /* If we have not seen this color before, find nearest colormap entry */
  178723. /* and update the cache */
  178724. if (*cachep == 0)
  178725. fill_inverse_cmap(cinfo, c0,c1,c2);
  178726. /* Now emit the colormap index for this cell */
  178727. *outptr++ = (JSAMPLE) (*cachep - 1);
  178728. }
  178729. }
  178730. }
  178731. METHODDEF(void)
  178732. pass2_fs_dither (j_decompress_ptr cinfo,
  178733. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178734. /* This version performs Floyd-Steinberg dithering */
  178735. {
  178736. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178737. hist3d histogram = cquantize->histogram;
  178738. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178739. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178740. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178741. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178742. JSAMPROW inptr; /* => current input pixel */
  178743. JSAMPROW outptr; /* => current output pixel */
  178744. histptr cachep;
  178745. int dir; /* +1 or -1 depending on direction */
  178746. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178747. int row;
  178748. JDIMENSION col;
  178749. JDIMENSION width = cinfo->output_width;
  178750. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178751. int *error_limit = cquantize->error_limiter;
  178752. JSAMPROW colormap0 = cinfo->colormap[0];
  178753. JSAMPROW colormap1 = cinfo->colormap[1];
  178754. JSAMPROW colormap2 = cinfo->colormap[2];
  178755. SHIFT_TEMPS
  178756. for (row = 0; row < num_rows; row++) {
  178757. inptr = input_buf[row];
  178758. outptr = output_buf[row];
  178759. if (cquantize->on_odd_row) {
  178760. /* work right to left in this row */
  178761. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178762. outptr += width-1;
  178763. dir = -1;
  178764. dir3 = -3;
  178765. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178766. cquantize->on_odd_row = FALSE; /* flip for next time */
  178767. } else {
  178768. /* work left to right in this row */
  178769. dir = 1;
  178770. dir3 = 3;
  178771. errorptr = cquantize->fserrors; /* => entry before first real column */
  178772. cquantize->on_odd_row = TRUE; /* flip for next time */
  178773. }
  178774. /* Preset error values: no error propagated to first pixel from left */
  178775. cur0 = cur1 = cur2 = 0;
  178776. /* and no error propagated to row below yet */
  178777. belowerr0 = belowerr1 = belowerr2 = 0;
  178778. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178779. for (col = width; col > 0; col--) {
  178780. /* curN holds the error propagated from the previous pixel on the
  178781. * current line. Add the error propagated from the previous line
  178782. * to form the complete error correction term for this pixel, and
  178783. * round the error term (which is expressed * 16) to an integer.
  178784. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178785. * for either sign of the error value.
  178786. * Note: errorptr points to *previous* column's array entry.
  178787. */
  178788. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178789. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178790. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178791. /* Limit the error using transfer function set by init_error_limit.
  178792. * See comments with init_error_limit for rationale.
  178793. */
  178794. cur0 = error_limit[cur0];
  178795. cur1 = error_limit[cur1];
  178796. cur2 = error_limit[cur2];
  178797. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178798. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178799. * this sets the required size of the range_limit array.
  178800. */
  178801. cur0 += GETJSAMPLE(inptr[0]);
  178802. cur1 += GETJSAMPLE(inptr[1]);
  178803. cur2 += GETJSAMPLE(inptr[2]);
  178804. cur0 = GETJSAMPLE(range_limit[cur0]);
  178805. cur1 = GETJSAMPLE(range_limit[cur1]);
  178806. cur2 = GETJSAMPLE(range_limit[cur2]);
  178807. /* Index into the cache with adjusted pixel value */
  178808. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178809. /* If we have not seen this color before, find nearest colormap */
  178810. /* entry and update the cache */
  178811. if (*cachep == 0)
  178812. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178813. /* Now emit the colormap index for this cell */
  178814. { register int pixcode = *cachep - 1;
  178815. *outptr = (JSAMPLE) pixcode;
  178816. /* Compute representation error for this pixel */
  178817. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178818. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178819. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178820. }
  178821. /* Compute error fractions to be propagated to adjacent pixels.
  178822. * Add these into the running sums, and simultaneously shift the
  178823. * next-line error sums left by 1 column.
  178824. */
  178825. { register LOCFSERROR bnexterr, delta;
  178826. bnexterr = cur0; /* Process component 0 */
  178827. delta = cur0 * 2;
  178828. cur0 += delta; /* form error * 3 */
  178829. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178830. cur0 += delta; /* form error * 5 */
  178831. bpreverr0 = belowerr0 + cur0;
  178832. belowerr0 = bnexterr;
  178833. cur0 += delta; /* form error * 7 */
  178834. bnexterr = cur1; /* Process component 1 */
  178835. delta = cur1 * 2;
  178836. cur1 += delta; /* form error * 3 */
  178837. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178838. cur1 += delta; /* form error * 5 */
  178839. bpreverr1 = belowerr1 + cur1;
  178840. belowerr1 = bnexterr;
  178841. cur1 += delta; /* form error * 7 */
  178842. bnexterr = cur2; /* Process component 2 */
  178843. delta = cur2 * 2;
  178844. cur2 += delta; /* form error * 3 */
  178845. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178846. cur2 += delta; /* form error * 5 */
  178847. bpreverr2 = belowerr2 + cur2;
  178848. belowerr2 = bnexterr;
  178849. cur2 += delta; /* form error * 7 */
  178850. }
  178851. /* At this point curN contains the 7/16 error value to be propagated
  178852. * to the next pixel on the current line, and all the errors for the
  178853. * next line have been shifted over. We are therefore ready to move on.
  178854. */
  178855. inptr += dir3; /* Advance pixel pointers to next column */
  178856. outptr += dir;
  178857. errorptr += dir3; /* advance errorptr to current column */
  178858. }
  178859. /* Post-loop cleanup: we must unload the final error values into the
  178860. * final fserrors[] entry. Note we need not unload belowerrN because
  178861. * it is for the dummy column before or after the actual array.
  178862. */
  178863. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178864. errorptr[1] = (FSERROR) bpreverr1;
  178865. errorptr[2] = (FSERROR) bpreverr2;
  178866. }
  178867. }
  178868. /*
  178869. * Initialize the error-limiting transfer function (lookup table).
  178870. * The raw F-S error computation can potentially compute error values of up to
  178871. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178872. * much less, otherwise obviously wrong pixels will be created. (Typical
  178873. * effects include weird fringes at color-area boundaries, isolated bright
  178874. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178875. * is to ensure that the "corners" of the color cube are allocated as output
  178876. * colors; then repeated errors in the same direction cannot cause cascading
  178877. * error buildup. However, that only prevents the error from getting
  178878. * completely out of hand; Aaron Giles reports that error limiting improves
  178879. * the results even with corner colors allocated.
  178880. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178881. * well, but the smoother transfer function used below is even better. Thanks
  178882. * to Aaron Giles for this idea.
  178883. */
  178884. LOCAL(void)
  178885. init_error_limit (j_decompress_ptr cinfo)
  178886. /* Allocate and fill in the error_limiter table */
  178887. {
  178888. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178889. int * table;
  178890. int in, out;
  178891. table = (int *) (*cinfo->mem->alloc_small)
  178892. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178893. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178894. cquantize->error_limiter = table;
  178895. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178896. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178897. out = 0;
  178898. for (in = 0; in < STEPSIZE; in++, out++) {
  178899. table[in] = out; table[-in] = -out;
  178900. }
  178901. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178902. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178903. table[in] = out; table[-in] = -out;
  178904. }
  178905. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178906. for (; in <= MAXJSAMPLE; in++) {
  178907. table[in] = out; table[-in] = -out;
  178908. }
  178909. #undef STEPSIZE
  178910. }
  178911. /*
  178912. * Finish up at the end of each pass.
  178913. */
  178914. METHODDEF(void)
  178915. finish_pass1 (j_decompress_ptr cinfo)
  178916. {
  178917. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178918. /* Select the representative colors and fill in cinfo->colormap */
  178919. cinfo->colormap = cquantize->sv_colormap;
  178920. select_colors(cinfo, cquantize->desired);
  178921. /* Force next pass to zero the color index table */
  178922. cquantize->needs_zeroed = TRUE;
  178923. }
  178924. METHODDEF(void)
  178925. finish_pass2 (j_decompress_ptr)
  178926. {
  178927. /* no work */
  178928. }
  178929. /*
  178930. * Initialize for each processing pass.
  178931. */
  178932. METHODDEF(void)
  178933. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178934. {
  178935. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178936. hist3d histogram = cquantize->histogram;
  178937. int i;
  178938. /* Only F-S dithering or no dithering is supported. */
  178939. /* If user asks for ordered dither, give him F-S. */
  178940. if (cinfo->dither_mode != JDITHER_NONE)
  178941. cinfo->dither_mode = JDITHER_FS;
  178942. if (is_pre_scan) {
  178943. /* Set up method pointers */
  178944. cquantize->pub.color_quantize = prescan_quantize;
  178945. cquantize->pub.finish_pass = finish_pass1;
  178946. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178947. } else {
  178948. /* Set up method pointers */
  178949. if (cinfo->dither_mode == JDITHER_FS)
  178950. cquantize->pub.color_quantize = pass2_fs_dither;
  178951. else
  178952. cquantize->pub.color_quantize = pass2_no_dither;
  178953. cquantize->pub.finish_pass = finish_pass2;
  178954. /* Make sure color count is acceptable */
  178955. i = cinfo->actual_number_of_colors;
  178956. if (i < 1)
  178957. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178958. if (i > MAXNUMCOLORS)
  178959. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178960. if (cinfo->dither_mode == JDITHER_FS) {
  178961. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178962. (3 * SIZEOF(FSERROR)));
  178963. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178964. if (cquantize->fserrors == NULL)
  178965. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178966. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178967. /* Initialize the propagated errors to zero. */
  178968. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178969. /* Make the error-limit table if we didn't already. */
  178970. if (cquantize->error_limiter == NULL)
  178971. init_error_limit(cinfo);
  178972. cquantize->on_odd_row = FALSE;
  178973. }
  178974. }
  178975. /* Zero the histogram or inverse color map, if necessary */
  178976. if (cquantize->needs_zeroed) {
  178977. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178978. jzero_far((void FAR *) histogram[i],
  178979. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178980. }
  178981. cquantize->needs_zeroed = FALSE;
  178982. }
  178983. }
  178984. /*
  178985. * Switch to a new external colormap between output passes.
  178986. */
  178987. METHODDEF(void)
  178988. new_color_map_2_quant (j_decompress_ptr cinfo)
  178989. {
  178990. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178991. /* Reset the inverse color map */
  178992. cquantize->needs_zeroed = TRUE;
  178993. }
  178994. /*
  178995. * Module initialization routine for 2-pass color quantization.
  178996. */
  178997. GLOBAL(void)
  178998. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178999. {
  179000. my_cquantize_ptr2 cquantize;
  179001. int i;
  179002. cquantize = (my_cquantize_ptr2)
  179003. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179004. SIZEOF(my_cquantizer2));
  179005. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  179006. cquantize->pub.start_pass = start_pass_2_quant;
  179007. cquantize->pub.new_color_map = new_color_map_2_quant;
  179008. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  179009. cquantize->error_limiter = NULL;
  179010. /* Make sure jdmaster didn't give me a case I can't handle */
  179011. if (cinfo->out_color_components != 3)
  179012. ERREXIT(cinfo, JERR_NOTIMPL);
  179013. /* Allocate the histogram/inverse colormap storage */
  179014. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  179015. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  179016. for (i = 0; i < HIST_C0_ELEMS; i++) {
  179017. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  179018. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179019. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  179020. }
  179021. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  179022. /* Allocate storage for the completed colormap, if required.
  179023. * We do this now since it is FAR storage and may affect
  179024. * the memory manager's space calculations.
  179025. */
  179026. if (cinfo->enable_2pass_quant) {
  179027. /* Make sure color count is acceptable */
  179028. int desired = cinfo->desired_number_of_colors;
  179029. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  179030. if (desired < 8)
  179031. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  179032. /* Make sure colormap indexes can be represented by JSAMPLEs */
  179033. if (desired > MAXNUMCOLORS)
  179034. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  179035. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  179036. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  179037. cquantize->desired = desired;
  179038. } else
  179039. cquantize->sv_colormap = NULL;
  179040. /* Only F-S dithering or no dithering is supported. */
  179041. /* If user asks for ordered dither, give him F-S. */
  179042. if (cinfo->dither_mode != JDITHER_NONE)
  179043. cinfo->dither_mode = JDITHER_FS;
  179044. /* Allocate Floyd-Steinberg workspace if necessary.
  179045. * This isn't really needed until pass 2, but again it is FAR storage.
  179046. * Although we will cope with a later change in dither_mode,
  179047. * we do not promise to honor max_memory_to_use if dither_mode changes.
  179048. */
  179049. if (cinfo->dither_mode == JDITHER_FS) {
  179050. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  179051. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179052. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  179053. /* Might as well create the error-limiting table too. */
  179054. init_error_limit(cinfo);
  179055. }
  179056. }
  179057. #endif /* QUANT_2PASS_SUPPORTED */
  179058. /*** End of inlined file: jquant2.c ***/
  179059. /*** Start of inlined file: jutils.c ***/
  179060. #define JPEG_INTERNALS
  179061. /*
  179062. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  179063. * of a DCT block read in natural order (left to right, top to bottom).
  179064. */
  179065. #if 0 /* This table is not actually needed in v6a */
  179066. const int jpeg_zigzag_order[DCTSIZE2] = {
  179067. 0, 1, 5, 6, 14, 15, 27, 28,
  179068. 2, 4, 7, 13, 16, 26, 29, 42,
  179069. 3, 8, 12, 17, 25, 30, 41, 43,
  179070. 9, 11, 18, 24, 31, 40, 44, 53,
  179071. 10, 19, 23, 32, 39, 45, 52, 54,
  179072. 20, 22, 33, 38, 46, 51, 55, 60,
  179073. 21, 34, 37, 47, 50, 56, 59, 61,
  179074. 35, 36, 48, 49, 57, 58, 62, 63
  179075. };
  179076. #endif
  179077. /*
  179078. * jpeg_natural_order[i] is the natural-order position of the i'th element
  179079. * of zigzag order.
  179080. *
  179081. * When reading corrupted data, the Huffman decoders could attempt
  179082. * to reference an entry beyond the end of this array (if the decoded
  179083. * zero run length reaches past the end of the block). To prevent
  179084. * wild stores without adding an inner-loop test, we put some extra
  179085. * "63"s after the real entries. This will cause the extra coefficient
  179086. * to be stored in location 63 of the block, not somewhere random.
  179087. * The worst case would be a run-length of 15, which means we need 16
  179088. * fake entries.
  179089. */
  179090. const int jpeg_natural_order[DCTSIZE2+16] = {
  179091. 0, 1, 8, 16, 9, 2, 3, 10,
  179092. 17, 24, 32, 25, 18, 11, 4, 5,
  179093. 12, 19, 26, 33, 40, 48, 41, 34,
  179094. 27, 20, 13, 6, 7, 14, 21, 28,
  179095. 35, 42, 49, 56, 57, 50, 43, 36,
  179096. 29, 22, 15, 23, 30, 37, 44, 51,
  179097. 58, 59, 52, 45, 38, 31, 39, 46,
  179098. 53, 60, 61, 54, 47, 55, 62, 63,
  179099. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  179100. 63, 63, 63, 63, 63, 63, 63, 63
  179101. };
  179102. /*
  179103. * Arithmetic utilities
  179104. */
  179105. GLOBAL(long)
  179106. jdiv_round_up (long a, long b)
  179107. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  179108. /* Assumes a >= 0, b > 0 */
  179109. {
  179110. return (a + b - 1L) / b;
  179111. }
  179112. GLOBAL(long)
  179113. jround_up (long a, long b)
  179114. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  179115. /* Assumes a >= 0, b > 0 */
  179116. {
  179117. a += b - 1L;
  179118. return a - (a % b);
  179119. }
  179120. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  179121. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  179122. * are FAR and we're assuming a small-pointer memory model. However, some
  179123. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  179124. * in the small-model libraries. These will be used if USE_FMEM is defined.
  179125. * Otherwise, the routines below do it the hard way. (The performance cost
  179126. * is not all that great, because these routines aren't very heavily used.)
  179127. */
  179128. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  179129. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  179130. #define FMEMZERO(target,size) MEMZERO(target,size)
  179131. #else /* 80x86 case, define if we can */
  179132. #ifdef USE_FMEM
  179133. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  179134. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  179135. #endif
  179136. #endif
  179137. GLOBAL(void)
  179138. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  179139. JSAMPARRAY output_array, int dest_row,
  179140. int num_rows, JDIMENSION num_cols)
  179141. /* Copy some rows of samples from one place to another.
  179142. * num_rows rows are copied from input_array[source_row++]
  179143. * to output_array[dest_row++]; these areas may overlap for duplication.
  179144. * The source and destination arrays must be at least as wide as num_cols.
  179145. */
  179146. {
  179147. register JSAMPROW inptr, outptr;
  179148. #ifdef FMEMCOPY
  179149. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  179150. #else
  179151. register JDIMENSION count;
  179152. #endif
  179153. register int row;
  179154. input_array += source_row;
  179155. output_array += dest_row;
  179156. for (row = num_rows; row > 0; row--) {
  179157. inptr = *input_array++;
  179158. outptr = *output_array++;
  179159. #ifdef FMEMCOPY
  179160. FMEMCOPY(outptr, inptr, count);
  179161. #else
  179162. for (count = num_cols; count > 0; count--)
  179163. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  179164. #endif
  179165. }
  179166. }
  179167. GLOBAL(void)
  179168. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  179169. JDIMENSION num_blocks)
  179170. /* Copy a row of coefficient blocks from one place to another. */
  179171. {
  179172. #ifdef FMEMCOPY
  179173. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  179174. #else
  179175. register JCOEFPTR inptr, outptr;
  179176. register long count;
  179177. inptr = (JCOEFPTR) input_row;
  179178. outptr = (JCOEFPTR) output_row;
  179179. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  179180. *outptr++ = *inptr++;
  179181. }
  179182. #endif
  179183. }
  179184. GLOBAL(void)
  179185. jzero_far (void FAR * target, size_t bytestozero)
  179186. /* Zero out a chunk of FAR memory. */
  179187. /* This might be sample-array data, block-array data, or alloc_large data. */
  179188. {
  179189. #ifdef FMEMZERO
  179190. FMEMZERO(target, bytestozero);
  179191. #else
  179192. register char FAR * ptr = (char FAR *) target;
  179193. register size_t count;
  179194. for (count = bytestozero; count > 0; count--) {
  179195. *ptr++ = 0;
  179196. }
  179197. #endif
  179198. }
  179199. /*** End of inlined file: jutils.c ***/
  179200. /*** Start of inlined file: transupp.c ***/
  179201. /* Although this file really shouldn't have access to the library internals,
  179202. * it's helpful to let it call jround_up() and jcopy_block_row().
  179203. */
  179204. #define JPEG_INTERNALS
  179205. /*** Start of inlined file: transupp.h ***/
  179206. /* If you happen not to want the image transform support, disable it here */
  179207. #ifndef TRANSFORMS_SUPPORTED
  179208. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179209. #endif
  179210. /* Short forms of external names for systems with brain-damaged linkers. */
  179211. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179212. #define jtransform_request_workspace jTrRequest
  179213. #define jtransform_adjust_parameters jTrAdjust
  179214. #define jtransform_execute_transformation jTrExec
  179215. #define jcopy_markers_setup jCMrkSetup
  179216. #define jcopy_markers_execute jCMrkExec
  179217. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179218. /*
  179219. * Codes for supported types of image transformations.
  179220. */
  179221. typedef enum {
  179222. JXFORM_NONE, /* no transformation */
  179223. JXFORM_FLIP_H, /* horizontal flip */
  179224. JXFORM_FLIP_V, /* vertical flip */
  179225. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179226. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179227. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179228. JXFORM_ROT_180, /* 180-degree rotation */
  179229. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179230. } JXFORM_CODE;
  179231. /*
  179232. * Although rotating and flipping data expressed as DCT coefficients is not
  179233. * hard, there is an asymmetry in the JPEG format specification for images
  179234. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179235. * image edges are padded out to the next iMCU boundary with junk data; but
  179236. * no padding is possible at the top and left edges. If we were to flip
  179237. * the whole image including the pad data, then pad garbage would become
  179238. * visible at the top and/or left, and real pixels would disappear into the
  179239. * pad margins --- perhaps permanently, since encoders & decoders may not
  179240. * bother to preserve DCT blocks that appear to be completely outside the
  179241. * nominal image area. So, we have to exclude any partial iMCUs from the
  179242. * basic transformation.
  179243. *
  179244. * Transpose is the only transformation that can handle partial iMCUs at the
  179245. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179246. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179247. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179248. * The other transforms are defined as combinations of these basic transforms
  179249. * and process edge blocks in a way that preserves the equivalence.
  179250. *
  179251. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179252. * this is not strictly lossless, but it usually gives the best-looking
  179253. * result for odd-size images. Note that when this option is active,
  179254. * the expected mathematical equivalences between the transforms may not hold.
  179255. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179256. * followed by -rot 180 -trim trims both edges.)
  179257. *
  179258. * We also offer a "force to grayscale" option, which simply discards the
  179259. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179260. * the luminance channel is preserved exactly. It's not the same kind of
  179261. * thing as the rotate/flip transformations, but it's convenient to handle it
  179262. * as part of this package, mainly because the transformation routines have to
  179263. * be aware of the option to know how many components to work on.
  179264. */
  179265. typedef struct {
  179266. /* Options: set by caller */
  179267. JXFORM_CODE transform; /* image transform operator */
  179268. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179269. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179270. /* Internal workspace: caller should not touch these */
  179271. int num_components; /* # of components in workspace */
  179272. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179273. } jpeg_transform_info;
  179274. #if TRANSFORMS_SUPPORTED
  179275. /* Request any required workspace */
  179276. EXTERN(void) jtransform_request_workspace
  179277. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179278. /* Adjust output image parameters */
  179279. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179280. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179281. jvirt_barray_ptr *src_coef_arrays,
  179282. jpeg_transform_info *info));
  179283. /* Execute the actual transformation, if any */
  179284. EXTERN(void) jtransform_execute_transformation
  179285. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179286. jvirt_barray_ptr *src_coef_arrays,
  179287. jpeg_transform_info *info));
  179288. #endif /* TRANSFORMS_SUPPORTED */
  179289. /*
  179290. * Support for copying optional markers from source to destination file.
  179291. */
  179292. typedef enum {
  179293. JCOPYOPT_NONE, /* copy no optional markers */
  179294. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179295. JCOPYOPT_ALL /* copy all optional markers */
  179296. } JCOPY_OPTION;
  179297. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179298. /* Setup decompression object to save desired markers in memory */
  179299. EXTERN(void) jcopy_markers_setup
  179300. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179301. /* Copy markers saved in the given source object to the destination object */
  179302. EXTERN(void) jcopy_markers_execute
  179303. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179304. JCOPY_OPTION option));
  179305. /*** End of inlined file: transupp.h ***/
  179306. /* My own external interface */
  179307. #if TRANSFORMS_SUPPORTED
  179308. /*
  179309. * Lossless image transformation routines. These routines work on DCT
  179310. * coefficient arrays and thus do not require any lossy decompression
  179311. * or recompression of the image.
  179312. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179313. *
  179314. * Horizontal flipping is done in-place, using a single top-to-bottom
  179315. * pass through the virtual source array. It will thus be much the
  179316. * fastest option for images larger than main memory.
  179317. *
  179318. * The other routines require a set of destination virtual arrays, so they
  179319. * need twice as much memory as jpegtran normally does. The destination
  179320. * arrays are always written in normal scan order (top to bottom) because
  179321. * the virtual array manager expects this. The source arrays will be scanned
  179322. * in the corresponding order, which means multiple passes through the source
  179323. * arrays for most of the transforms. That could result in much thrashing
  179324. * if the image is larger than main memory.
  179325. *
  179326. * Some notes about the operating environment of the individual transform
  179327. * routines:
  179328. * 1. Both the source and destination virtual arrays are allocated from the
  179329. * source JPEG object, and therefore should be manipulated by calling the
  179330. * source's memory manager.
  179331. * 2. The destination's component count should be used. It may be smaller
  179332. * than the source's when forcing to grayscale.
  179333. * 3. Likewise the destination's sampling factors should be used. When
  179334. * forcing to grayscale the destination's sampling factors will be all 1,
  179335. * and we may as well take that as the effective iMCU size.
  179336. * 4. When "trim" is in effect, the destination's dimensions will be the
  179337. * trimmed values but the source's will be untrimmed.
  179338. * 5. All the routines assume that the source and destination buffers are
  179339. * padded out to a full iMCU boundary. This is true, although for the
  179340. * source buffer it is an undocumented property of jdcoefct.c.
  179341. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179342. * dimensions and ignore the source's.
  179343. */
  179344. LOCAL(void)
  179345. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179346. jvirt_barray_ptr *src_coef_arrays)
  179347. /* Horizontal flip; done in-place, so no separate dest array is required */
  179348. {
  179349. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179350. int ci, k, offset_y;
  179351. JBLOCKARRAY buffer;
  179352. JCOEFPTR ptr1, ptr2;
  179353. JCOEF temp1, temp2;
  179354. jpeg_component_info *compptr;
  179355. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179356. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179357. * mirroring by changing the signs of odd-numbered columns.
  179358. * Partial iMCUs at the right edge are left untouched.
  179359. */
  179360. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179361. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179362. compptr = dstinfo->comp_info + ci;
  179363. comp_width = MCU_cols * compptr->h_samp_factor;
  179364. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179365. blk_y += compptr->v_samp_factor) {
  179366. buffer = (*srcinfo->mem->access_virt_barray)
  179367. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179368. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179369. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179370. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179371. ptr1 = buffer[offset_y][blk_x];
  179372. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179373. /* this unrolled loop doesn't need to know which row it's on... */
  179374. for (k = 0; k < DCTSIZE2; k += 2) {
  179375. temp1 = *ptr1; /* swap even column */
  179376. temp2 = *ptr2;
  179377. *ptr1++ = temp2;
  179378. *ptr2++ = temp1;
  179379. temp1 = *ptr1; /* swap odd column with sign change */
  179380. temp2 = *ptr2;
  179381. *ptr1++ = -temp2;
  179382. *ptr2++ = -temp1;
  179383. }
  179384. }
  179385. }
  179386. }
  179387. }
  179388. }
  179389. LOCAL(void)
  179390. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179391. jvirt_barray_ptr *src_coef_arrays,
  179392. jvirt_barray_ptr *dst_coef_arrays)
  179393. /* Vertical flip */
  179394. {
  179395. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179396. int ci, i, j, offset_y;
  179397. JBLOCKARRAY src_buffer, dst_buffer;
  179398. JBLOCKROW src_row_ptr, dst_row_ptr;
  179399. JCOEFPTR src_ptr, dst_ptr;
  179400. jpeg_component_info *compptr;
  179401. /* We output into a separate array because we can't touch different
  179402. * rows of the source virtual array simultaneously. Otherwise, this
  179403. * is a pretty straightforward analog of horizontal flip.
  179404. * Within a DCT block, vertical mirroring is done by changing the signs
  179405. * of odd-numbered rows.
  179406. * Partial iMCUs at the bottom edge are copied verbatim.
  179407. */
  179408. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179409. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179410. compptr = dstinfo->comp_info + ci;
  179411. comp_height = MCU_rows * compptr->v_samp_factor;
  179412. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179413. dst_blk_y += compptr->v_samp_factor) {
  179414. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179415. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179416. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179417. if (dst_blk_y < comp_height) {
  179418. /* Row is within the mirrorable area. */
  179419. src_buffer = (*srcinfo->mem->access_virt_barray)
  179420. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179421. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179422. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179423. } else {
  179424. /* Bottom-edge blocks will be copied verbatim. */
  179425. src_buffer = (*srcinfo->mem->access_virt_barray)
  179426. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179427. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179428. }
  179429. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179430. if (dst_blk_y < comp_height) {
  179431. /* Row is within the mirrorable area. */
  179432. dst_row_ptr = dst_buffer[offset_y];
  179433. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179434. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179435. dst_blk_x++) {
  179436. dst_ptr = dst_row_ptr[dst_blk_x];
  179437. src_ptr = src_row_ptr[dst_blk_x];
  179438. for (i = 0; i < DCTSIZE; i += 2) {
  179439. /* copy even row */
  179440. for (j = 0; j < DCTSIZE; j++)
  179441. *dst_ptr++ = *src_ptr++;
  179442. /* copy odd row with sign change */
  179443. for (j = 0; j < DCTSIZE; j++)
  179444. *dst_ptr++ = - *src_ptr++;
  179445. }
  179446. }
  179447. } else {
  179448. /* Just copy row verbatim. */
  179449. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179450. compptr->width_in_blocks);
  179451. }
  179452. }
  179453. }
  179454. }
  179455. }
  179456. LOCAL(void)
  179457. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179458. jvirt_barray_ptr *src_coef_arrays,
  179459. jvirt_barray_ptr *dst_coef_arrays)
  179460. /* Transpose source into destination */
  179461. {
  179462. JDIMENSION dst_blk_x, dst_blk_y;
  179463. int ci, i, j, offset_x, offset_y;
  179464. JBLOCKARRAY src_buffer, dst_buffer;
  179465. JCOEFPTR src_ptr, dst_ptr;
  179466. jpeg_component_info *compptr;
  179467. /* Transposing pixels within a block just requires transposing the
  179468. * DCT coefficients.
  179469. * Partial iMCUs at the edges require no special treatment; we simply
  179470. * process all the available DCT blocks for every component.
  179471. */
  179472. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179473. compptr = dstinfo->comp_info + ci;
  179474. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179475. dst_blk_y += compptr->v_samp_factor) {
  179476. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179477. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179478. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179479. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179480. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179481. dst_blk_x += compptr->h_samp_factor) {
  179482. src_buffer = (*srcinfo->mem->access_virt_barray)
  179483. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179484. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179485. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179486. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179487. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179488. for (i = 0; i < DCTSIZE; i++)
  179489. for (j = 0; j < DCTSIZE; j++)
  179490. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179491. }
  179492. }
  179493. }
  179494. }
  179495. }
  179496. }
  179497. LOCAL(void)
  179498. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179499. jvirt_barray_ptr *src_coef_arrays,
  179500. jvirt_barray_ptr *dst_coef_arrays)
  179501. /* 90 degree rotation is equivalent to
  179502. * 1. Transposing the image;
  179503. * 2. Horizontal mirroring.
  179504. * These two steps are merged into a single processing routine.
  179505. */
  179506. {
  179507. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179508. int ci, i, j, offset_x, offset_y;
  179509. JBLOCKARRAY src_buffer, dst_buffer;
  179510. JCOEFPTR src_ptr, dst_ptr;
  179511. jpeg_component_info *compptr;
  179512. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179513. * at the (output) right edge properly. They just get transposed and
  179514. * not mirrored.
  179515. */
  179516. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179517. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179518. compptr = dstinfo->comp_info + ci;
  179519. comp_width = MCU_cols * compptr->h_samp_factor;
  179520. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179521. dst_blk_y += compptr->v_samp_factor) {
  179522. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179523. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179524. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179525. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179526. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179527. dst_blk_x += compptr->h_samp_factor) {
  179528. src_buffer = (*srcinfo->mem->access_virt_barray)
  179529. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179530. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179531. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179532. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179533. if (dst_blk_x < comp_width) {
  179534. /* Block is within the mirrorable area. */
  179535. dst_ptr = dst_buffer[offset_y]
  179536. [comp_width - dst_blk_x - offset_x - 1];
  179537. for (i = 0; i < DCTSIZE; i++) {
  179538. for (j = 0; j < DCTSIZE; j++)
  179539. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179540. i++;
  179541. for (j = 0; j < DCTSIZE; j++)
  179542. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179543. }
  179544. } else {
  179545. /* Edge blocks are transposed but not mirrored. */
  179546. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179547. for (i = 0; i < DCTSIZE; i++)
  179548. for (j = 0; j < DCTSIZE; j++)
  179549. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179550. }
  179551. }
  179552. }
  179553. }
  179554. }
  179555. }
  179556. }
  179557. LOCAL(void)
  179558. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179559. jvirt_barray_ptr *src_coef_arrays,
  179560. jvirt_barray_ptr *dst_coef_arrays)
  179561. /* 270 degree rotation is equivalent to
  179562. * 1. Horizontal mirroring;
  179563. * 2. Transposing the image.
  179564. * These two steps are merged into a single processing routine.
  179565. */
  179566. {
  179567. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179568. int ci, i, j, offset_x, offset_y;
  179569. JBLOCKARRAY src_buffer, dst_buffer;
  179570. JCOEFPTR src_ptr, dst_ptr;
  179571. jpeg_component_info *compptr;
  179572. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179573. * at the (output) bottom edge properly. They just get transposed and
  179574. * not mirrored.
  179575. */
  179576. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179577. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179578. compptr = dstinfo->comp_info + ci;
  179579. comp_height = MCU_rows * compptr->v_samp_factor;
  179580. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179581. dst_blk_y += compptr->v_samp_factor) {
  179582. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179583. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179584. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179585. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179586. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179587. dst_blk_x += compptr->h_samp_factor) {
  179588. src_buffer = (*srcinfo->mem->access_virt_barray)
  179589. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179590. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179591. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179592. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179593. if (dst_blk_y < comp_height) {
  179594. /* Block is within the mirrorable area. */
  179595. src_ptr = src_buffer[offset_x]
  179596. [comp_height - dst_blk_y - offset_y - 1];
  179597. for (i = 0; i < DCTSIZE; i++) {
  179598. for (j = 0; j < DCTSIZE; j++) {
  179599. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179600. j++;
  179601. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179602. }
  179603. }
  179604. } else {
  179605. /* Edge blocks are transposed but not mirrored. */
  179606. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179607. for (i = 0; i < DCTSIZE; i++)
  179608. for (j = 0; j < DCTSIZE; j++)
  179609. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179610. }
  179611. }
  179612. }
  179613. }
  179614. }
  179615. }
  179616. }
  179617. LOCAL(void)
  179618. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179619. jvirt_barray_ptr *src_coef_arrays,
  179620. jvirt_barray_ptr *dst_coef_arrays)
  179621. /* 180 degree rotation is equivalent to
  179622. * 1. Vertical mirroring;
  179623. * 2. Horizontal mirroring.
  179624. * These two steps are merged into a single processing routine.
  179625. */
  179626. {
  179627. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179628. int ci, i, j, offset_y;
  179629. JBLOCKARRAY src_buffer, dst_buffer;
  179630. JBLOCKROW src_row_ptr, dst_row_ptr;
  179631. JCOEFPTR src_ptr, dst_ptr;
  179632. jpeg_component_info *compptr;
  179633. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179634. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179635. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179636. compptr = dstinfo->comp_info + ci;
  179637. comp_width = MCU_cols * compptr->h_samp_factor;
  179638. comp_height = MCU_rows * compptr->v_samp_factor;
  179639. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179640. dst_blk_y += compptr->v_samp_factor) {
  179641. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179642. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179643. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179644. if (dst_blk_y < comp_height) {
  179645. /* Row is within the vertically mirrorable area. */
  179646. src_buffer = (*srcinfo->mem->access_virt_barray)
  179647. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179648. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179649. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179650. } else {
  179651. /* Bottom-edge rows are only mirrored horizontally. */
  179652. src_buffer = (*srcinfo->mem->access_virt_barray)
  179653. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179654. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179655. }
  179656. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179657. if (dst_blk_y < comp_height) {
  179658. /* Row is within the mirrorable area. */
  179659. dst_row_ptr = dst_buffer[offset_y];
  179660. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179661. /* Process the blocks that can be mirrored both ways. */
  179662. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179663. dst_ptr = dst_row_ptr[dst_blk_x];
  179664. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179665. for (i = 0; i < DCTSIZE; i += 2) {
  179666. /* For even row, negate every odd column. */
  179667. for (j = 0; j < DCTSIZE; j += 2) {
  179668. *dst_ptr++ = *src_ptr++;
  179669. *dst_ptr++ = - *src_ptr++;
  179670. }
  179671. /* For odd row, negate every even column. */
  179672. for (j = 0; j < DCTSIZE; j += 2) {
  179673. *dst_ptr++ = - *src_ptr++;
  179674. *dst_ptr++ = *src_ptr++;
  179675. }
  179676. }
  179677. }
  179678. /* Any remaining right-edge blocks are only mirrored vertically. */
  179679. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179680. dst_ptr = dst_row_ptr[dst_blk_x];
  179681. src_ptr = src_row_ptr[dst_blk_x];
  179682. for (i = 0; i < DCTSIZE; i += 2) {
  179683. for (j = 0; j < DCTSIZE; j++)
  179684. *dst_ptr++ = *src_ptr++;
  179685. for (j = 0; j < DCTSIZE; j++)
  179686. *dst_ptr++ = - *src_ptr++;
  179687. }
  179688. }
  179689. } else {
  179690. /* Remaining rows are just mirrored horizontally. */
  179691. dst_row_ptr = dst_buffer[offset_y];
  179692. src_row_ptr = src_buffer[offset_y];
  179693. /* Process the blocks that can be mirrored. */
  179694. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179695. dst_ptr = dst_row_ptr[dst_blk_x];
  179696. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179697. for (i = 0; i < DCTSIZE2; i += 2) {
  179698. *dst_ptr++ = *src_ptr++;
  179699. *dst_ptr++ = - *src_ptr++;
  179700. }
  179701. }
  179702. /* Any remaining right-edge blocks are only copied. */
  179703. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179704. dst_ptr = dst_row_ptr[dst_blk_x];
  179705. src_ptr = src_row_ptr[dst_blk_x];
  179706. for (i = 0; i < DCTSIZE2; i++)
  179707. *dst_ptr++ = *src_ptr++;
  179708. }
  179709. }
  179710. }
  179711. }
  179712. }
  179713. }
  179714. LOCAL(void)
  179715. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179716. jvirt_barray_ptr *src_coef_arrays,
  179717. jvirt_barray_ptr *dst_coef_arrays)
  179718. /* Transverse transpose is equivalent to
  179719. * 1. 180 degree rotation;
  179720. * 2. Transposition;
  179721. * or
  179722. * 1. Horizontal mirroring;
  179723. * 2. Transposition;
  179724. * 3. Horizontal mirroring.
  179725. * These steps are merged into a single processing routine.
  179726. */
  179727. {
  179728. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179729. int ci, i, j, offset_x, offset_y;
  179730. JBLOCKARRAY src_buffer, dst_buffer;
  179731. JCOEFPTR src_ptr, dst_ptr;
  179732. jpeg_component_info *compptr;
  179733. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179734. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179735. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179736. compptr = dstinfo->comp_info + ci;
  179737. comp_width = MCU_cols * compptr->h_samp_factor;
  179738. comp_height = MCU_rows * compptr->v_samp_factor;
  179739. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179740. dst_blk_y += compptr->v_samp_factor) {
  179741. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179742. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179743. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179744. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179745. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179746. dst_blk_x += compptr->h_samp_factor) {
  179747. src_buffer = (*srcinfo->mem->access_virt_barray)
  179748. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179749. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179750. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179751. if (dst_blk_y < comp_height) {
  179752. src_ptr = src_buffer[offset_x]
  179753. [comp_height - dst_blk_y - offset_y - 1];
  179754. if (dst_blk_x < comp_width) {
  179755. /* Block is within the mirrorable area. */
  179756. dst_ptr = dst_buffer[offset_y]
  179757. [comp_width - dst_blk_x - offset_x - 1];
  179758. for (i = 0; i < DCTSIZE; i++) {
  179759. for (j = 0; j < DCTSIZE; j++) {
  179760. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179761. j++;
  179762. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179763. }
  179764. i++;
  179765. for (j = 0; j < DCTSIZE; j++) {
  179766. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179767. j++;
  179768. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179769. }
  179770. }
  179771. } else {
  179772. /* Right-edge blocks are mirrored in y only */
  179773. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179774. for (i = 0; i < DCTSIZE; i++) {
  179775. for (j = 0; j < DCTSIZE; j++) {
  179776. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179777. j++;
  179778. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179779. }
  179780. }
  179781. }
  179782. } else {
  179783. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179784. if (dst_blk_x < comp_width) {
  179785. /* Bottom-edge blocks are mirrored in x only */
  179786. dst_ptr = dst_buffer[offset_y]
  179787. [comp_width - dst_blk_x - offset_x - 1];
  179788. for (i = 0; i < DCTSIZE; i++) {
  179789. for (j = 0; j < DCTSIZE; j++)
  179790. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179791. i++;
  179792. for (j = 0; j < DCTSIZE; j++)
  179793. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179794. }
  179795. } else {
  179796. /* At lower right corner, just transpose, no mirroring */
  179797. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179798. for (i = 0; i < DCTSIZE; i++)
  179799. for (j = 0; j < DCTSIZE; j++)
  179800. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179801. }
  179802. }
  179803. }
  179804. }
  179805. }
  179806. }
  179807. }
  179808. }
  179809. /* Request any required workspace.
  179810. *
  179811. * We allocate the workspace virtual arrays from the source decompression
  179812. * object, so that all the arrays (both the original data and the workspace)
  179813. * will be taken into account while making memory management decisions.
  179814. * Hence, this routine must be called after jpeg_read_header (which reads
  179815. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179816. * the source's virtual arrays).
  179817. */
  179818. GLOBAL(void)
  179819. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179820. jpeg_transform_info *info)
  179821. {
  179822. jvirt_barray_ptr *coef_arrays = NULL;
  179823. jpeg_component_info *compptr;
  179824. int ci;
  179825. if (info->force_grayscale &&
  179826. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179827. srcinfo->num_components == 3) {
  179828. /* We'll only process the first component */
  179829. info->num_components = 1;
  179830. } else {
  179831. /* Process all the components */
  179832. info->num_components = srcinfo->num_components;
  179833. }
  179834. switch (info->transform) {
  179835. case JXFORM_NONE:
  179836. case JXFORM_FLIP_H:
  179837. /* Don't need a workspace array */
  179838. break;
  179839. case JXFORM_FLIP_V:
  179840. case JXFORM_ROT_180:
  179841. /* Need workspace arrays having same dimensions as source image.
  179842. * Note that we allocate arrays padded out to the next iMCU boundary,
  179843. * so that transform routines need not worry about missing edge blocks.
  179844. */
  179845. coef_arrays = (jvirt_barray_ptr *)
  179846. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179847. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179848. for (ci = 0; ci < info->num_components; ci++) {
  179849. compptr = srcinfo->comp_info + ci;
  179850. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179851. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179852. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179853. (long) compptr->h_samp_factor),
  179854. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179855. (long) compptr->v_samp_factor),
  179856. (JDIMENSION) compptr->v_samp_factor);
  179857. }
  179858. break;
  179859. case JXFORM_TRANSPOSE:
  179860. case JXFORM_TRANSVERSE:
  179861. case JXFORM_ROT_90:
  179862. case JXFORM_ROT_270:
  179863. /* Need workspace arrays having transposed dimensions.
  179864. * Note that we allocate arrays padded out to the next iMCU boundary,
  179865. * so that transform routines need not worry about missing edge blocks.
  179866. */
  179867. coef_arrays = (jvirt_barray_ptr *)
  179868. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179869. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179870. for (ci = 0; ci < info->num_components; ci++) {
  179871. compptr = srcinfo->comp_info + ci;
  179872. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179873. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179874. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179875. (long) compptr->v_samp_factor),
  179876. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179877. (long) compptr->h_samp_factor),
  179878. (JDIMENSION) compptr->h_samp_factor);
  179879. }
  179880. break;
  179881. }
  179882. info->workspace_coef_arrays = coef_arrays;
  179883. }
  179884. /* Transpose destination image parameters */
  179885. LOCAL(void)
  179886. transpose_critical_parameters (j_compress_ptr dstinfo)
  179887. {
  179888. int tblno, i, j, ci, itemp;
  179889. jpeg_component_info *compptr;
  179890. JQUANT_TBL *qtblptr;
  179891. JDIMENSION dtemp;
  179892. UINT16 qtemp;
  179893. /* Transpose basic image dimensions */
  179894. dtemp = dstinfo->image_width;
  179895. dstinfo->image_width = dstinfo->image_height;
  179896. dstinfo->image_height = dtemp;
  179897. /* Transpose sampling factors */
  179898. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179899. compptr = dstinfo->comp_info + ci;
  179900. itemp = compptr->h_samp_factor;
  179901. compptr->h_samp_factor = compptr->v_samp_factor;
  179902. compptr->v_samp_factor = itemp;
  179903. }
  179904. /* Transpose quantization tables */
  179905. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179906. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179907. if (qtblptr != NULL) {
  179908. for (i = 0; i < DCTSIZE; i++) {
  179909. for (j = 0; j < i; j++) {
  179910. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179911. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179912. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179913. }
  179914. }
  179915. }
  179916. }
  179917. }
  179918. /* Trim off any partial iMCUs on the indicated destination edge */
  179919. LOCAL(void)
  179920. trim_right_edge (j_compress_ptr dstinfo)
  179921. {
  179922. int ci, max_h_samp_factor;
  179923. JDIMENSION MCU_cols;
  179924. /* We have to compute max_h_samp_factor ourselves,
  179925. * because it hasn't been set yet in the destination
  179926. * (and we don't want to use the source's value).
  179927. */
  179928. max_h_samp_factor = 1;
  179929. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179930. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179931. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179932. }
  179933. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179934. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179935. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179936. }
  179937. LOCAL(void)
  179938. trim_bottom_edge (j_compress_ptr dstinfo)
  179939. {
  179940. int ci, max_v_samp_factor;
  179941. JDIMENSION MCU_rows;
  179942. /* We have to compute max_v_samp_factor ourselves,
  179943. * because it hasn't been set yet in the destination
  179944. * (and we don't want to use the source's value).
  179945. */
  179946. max_v_samp_factor = 1;
  179947. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179948. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179949. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179950. }
  179951. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179952. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179953. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179954. }
  179955. /* Adjust output image parameters as needed.
  179956. *
  179957. * This must be called after jpeg_copy_critical_parameters()
  179958. * and before jpeg_write_coefficients().
  179959. *
  179960. * The return value is the set of virtual coefficient arrays to be written
  179961. * (either the ones allocated by jtransform_request_workspace, or the
  179962. * original source data arrays). The caller will need to pass this value
  179963. * to jpeg_write_coefficients().
  179964. */
  179965. GLOBAL(jvirt_barray_ptr *)
  179966. jtransform_adjust_parameters (j_decompress_ptr,
  179967. j_compress_ptr dstinfo,
  179968. jvirt_barray_ptr *src_coef_arrays,
  179969. jpeg_transform_info *info)
  179970. {
  179971. /* If force-to-grayscale is requested, adjust destination parameters */
  179972. if (info->force_grayscale) {
  179973. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179974. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179975. * will get set to 1, which typically won't match the source.
  179976. * In fact we do this even if the source is already grayscale; that
  179977. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179978. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179979. */
  179980. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179981. dstinfo->num_components == 3) ||
  179982. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179983. dstinfo->num_components == 1)) {
  179984. /* We have to preserve the source's quantization table number. */
  179985. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179986. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179987. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179988. } else {
  179989. /* Sorry, can't do it */
  179990. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179991. }
  179992. }
  179993. /* Correct the destination's image dimensions etc if necessary */
  179994. switch (info->transform) {
  179995. case JXFORM_NONE:
  179996. /* Nothing to do */
  179997. break;
  179998. case JXFORM_FLIP_H:
  179999. if (info->trim)
  180000. trim_right_edge(dstinfo);
  180001. break;
  180002. case JXFORM_FLIP_V:
  180003. if (info->trim)
  180004. trim_bottom_edge(dstinfo);
  180005. break;
  180006. case JXFORM_TRANSPOSE:
  180007. transpose_critical_parameters(dstinfo);
  180008. /* transpose does NOT have to trim anything */
  180009. break;
  180010. case JXFORM_TRANSVERSE:
  180011. transpose_critical_parameters(dstinfo);
  180012. if (info->trim) {
  180013. trim_right_edge(dstinfo);
  180014. trim_bottom_edge(dstinfo);
  180015. }
  180016. break;
  180017. case JXFORM_ROT_90:
  180018. transpose_critical_parameters(dstinfo);
  180019. if (info->trim)
  180020. trim_right_edge(dstinfo);
  180021. break;
  180022. case JXFORM_ROT_180:
  180023. if (info->trim) {
  180024. trim_right_edge(dstinfo);
  180025. trim_bottom_edge(dstinfo);
  180026. }
  180027. break;
  180028. case JXFORM_ROT_270:
  180029. transpose_critical_parameters(dstinfo);
  180030. if (info->trim)
  180031. trim_bottom_edge(dstinfo);
  180032. break;
  180033. }
  180034. /* Return the appropriate output data set */
  180035. if (info->workspace_coef_arrays != NULL)
  180036. return info->workspace_coef_arrays;
  180037. return src_coef_arrays;
  180038. }
  180039. /* Execute the actual transformation, if any.
  180040. *
  180041. * This must be called *after* jpeg_write_coefficients, because it depends
  180042. * on jpeg_write_coefficients to have computed subsidiary values such as
  180043. * the per-component width and height fields in the destination object.
  180044. *
  180045. * Note that some transformations will modify the source data arrays!
  180046. */
  180047. GLOBAL(void)
  180048. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  180049. j_compress_ptr dstinfo,
  180050. jvirt_barray_ptr *src_coef_arrays,
  180051. jpeg_transform_info *info)
  180052. {
  180053. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  180054. switch (info->transform) {
  180055. case JXFORM_NONE:
  180056. break;
  180057. case JXFORM_FLIP_H:
  180058. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  180059. break;
  180060. case JXFORM_FLIP_V:
  180061. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180062. break;
  180063. case JXFORM_TRANSPOSE:
  180064. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180065. break;
  180066. case JXFORM_TRANSVERSE:
  180067. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180068. break;
  180069. case JXFORM_ROT_90:
  180070. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180071. break;
  180072. case JXFORM_ROT_180:
  180073. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180074. break;
  180075. case JXFORM_ROT_270:
  180076. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180077. break;
  180078. }
  180079. }
  180080. #endif /* TRANSFORMS_SUPPORTED */
  180081. /* Setup decompression object to save desired markers in memory.
  180082. * This must be called before jpeg_read_header() to have the desired effect.
  180083. */
  180084. GLOBAL(void)
  180085. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  180086. {
  180087. #ifdef SAVE_MARKERS_SUPPORTED
  180088. int m;
  180089. /* Save comments except under NONE option */
  180090. if (option != JCOPYOPT_NONE) {
  180091. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  180092. }
  180093. /* Save all types of APPn markers iff ALL option */
  180094. if (option == JCOPYOPT_ALL) {
  180095. for (m = 0; m < 16; m++)
  180096. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  180097. }
  180098. #endif /* SAVE_MARKERS_SUPPORTED */
  180099. }
  180100. /* Copy markers saved in the given source object to the destination object.
  180101. * This should be called just after jpeg_start_compress() or
  180102. * jpeg_write_coefficients().
  180103. * Note that those routines will have written the SOI, and also the
  180104. * JFIF APP0 or Adobe APP14 markers if selected.
  180105. */
  180106. GLOBAL(void)
  180107. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180108. JCOPY_OPTION)
  180109. {
  180110. jpeg_saved_marker_ptr marker;
  180111. /* In the current implementation, we don't actually need to examine the
  180112. * option flag here; we just copy everything that got saved.
  180113. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  180114. * if the encoder library already wrote one.
  180115. */
  180116. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  180117. if (dstinfo->write_JFIF_header &&
  180118. marker->marker == JPEG_APP0 &&
  180119. marker->data_length >= 5 &&
  180120. GETJOCTET(marker->data[0]) == 0x4A &&
  180121. GETJOCTET(marker->data[1]) == 0x46 &&
  180122. GETJOCTET(marker->data[2]) == 0x49 &&
  180123. GETJOCTET(marker->data[3]) == 0x46 &&
  180124. GETJOCTET(marker->data[4]) == 0)
  180125. continue; /* reject duplicate JFIF */
  180126. if (dstinfo->write_Adobe_marker &&
  180127. marker->marker == JPEG_APP0+14 &&
  180128. marker->data_length >= 5 &&
  180129. GETJOCTET(marker->data[0]) == 0x41 &&
  180130. GETJOCTET(marker->data[1]) == 0x64 &&
  180131. GETJOCTET(marker->data[2]) == 0x6F &&
  180132. GETJOCTET(marker->data[3]) == 0x62 &&
  180133. GETJOCTET(marker->data[4]) == 0x65)
  180134. continue; /* reject duplicate Adobe */
  180135. #ifdef NEED_FAR_POINTERS
  180136. /* We could use jpeg_write_marker if the data weren't FAR... */
  180137. {
  180138. unsigned int i;
  180139. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  180140. for (i = 0; i < marker->data_length; i++)
  180141. jpeg_write_m_byte(dstinfo, marker->data[i]);
  180142. }
  180143. #else
  180144. jpeg_write_marker(dstinfo, marker->marker,
  180145. marker->data, marker->data_length);
  180146. #endif
  180147. }
  180148. }
  180149. /*** End of inlined file: transupp.c ***/
  180150. #else
  180151. #define JPEG_INTERNALS
  180152. #undef FAR
  180153. #include <jpeglib.h>
  180154. #endif
  180155. }
  180156. #undef max
  180157. #undef min
  180158. #if JUCE_MSVC
  180159. #pragma warning (pop)
  180160. #endif
  180161. BEGIN_JUCE_NAMESPACE
  180162. namespace JPEGHelpers
  180163. {
  180164. using namespace jpeglibNamespace;
  180165. #if ! JUCE_MSVC
  180166. using jpeglibNamespace::boolean;
  180167. #endif
  180168. struct JPEGDecodingFailure {};
  180169. void fatalErrorHandler (j_common_ptr)
  180170. {
  180171. throw JPEGDecodingFailure();
  180172. }
  180173. void silentErrorCallback1 (j_common_ptr) {}
  180174. void silentErrorCallback2 (j_common_ptr, int) {}
  180175. void silentErrorCallback3 (j_common_ptr, char*) {}
  180176. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  180177. {
  180178. zerostruct (err);
  180179. err.error_exit = fatalErrorHandler;
  180180. err.emit_message = silentErrorCallback2;
  180181. err.output_message = silentErrorCallback1;
  180182. err.format_message = silentErrorCallback3;
  180183. err.reset_error_mgr = silentErrorCallback1;
  180184. }
  180185. void dummyCallback1 (j_decompress_ptr)
  180186. {
  180187. }
  180188. void jpegSkip (j_decompress_ptr decompStruct, long num)
  180189. {
  180190. decompStruct->src->next_input_byte += num;
  180191. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  180192. decompStruct->src->bytes_in_buffer -= num;
  180193. }
  180194. boolean jpegFill (j_decompress_ptr)
  180195. {
  180196. return 0;
  180197. }
  180198. const int jpegBufferSize = 512;
  180199. struct JuceJpegDest : public jpeg_destination_mgr
  180200. {
  180201. OutputStream* output;
  180202. char* buffer;
  180203. };
  180204. void jpegWriteInit (j_compress_ptr)
  180205. {
  180206. }
  180207. void jpegWriteTerminate (j_compress_ptr cinfo)
  180208. {
  180209. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180210. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180211. dest->output->write (dest->buffer, (int) numToWrite);
  180212. }
  180213. boolean jpegWriteFlush (j_compress_ptr cinfo)
  180214. {
  180215. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180216. const int numToWrite = jpegBufferSize;
  180217. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180218. dest->free_in_buffer = jpegBufferSize;
  180219. return dest->output->write (dest->buffer, numToWrite);
  180220. }
  180221. }
  180222. JPEGImageFormat::JPEGImageFormat()
  180223. : quality (-1.0f)
  180224. {
  180225. }
  180226. JPEGImageFormat::~JPEGImageFormat() {}
  180227. void JPEGImageFormat::setQuality (const float newQuality)
  180228. {
  180229. quality = newQuality;
  180230. }
  180231. const String JPEGImageFormat::getFormatName()
  180232. {
  180233. return "JPEG";
  180234. }
  180235. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180236. {
  180237. const int bytesNeeded = 10;
  180238. uint8 header [bytesNeeded];
  180239. if (in.read (header, bytesNeeded) == bytesNeeded)
  180240. {
  180241. return header[0] == 0xff
  180242. && header[1] == 0xd8
  180243. && header[2] == 0xff
  180244. && (header[3] == 0xe0 || header[3] == 0xe1);
  180245. }
  180246. return false;
  180247. }
  180248. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180249. const Image juce_loadWithCoreImage (InputStream& input);
  180250. #endif
  180251. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180252. {
  180253. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180254. return juce_loadWithCoreImage (in);
  180255. #else
  180256. using namespace jpeglibNamespace;
  180257. using namespace JPEGHelpers;
  180258. MemoryOutputStream mb;
  180259. mb.writeFromInputStream (in, -1);
  180260. Image image;
  180261. if (mb.getDataSize() > 16)
  180262. {
  180263. struct jpeg_decompress_struct jpegDecompStruct;
  180264. struct jpeg_error_mgr jerr;
  180265. setupSilentErrorHandler (jerr);
  180266. jpegDecompStruct.err = &jerr;
  180267. jpeg_create_decompress (&jpegDecompStruct);
  180268. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180269. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180270. jpegDecompStruct.src->init_source = dummyCallback1;
  180271. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180272. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180273. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180274. jpegDecompStruct.src->term_source = dummyCallback1;
  180275. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180276. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180277. try
  180278. {
  180279. jpeg_read_header (&jpegDecompStruct, TRUE);
  180280. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180281. const int width = jpegDecompStruct.output_width;
  180282. const int height = jpegDecompStruct.output_height;
  180283. jpegDecompStruct.out_color_space = JCS_RGB;
  180284. JSAMPARRAY buffer
  180285. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180286. JPOOL_IMAGE,
  180287. width * 3, 1);
  180288. if (jpeg_start_decompress (&jpegDecompStruct))
  180289. {
  180290. image = Image (Image::RGB, width, height, false);
  180291. image.getProperties()->set ("originalImageHadAlpha", false);
  180292. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180293. const Image::BitmapData destData (image, true);
  180294. for (int y = 0; y < height; ++y)
  180295. {
  180296. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180297. const uint8* src = *buffer;
  180298. uint8* dest = destData.getLinePointer (y);
  180299. if (hasAlphaChan)
  180300. {
  180301. for (int i = width; --i >= 0;)
  180302. {
  180303. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180304. ((PixelARGB*) dest)->premultiply();
  180305. dest += destData.pixelStride;
  180306. src += 3;
  180307. }
  180308. }
  180309. else
  180310. {
  180311. for (int i = width; --i >= 0;)
  180312. {
  180313. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180314. dest += destData.pixelStride;
  180315. src += 3;
  180316. }
  180317. }
  180318. }
  180319. jpeg_finish_decompress (&jpegDecompStruct);
  180320. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180321. }
  180322. jpeg_destroy_decompress (&jpegDecompStruct);
  180323. }
  180324. catch (...)
  180325. {}
  180326. }
  180327. return image;
  180328. #endif
  180329. }
  180330. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180331. {
  180332. using namespace jpeglibNamespace;
  180333. using namespace JPEGHelpers;
  180334. if (image.hasAlphaChannel())
  180335. {
  180336. // this method could fill the background in white and still save the image..
  180337. jassertfalse;
  180338. return true;
  180339. }
  180340. struct jpeg_compress_struct jpegCompStruct;
  180341. struct jpeg_error_mgr jerr;
  180342. setupSilentErrorHandler (jerr);
  180343. jpegCompStruct.err = &jerr;
  180344. jpeg_create_compress (&jpegCompStruct);
  180345. JuceJpegDest dest;
  180346. jpegCompStruct.dest = &dest;
  180347. dest.output = &out;
  180348. HeapBlock <char> tempBuffer (jpegBufferSize);
  180349. dest.buffer = tempBuffer;
  180350. dest.next_output_byte = (JOCTET*) dest.buffer;
  180351. dest.free_in_buffer = jpegBufferSize;
  180352. dest.init_destination = jpegWriteInit;
  180353. dest.empty_output_buffer = jpegWriteFlush;
  180354. dest.term_destination = jpegWriteTerminate;
  180355. jpegCompStruct.image_width = image.getWidth();
  180356. jpegCompStruct.image_height = image.getHeight();
  180357. jpegCompStruct.input_components = 3;
  180358. jpegCompStruct.in_color_space = JCS_RGB;
  180359. jpegCompStruct.write_JFIF_header = 1;
  180360. jpegCompStruct.X_density = 72;
  180361. jpegCompStruct.Y_density = 72;
  180362. jpeg_set_defaults (&jpegCompStruct);
  180363. jpegCompStruct.dct_method = JDCT_FLOAT;
  180364. jpegCompStruct.optimize_coding = 1;
  180365. //jpegCompStruct.smoothing_factor = 10;
  180366. if (quality < 0.0f)
  180367. quality = 0.85f;
  180368. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180369. jpeg_start_compress (&jpegCompStruct, TRUE);
  180370. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180371. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180372. JPOOL_IMAGE, strideBytes, 1);
  180373. const Image::BitmapData srcData (image, false);
  180374. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180375. {
  180376. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180377. uint8* dst = *buffer;
  180378. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180379. {
  180380. *dst++ = ((const PixelRGB*) src)->getRed();
  180381. *dst++ = ((const PixelRGB*) src)->getGreen();
  180382. *dst++ = ((const PixelRGB*) src)->getBlue();
  180383. src += srcData.pixelStride;
  180384. }
  180385. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180386. }
  180387. jpeg_finish_compress (&jpegCompStruct);
  180388. jpeg_destroy_compress (&jpegCompStruct);
  180389. out.flush();
  180390. return true;
  180391. }
  180392. END_JUCE_NAMESPACE
  180393. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180394. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180395. #if JUCE_MSVC
  180396. #pragma warning (push)
  180397. #pragma warning (disable: 4390 4611)
  180398. #endif
  180399. namespace zlibNamespace
  180400. {
  180401. #if JUCE_INCLUDE_ZLIB_CODE
  180402. #undef OS_CODE
  180403. #undef fdopen
  180404. #undef OS_CODE
  180405. #else
  180406. #include <zlib.h>
  180407. #endif
  180408. }
  180409. namespace pnglibNamespace
  180410. {
  180411. using namespace zlibNamespace;
  180412. #if JUCE_INCLUDE_PNGLIB_CODE
  180413. #if _MSC_VER != 1310
  180414. using ::calloc; // (causes conflict in VS.NET 2003)
  180415. using ::malloc;
  180416. using ::free;
  180417. #endif
  180418. using ::abs;
  180419. #define PNG_INTERNAL
  180420. #define NO_DUMMY_DECL
  180421. #define PNG_SETJMP_NOT_SUPPORTED
  180422. /*** Start of inlined file: png.h ***/
  180423. /* png.h - header file for PNG reference library
  180424. *
  180425. * libpng version 1.2.21 - October 4, 2007
  180426. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180427. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180428. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180429. *
  180430. * Authors and maintainers:
  180431. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180432. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180433. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180434. * See also "Contributing Authors", below.
  180435. *
  180436. * Note about libpng version numbers:
  180437. *
  180438. * Due to various miscommunications, unforeseen code incompatibilities
  180439. * and occasional factors outside the authors' control, version numbering
  180440. * on the library has not always been consistent and straightforward.
  180441. * The following table summarizes matters since version 0.89c, which was
  180442. * the first widely used release:
  180443. *
  180444. * source png.h png.h shared-lib
  180445. * version string int version
  180446. * ------- ------ ----- ----------
  180447. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180448. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180449. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180450. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180451. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180452. * 0.97c 0.97 97 2.0.97
  180453. * 0.98 0.98 98 2.0.98
  180454. * 0.99 0.99 98 2.0.99
  180455. * 0.99a-m 0.99 99 2.0.99
  180456. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180457. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180458. * 1.0.1 png.h string is 10001 2.1.0
  180459. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180460. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180461. * 1.0.2a-b 10003 version, except as noted.
  180462. * 1.0.3 10003
  180463. * 1.0.3a-d 10004
  180464. * 1.0.4 10004
  180465. * 1.0.4a-f 10005
  180466. * 1.0.5 (+ 2 patches) 10005
  180467. * 1.0.5a-d 10006
  180468. * 1.0.5e-r 10100 (not source compatible)
  180469. * 1.0.5s-v 10006 (not binary compatible)
  180470. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180471. * 1.0.6d-f 10007 (still binary incompatible)
  180472. * 1.0.6g 10007
  180473. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180474. * 1.0.6i 10007 10.6i
  180475. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180476. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180477. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180478. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180479. * 1.0.7 1 10007 (still compatible)
  180480. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180481. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180482. * 1.0.8 1 10008 2.1.0.8
  180483. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180484. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180485. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180486. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180487. * 1.0.9 1 10009 2.1.0.9
  180488. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180489. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180490. * 1.0.10 1 10010 2.1.0.10
  180491. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180492. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180493. * 1.0.11 1 10011 2.1.0.11
  180494. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180495. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180496. * 1.0.12 2 10012 2.1.0.12
  180497. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180498. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180499. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180500. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180501. * 1.2.0 3 10200 3.1.2.0
  180502. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180503. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180504. * 1.2.1 3 10201 3.1.2.1
  180505. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180506. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180507. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180508. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180509. * 1.0.13 10 10013 10.so.0.1.0.13
  180510. * 1.2.2 12 10202 12.so.0.1.2.2
  180511. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180512. * 1.2.3 12 10203 12.so.0.1.2.3
  180513. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180514. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180515. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180516. * 1.0.14 10 10014 10.so.0.1.0.14
  180517. * 1.2.4 13 10204 12.so.0.1.2.4
  180518. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180519. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180520. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180521. * 1.0.15 10 10015 10.so.0.1.0.15
  180522. * 1.2.5 13 10205 12.so.0.1.2.5
  180523. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180524. * 1.0.16 10 10016 10.so.0.1.0.16
  180525. * 1.2.6 13 10206 12.so.0.1.2.6
  180526. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180527. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180528. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180529. * 1.0.17 10 10017 10.so.0.1.0.17
  180530. * 1.2.7 13 10207 12.so.0.1.2.7
  180531. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180532. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180533. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180534. * 1.0.18 10 10018 10.so.0.1.0.18
  180535. * 1.2.8 13 10208 12.so.0.1.2.8
  180536. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180537. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180538. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180539. * 1.2.9 13 10209 12.so.0.9[.0]
  180540. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180541. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180542. * 1.2.10 13 10210 12.so.0.10[.0]
  180543. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180544. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180545. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180546. * 1.0.19 10 10019 10.so.0.19[.0]
  180547. * 1.2.11 13 10211 12.so.0.11[.0]
  180548. * 1.0.20 10 10020 10.so.0.20[.0]
  180549. * 1.2.12 13 10212 12.so.0.12[.0]
  180550. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180551. * 1.0.21 10 10021 10.so.0.21[.0]
  180552. * 1.2.13 13 10213 12.so.0.13[.0]
  180553. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180554. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180555. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180556. * 1.0.22 10 10022 10.so.0.22[.0]
  180557. * 1.2.14 13 10214 12.so.0.14[.0]
  180558. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180559. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180560. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180561. * 1.0.23 10 10023 10.so.0.23[.0]
  180562. * 1.2.15 13 10215 12.so.0.15[.0]
  180563. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180564. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180565. * 1.0.24 10 10024 10.so.0.24[.0]
  180566. * 1.2.16 13 10216 12.so.0.16[.0]
  180567. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180568. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180569. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180570. * 1.0.25 10 10025 10.so.0.25[.0]
  180571. * 1.2.17 13 10217 12.so.0.17[.0]
  180572. * 1.0.26 10 10026 10.so.0.26[.0]
  180573. * 1.2.18 13 10218 12.so.0.18[.0]
  180574. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180575. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180576. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180577. * 1.0.27 10 10027 10.so.0.27[.0]
  180578. * 1.2.19 13 10219 12.so.0.19[.0]
  180579. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180580. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180581. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180582. * 1.0.28 10 10028 10.so.0.28[.0]
  180583. * 1.2.20 13 10220 12.so.0.20[.0]
  180584. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180585. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180586. * 1.0.29 10 10029 10.so.0.29[.0]
  180587. * 1.2.21 13 10221 12.so.0.21[.0]
  180588. *
  180589. * Henceforth the source version will match the shared-library major
  180590. * and minor numbers; the shared-library major version number will be
  180591. * used for changes in backward compatibility, as it is intended. The
  180592. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180593. * for applications, is an unsigned integer of the form xyyzz corresponding
  180594. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180595. * were given the previous public release number plus a letter, until
  180596. * version 1.0.6j; from then on they were given the upcoming public
  180597. * release number plus "betaNN" or "rcN".
  180598. *
  180599. * Binary incompatibility exists only when applications make direct access
  180600. * to the info_ptr or png_ptr members through png.h, and the compiled
  180601. * application is loaded with a different version of the library.
  180602. *
  180603. * DLLNUM will change each time there are forward or backward changes
  180604. * in binary compatibility (e.g., when a new feature is added).
  180605. *
  180606. * See libpng.txt or libpng.3 for more information. The PNG specification
  180607. * is available as a W3C Recommendation and as an ISO Specification,
  180608. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180609. */
  180610. /*
  180611. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180612. *
  180613. * If you modify libpng you may insert additional notices immediately following
  180614. * this sentence.
  180615. *
  180616. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180617. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180618. * distributed according to the same disclaimer and license as libpng-1.2.5
  180619. * with the following individual added to the list of Contributing Authors:
  180620. *
  180621. * Cosmin Truta
  180622. *
  180623. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180624. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180625. * distributed according to the same disclaimer and license as libpng-1.0.6
  180626. * with the following individuals added to the list of Contributing Authors:
  180627. *
  180628. * Simon-Pierre Cadieux
  180629. * Eric S. Raymond
  180630. * Gilles Vollant
  180631. *
  180632. * and with the following additions to the disclaimer:
  180633. *
  180634. * There is no warranty against interference with your enjoyment of the
  180635. * library or against infringement. There is no warranty that our
  180636. * efforts or the library will fulfill any of your particular purposes
  180637. * or needs. This library is provided with all faults, and the entire
  180638. * risk of satisfactory quality, performance, accuracy, and effort is with
  180639. * the user.
  180640. *
  180641. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180642. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180643. * distributed according to the same disclaimer and license as libpng-0.96,
  180644. * with the following individuals added to the list of Contributing Authors:
  180645. *
  180646. * Tom Lane
  180647. * Glenn Randers-Pehrson
  180648. * Willem van Schaik
  180649. *
  180650. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180651. * Copyright (c) 1996, 1997 Andreas Dilger
  180652. * Distributed according to the same disclaimer and license as libpng-0.88,
  180653. * with the following individuals added to the list of Contributing Authors:
  180654. *
  180655. * John Bowler
  180656. * Kevin Bracey
  180657. * Sam Bushell
  180658. * Magnus Holmgren
  180659. * Greg Roelofs
  180660. * Tom Tanner
  180661. *
  180662. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180663. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180664. *
  180665. * For the purposes of this copyright and license, "Contributing Authors"
  180666. * is defined as the following set of individuals:
  180667. *
  180668. * Andreas Dilger
  180669. * Dave Martindale
  180670. * Guy Eric Schalnat
  180671. * Paul Schmidt
  180672. * Tim Wegner
  180673. *
  180674. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180675. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180676. * including, without limitation, the warranties of merchantability and of
  180677. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180678. * assume no liability for direct, indirect, incidental, special, exemplary,
  180679. * or consequential damages, which may result from the use of the PNG
  180680. * Reference Library, even if advised of the possibility of such damage.
  180681. *
  180682. * Permission is hereby granted to use, copy, modify, and distribute this
  180683. * source code, or portions hereof, for any purpose, without fee, subject
  180684. * to the following restrictions:
  180685. *
  180686. * 1. The origin of this source code must not be misrepresented.
  180687. *
  180688. * 2. Altered versions must be plainly marked as such and
  180689. * must not be misrepresented as being the original source.
  180690. *
  180691. * 3. This Copyright notice may not be removed or altered from
  180692. * any source or altered source distribution.
  180693. *
  180694. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180695. * fee, and encourage the use of this source code as a component to
  180696. * supporting the PNG file format in commercial products. If you use this
  180697. * source code in a product, acknowledgment is not required but would be
  180698. * appreciated.
  180699. */
  180700. /*
  180701. * A "png_get_copyright" function is available, for convenient use in "about"
  180702. * boxes and the like:
  180703. *
  180704. * printf("%s",png_get_copyright(NULL));
  180705. *
  180706. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180707. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180708. */
  180709. /*
  180710. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180711. * certification mark of the Open Source Initiative.
  180712. */
  180713. /*
  180714. * The contributing authors would like to thank all those who helped
  180715. * with testing, bug fixes, and patience. This wouldn't have been
  180716. * possible without all of you.
  180717. *
  180718. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180719. */
  180720. /*
  180721. * Y2K compliance in libpng:
  180722. * =========================
  180723. *
  180724. * October 4, 2007
  180725. *
  180726. * Since the PNG Development group is an ad-hoc body, we can't make
  180727. * an official declaration.
  180728. *
  180729. * This is your unofficial assurance that libpng from version 0.71 and
  180730. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180731. * versions were also Y2K compliant.
  180732. *
  180733. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180734. * that will hold years up to 65535. The other two hold the date in text
  180735. * format, and will hold years up to 9999.
  180736. *
  180737. * The integer is
  180738. * "png_uint_16 year" in png_time_struct.
  180739. *
  180740. * The strings are
  180741. * "png_charp time_buffer" in png_struct and
  180742. * "near_time_buffer", which is a local character string in png.c.
  180743. *
  180744. * There are seven time-related functions:
  180745. * png.c: png_convert_to_rfc_1123() in png.c
  180746. * (formerly png_convert_to_rfc_1152() in error)
  180747. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180748. * png_convert_from_time_t() in pngwrite.c
  180749. * png_get_tIME() in pngget.c
  180750. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180751. * png_set_tIME() in pngset.c
  180752. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180753. *
  180754. * All handle dates properly in a Y2K environment. The
  180755. * png_convert_from_time_t() function calls gmtime() to convert from system
  180756. * clock time, which returns (year - 1900), which we properly convert to
  180757. * the full 4-digit year. There is a possibility that applications using
  180758. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180759. * function, or that they are incorrectly passing only a 2-digit year
  180760. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180761. * but this is not under our control. The libpng documentation has always
  180762. * stated that it works with 4-digit years, and the APIs have been
  180763. * documented as such.
  180764. *
  180765. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180766. * integer to hold the year, and can hold years as large as 65535.
  180767. *
  180768. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180769. * no date-related code.
  180770. *
  180771. * Glenn Randers-Pehrson
  180772. * libpng maintainer
  180773. * PNG Development Group
  180774. */
  180775. #ifndef PNG_H
  180776. #define PNG_H
  180777. /* This is not the place to learn how to use libpng. The file libpng.txt
  180778. * describes how to use libpng, and the file example.c summarizes it
  180779. * with some code on which to build. This file is useful for looking
  180780. * at the actual function definitions and structure components.
  180781. */
  180782. /* Version information for png.h - this should match the version in png.c */
  180783. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180784. #define PNG_HEADER_VERSION_STRING \
  180785. " libpng version 1.2.21 - October 4, 2007\n"
  180786. #define PNG_LIBPNG_VER_SONUM 0
  180787. #define PNG_LIBPNG_VER_DLLNUM 13
  180788. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180789. #define PNG_LIBPNG_VER_MAJOR 1
  180790. #define PNG_LIBPNG_VER_MINOR 2
  180791. #define PNG_LIBPNG_VER_RELEASE 21
  180792. /* This should match the numeric part of the final component of
  180793. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180794. #define PNG_LIBPNG_VER_BUILD 0
  180795. /* Release Status */
  180796. #define PNG_LIBPNG_BUILD_ALPHA 1
  180797. #define PNG_LIBPNG_BUILD_BETA 2
  180798. #define PNG_LIBPNG_BUILD_RC 3
  180799. #define PNG_LIBPNG_BUILD_STABLE 4
  180800. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180801. /* Release-Specific Flags */
  180802. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180803. PNG_LIBPNG_BUILD_STABLE only */
  180804. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180805. PNG_LIBPNG_BUILD_SPECIAL */
  180806. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180807. PNG_LIBPNG_BUILD_PRIVATE */
  180808. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180809. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180810. * We must not include leading zeros.
  180811. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180812. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180813. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180814. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180815. #ifndef PNG_VERSION_INFO_ONLY
  180816. /* include the compression library's header */
  180817. #endif
  180818. /* include all user configurable info, including optional assembler routines */
  180819. /*** Start of inlined file: pngconf.h ***/
  180820. /* pngconf.h - machine configurable file for libpng
  180821. *
  180822. * libpng version 1.2.21 - October 4, 2007
  180823. * For conditions of distribution and use, see copyright notice in png.h
  180824. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180825. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180826. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180827. */
  180828. /* Any machine specific code is near the front of this file, so if you
  180829. * are configuring libpng for a machine, you may want to read the section
  180830. * starting here down to where it starts to typedef png_color, png_text,
  180831. * and png_info.
  180832. */
  180833. #ifndef PNGCONF_H
  180834. #define PNGCONF_H
  180835. #define PNG_1_2_X
  180836. // These are some Juce config settings that should remove any unnecessary code bloat..
  180837. #define PNG_NO_STDIO 1
  180838. #define PNG_DEBUG 0
  180839. #define PNG_NO_WARNINGS 1
  180840. #define PNG_NO_ERROR_TEXT 1
  180841. #define PNG_NO_ERROR_NUMBERS 1
  180842. #define PNG_NO_USER_MEM 1
  180843. #define PNG_NO_READ_iCCP 1
  180844. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180845. #define PNG_NO_READ_USER_CHUNKS 1
  180846. #define PNG_NO_READ_iTXt 1
  180847. #define PNG_NO_READ_sCAL 1
  180848. #define PNG_NO_READ_sPLT 1
  180849. #define png_error(a, b) png_err(a)
  180850. #define png_warning(a, b)
  180851. #define png_chunk_error(a, b) png_err(a)
  180852. #define png_chunk_warning(a, b)
  180853. /*
  180854. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180855. * includes the resource compiler for Windows DLL configurations.
  180856. */
  180857. #ifdef PNG_USER_CONFIG
  180858. # ifndef PNG_USER_PRIVATEBUILD
  180859. # define PNG_USER_PRIVATEBUILD
  180860. # endif
  180861. #include "pngusr.h"
  180862. #endif
  180863. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180864. #ifdef PNG_CONFIGURE_LIBPNG
  180865. #ifdef HAVE_CONFIG_H
  180866. #include "config.h"
  180867. #endif
  180868. #endif
  180869. /*
  180870. * Added at libpng-1.2.8
  180871. *
  180872. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180873. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180874. * the DLL was built>
  180875. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180876. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180877. * distinguish your DLL from those of the official release. These
  180878. * correspond to the trailing letters that come after the version
  180879. * number and must match your private DLL name>
  180880. * e.g. // private DLL "libpng13gx.dll"
  180881. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180882. *
  180883. * The following macros are also at your disposal if you want to complete the
  180884. * DLL VERSIONINFO structure.
  180885. * - PNG_USER_VERSIONINFO_COMMENTS
  180886. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180887. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180888. */
  180889. #ifdef __STDC__
  180890. #ifdef SPECIALBUILD
  180891. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180892. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180893. #endif
  180894. #ifdef PRIVATEBUILD
  180895. # pragma message("PRIVATEBUILD is deprecated.\
  180896. Use PNG_USER_PRIVATEBUILD instead.")
  180897. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180898. #endif
  180899. #endif /* __STDC__ */
  180900. #ifndef PNG_VERSION_INFO_ONLY
  180901. /* End of material added to libpng-1.2.8 */
  180902. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180903. Restored at libpng-1.2.21 */
  180904. # define PNG_WARN_UNINITIALIZED_ROW 1
  180905. /* End of material added at libpng-1.2.19/1.2.21 */
  180906. /* This is the size of the compression buffer, and thus the size of
  180907. * an IDAT chunk. Make this whatever size you feel is best for your
  180908. * machine. One of these will be allocated per png_struct. When this
  180909. * is full, it writes the data to the disk, and does some other
  180910. * calculations. Making this an extremely small size will slow
  180911. * the library down, but you may want to experiment to determine
  180912. * where it becomes significant, if you are concerned with memory
  180913. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180914. * this describes the size of the buffer available to read the data in.
  180915. * Unless this gets smaller than the size of a row (compressed),
  180916. * it should not make much difference how big this is.
  180917. */
  180918. #ifndef PNG_ZBUF_SIZE
  180919. # define PNG_ZBUF_SIZE 8192
  180920. #endif
  180921. /* Enable if you want a write-only libpng */
  180922. #ifndef PNG_NO_READ_SUPPORTED
  180923. # define PNG_READ_SUPPORTED
  180924. #endif
  180925. /* Enable if you want a read-only libpng */
  180926. #ifndef PNG_NO_WRITE_SUPPORTED
  180927. # define PNG_WRITE_SUPPORTED
  180928. #endif
  180929. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180930. support PNGs that are embedded in MNG datastreams */
  180931. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180932. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180933. # define PNG_MNG_FEATURES_SUPPORTED
  180934. # endif
  180935. #endif
  180936. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180937. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180938. # define PNG_FLOATING_POINT_SUPPORTED
  180939. # endif
  180940. #endif
  180941. /* If you are running on a machine where you cannot allocate more
  180942. * than 64K of memory at once, uncomment this. While libpng will not
  180943. * normally need that much memory in a chunk (unless you load up a very
  180944. * large file), zlib needs to know how big of a chunk it can use, and
  180945. * libpng thus makes sure to check any memory allocation to verify it
  180946. * will fit into memory.
  180947. #define PNG_MAX_MALLOC_64K
  180948. */
  180949. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180950. # define PNG_MAX_MALLOC_64K
  180951. #endif
  180952. /* Special munging to support doing things the 'cygwin' way:
  180953. * 'Normal' png-on-win32 defines/defaults:
  180954. * PNG_BUILD_DLL -- building dll
  180955. * PNG_USE_DLL -- building an application, linking to dll
  180956. * (no define) -- building static library, or building an
  180957. * application and linking to the static lib
  180958. * 'Cygwin' defines/defaults:
  180959. * PNG_BUILD_DLL -- (ignored) building the dll
  180960. * (no define) -- (ignored) building an application, linking to the dll
  180961. * PNG_STATIC -- (ignored) building the static lib, or building an
  180962. * application that links to the static lib.
  180963. * ALL_STATIC -- (ignored) building various static libs, or building an
  180964. * application that links to the static libs.
  180965. * Thus,
  180966. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180967. * this bit of #ifdefs will define the 'correct' config variables based on
  180968. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180969. * unnecessary.
  180970. *
  180971. * Also, the precedence order is:
  180972. * ALL_STATIC (since we can't #undef something outside our namespace)
  180973. * PNG_BUILD_DLL
  180974. * PNG_STATIC
  180975. * (nothing) == PNG_USE_DLL
  180976. *
  180977. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180978. * of auto-import in binutils, we no longer need to worry about
  180979. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180980. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180981. * to __declspec() stuff. However, we DO need to worry about
  180982. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180983. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180984. */
  180985. #if defined(__CYGWIN__)
  180986. # if defined(ALL_STATIC)
  180987. # if defined(PNG_BUILD_DLL)
  180988. # undef PNG_BUILD_DLL
  180989. # endif
  180990. # if defined(PNG_USE_DLL)
  180991. # undef PNG_USE_DLL
  180992. # endif
  180993. # if defined(PNG_DLL)
  180994. # undef PNG_DLL
  180995. # endif
  180996. # if !defined(PNG_STATIC)
  180997. # define PNG_STATIC
  180998. # endif
  180999. # else
  181000. # if defined (PNG_BUILD_DLL)
  181001. # if defined(PNG_STATIC)
  181002. # undef PNG_STATIC
  181003. # endif
  181004. # if defined(PNG_USE_DLL)
  181005. # undef PNG_USE_DLL
  181006. # endif
  181007. # if !defined(PNG_DLL)
  181008. # define PNG_DLL
  181009. # endif
  181010. # else
  181011. # if defined(PNG_STATIC)
  181012. # if defined(PNG_USE_DLL)
  181013. # undef PNG_USE_DLL
  181014. # endif
  181015. # if defined(PNG_DLL)
  181016. # undef PNG_DLL
  181017. # endif
  181018. # else
  181019. # if !defined(PNG_USE_DLL)
  181020. # define PNG_USE_DLL
  181021. # endif
  181022. # if !defined(PNG_DLL)
  181023. # define PNG_DLL
  181024. # endif
  181025. # endif
  181026. # endif
  181027. # endif
  181028. #endif
  181029. /* This protects us against compilers that run on a windowing system
  181030. * and thus don't have or would rather us not use the stdio types:
  181031. * stdin, stdout, and stderr. The only one currently used is stderr
  181032. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  181033. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  181034. * will also prevent these, plus will prevent the entire set of stdio
  181035. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  181036. * unless (PNG_DEBUG > 0) has been #defined.
  181037. *
  181038. * #define PNG_NO_CONSOLE_IO
  181039. * #define PNG_NO_STDIO
  181040. */
  181041. #if defined(_WIN32_WCE)
  181042. # include <windows.h>
  181043. /* Console I/O functions are not supported on WindowsCE */
  181044. # define PNG_NO_CONSOLE_IO
  181045. # ifdef PNG_DEBUG
  181046. # undef PNG_DEBUG
  181047. # endif
  181048. #endif
  181049. #ifdef PNG_BUILD_DLL
  181050. # ifndef PNG_CONSOLE_IO_SUPPORTED
  181051. # ifndef PNG_NO_CONSOLE_IO
  181052. # define PNG_NO_CONSOLE_IO
  181053. # endif
  181054. # endif
  181055. #endif
  181056. # ifdef PNG_NO_STDIO
  181057. # ifndef PNG_NO_CONSOLE_IO
  181058. # define PNG_NO_CONSOLE_IO
  181059. # endif
  181060. # ifdef PNG_DEBUG
  181061. # if (PNG_DEBUG > 0)
  181062. # include <stdio.h>
  181063. # endif
  181064. # endif
  181065. # else
  181066. # if !defined(_WIN32_WCE)
  181067. /* "stdio.h" functions are not supported on WindowsCE */
  181068. # include <stdio.h>
  181069. # endif
  181070. # endif
  181071. /* This macro protects us against machines that don't have function
  181072. * prototypes (ie K&R style headers). If your compiler does not handle
  181073. * function prototypes, define this macro and use the included ansi2knr.
  181074. * I've always been able to use _NO_PROTO as the indicator, but you may
  181075. * need to drag the empty declaration out in front of here, or change the
  181076. * ifdef to suit your own needs.
  181077. */
  181078. #ifndef PNGARG
  181079. #ifdef OF /* zlib prototype munger */
  181080. # define PNGARG(arglist) OF(arglist)
  181081. #else
  181082. #ifdef _NO_PROTO
  181083. # define PNGARG(arglist) ()
  181084. # ifndef PNG_TYPECAST_NULL
  181085. # define PNG_TYPECAST_NULL
  181086. # endif
  181087. #else
  181088. # define PNGARG(arglist) arglist
  181089. #endif /* _NO_PROTO */
  181090. #endif /* OF */
  181091. #endif /* PNGARG */
  181092. /* Try to determine if we are compiling on a Mac. Note that testing for
  181093. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  181094. * on non-Mac platforms.
  181095. */
  181096. #ifndef MACOS
  181097. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  181098. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  181099. # define MACOS
  181100. # endif
  181101. #endif
  181102. /* enough people need this for various reasons to include it here */
  181103. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  181104. # include <sys/types.h>
  181105. #endif
  181106. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  181107. # define PNG_SETJMP_SUPPORTED
  181108. #endif
  181109. #ifdef PNG_SETJMP_SUPPORTED
  181110. /* This is an attempt to force a single setjmp behaviour on Linux. If
  181111. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  181112. */
  181113. # ifdef __linux__
  181114. # ifdef _BSD_SOURCE
  181115. # define PNG_SAVE_BSD_SOURCE
  181116. # undef _BSD_SOURCE
  181117. # endif
  181118. # ifdef _SETJMP_H
  181119. /* If you encounter a compiler error here, see the explanation
  181120. * near the end of INSTALL.
  181121. */
  181122. __png.h__ already includes setjmp.h;
  181123. __dont__ include it again.;
  181124. # endif
  181125. # endif /* __linux__ */
  181126. /* include setjmp.h for error handling */
  181127. # include <setjmp.h>
  181128. # ifdef __linux__
  181129. # ifdef PNG_SAVE_BSD_SOURCE
  181130. # define _BSD_SOURCE
  181131. # undef PNG_SAVE_BSD_SOURCE
  181132. # endif
  181133. # endif /* __linux__ */
  181134. #endif /* PNG_SETJMP_SUPPORTED */
  181135. #ifdef BSD
  181136. #if ! JUCE_MAC
  181137. # include <strings.h>
  181138. #endif
  181139. #else
  181140. # include <string.h>
  181141. #endif
  181142. /* Other defines for things like memory and the like can go here. */
  181143. #ifdef PNG_INTERNAL
  181144. #include <stdlib.h>
  181145. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  181146. * aren't usually used outside the library (as far as I know), so it is
  181147. * debatable if they should be exported at all. In the future, when it is
  181148. * possible to have run-time registry of chunk-handling functions, some of
  181149. * these will be made available again.
  181150. #define PNG_EXTERN extern
  181151. */
  181152. #define PNG_EXTERN
  181153. /* Other defines specific to compilers can go here. Try to keep
  181154. * them inside an appropriate ifdef/endif pair for portability.
  181155. */
  181156. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  181157. # if defined(MACOS)
  181158. /* We need to check that <math.h> hasn't already been included earlier
  181159. * as it seems it doesn't agree with <fp.h>, yet we should really use
  181160. * <fp.h> if possible.
  181161. */
  181162. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  181163. # include <fp.h>
  181164. # endif
  181165. # else
  181166. # include <math.h>
  181167. # endif
  181168. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  181169. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  181170. * MATH=68881
  181171. */
  181172. # include <m68881.h>
  181173. # endif
  181174. #endif
  181175. /* Codewarrior on NT has linking problems without this. */
  181176. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  181177. # define PNG_ALWAYS_EXTERN
  181178. #endif
  181179. /* This provides the non-ANSI (far) memory allocation routines. */
  181180. #if defined(__TURBOC__) && defined(__MSDOS__)
  181181. # include <mem.h>
  181182. # include <alloc.h>
  181183. #endif
  181184. /* I have no idea why is this necessary... */
  181185. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  181186. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  181187. # include <malloc.h>
  181188. #endif
  181189. /* This controls how fine the dithering gets. As this allocates
  181190. * a largish chunk of memory (32K), those who are not as concerned
  181191. * with dithering quality can decrease some or all of these.
  181192. */
  181193. #ifndef PNG_DITHER_RED_BITS
  181194. # define PNG_DITHER_RED_BITS 5
  181195. #endif
  181196. #ifndef PNG_DITHER_GREEN_BITS
  181197. # define PNG_DITHER_GREEN_BITS 5
  181198. #endif
  181199. #ifndef PNG_DITHER_BLUE_BITS
  181200. # define PNG_DITHER_BLUE_BITS 5
  181201. #endif
  181202. /* This controls how fine the gamma correction becomes when you
  181203. * are only interested in 8 bits anyway. Increasing this value
  181204. * results in more memory being used, and more pow() functions
  181205. * being called to fill in the gamma tables. Don't set this value
  181206. * less then 8, and even that may not work (I haven't tested it).
  181207. */
  181208. #ifndef PNG_MAX_GAMMA_8
  181209. # define PNG_MAX_GAMMA_8 11
  181210. #endif
  181211. /* This controls how much a difference in gamma we can tolerate before
  181212. * we actually start doing gamma conversion.
  181213. */
  181214. #ifndef PNG_GAMMA_THRESHOLD
  181215. # define PNG_GAMMA_THRESHOLD 0.05
  181216. #endif
  181217. #endif /* PNG_INTERNAL */
  181218. /* The following uses const char * instead of char * for error
  181219. * and warning message functions, so some compilers won't complain.
  181220. * If you do not want to use const, define PNG_NO_CONST here.
  181221. */
  181222. #ifndef PNG_NO_CONST
  181223. # define PNG_CONST const
  181224. #else
  181225. # define PNG_CONST
  181226. #endif
  181227. /* The following defines give you the ability to remove code from the
  181228. * library that you will not be using. I wish I could figure out how to
  181229. * automate this, but I can't do that without making it seriously hard
  181230. * on the users. So if you are not using an ability, change the #define
  181231. * to and #undef, and that part of the library will not be compiled. If
  181232. * your linker can't find a function, you may want to make sure the
  181233. * ability is defined here. Some of these depend upon some others being
  181234. * defined. I haven't figured out all the interactions here, so you may
  181235. * have to experiment awhile to get everything to compile. If you are
  181236. * creating or using a shared library, you probably shouldn't touch this,
  181237. * as it will affect the size of the structures, and this will cause bad
  181238. * things to happen if the library and/or application ever change.
  181239. */
  181240. /* Any features you will not be using can be undef'ed here */
  181241. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181242. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181243. * on the compile line, then pick and choose which ones to define without
  181244. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181245. * if you only want to have a png-compliant reader/writer but don't need
  181246. * any of the extra transformations. This saves about 80 kbytes in a
  181247. * typical installation of the library. (PNG_NO_* form added in version
  181248. * 1.0.1c, for consistency)
  181249. */
  181250. /* The size of the png_text structure changed in libpng-1.0.6 when
  181251. * iTXt support was added. iTXt support was turned off by default through
  181252. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181253. * instead of calling png_set_text() and letting libpng malloc it. It
  181254. * was turned on by default in libpng-1.3.0.
  181255. */
  181256. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181257. # ifndef PNG_NO_iTXt_SUPPORTED
  181258. # define PNG_NO_iTXt_SUPPORTED
  181259. # endif
  181260. # ifndef PNG_NO_READ_iTXt
  181261. # define PNG_NO_READ_iTXt
  181262. # endif
  181263. # ifndef PNG_NO_WRITE_iTXt
  181264. # define PNG_NO_WRITE_iTXt
  181265. # endif
  181266. #endif
  181267. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181268. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181269. # define PNG_READ_iTXt
  181270. # endif
  181271. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181272. # define PNG_WRITE_iTXt
  181273. # endif
  181274. #endif
  181275. /* The following support, added after version 1.0.0, can be turned off here en
  181276. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181277. * with old applications that require the length of png_struct and png_info
  181278. * to remain unchanged.
  181279. */
  181280. #ifdef PNG_LEGACY_SUPPORTED
  181281. # define PNG_NO_FREE_ME
  181282. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181283. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181284. # define PNG_NO_READ_USER_CHUNKS
  181285. # define PNG_NO_READ_iCCP
  181286. # define PNG_NO_WRITE_iCCP
  181287. # define PNG_NO_READ_iTXt
  181288. # define PNG_NO_WRITE_iTXt
  181289. # define PNG_NO_READ_sCAL
  181290. # define PNG_NO_WRITE_sCAL
  181291. # define PNG_NO_READ_sPLT
  181292. # define PNG_NO_WRITE_sPLT
  181293. # define PNG_NO_INFO_IMAGE
  181294. # define PNG_NO_READ_RGB_TO_GRAY
  181295. # define PNG_NO_READ_USER_TRANSFORM
  181296. # define PNG_NO_WRITE_USER_TRANSFORM
  181297. # define PNG_NO_USER_MEM
  181298. # define PNG_NO_READ_EMPTY_PLTE
  181299. # define PNG_NO_MNG_FEATURES
  181300. # define PNG_NO_FIXED_POINT_SUPPORTED
  181301. #endif
  181302. /* Ignore attempt to turn off both floating and fixed point support */
  181303. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181304. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181305. # define PNG_FIXED_POINT_SUPPORTED
  181306. #endif
  181307. #ifndef PNG_NO_FREE_ME
  181308. # define PNG_FREE_ME_SUPPORTED
  181309. #endif
  181310. #if defined(PNG_READ_SUPPORTED)
  181311. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181312. !defined(PNG_NO_READ_TRANSFORMS)
  181313. # define PNG_READ_TRANSFORMS_SUPPORTED
  181314. #endif
  181315. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181316. # ifndef PNG_NO_READ_EXPAND
  181317. # define PNG_READ_EXPAND_SUPPORTED
  181318. # endif
  181319. # ifndef PNG_NO_READ_SHIFT
  181320. # define PNG_READ_SHIFT_SUPPORTED
  181321. # endif
  181322. # ifndef PNG_NO_READ_PACK
  181323. # define PNG_READ_PACK_SUPPORTED
  181324. # endif
  181325. # ifndef PNG_NO_READ_BGR
  181326. # define PNG_READ_BGR_SUPPORTED
  181327. # endif
  181328. # ifndef PNG_NO_READ_SWAP
  181329. # define PNG_READ_SWAP_SUPPORTED
  181330. # endif
  181331. # ifndef PNG_NO_READ_PACKSWAP
  181332. # define PNG_READ_PACKSWAP_SUPPORTED
  181333. # endif
  181334. # ifndef PNG_NO_READ_INVERT
  181335. # define PNG_READ_INVERT_SUPPORTED
  181336. # endif
  181337. # ifndef PNG_NO_READ_DITHER
  181338. # define PNG_READ_DITHER_SUPPORTED
  181339. # endif
  181340. # ifndef PNG_NO_READ_BACKGROUND
  181341. # define PNG_READ_BACKGROUND_SUPPORTED
  181342. # endif
  181343. # ifndef PNG_NO_READ_16_TO_8
  181344. # define PNG_READ_16_TO_8_SUPPORTED
  181345. # endif
  181346. # ifndef PNG_NO_READ_FILLER
  181347. # define PNG_READ_FILLER_SUPPORTED
  181348. # endif
  181349. # ifndef PNG_NO_READ_GAMMA
  181350. # define PNG_READ_GAMMA_SUPPORTED
  181351. # endif
  181352. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181353. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181354. # endif
  181355. # ifndef PNG_NO_READ_SWAP_ALPHA
  181356. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181357. # endif
  181358. # ifndef PNG_NO_READ_INVERT_ALPHA
  181359. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181360. # endif
  181361. # ifndef PNG_NO_READ_STRIP_ALPHA
  181362. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181363. # endif
  181364. # ifndef PNG_NO_READ_USER_TRANSFORM
  181365. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181366. # endif
  181367. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181368. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181369. # endif
  181370. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181371. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181372. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181373. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181374. #endif /* about interlacing capability! You'll */
  181375. /* still have interlacing unless you change the following line: */
  181376. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181377. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181378. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181379. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181380. # endif
  181381. #endif
  181382. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181383. /* Deprecated, will be removed from version 2.0.0.
  181384. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181385. #ifndef PNG_NO_READ_EMPTY_PLTE
  181386. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181387. #endif
  181388. #endif
  181389. #endif /* PNG_READ_SUPPORTED */
  181390. #if defined(PNG_WRITE_SUPPORTED)
  181391. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181392. !defined(PNG_NO_WRITE_TRANSFORMS)
  181393. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181394. #endif
  181395. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181396. # ifndef PNG_NO_WRITE_SHIFT
  181397. # define PNG_WRITE_SHIFT_SUPPORTED
  181398. # endif
  181399. # ifndef PNG_NO_WRITE_PACK
  181400. # define PNG_WRITE_PACK_SUPPORTED
  181401. # endif
  181402. # ifndef PNG_NO_WRITE_BGR
  181403. # define PNG_WRITE_BGR_SUPPORTED
  181404. # endif
  181405. # ifndef PNG_NO_WRITE_SWAP
  181406. # define PNG_WRITE_SWAP_SUPPORTED
  181407. # endif
  181408. # ifndef PNG_NO_WRITE_PACKSWAP
  181409. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181410. # endif
  181411. # ifndef PNG_NO_WRITE_INVERT
  181412. # define PNG_WRITE_INVERT_SUPPORTED
  181413. # endif
  181414. # ifndef PNG_NO_WRITE_FILLER
  181415. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181416. # endif
  181417. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181418. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181419. # endif
  181420. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181421. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181422. # endif
  181423. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181424. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181425. # endif
  181426. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181427. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181428. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181429. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181430. encoders, but can cause trouble
  181431. if left undefined */
  181432. #endif
  181433. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181434. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181435. defined(PNG_FLOATING_POINT_SUPPORTED)
  181436. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181437. #endif
  181438. #ifndef PNG_NO_WRITE_FLUSH
  181439. # define PNG_WRITE_FLUSH_SUPPORTED
  181440. #endif
  181441. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181442. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181443. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181444. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181445. #endif
  181446. #endif
  181447. #endif /* PNG_WRITE_SUPPORTED */
  181448. #ifndef PNG_1_0_X
  181449. # ifndef PNG_NO_ERROR_NUMBERS
  181450. # define PNG_ERROR_NUMBERS_SUPPORTED
  181451. # endif
  181452. #endif /* PNG_1_0_X */
  181453. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181454. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181455. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181456. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181457. # endif
  181458. #endif
  181459. #ifndef PNG_NO_STDIO
  181460. # define PNG_TIME_RFC1123_SUPPORTED
  181461. #endif
  181462. /* This adds extra functions in pngget.c for accessing data from the
  181463. * info pointer (added in version 0.99)
  181464. * png_get_image_width()
  181465. * png_get_image_height()
  181466. * png_get_bit_depth()
  181467. * png_get_color_type()
  181468. * png_get_compression_type()
  181469. * png_get_filter_type()
  181470. * png_get_interlace_type()
  181471. * png_get_pixel_aspect_ratio()
  181472. * png_get_pixels_per_meter()
  181473. * png_get_x_offset_pixels()
  181474. * png_get_y_offset_pixels()
  181475. * png_get_x_offset_microns()
  181476. * png_get_y_offset_microns()
  181477. */
  181478. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181479. # define PNG_EASY_ACCESS_SUPPORTED
  181480. #endif
  181481. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181482. * and removed from version 1.2.20. The following will be removed
  181483. * from libpng-1.4.0
  181484. */
  181485. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181486. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181487. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181488. # endif
  181489. #endif
  181490. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181491. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181492. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181493. # endif
  181494. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181495. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181496. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181497. # define PNG_NO_MMX_CODE
  181498. # endif
  181499. # endif
  181500. # if defined(__APPLE__)
  181501. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181502. # define PNG_NO_MMX_CODE
  181503. # endif
  181504. # endif
  181505. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181506. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181507. # define PNG_NO_MMX_CODE
  181508. # endif
  181509. # endif
  181510. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181511. # define PNG_MMX_CODE_SUPPORTED
  181512. # endif
  181513. #endif
  181514. /* end of obsolete code to be removed from libpng-1.4.0 */
  181515. #if !defined(PNG_1_0_X)
  181516. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181517. # define PNG_USER_MEM_SUPPORTED
  181518. #endif
  181519. #endif /* PNG_1_0_X */
  181520. /* Added at libpng-1.2.6 */
  181521. #if !defined(PNG_1_0_X)
  181522. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181523. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181524. # define PNG_SET_USER_LIMITS_SUPPORTED
  181525. #endif
  181526. #endif
  181527. #endif /* PNG_1_0_X */
  181528. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181529. * how large, set these limits to 0x7fffffffL
  181530. */
  181531. #ifndef PNG_USER_WIDTH_MAX
  181532. # define PNG_USER_WIDTH_MAX 1000000L
  181533. #endif
  181534. #ifndef PNG_USER_HEIGHT_MAX
  181535. # define PNG_USER_HEIGHT_MAX 1000000L
  181536. #endif
  181537. /* These are currently experimental features, define them if you want */
  181538. /* very little testing */
  181539. /*
  181540. #ifdef PNG_READ_SUPPORTED
  181541. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181542. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181543. # endif
  181544. #endif
  181545. */
  181546. /* This is only for PowerPC big-endian and 680x0 systems */
  181547. /* some testing */
  181548. /*
  181549. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181550. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181551. #endif
  181552. */
  181553. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181554. /*
  181555. #define PNG_NO_POINTER_INDEXING
  181556. */
  181557. /* These functions are turned off by default, as they will be phased out. */
  181558. /*
  181559. #define PNG_USELESS_TESTS_SUPPORTED
  181560. #define PNG_CORRECT_PALETTE_SUPPORTED
  181561. */
  181562. /* Any chunks you are not interested in, you can undef here. The
  181563. * ones that allocate memory may be expecially important (hIST,
  181564. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181565. * a bit smaller.
  181566. */
  181567. #if defined(PNG_READ_SUPPORTED) && \
  181568. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181569. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181570. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181571. #endif
  181572. #if defined(PNG_WRITE_SUPPORTED) && \
  181573. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181574. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181575. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181576. #endif
  181577. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181578. #ifdef PNG_NO_READ_TEXT
  181579. # define PNG_NO_READ_iTXt
  181580. # define PNG_NO_READ_tEXt
  181581. # define PNG_NO_READ_zTXt
  181582. #endif
  181583. #ifndef PNG_NO_READ_bKGD
  181584. # define PNG_READ_bKGD_SUPPORTED
  181585. # define PNG_bKGD_SUPPORTED
  181586. #endif
  181587. #ifndef PNG_NO_READ_cHRM
  181588. # define PNG_READ_cHRM_SUPPORTED
  181589. # define PNG_cHRM_SUPPORTED
  181590. #endif
  181591. #ifndef PNG_NO_READ_gAMA
  181592. # define PNG_READ_gAMA_SUPPORTED
  181593. # define PNG_gAMA_SUPPORTED
  181594. #endif
  181595. #ifndef PNG_NO_READ_hIST
  181596. # define PNG_READ_hIST_SUPPORTED
  181597. # define PNG_hIST_SUPPORTED
  181598. #endif
  181599. #ifndef PNG_NO_READ_iCCP
  181600. # define PNG_READ_iCCP_SUPPORTED
  181601. # define PNG_iCCP_SUPPORTED
  181602. #endif
  181603. #ifndef PNG_NO_READ_iTXt
  181604. # ifndef PNG_READ_iTXt_SUPPORTED
  181605. # define PNG_READ_iTXt_SUPPORTED
  181606. # endif
  181607. # ifndef PNG_iTXt_SUPPORTED
  181608. # define PNG_iTXt_SUPPORTED
  181609. # endif
  181610. #endif
  181611. #ifndef PNG_NO_READ_oFFs
  181612. # define PNG_READ_oFFs_SUPPORTED
  181613. # define PNG_oFFs_SUPPORTED
  181614. #endif
  181615. #ifndef PNG_NO_READ_pCAL
  181616. # define PNG_READ_pCAL_SUPPORTED
  181617. # define PNG_pCAL_SUPPORTED
  181618. #endif
  181619. #ifndef PNG_NO_READ_sCAL
  181620. # define PNG_READ_sCAL_SUPPORTED
  181621. # define PNG_sCAL_SUPPORTED
  181622. #endif
  181623. #ifndef PNG_NO_READ_pHYs
  181624. # define PNG_READ_pHYs_SUPPORTED
  181625. # define PNG_pHYs_SUPPORTED
  181626. #endif
  181627. #ifndef PNG_NO_READ_sBIT
  181628. # define PNG_READ_sBIT_SUPPORTED
  181629. # define PNG_sBIT_SUPPORTED
  181630. #endif
  181631. #ifndef PNG_NO_READ_sPLT
  181632. # define PNG_READ_sPLT_SUPPORTED
  181633. # define PNG_sPLT_SUPPORTED
  181634. #endif
  181635. #ifndef PNG_NO_READ_sRGB
  181636. # define PNG_READ_sRGB_SUPPORTED
  181637. # define PNG_sRGB_SUPPORTED
  181638. #endif
  181639. #ifndef PNG_NO_READ_tEXt
  181640. # define PNG_READ_tEXt_SUPPORTED
  181641. # define PNG_tEXt_SUPPORTED
  181642. #endif
  181643. #ifndef PNG_NO_READ_tIME
  181644. # define PNG_READ_tIME_SUPPORTED
  181645. # define PNG_tIME_SUPPORTED
  181646. #endif
  181647. #ifndef PNG_NO_READ_tRNS
  181648. # define PNG_READ_tRNS_SUPPORTED
  181649. # define PNG_tRNS_SUPPORTED
  181650. #endif
  181651. #ifndef PNG_NO_READ_zTXt
  181652. # define PNG_READ_zTXt_SUPPORTED
  181653. # define PNG_zTXt_SUPPORTED
  181654. #endif
  181655. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181656. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181657. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181658. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181659. # endif
  181660. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181661. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181662. # endif
  181663. #endif
  181664. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181665. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181666. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181667. # define PNG_USER_CHUNKS_SUPPORTED
  181668. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181669. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181670. # endif
  181671. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181672. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181673. # endif
  181674. #endif
  181675. #ifndef PNG_NO_READ_OPT_PLTE
  181676. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181677. #endif /* optional PLTE chunk in RGB and RGBA images */
  181678. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181679. defined(PNG_READ_zTXt_SUPPORTED)
  181680. # define PNG_READ_TEXT_SUPPORTED
  181681. # define PNG_TEXT_SUPPORTED
  181682. #endif
  181683. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181684. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181685. #ifdef PNG_NO_WRITE_TEXT
  181686. # define PNG_NO_WRITE_iTXt
  181687. # define PNG_NO_WRITE_tEXt
  181688. # define PNG_NO_WRITE_zTXt
  181689. #endif
  181690. #ifndef PNG_NO_WRITE_bKGD
  181691. # define PNG_WRITE_bKGD_SUPPORTED
  181692. # ifndef PNG_bKGD_SUPPORTED
  181693. # define PNG_bKGD_SUPPORTED
  181694. # endif
  181695. #endif
  181696. #ifndef PNG_NO_WRITE_cHRM
  181697. # define PNG_WRITE_cHRM_SUPPORTED
  181698. # ifndef PNG_cHRM_SUPPORTED
  181699. # define PNG_cHRM_SUPPORTED
  181700. # endif
  181701. #endif
  181702. #ifndef PNG_NO_WRITE_gAMA
  181703. # define PNG_WRITE_gAMA_SUPPORTED
  181704. # ifndef PNG_gAMA_SUPPORTED
  181705. # define PNG_gAMA_SUPPORTED
  181706. # endif
  181707. #endif
  181708. #ifndef PNG_NO_WRITE_hIST
  181709. # define PNG_WRITE_hIST_SUPPORTED
  181710. # ifndef PNG_hIST_SUPPORTED
  181711. # define PNG_hIST_SUPPORTED
  181712. # endif
  181713. #endif
  181714. #ifndef PNG_NO_WRITE_iCCP
  181715. # define PNG_WRITE_iCCP_SUPPORTED
  181716. # ifndef PNG_iCCP_SUPPORTED
  181717. # define PNG_iCCP_SUPPORTED
  181718. # endif
  181719. #endif
  181720. #ifndef PNG_NO_WRITE_iTXt
  181721. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181722. # define PNG_WRITE_iTXt_SUPPORTED
  181723. # endif
  181724. # ifndef PNG_iTXt_SUPPORTED
  181725. # define PNG_iTXt_SUPPORTED
  181726. # endif
  181727. #endif
  181728. #ifndef PNG_NO_WRITE_oFFs
  181729. # define PNG_WRITE_oFFs_SUPPORTED
  181730. # ifndef PNG_oFFs_SUPPORTED
  181731. # define PNG_oFFs_SUPPORTED
  181732. # endif
  181733. #endif
  181734. #ifndef PNG_NO_WRITE_pCAL
  181735. # define PNG_WRITE_pCAL_SUPPORTED
  181736. # ifndef PNG_pCAL_SUPPORTED
  181737. # define PNG_pCAL_SUPPORTED
  181738. # endif
  181739. #endif
  181740. #ifndef PNG_NO_WRITE_sCAL
  181741. # define PNG_WRITE_sCAL_SUPPORTED
  181742. # ifndef PNG_sCAL_SUPPORTED
  181743. # define PNG_sCAL_SUPPORTED
  181744. # endif
  181745. #endif
  181746. #ifndef PNG_NO_WRITE_pHYs
  181747. # define PNG_WRITE_pHYs_SUPPORTED
  181748. # ifndef PNG_pHYs_SUPPORTED
  181749. # define PNG_pHYs_SUPPORTED
  181750. # endif
  181751. #endif
  181752. #ifndef PNG_NO_WRITE_sBIT
  181753. # define PNG_WRITE_sBIT_SUPPORTED
  181754. # ifndef PNG_sBIT_SUPPORTED
  181755. # define PNG_sBIT_SUPPORTED
  181756. # endif
  181757. #endif
  181758. #ifndef PNG_NO_WRITE_sPLT
  181759. # define PNG_WRITE_sPLT_SUPPORTED
  181760. # ifndef PNG_sPLT_SUPPORTED
  181761. # define PNG_sPLT_SUPPORTED
  181762. # endif
  181763. #endif
  181764. #ifndef PNG_NO_WRITE_sRGB
  181765. # define PNG_WRITE_sRGB_SUPPORTED
  181766. # ifndef PNG_sRGB_SUPPORTED
  181767. # define PNG_sRGB_SUPPORTED
  181768. # endif
  181769. #endif
  181770. #ifndef PNG_NO_WRITE_tEXt
  181771. # define PNG_WRITE_tEXt_SUPPORTED
  181772. # ifndef PNG_tEXt_SUPPORTED
  181773. # define PNG_tEXt_SUPPORTED
  181774. # endif
  181775. #endif
  181776. #ifndef PNG_NO_WRITE_tIME
  181777. # define PNG_WRITE_tIME_SUPPORTED
  181778. # ifndef PNG_tIME_SUPPORTED
  181779. # define PNG_tIME_SUPPORTED
  181780. # endif
  181781. #endif
  181782. #ifndef PNG_NO_WRITE_tRNS
  181783. # define PNG_WRITE_tRNS_SUPPORTED
  181784. # ifndef PNG_tRNS_SUPPORTED
  181785. # define PNG_tRNS_SUPPORTED
  181786. # endif
  181787. #endif
  181788. #ifndef PNG_NO_WRITE_zTXt
  181789. # define PNG_WRITE_zTXt_SUPPORTED
  181790. # ifndef PNG_zTXt_SUPPORTED
  181791. # define PNG_zTXt_SUPPORTED
  181792. # endif
  181793. #endif
  181794. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181795. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181796. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181797. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181798. # endif
  181799. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181800. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181801. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181802. # endif
  181803. # endif
  181804. #endif
  181805. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181806. defined(PNG_WRITE_zTXt_SUPPORTED)
  181807. # define PNG_WRITE_TEXT_SUPPORTED
  181808. # ifndef PNG_TEXT_SUPPORTED
  181809. # define PNG_TEXT_SUPPORTED
  181810. # endif
  181811. #endif
  181812. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181813. /* Turn this off to disable png_read_png() and
  181814. * png_write_png() and leave the row_pointers member
  181815. * out of the info structure.
  181816. */
  181817. #ifndef PNG_NO_INFO_IMAGE
  181818. # define PNG_INFO_IMAGE_SUPPORTED
  181819. #endif
  181820. /* need the time information for reading tIME chunks */
  181821. #if defined(PNG_tIME_SUPPORTED)
  181822. # if !defined(_WIN32_WCE)
  181823. /* "time.h" functions are not supported on WindowsCE */
  181824. # include <time.h>
  181825. # endif
  181826. #endif
  181827. /* Some typedefs to get us started. These should be safe on most of the
  181828. * common platforms. The typedefs should be at least as large as the
  181829. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181830. * don't have to be exactly that size. Some compilers dislike passing
  181831. * unsigned shorts as function parameters, so you may be better off using
  181832. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181833. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181834. */
  181835. typedef unsigned long png_uint_32;
  181836. typedef long png_int_32;
  181837. typedef unsigned short png_uint_16;
  181838. typedef short png_int_16;
  181839. typedef unsigned char png_byte;
  181840. /* This is usually size_t. It is typedef'ed just in case you need it to
  181841. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181842. #ifdef PNG_SIZE_T
  181843. typedef PNG_SIZE_T png_size_t;
  181844. # define png_sizeof(x) png_convert_size(sizeof (x))
  181845. #else
  181846. typedef size_t png_size_t;
  181847. # define png_sizeof(x) sizeof (x)
  181848. #endif
  181849. /* The following is needed for medium model support. It cannot be in the
  181850. * PNG_INTERNAL section. Needs modification for other compilers besides
  181851. * MSC. Model independent support declares all arrays and pointers to be
  181852. * large using the far keyword. The zlib version used must also support
  181853. * model independent data. As of version zlib 1.0.4, the necessary changes
  181854. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181855. * changes that are needed. (Tim Wegner)
  181856. */
  181857. /* Separate compiler dependencies (problem here is that zlib.h always
  181858. defines FAR. (SJT) */
  181859. #ifdef __BORLANDC__
  181860. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181861. # define LDATA 1
  181862. # else
  181863. # define LDATA 0
  181864. # endif
  181865. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181866. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181867. # define PNG_MAX_MALLOC_64K
  181868. # if (LDATA != 1)
  181869. # ifndef FAR
  181870. # define FAR __far
  181871. # endif
  181872. # define USE_FAR_KEYWORD
  181873. # endif /* LDATA != 1 */
  181874. /* Possibly useful for moving data out of default segment.
  181875. * Uncomment it if you want. Could also define FARDATA as
  181876. * const if your compiler supports it. (SJT)
  181877. # define FARDATA FAR
  181878. */
  181879. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181880. #endif /* __BORLANDC__ */
  181881. /* Suggest testing for specific compiler first before testing for
  181882. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181883. * making reliance oncertain keywords suspect. (SJT)
  181884. */
  181885. /* MSC Medium model */
  181886. #if defined(FAR)
  181887. # if defined(M_I86MM)
  181888. # define USE_FAR_KEYWORD
  181889. # define FARDATA FAR
  181890. # include <dos.h>
  181891. # endif
  181892. #endif
  181893. /* SJT: default case */
  181894. #ifndef FAR
  181895. # define FAR
  181896. #endif
  181897. /* At this point FAR is always defined */
  181898. #ifndef FARDATA
  181899. # define FARDATA
  181900. #endif
  181901. /* Typedef for floating-point numbers that are converted
  181902. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181903. typedef png_int_32 png_fixed_point;
  181904. /* Add typedefs for pointers */
  181905. typedef void FAR * png_voidp;
  181906. typedef png_byte FAR * png_bytep;
  181907. typedef png_uint_32 FAR * png_uint_32p;
  181908. typedef png_int_32 FAR * png_int_32p;
  181909. typedef png_uint_16 FAR * png_uint_16p;
  181910. typedef png_int_16 FAR * png_int_16p;
  181911. typedef PNG_CONST char FAR * png_const_charp;
  181912. typedef char FAR * png_charp;
  181913. typedef png_fixed_point FAR * png_fixed_point_p;
  181914. #ifndef PNG_NO_STDIO
  181915. #if defined(_WIN32_WCE)
  181916. typedef HANDLE png_FILE_p;
  181917. #else
  181918. typedef FILE * png_FILE_p;
  181919. #endif
  181920. #endif
  181921. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181922. typedef double FAR * png_doublep;
  181923. #endif
  181924. /* Pointers to pointers; i.e. arrays */
  181925. typedef png_byte FAR * FAR * png_bytepp;
  181926. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181927. typedef png_int_32 FAR * FAR * png_int_32pp;
  181928. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181929. typedef png_int_16 FAR * FAR * png_int_16pp;
  181930. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181931. typedef char FAR * FAR * png_charpp;
  181932. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181933. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181934. typedef double FAR * FAR * png_doublepp;
  181935. #endif
  181936. /* Pointers to pointers to pointers; i.e., pointer to array */
  181937. typedef char FAR * FAR * FAR * png_charppp;
  181938. #if 0
  181939. /* SPC - Is this stuff deprecated? */
  181940. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181941. /* libpng typedefs for types in zlib. If zlib changes
  181942. * or another compression library is used, then change these.
  181943. * Eliminates need to change all the source files.
  181944. */
  181945. typedef charf * png_zcharp;
  181946. typedef charf * FAR * png_zcharpp;
  181947. typedef z_stream FAR * png_zstreamp;
  181948. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181949. /*
  181950. * Define PNG_BUILD_DLL if the module being built is a Windows
  181951. * LIBPNG DLL.
  181952. *
  181953. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181954. * It is equivalent to Microsoft predefined macro _DLL that is
  181955. * automatically defined when you compile using the share
  181956. * version of the CRT (C Run-Time library)
  181957. *
  181958. * The cygwin mods make this behavior a little different:
  181959. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181960. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181961. * -or- if you are building an application that you want to link to the
  181962. * static library.
  181963. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181964. * the other flags is defined.
  181965. */
  181966. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181967. # define PNG_DLL
  181968. #endif
  181969. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181970. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181971. * command-line override
  181972. */
  181973. #if defined(__CYGWIN__)
  181974. # if !defined(PNG_STATIC)
  181975. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181976. # undef PNG_USE_GLOBAL_ARRAYS
  181977. # endif
  181978. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181979. # define PNG_USE_LOCAL_ARRAYS
  181980. # endif
  181981. # else
  181982. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181983. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181984. # undef PNG_USE_GLOBAL_ARRAYS
  181985. # endif
  181986. # endif
  181987. # endif
  181988. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181989. # define PNG_USE_LOCAL_ARRAYS
  181990. # endif
  181991. #endif
  181992. /* Do not use global arrays (helps with building DLL's)
  181993. * They are no longer used in libpng itself, since version 1.0.5c,
  181994. * but might be required for some pre-1.0.5c applications.
  181995. */
  181996. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181997. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181998. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181999. # define PNG_USE_LOCAL_ARRAYS
  182000. # else
  182001. # define PNG_USE_GLOBAL_ARRAYS
  182002. # endif
  182003. #endif
  182004. #if defined(__CYGWIN__)
  182005. # undef PNGAPI
  182006. # define PNGAPI __cdecl
  182007. # undef PNG_IMPEXP
  182008. # define PNG_IMPEXP
  182009. #endif
  182010. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  182011. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  182012. * Don't ignore those warnings; you must also reset the default calling
  182013. * convention in your compiler to match your PNGAPI, and you must build
  182014. * zlib and your applications the same way you build libpng.
  182015. */
  182016. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  182017. # ifndef PNG_NO_MODULEDEF
  182018. # define PNG_NO_MODULEDEF
  182019. # endif
  182020. #endif
  182021. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  182022. # define PNG_IMPEXP
  182023. #endif
  182024. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  182025. (( defined(_Windows) || defined(_WINDOWS) || \
  182026. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  182027. # ifndef PNGAPI
  182028. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  182029. # define PNGAPI __cdecl
  182030. # else
  182031. # define PNGAPI _cdecl
  182032. # endif
  182033. # endif
  182034. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  182035. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  182036. # define PNG_IMPEXP
  182037. # endif
  182038. # if !defined(PNG_IMPEXP)
  182039. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182040. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  182041. /* Borland/Microsoft */
  182042. # if defined(_MSC_VER) || defined(__BORLANDC__)
  182043. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  182044. # define PNG_EXPORT PNG_EXPORT_TYPE1
  182045. # else
  182046. # define PNG_EXPORT PNG_EXPORT_TYPE2
  182047. # if defined(PNG_BUILD_DLL)
  182048. # define PNG_IMPEXP __export
  182049. # else
  182050. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  182051. VC++ */
  182052. # endif /* Exists in Borland C++ for
  182053. C++ classes (== huge) */
  182054. # endif
  182055. # endif
  182056. # if !defined(PNG_IMPEXP)
  182057. # if defined(PNG_BUILD_DLL)
  182058. # define PNG_IMPEXP __declspec(dllexport)
  182059. # else
  182060. # define PNG_IMPEXP __declspec(dllimport)
  182061. # endif
  182062. # endif
  182063. # endif /* PNG_IMPEXP */
  182064. #else /* !(DLL || non-cygwin WINDOWS) */
  182065. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  182066. # ifndef PNGAPI
  182067. # define PNGAPI _System
  182068. # endif
  182069. # else
  182070. # if 0 /* ... other platforms, with other meanings */
  182071. # endif
  182072. # endif
  182073. #endif
  182074. #ifndef PNGAPI
  182075. # define PNGAPI
  182076. #endif
  182077. #ifndef PNG_IMPEXP
  182078. # define PNG_IMPEXP
  182079. #endif
  182080. #ifdef PNG_BUILDSYMS
  182081. # ifndef PNG_EXPORT
  182082. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  182083. # endif
  182084. # ifdef PNG_USE_GLOBAL_ARRAYS
  182085. # ifndef PNG_EXPORT_VAR
  182086. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  182087. # endif
  182088. # endif
  182089. #endif
  182090. #ifndef PNG_EXPORT
  182091. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182092. #endif
  182093. #ifdef PNG_USE_GLOBAL_ARRAYS
  182094. # ifndef PNG_EXPORT_VAR
  182095. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  182096. # endif
  182097. #endif
  182098. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  182099. * functions that are passed far data must be model independent.
  182100. */
  182101. #ifndef PNG_ABORT
  182102. # define PNG_ABORT() abort()
  182103. #endif
  182104. #ifdef PNG_SETJMP_SUPPORTED
  182105. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  182106. #else
  182107. # define png_jmpbuf(png_ptr) \
  182108. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  182109. #endif
  182110. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  182111. /* use this to make far-to-near assignments */
  182112. # define CHECK 1
  182113. # define NOCHECK 0
  182114. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  182115. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  182116. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  182117. # define png_strcpy _fstrcpy
  182118. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  182119. # define png_strlen _fstrlen
  182120. # define png_memcmp _fmemcmp /* SJT: added */
  182121. # define png_memcpy _fmemcpy
  182122. # define png_memset _fmemset
  182123. #else /* use the usual functions */
  182124. # define CVT_PTR(ptr) (ptr)
  182125. # define CVT_PTR_NOCHECK(ptr) (ptr)
  182126. # ifndef PNG_NO_SNPRINTF
  182127. # ifdef _MSC_VER
  182128. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  182129. # define png_snprintf2 _snprintf
  182130. # define png_snprintf6 _snprintf
  182131. # else
  182132. # define png_snprintf snprintf /* Added to v 1.2.19 */
  182133. # define png_snprintf2 snprintf
  182134. # define png_snprintf6 snprintf
  182135. # endif
  182136. # else
  182137. /* You don't have or don't want to use snprintf(). Caution: Using
  182138. * sprintf instead of snprintf exposes your application to accidental
  182139. * or malevolent buffer overflows. If you don't have snprintf()
  182140. * as a general rule you should provide one (you can get one from
  182141. * Portable OpenSSH). */
  182142. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  182143. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  182144. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  182145. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  182146. # endif
  182147. # define png_strcpy strcpy
  182148. # define png_strncpy strncpy /* Added to v 1.2.6 */
  182149. # define png_strlen strlen
  182150. # define png_memcmp memcmp /* SJT: added */
  182151. # define png_memcpy memcpy
  182152. # define png_memset memset
  182153. #endif
  182154. /* End of memory model independent support */
  182155. /* Just a little check that someone hasn't tried to define something
  182156. * contradictory.
  182157. */
  182158. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  182159. # undef PNG_ZBUF_SIZE
  182160. # define PNG_ZBUF_SIZE 65536L
  182161. #endif
  182162. /* Added at libpng-1.2.8 */
  182163. #endif /* PNG_VERSION_INFO_ONLY */
  182164. #endif /* PNGCONF_H */
  182165. /*** End of inlined file: pngconf.h ***/
  182166. #ifdef _MSC_VER
  182167. #pragma warning (disable: 4996 4100)
  182168. #endif
  182169. /*
  182170. * Added at libpng-1.2.8 */
  182171. /* Ref MSDN: Private as priority over Special
  182172. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  182173. * procedures. If this value is given, the StringFileInfo block must
  182174. * contain a PrivateBuild string.
  182175. *
  182176. * VS_FF_SPECIALBUILD File *was* built by the original company using
  182177. * standard release procedures but is a variation of the standard
  182178. * file of the same version number. If this value is given, the
  182179. * StringFileInfo block must contain a SpecialBuild string.
  182180. */
  182181. #if defined(PNG_USER_PRIVATEBUILD)
  182182. # define PNG_LIBPNG_BUILD_TYPE \
  182183. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  182184. #else
  182185. # if defined(PNG_LIBPNG_SPECIALBUILD)
  182186. # define PNG_LIBPNG_BUILD_TYPE \
  182187. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  182188. # else
  182189. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  182190. # endif
  182191. #endif
  182192. #ifndef PNG_VERSION_INFO_ONLY
  182193. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  182194. #ifdef __cplusplus
  182195. //extern "C" {
  182196. #endif /* __cplusplus */
  182197. /* This file is arranged in several sections. The first section contains
  182198. * structure and type definitions. The second section contains the external
  182199. * library functions, while the third has the internal library functions,
  182200. * which applications aren't expected to use directly.
  182201. */
  182202. #ifndef PNG_NO_TYPECAST_NULL
  182203. #define int_p_NULL (int *)NULL
  182204. #define png_bytep_NULL (png_bytep)NULL
  182205. #define png_bytepp_NULL (png_bytepp)NULL
  182206. #define png_doublep_NULL (png_doublep)NULL
  182207. #define png_error_ptr_NULL (png_error_ptr)NULL
  182208. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182209. #define png_free_ptr_NULL (png_free_ptr)NULL
  182210. #define png_infopp_NULL (png_infopp)NULL
  182211. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182212. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182213. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182214. #define png_structp_NULL (png_structp)NULL
  182215. #define png_uint_16p_NULL (png_uint_16p)NULL
  182216. #define png_voidp_NULL (png_voidp)NULL
  182217. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182218. #else
  182219. #define int_p_NULL NULL
  182220. #define png_bytep_NULL NULL
  182221. #define png_bytepp_NULL NULL
  182222. #define png_doublep_NULL NULL
  182223. #define png_error_ptr_NULL NULL
  182224. #define png_flush_ptr_NULL NULL
  182225. #define png_free_ptr_NULL NULL
  182226. #define png_infopp_NULL NULL
  182227. #define png_malloc_ptr_NULL NULL
  182228. #define png_read_status_ptr_NULL NULL
  182229. #define png_rw_ptr_NULL NULL
  182230. #define png_structp_NULL NULL
  182231. #define png_uint_16p_NULL NULL
  182232. #define png_voidp_NULL NULL
  182233. #define png_write_status_ptr_NULL NULL
  182234. #endif
  182235. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182236. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182237. /* Version information for C files, stored in png.c. This had better match
  182238. * the version above.
  182239. */
  182240. #ifdef PNG_USE_GLOBAL_ARRAYS
  182241. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182242. /* need room for 99.99.99beta99z */
  182243. #else
  182244. #define png_libpng_ver png_get_header_ver(NULL)
  182245. #endif
  182246. #ifdef PNG_USE_GLOBAL_ARRAYS
  182247. /* This was removed in version 1.0.5c */
  182248. /* Structures to facilitate easy interlacing. See png.c for more details */
  182249. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182250. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182251. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182252. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182253. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182254. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182255. /* This isn't currently used. If you need it, see png.c for more details.
  182256. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182257. */
  182258. #endif
  182259. #endif /* PNG_NO_EXTERN */
  182260. /* Three color definitions. The order of the red, green, and blue, (and the
  182261. * exact size) is not important, although the size of the fields need to
  182262. * be png_byte or png_uint_16 (as defined below).
  182263. */
  182264. typedef struct png_color_struct
  182265. {
  182266. png_byte red;
  182267. png_byte green;
  182268. png_byte blue;
  182269. } png_color;
  182270. typedef png_color FAR * png_colorp;
  182271. typedef png_color FAR * FAR * png_colorpp;
  182272. typedef struct png_color_16_struct
  182273. {
  182274. png_byte index; /* used for palette files */
  182275. png_uint_16 red; /* for use in red green blue files */
  182276. png_uint_16 green;
  182277. png_uint_16 blue;
  182278. png_uint_16 gray; /* for use in grayscale files */
  182279. } png_color_16;
  182280. typedef png_color_16 FAR * png_color_16p;
  182281. typedef png_color_16 FAR * FAR * png_color_16pp;
  182282. typedef struct png_color_8_struct
  182283. {
  182284. png_byte red; /* for use in red green blue files */
  182285. png_byte green;
  182286. png_byte blue;
  182287. png_byte gray; /* for use in grayscale files */
  182288. png_byte alpha; /* for alpha channel files */
  182289. } png_color_8;
  182290. typedef png_color_8 FAR * png_color_8p;
  182291. typedef png_color_8 FAR * FAR * png_color_8pp;
  182292. /*
  182293. * The following two structures are used for the in-core representation
  182294. * of sPLT chunks.
  182295. */
  182296. typedef struct png_sPLT_entry_struct
  182297. {
  182298. png_uint_16 red;
  182299. png_uint_16 green;
  182300. png_uint_16 blue;
  182301. png_uint_16 alpha;
  182302. png_uint_16 frequency;
  182303. } png_sPLT_entry;
  182304. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182305. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182306. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182307. * occupy the LSB of their respective members, and the MSB of each member
  182308. * is zero-filled. The frequency member always occupies the full 16 bits.
  182309. */
  182310. typedef struct png_sPLT_struct
  182311. {
  182312. png_charp name; /* palette name */
  182313. png_byte depth; /* depth of palette samples */
  182314. png_sPLT_entryp entries; /* palette entries */
  182315. png_int_32 nentries; /* number of palette entries */
  182316. } png_sPLT_t;
  182317. typedef png_sPLT_t FAR * png_sPLT_tp;
  182318. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182319. #ifdef PNG_TEXT_SUPPORTED
  182320. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182321. * and whether that contents is compressed or not. The "key" field
  182322. * points to a regular zero-terminated C string. The "text", "lang", and
  182323. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182324. * However, the * structure returned by png_get_text() will always contain
  182325. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182326. * so they can be safely used in printf() and other string-handling functions.
  182327. */
  182328. typedef struct png_text_struct
  182329. {
  182330. int compression; /* compression value:
  182331. -1: tEXt, none
  182332. 0: zTXt, deflate
  182333. 1: iTXt, none
  182334. 2: iTXt, deflate */
  182335. png_charp key; /* keyword, 1-79 character description of "text" */
  182336. png_charp text; /* comment, may be an empty string (ie "")
  182337. or a NULL pointer */
  182338. png_size_t text_length; /* length of the text string */
  182339. #ifdef PNG_iTXt_SUPPORTED
  182340. png_size_t itxt_length; /* length of the itxt string */
  182341. png_charp lang; /* language code, 0-79 characters
  182342. or a NULL pointer */
  182343. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182344. chars or a NULL pointer */
  182345. #endif
  182346. } png_text;
  182347. typedef png_text FAR * png_textp;
  182348. typedef png_text FAR * FAR * png_textpp;
  182349. #endif
  182350. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182351. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182352. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182353. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182354. #define PNG_TEXT_COMPRESSION_NONE -1
  182355. #define PNG_TEXT_COMPRESSION_zTXt 0
  182356. #define PNG_ITXT_COMPRESSION_NONE 1
  182357. #define PNG_ITXT_COMPRESSION_zTXt 2
  182358. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182359. /* png_time is a way to hold the time in an machine independent way.
  182360. * Two conversions are provided, both from time_t and struct tm. There
  182361. * is no portable way to convert to either of these structures, as far
  182362. * as I know. If you know of a portable way, send it to me. As a side
  182363. * note - PNG has always been Year 2000 compliant!
  182364. */
  182365. typedef struct png_time_struct
  182366. {
  182367. png_uint_16 year; /* full year, as in, 1995 */
  182368. png_byte month; /* month of year, 1 - 12 */
  182369. png_byte day; /* day of month, 1 - 31 */
  182370. png_byte hour; /* hour of day, 0 - 23 */
  182371. png_byte minute; /* minute of hour, 0 - 59 */
  182372. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182373. } png_time;
  182374. typedef png_time FAR * png_timep;
  182375. typedef png_time FAR * FAR * png_timepp;
  182376. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182377. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182378. * no specific support. The idea is that we can use this to queue
  182379. * up private chunks for output even though the library doesn't actually
  182380. * know about their semantics.
  182381. */
  182382. typedef struct png_unknown_chunk_t
  182383. {
  182384. png_byte name[5];
  182385. png_byte *data;
  182386. png_size_t size;
  182387. /* libpng-using applications should NOT directly modify this byte. */
  182388. png_byte location; /* mode of operation at read time */
  182389. }
  182390. png_unknown_chunk;
  182391. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182392. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182393. #endif
  182394. /* png_info is a structure that holds the information in a PNG file so
  182395. * that the application can find out the characteristics of the image.
  182396. * If you are reading the file, this structure will tell you what is
  182397. * in the PNG file. If you are writing the file, fill in the information
  182398. * you want to put into the PNG file, then call png_write_info().
  182399. * The names chosen should be very close to the PNG specification, so
  182400. * consult that document for information about the meaning of each field.
  182401. *
  182402. * With libpng < 0.95, it was only possible to directly set and read the
  182403. * the values in the png_info_struct, which meant that the contents and
  182404. * order of the values had to remain fixed. With libpng 0.95 and later,
  182405. * however, there are now functions that abstract the contents of
  182406. * png_info_struct from the application, so this makes it easier to use
  182407. * libpng with dynamic libraries, and even makes it possible to use
  182408. * libraries that don't have all of the libpng ancillary chunk-handing
  182409. * functionality.
  182410. *
  182411. * In any case, the order of the parameters in png_info_struct should NOT
  182412. * be changed for as long as possible to keep compatibility with applications
  182413. * that use the old direct-access method with png_info_struct.
  182414. *
  182415. * The following members may have allocated storage attached that should be
  182416. * cleaned up before the structure is discarded: palette, trans, text,
  182417. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182418. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182419. * are automatically freed when the info structure is deallocated, if they were
  182420. * allocated internally by libpng. This behavior can be changed by means
  182421. * of the png_data_freer() function.
  182422. *
  182423. * More allocation details: all the chunk-reading functions that
  182424. * change these members go through the corresponding png_set_*
  182425. * functions. A function to clear these members is available: see
  182426. * png_free_data(). The png_set_* functions do not depend on being
  182427. * able to point info structure members to any of the storage they are
  182428. * passed (they make their own copies), EXCEPT that the png_set_text
  182429. * functions use the same storage passed to them in the text_ptr or
  182430. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182431. * functions do not make their own copies.
  182432. */
  182433. typedef struct png_info_struct
  182434. {
  182435. /* the following are necessary for every PNG file */
  182436. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182437. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182438. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182439. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182440. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182441. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182442. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182443. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182444. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182445. /* The following three should have been named *_method not *_type */
  182446. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182447. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182448. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182449. /* The following is informational only on read, and not used on writes. */
  182450. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182451. png_byte pixel_depth; /* number of bits per pixel */
  182452. png_byte spare_byte; /* to align the data, and for future use */
  182453. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182454. /* The rest of the data is optional. If you are reading, check the
  182455. * valid field to see if the information in these are valid. If you
  182456. * are writing, set the valid field to those chunks you want written,
  182457. * and initialize the appropriate fields below.
  182458. */
  182459. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182460. /* The gAMA chunk describes the gamma characteristics of the system
  182461. * on which the image was created, normally in the range [1.0, 2.5].
  182462. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182463. */
  182464. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182465. #endif
  182466. #if defined(PNG_sRGB_SUPPORTED)
  182467. /* GR-P, 0.96a */
  182468. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182469. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182470. #endif
  182471. #if defined(PNG_TEXT_SUPPORTED)
  182472. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182473. * uncompressed, compressed, and optionally compressed forms, respectively.
  182474. * The data in "text" is an array of pointers to uncompressed,
  182475. * null-terminated C strings. Each chunk has a keyword that describes the
  182476. * textual data contained in that chunk. Keywords are not required to be
  182477. * unique, and the text string may be empty. Any number of text chunks may
  182478. * be in an image.
  182479. */
  182480. int num_text; /* number of comments read/to write */
  182481. int max_text; /* current size of text array */
  182482. png_textp text; /* array of comments read/to write */
  182483. #endif /* PNG_TEXT_SUPPORTED */
  182484. #if defined(PNG_tIME_SUPPORTED)
  182485. /* The tIME chunk holds the last time the displayed image data was
  182486. * modified. See the png_time struct for the contents of this struct.
  182487. */
  182488. png_time mod_time;
  182489. #endif
  182490. #if defined(PNG_sBIT_SUPPORTED)
  182491. /* The sBIT chunk specifies the number of significant high-order bits
  182492. * in the pixel data. Values are in the range [1, bit_depth], and are
  182493. * only specified for the channels in the pixel data. The contents of
  182494. * the low-order bits is not specified. Data is valid if
  182495. * (valid & PNG_INFO_sBIT) is non-zero.
  182496. */
  182497. png_color_8 sig_bit; /* significant bits in color channels */
  182498. #endif
  182499. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182500. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182501. /* The tRNS chunk supplies transparency data for paletted images and
  182502. * other image types that don't need a full alpha channel. There are
  182503. * "num_trans" transparency values for a paletted image, stored in the
  182504. * same order as the palette colors, starting from index 0. Values
  182505. * for the data are in the range [0, 255], ranging from fully transparent
  182506. * to fully opaque, respectively. For non-paletted images, there is a
  182507. * single color specified that should be treated as fully transparent.
  182508. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182509. */
  182510. png_bytep trans; /* transparent values for paletted image */
  182511. png_color_16 trans_values; /* transparent color for non-palette image */
  182512. #endif
  182513. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182514. /* The bKGD chunk gives the suggested image background color if the
  182515. * display program does not have its own background color and the image
  182516. * is needs to composited onto a background before display. The colors
  182517. * in "background" are normally in the same color space/depth as the
  182518. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182519. */
  182520. png_color_16 background;
  182521. #endif
  182522. #if defined(PNG_oFFs_SUPPORTED)
  182523. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182524. * and downwards from the top-left corner of the display, page, or other
  182525. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182526. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182527. */
  182528. png_int_32 x_offset; /* x offset on page */
  182529. png_int_32 y_offset; /* y offset on page */
  182530. png_byte offset_unit_type; /* offset units type */
  182531. #endif
  182532. #if defined(PNG_pHYs_SUPPORTED)
  182533. /* The pHYs chunk gives the physical pixel density of the image for
  182534. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182535. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182536. */
  182537. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182538. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182539. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182540. #endif
  182541. #if defined(PNG_hIST_SUPPORTED)
  182542. /* The hIST chunk contains the relative frequency or importance of the
  182543. * various palette entries, so that a viewer can intelligently select a
  182544. * reduced-color palette, if required. Data is an array of "num_palette"
  182545. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182546. * is non-zero.
  182547. */
  182548. png_uint_16p hist;
  182549. #endif
  182550. #ifdef PNG_cHRM_SUPPORTED
  182551. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182552. * on which the PNG was created. This data allows the viewer to do gamut
  182553. * mapping of the input image to ensure that the viewer sees the same
  182554. * colors in the image as the creator. Values are in the range
  182555. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182556. */
  182557. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182558. float x_white;
  182559. float y_white;
  182560. float x_red;
  182561. float y_red;
  182562. float x_green;
  182563. float y_green;
  182564. float x_blue;
  182565. float y_blue;
  182566. #endif
  182567. #endif
  182568. #if defined(PNG_pCAL_SUPPORTED)
  182569. /* The pCAL chunk describes a transformation between the stored pixel
  182570. * values and original physical data values used to create the image.
  182571. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182572. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182573. * (possibly non-linear) transformation function given by "pcal_type"
  182574. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182575. * defines below, and the PNG-Group's PNG extensions document for a
  182576. * complete description of the transformations and how they should be
  182577. * implemented, and for a description of the ASCII parameter strings.
  182578. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182579. */
  182580. png_charp pcal_purpose; /* pCAL chunk description string */
  182581. png_int_32 pcal_X0; /* minimum value */
  182582. png_int_32 pcal_X1; /* maximum value */
  182583. png_charp pcal_units; /* Latin-1 string giving physical units */
  182584. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182585. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182586. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182587. #endif
  182588. /* New members added in libpng-1.0.6 */
  182589. #ifdef PNG_FREE_ME_SUPPORTED
  182590. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182591. #endif
  182592. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182593. /* storage for unknown chunks that the library doesn't recognize. */
  182594. png_unknown_chunkp unknown_chunks;
  182595. png_size_t unknown_chunks_num;
  182596. #endif
  182597. #if defined(PNG_iCCP_SUPPORTED)
  182598. /* iCCP chunk data. */
  182599. png_charp iccp_name; /* profile name */
  182600. png_charp iccp_profile; /* International Color Consortium profile data */
  182601. /* Note to maintainer: should be png_bytep */
  182602. png_uint_32 iccp_proflen; /* ICC profile data length */
  182603. png_byte iccp_compression; /* Always zero */
  182604. #endif
  182605. #if defined(PNG_sPLT_SUPPORTED)
  182606. /* data on sPLT chunks (there may be more than one). */
  182607. png_sPLT_tp splt_palettes;
  182608. png_uint_32 splt_palettes_num;
  182609. #endif
  182610. #if defined(PNG_sCAL_SUPPORTED)
  182611. /* The sCAL chunk describes the actual physical dimensions of the
  182612. * subject matter of the graphic. The chunk contains a unit specification
  182613. * a byte value, and two ASCII strings representing floating-point
  182614. * values. The values are width and height corresponsing to one pixel
  182615. * in the image. This external representation is converted to double
  182616. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182617. */
  182618. png_byte scal_unit; /* unit of physical scale */
  182619. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182620. double scal_pixel_width; /* width of one pixel */
  182621. double scal_pixel_height; /* height of one pixel */
  182622. #endif
  182623. #ifdef PNG_FIXED_POINT_SUPPORTED
  182624. png_charp scal_s_width; /* string containing height */
  182625. png_charp scal_s_height; /* string containing width */
  182626. #endif
  182627. #endif
  182628. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182629. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182630. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182631. png_bytepp row_pointers; /* the image bits */
  182632. #endif
  182633. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182634. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182635. #endif
  182636. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182637. png_fixed_point int_x_white;
  182638. png_fixed_point int_y_white;
  182639. png_fixed_point int_x_red;
  182640. png_fixed_point int_y_red;
  182641. png_fixed_point int_x_green;
  182642. png_fixed_point int_y_green;
  182643. png_fixed_point int_x_blue;
  182644. png_fixed_point int_y_blue;
  182645. #endif
  182646. } png_info;
  182647. typedef png_info FAR * png_infop;
  182648. typedef png_info FAR * FAR * png_infopp;
  182649. /* Maximum positive integer used in PNG is (2^31)-1 */
  182650. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182651. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182652. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182653. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182654. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182655. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182656. #endif
  182657. /* These describe the color_type field in png_info. */
  182658. /* color type masks */
  182659. #define PNG_COLOR_MASK_PALETTE 1
  182660. #define PNG_COLOR_MASK_COLOR 2
  182661. #define PNG_COLOR_MASK_ALPHA 4
  182662. /* color types. Note that not all combinations are legal */
  182663. #define PNG_COLOR_TYPE_GRAY 0
  182664. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182665. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182666. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182667. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182668. /* aliases */
  182669. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182670. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182671. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182672. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182673. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182674. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182675. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182676. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182677. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182678. /* These are for the interlacing type. These values should NOT be changed. */
  182679. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182680. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182681. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182682. /* These are for the oFFs chunk. These values should NOT be changed. */
  182683. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182684. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182685. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182686. /* These are for the pCAL chunk. These values should NOT be changed. */
  182687. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182688. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182689. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182690. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182691. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182692. /* These are for the sCAL chunk. These values should NOT be changed. */
  182693. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182694. #define PNG_SCALE_METER 1 /* meters per pixel */
  182695. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182696. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182697. /* These are for the pHYs chunk. These values should NOT be changed. */
  182698. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182699. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182700. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182701. /* These are for the sRGB chunk. These values should NOT be changed. */
  182702. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182703. #define PNG_sRGB_INTENT_RELATIVE 1
  182704. #define PNG_sRGB_INTENT_SATURATION 2
  182705. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182706. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182707. /* This is for text chunks */
  182708. #define PNG_KEYWORD_MAX_LENGTH 79
  182709. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182710. #define PNG_MAX_PALETTE_LENGTH 256
  182711. /* These determine if an ancillary chunk's data has been successfully read
  182712. * from the PNG header, or if the application has filled in the corresponding
  182713. * data in the info_struct to be written into the output file. The values
  182714. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182715. */
  182716. #define PNG_INFO_gAMA 0x0001
  182717. #define PNG_INFO_sBIT 0x0002
  182718. #define PNG_INFO_cHRM 0x0004
  182719. #define PNG_INFO_PLTE 0x0008
  182720. #define PNG_INFO_tRNS 0x0010
  182721. #define PNG_INFO_bKGD 0x0020
  182722. #define PNG_INFO_hIST 0x0040
  182723. #define PNG_INFO_pHYs 0x0080
  182724. #define PNG_INFO_oFFs 0x0100
  182725. #define PNG_INFO_tIME 0x0200
  182726. #define PNG_INFO_pCAL 0x0400
  182727. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182728. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182729. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182730. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182731. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182732. /* This is used for the transformation routines, as some of them
  182733. * change these values for the row. It also should enable using
  182734. * the routines for other purposes.
  182735. */
  182736. typedef struct png_row_info_struct
  182737. {
  182738. png_uint_32 width; /* width of row */
  182739. png_uint_32 rowbytes; /* number of bytes in row */
  182740. png_byte color_type; /* color type of row */
  182741. png_byte bit_depth; /* bit depth of row */
  182742. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182743. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182744. } png_row_info;
  182745. typedef png_row_info FAR * png_row_infop;
  182746. typedef png_row_info FAR * FAR * png_row_infopp;
  182747. /* These are the function types for the I/O functions and for the functions
  182748. * that allow the user to override the default I/O functions with his or her
  182749. * own. The png_error_ptr type should match that of user-supplied warning
  182750. * and error functions, while the png_rw_ptr type should match that of the
  182751. * user read/write data functions.
  182752. */
  182753. typedef struct png_struct_def png_struct;
  182754. typedef png_struct FAR * png_structp;
  182755. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182756. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182757. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182758. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182759. int));
  182760. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182761. int));
  182762. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182763. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182764. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182765. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182766. png_uint_32, int));
  182767. #endif
  182768. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182769. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182770. defined(PNG_LEGACY_SUPPORTED)
  182771. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182772. png_row_infop, png_bytep));
  182773. #endif
  182774. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182775. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182776. #endif
  182777. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182778. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182779. #endif
  182780. /* Transform masks for the high-level interface */
  182781. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182782. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182783. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182784. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182785. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182786. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182787. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182788. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182789. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182790. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182791. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182792. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182793. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182794. /* Flags for MNG supported features */
  182795. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182796. #define PNG_FLAG_MNG_FILTER_64 0x04
  182797. #define PNG_ALL_MNG_FEATURES 0x05
  182798. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182799. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182800. /* The structure that holds the information to read and write PNG files.
  182801. * The only people who need to care about what is inside of this are the
  182802. * people who will be modifying the library for their own special needs.
  182803. * It should NOT be accessed directly by an application, except to store
  182804. * the jmp_buf.
  182805. */
  182806. struct png_struct_def
  182807. {
  182808. #ifdef PNG_SETJMP_SUPPORTED
  182809. jmp_buf jmpbuf; /* used in png_error */
  182810. #endif
  182811. png_error_ptr error_fn; /* function for printing errors and aborting */
  182812. png_error_ptr warning_fn; /* function for printing warnings */
  182813. png_voidp error_ptr; /* user supplied struct for error functions */
  182814. png_rw_ptr write_data_fn; /* function for writing output data */
  182815. png_rw_ptr read_data_fn; /* function for reading input data */
  182816. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182817. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182818. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182819. #endif
  182820. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182821. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182822. #endif
  182823. /* These were added in libpng-1.0.2 */
  182824. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182825. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182826. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182827. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182828. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182829. png_byte user_transform_channels; /* channels in user transformed pixels */
  182830. #endif
  182831. #endif
  182832. png_uint_32 mode; /* tells us where we are in the PNG file */
  182833. png_uint_32 flags; /* flags indicating various things to libpng */
  182834. png_uint_32 transformations; /* which transformations to perform */
  182835. z_stream zstream; /* pointer to decompression structure (below) */
  182836. png_bytep zbuf; /* buffer for zlib */
  182837. png_size_t zbuf_size; /* size of zbuf */
  182838. int zlib_level; /* holds zlib compression level */
  182839. int zlib_method; /* holds zlib compression method */
  182840. int zlib_window_bits; /* holds zlib compression window bits */
  182841. int zlib_mem_level; /* holds zlib compression memory level */
  182842. int zlib_strategy; /* holds zlib compression strategy */
  182843. png_uint_32 width; /* width of image in pixels */
  182844. png_uint_32 height; /* height of image in pixels */
  182845. png_uint_32 num_rows; /* number of rows in current pass */
  182846. png_uint_32 usr_width; /* width of row at start of write */
  182847. png_uint_32 rowbytes; /* size of row in bytes */
  182848. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182849. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182850. png_uint_32 row_number; /* current row in interlace pass */
  182851. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182852. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182853. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182854. png_bytep up_row; /* buffer to save "up" row when filtering */
  182855. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182856. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182857. png_row_info row_info; /* used for transformation routines */
  182858. png_uint_32 idat_size; /* current IDAT size for read */
  182859. png_uint_32 crc; /* current chunk CRC value */
  182860. png_colorp palette; /* palette from the input file */
  182861. png_uint_16 num_palette; /* number of color entries in palette */
  182862. png_uint_16 num_trans; /* number of transparency values */
  182863. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182864. png_byte compression; /* file compression type (always 0) */
  182865. png_byte filter; /* file filter type (always 0) */
  182866. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182867. png_byte pass; /* current interlace pass (0 - 6) */
  182868. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182869. png_byte color_type; /* color type of file */
  182870. png_byte bit_depth; /* bit depth of file */
  182871. png_byte usr_bit_depth; /* bit depth of users row */
  182872. png_byte pixel_depth; /* number of bits per pixel */
  182873. png_byte channels; /* number of channels in file */
  182874. png_byte usr_channels; /* channels at start of write */
  182875. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182876. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182877. #ifdef PNG_LEGACY_SUPPORTED
  182878. png_byte filler; /* filler byte for pixel expansion */
  182879. #else
  182880. png_uint_16 filler; /* filler bytes for pixel expansion */
  182881. #endif
  182882. #endif
  182883. #if defined(PNG_bKGD_SUPPORTED)
  182884. png_byte background_gamma_type;
  182885. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182886. float background_gamma;
  182887. # endif
  182888. png_color_16 background; /* background color in screen gamma space */
  182889. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182890. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182891. #endif
  182892. #endif /* PNG_bKGD_SUPPORTED */
  182893. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182894. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182895. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182896. png_uint_32 flush_rows; /* number of rows written since last flush */
  182897. #endif
  182898. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182899. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182900. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182901. float gamma; /* file gamma value */
  182902. float screen_gamma; /* screen gamma value (display_exponent) */
  182903. #endif
  182904. #endif
  182905. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182906. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182907. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182908. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182909. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182910. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182911. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182912. #endif
  182913. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182914. png_color_8 sig_bit; /* significant bits in each available channel */
  182915. #endif
  182916. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182917. png_color_8 shift; /* shift for significant bit tranformation */
  182918. #endif
  182919. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182920. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182921. png_bytep trans; /* transparency values for paletted files */
  182922. png_color_16 trans_values; /* transparency values for non-paletted files */
  182923. #endif
  182924. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182925. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182926. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182927. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182928. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182929. png_progressive_end_ptr end_fn; /* called after image is complete */
  182930. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182931. png_bytep save_buffer; /* buffer for previously read data */
  182932. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182933. png_bytep current_buffer; /* buffer for recently used data */
  182934. png_uint_32 push_length; /* size of current input chunk */
  182935. png_uint_32 skip_length; /* bytes to skip in input data */
  182936. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182937. png_size_t save_buffer_max; /* total size of save_buffer */
  182938. png_size_t buffer_size; /* total amount of available input data */
  182939. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182940. int process_mode; /* what push library is currently doing */
  182941. int cur_palette; /* current push library palette index */
  182942. # if defined(PNG_TEXT_SUPPORTED)
  182943. png_size_t current_text_size; /* current size of text input data */
  182944. png_size_t current_text_left; /* how much text left to read in input */
  182945. png_charp current_text; /* current text chunk buffer */
  182946. png_charp current_text_ptr; /* current location in current_text */
  182947. # endif /* PNG_TEXT_SUPPORTED */
  182948. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182949. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182950. /* for the Borland special 64K segment handler */
  182951. png_bytepp offset_table_ptr;
  182952. png_bytep offset_table;
  182953. png_uint_16 offset_table_number;
  182954. png_uint_16 offset_table_count;
  182955. png_uint_16 offset_table_count_free;
  182956. #endif
  182957. #if defined(PNG_READ_DITHER_SUPPORTED)
  182958. png_bytep palette_lookup; /* lookup table for dithering */
  182959. png_bytep dither_index; /* index translation for palette files */
  182960. #endif
  182961. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182962. png_uint_16p hist; /* histogram */
  182963. #endif
  182964. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182965. png_byte heuristic_method; /* heuristic for row filter selection */
  182966. png_byte num_prev_filters; /* number of weights for previous rows */
  182967. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182968. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182969. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182970. png_uint_16p filter_costs; /* relative filter calculation cost */
  182971. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182972. #endif
  182973. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182974. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182975. #endif
  182976. /* New members added in libpng-1.0.6 */
  182977. #ifdef PNG_FREE_ME_SUPPORTED
  182978. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182979. #endif
  182980. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182981. png_voidp user_chunk_ptr;
  182982. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182983. #endif
  182984. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182985. int num_chunk_list;
  182986. png_bytep chunk_list;
  182987. #endif
  182988. /* New members added in libpng-1.0.3 */
  182989. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182990. png_byte rgb_to_gray_status;
  182991. /* These were changed from png_byte in libpng-1.0.6 */
  182992. png_uint_16 rgb_to_gray_red_coeff;
  182993. png_uint_16 rgb_to_gray_green_coeff;
  182994. png_uint_16 rgb_to_gray_blue_coeff;
  182995. #endif
  182996. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182997. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182998. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182999. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183000. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  183001. #ifdef PNG_1_0_X
  183002. png_byte mng_features_permitted;
  183003. #else
  183004. png_uint_32 mng_features_permitted;
  183005. #endif /* PNG_1_0_X */
  183006. #endif
  183007. /* New member added in libpng-1.0.7 */
  183008. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183009. png_fixed_point int_gamma;
  183010. #endif
  183011. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  183012. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  183013. png_byte filter_type;
  183014. #endif
  183015. #if defined(PNG_1_0_X)
  183016. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  183017. png_uint_32 row_buf_size;
  183018. #endif
  183019. /* New members added in libpng-1.2.0 */
  183020. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183021. # if !defined(PNG_1_0_X)
  183022. # if defined(PNG_MMX_CODE_SUPPORTED)
  183023. png_byte mmx_bitdepth_threshold;
  183024. png_uint_32 mmx_rowbytes_threshold;
  183025. # endif
  183026. png_uint_32 asm_flags;
  183027. # endif
  183028. #endif
  183029. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  183030. #ifdef PNG_USER_MEM_SUPPORTED
  183031. png_voidp mem_ptr; /* user supplied struct for mem functions */
  183032. png_malloc_ptr malloc_fn; /* function for allocating memory */
  183033. png_free_ptr free_fn; /* function for freeing memory */
  183034. #endif
  183035. /* New member added in libpng-1.0.13 and 1.2.0 */
  183036. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  183037. #if defined(PNG_READ_DITHER_SUPPORTED)
  183038. /* The following three members were added at version 1.0.14 and 1.2.4 */
  183039. png_bytep dither_sort; /* working sort array */
  183040. png_bytep index_to_palette; /* where the original index currently is */
  183041. /* in the palette */
  183042. png_bytep palette_to_index; /* which original index points to this */
  183043. /* palette color */
  183044. #endif
  183045. /* New members added in libpng-1.0.16 and 1.2.6 */
  183046. png_byte compression_type;
  183047. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183048. png_uint_32 user_width_max;
  183049. png_uint_32 user_height_max;
  183050. #endif
  183051. /* New member added in libpng-1.0.25 and 1.2.17 */
  183052. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183053. /* storage for unknown chunk that the library doesn't recognize. */
  183054. png_unknown_chunk unknown_chunk;
  183055. #endif
  183056. };
  183057. /* This triggers a compiler error in png.c, if png.c and png.h
  183058. * do not agree upon the version number.
  183059. */
  183060. typedef png_structp version_1_2_21;
  183061. typedef png_struct FAR * FAR * png_structpp;
  183062. /* Here are the function definitions most commonly used. This is not
  183063. * the place to find out how to use libpng. See libpng.txt for the
  183064. * full explanation, see example.c for the summary. This just provides
  183065. * a simple one line description of the use of each function.
  183066. */
  183067. /* Returns the version number of the library */
  183068. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  183069. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  183070. * Handling more than 8 bytes from the beginning of the file is an error.
  183071. */
  183072. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  183073. int num_bytes));
  183074. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  183075. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  183076. * signature, and non-zero otherwise. Having num_to_check == 0 or
  183077. * start > 7 will always fail (ie return non-zero).
  183078. */
  183079. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  183080. png_size_t num_to_check));
  183081. /* Simple signature checking function. This is the same as calling
  183082. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  183083. */
  183084. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  183085. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  183086. extern PNG_EXPORT(png_structp,png_create_read_struct)
  183087. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183088. png_error_ptr error_fn, png_error_ptr warn_fn));
  183089. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  183090. extern PNG_EXPORT(png_structp,png_create_write_struct)
  183091. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183092. png_error_ptr error_fn, png_error_ptr warn_fn));
  183093. #ifdef PNG_WRITE_SUPPORTED
  183094. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  183095. PNGARG((png_structp png_ptr));
  183096. #endif
  183097. #ifdef PNG_WRITE_SUPPORTED
  183098. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  183099. PNGARG((png_structp png_ptr, png_uint_32 size));
  183100. #endif
  183101. /* Reset the compression stream */
  183102. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  183103. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  183104. #ifdef PNG_USER_MEM_SUPPORTED
  183105. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  183106. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183107. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183108. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183109. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  183110. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183111. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183112. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183113. #endif
  183114. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  183115. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  183116. png_bytep chunk_name, png_bytep data, png_size_t length));
  183117. /* Write the start of a PNG chunk - length and chunk name. */
  183118. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  183119. png_bytep chunk_name, png_uint_32 length));
  183120. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  183121. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  183122. png_bytep data, png_size_t length));
  183123. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  183124. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  183125. /* Allocate and initialize the info structure */
  183126. extern PNG_EXPORT(png_infop,png_create_info_struct)
  183127. PNGARG((png_structp png_ptr));
  183128. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183129. /* Initialize the info structure (old interface - DEPRECATED) */
  183130. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  183131. #undef png_info_init
  183132. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  183133. png_sizeof(png_info));
  183134. #endif
  183135. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  183136. png_size_t png_info_struct_size));
  183137. /* Writes all the PNG information before the image. */
  183138. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  183139. png_infop info_ptr));
  183140. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  183141. png_infop info_ptr));
  183142. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183143. /* read the information before the actual image data. */
  183144. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  183145. png_infop info_ptr));
  183146. #endif
  183147. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183148. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  183149. PNGARG((png_structp png_ptr, png_timep ptime));
  183150. #endif
  183151. #if !defined(_WIN32_WCE)
  183152. /* "time.h" functions are not supported on WindowsCE */
  183153. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183154. /* convert from a struct tm to png_time */
  183155. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  183156. struct tm FAR * ttime));
  183157. /* convert from time_t to png_time. Uses gmtime() */
  183158. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  183159. time_t ttime));
  183160. #endif /* PNG_WRITE_tIME_SUPPORTED */
  183161. #endif /* _WIN32_WCE */
  183162. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183163. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  183164. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  183165. #if !defined(PNG_1_0_X)
  183166. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  183167. png_ptr));
  183168. #endif
  183169. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  183170. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  183171. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183172. /* Deprecated */
  183173. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  183174. #endif
  183175. #endif
  183176. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183177. /* Use blue, green, red order for pixels. */
  183178. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  183179. #endif
  183180. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183181. /* Expand the grayscale to 24-bit RGB if necessary. */
  183182. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  183183. #endif
  183184. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183185. /* Reduce RGB to grayscale. */
  183186. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183187. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  183188. int error_action, double red, double green ));
  183189. #endif
  183190. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  183191. int error_action, png_fixed_point red, png_fixed_point green ));
  183192. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  183193. png_ptr));
  183194. #endif
  183195. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183196. png_colorp palette));
  183197. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183198. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183199. #endif
  183200. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183201. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183202. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183203. #endif
  183204. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183205. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183206. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183207. #endif
  183208. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183209. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183210. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183211. png_uint_32 filler, int flags));
  183212. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183213. #define PNG_FILLER_BEFORE 0
  183214. #define PNG_FILLER_AFTER 1
  183215. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183216. #if !defined(PNG_1_0_X)
  183217. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183218. png_uint_32 filler, int flags));
  183219. #endif
  183220. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183221. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183222. /* Swap bytes in 16-bit depth files. */
  183223. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183224. #endif
  183225. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183226. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183227. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183228. #endif
  183229. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183230. /* Swap packing order of pixels in bytes. */
  183231. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183232. #endif
  183233. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183234. /* Converts files to legal bit depths. */
  183235. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183236. png_color_8p true_bits));
  183237. #endif
  183238. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183239. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183240. /* Have the code handle the interlacing. Returns the number of passes. */
  183241. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183242. #endif
  183243. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183244. /* Invert monochrome files */
  183245. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183246. #endif
  183247. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183248. /* Handle alpha and tRNS by replacing with a background color. */
  183249. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183250. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183251. png_color_16p background_color, int background_gamma_code,
  183252. int need_expand, double background_gamma));
  183253. #endif
  183254. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183255. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183256. #define PNG_BACKGROUND_GAMMA_FILE 2
  183257. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183258. #endif
  183259. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183260. /* strip the second byte of information from a 16-bit depth file. */
  183261. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183262. #endif
  183263. #if defined(PNG_READ_DITHER_SUPPORTED)
  183264. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183265. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183266. png_colorp palette, int num_palette, int maximum_colors,
  183267. png_uint_16p histogram, int full_dither));
  183268. #endif
  183269. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183270. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183271. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183272. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183273. double screen_gamma, double default_file_gamma));
  183274. #endif
  183275. #endif
  183276. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183277. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183278. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183279. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183280. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183281. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183282. int empty_plte_permitted));
  183283. #endif
  183284. #endif
  183285. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183286. /* Set how many lines between output flushes - 0 for no flushing */
  183287. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183288. /* Flush the current PNG output buffer */
  183289. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183290. #endif
  183291. /* optional update palette with requested transformations */
  183292. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183293. /* optional call to update the users info structure */
  183294. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183295. png_infop info_ptr));
  183296. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183297. /* read one or more rows of image data. */
  183298. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183299. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183300. #endif
  183301. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183302. /* read a row of data. */
  183303. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183304. png_bytep row,
  183305. png_bytep display_row));
  183306. #endif
  183307. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183308. /* read the whole image into memory at once. */
  183309. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183310. png_bytepp image));
  183311. #endif
  183312. /* write a row of image data */
  183313. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183314. png_bytep row));
  183315. /* write a few rows of image data */
  183316. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183317. png_bytepp row, png_uint_32 num_rows));
  183318. /* write the image data */
  183319. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183320. png_bytepp image));
  183321. /* writes the end of the PNG file. */
  183322. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183323. png_infop info_ptr));
  183324. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183325. /* read the end of the PNG file. */
  183326. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183327. png_infop info_ptr));
  183328. #endif
  183329. /* free any memory associated with the png_info_struct */
  183330. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183331. png_infopp info_ptr_ptr));
  183332. /* free any memory associated with the png_struct and the png_info_structs */
  183333. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183334. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183335. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183336. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183337. png_infop end_info_ptr));
  183338. /* free any memory associated with the png_struct and the png_info_structs */
  183339. extern PNG_EXPORT(void,png_destroy_write_struct)
  183340. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183341. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183342. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183343. /* set the libpng method of handling chunk CRC errors */
  183344. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183345. int crit_action, int ancil_action));
  183346. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183347. * ancillary and critical chunks, and whether to use the data contained
  183348. * therein. Note that it is impossible to "discard" data in a critical
  183349. * chunk. For versions prior to 0.90, the action was always error/quit,
  183350. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183351. * chunks is warn/discard. These values should NOT be changed.
  183352. *
  183353. * value action:critical action:ancillary
  183354. */
  183355. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183356. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183357. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183358. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183359. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183360. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183361. /* These functions give the user control over the scan-line filtering in
  183362. * libpng and the compression methods used by zlib. These functions are
  183363. * mainly useful for testing, as the defaults should work with most users.
  183364. * Those users who are tight on memory or want faster performance at the
  183365. * expense of compression can modify them. See the compression library
  183366. * header file (zlib.h) for an explination of the compression functions.
  183367. */
  183368. /* set the filtering method(s) used by libpng. Currently, the only valid
  183369. * value for "method" is 0.
  183370. */
  183371. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183372. int filters));
  183373. /* Flags for png_set_filter() to say which filters to use. The flags
  183374. * are chosen so that they don't conflict with real filter types
  183375. * below, in case they are supplied instead of the #defined constants.
  183376. * These values should NOT be changed.
  183377. */
  183378. #define PNG_NO_FILTERS 0x00
  183379. #define PNG_FILTER_NONE 0x08
  183380. #define PNG_FILTER_SUB 0x10
  183381. #define PNG_FILTER_UP 0x20
  183382. #define PNG_FILTER_AVG 0x40
  183383. #define PNG_FILTER_PAETH 0x80
  183384. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183385. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183386. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183387. * These defines should NOT be changed.
  183388. */
  183389. #define PNG_FILTER_VALUE_NONE 0
  183390. #define PNG_FILTER_VALUE_SUB 1
  183391. #define PNG_FILTER_VALUE_UP 2
  183392. #define PNG_FILTER_VALUE_AVG 3
  183393. #define PNG_FILTER_VALUE_PAETH 4
  183394. #define PNG_FILTER_VALUE_LAST 5
  183395. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183396. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183397. * defines, either the default (minimum-sum-of-absolute-differences), or
  183398. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183399. *
  183400. * Weights are factors >= 1.0, indicating how important it is to keep the
  183401. * filter type consistent between rows. Larger numbers mean the current
  183402. * filter is that many times as likely to be the same as the "num_weights"
  183403. * previous filters. This is cumulative for each previous row with a weight.
  183404. * There needs to be "num_weights" values in "filter_weights", or it can be
  183405. * NULL if the weights aren't being specified. Weights have no influence on
  183406. * the selection of the first row filter. Well chosen weights can (in theory)
  183407. * improve the compression for a given image.
  183408. *
  183409. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183410. * filter type. Higher costs indicate more decoding expense, and are
  183411. * therefore less likely to be selected over a filter with lower computational
  183412. * costs. There needs to be a value in "filter_costs" for each valid filter
  183413. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183414. * setting the costs. Costs try to improve the speed of decompression without
  183415. * unduly increasing the compressed image size.
  183416. *
  183417. * A negative weight or cost indicates the default value is to be used, and
  183418. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183419. * The default values for both weights and costs are currently 1.0, but may
  183420. * change if good general weighting/cost heuristics can be found. If both
  183421. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183422. * to the UNWEIGHTED method, but with added encoding time/computation.
  183423. */
  183424. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183425. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183426. int heuristic_method, int num_weights, png_doublep filter_weights,
  183427. png_doublep filter_costs));
  183428. #endif
  183429. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183430. /* Heuristic used for row filter selection. These defines should NOT be
  183431. * changed.
  183432. */
  183433. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183434. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183435. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183436. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183437. /* Set the library compression level. Currently, valid values range from
  183438. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183439. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183440. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183441. * for PNG images, and do considerably fewer caclulations. In the future,
  183442. * these values may not correspond directly to the zlib compression levels.
  183443. */
  183444. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183445. int level));
  183446. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183447. PNGARG((png_structp png_ptr, int mem_level));
  183448. extern PNG_EXPORT(void,png_set_compression_strategy)
  183449. PNGARG((png_structp png_ptr, int strategy));
  183450. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183451. PNGARG((png_structp png_ptr, int window_bits));
  183452. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183453. int method));
  183454. /* These next functions are called for input/output, memory, and error
  183455. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183456. * and call standard C I/O routines such as fread(), fwrite(), and
  183457. * fprintf(). These functions can be made to use other I/O routines
  183458. * at run time for those applications that need to handle I/O in a
  183459. * different manner by calling png_set_???_fn(). See libpng.txt for
  183460. * more information.
  183461. */
  183462. #if !defined(PNG_NO_STDIO)
  183463. /* Initialize the input/output for the PNG file to the default functions. */
  183464. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183465. #endif
  183466. /* Replace the (error and abort), and warning functions with user
  183467. * supplied functions. If no messages are to be printed you must still
  183468. * write and use replacement functions. The replacement error_fn should
  183469. * still do a longjmp to the last setjmp location if you are using this
  183470. * method of error handling. If error_fn or warning_fn is NULL, the
  183471. * default function will be used.
  183472. */
  183473. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183474. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183475. /* Return the user pointer associated with the error functions */
  183476. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183477. /* Replace the default data output functions with a user supplied one(s).
  183478. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183479. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183480. * output_flush_fn will be ignored (and thus can be NULL).
  183481. */
  183482. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183483. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183484. /* Replace the default data input function with a user supplied one. */
  183485. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183486. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183487. /* Return the user pointer associated with the I/O functions */
  183488. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183489. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183490. png_read_status_ptr read_row_fn));
  183491. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183492. png_write_status_ptr write_row_fn));
  183493. #ifdef PNG_USER_MEM_SUPPORTED
  183494. /* Replace the default memory allocation functions with user supplied one(s). */
  183495. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183496. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183497. /* Return the user pointer associated with the memory functions */
  183498. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183499. #endif
  183500. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183501. defined(PNG_LEGACY_SUPPORTED)
  183502. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183503. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183504. #endif
  183505. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183506. defined(PNG_LEGACY_SUPPORTED)
  183507. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183508. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183509. #endif
  183510. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183511. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183512. defined(PNG_LEGACY_SUPPORTED)
  183513. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183514. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183515. int user_transform_channels));
  183516. /* Return the user pointer associated with the user transform functions */
  183517. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183518. PNGARG((png_structp png_ptr));
  183519. #endif
  183520. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183521. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183522. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183523. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183524. png_ptr));
  183525. #endif
  183526. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183527. /* Sets the function callbacks for the push reader, and a pointer to a
  183528. * user-defined structure available to the callback functions.
  183529. */
  183530. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183531. png_voidp progressive_ptr,
  183532. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183533. png_progressive_end_ptr end_fn));
  183534. /* returns the user pointer associated with the push read functions */
  183535. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183536. PNGARG((png_structp png_ptr));
  183537. /* function to be called when data becomes available */
  183538. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183539. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183540. /* function that combines rows. Not very much different than the
  183541. * png_combine_row() call. Is this even used?????
  183542. */
  183543. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183544. png_bytep old_row, png_bytep new_row));
  183545. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183546. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183547. png_uint_32 size));
  183548. #if defined(PNG_1_0_X)
  183549. # define png_malloc_warn png_malloc
  183550. #else
  183551. /* Added at libpng version 1.2.4 */
  183552. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183553. png_uint_32 size));
  183554. #endif
  183555. /* frees a pointer allocated by png_malloc() */
  183556. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183557. #if defined(PNG_1_0_X)
  183558. /* Function to allocate memory for zlib. */
  183559. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183560. uInt size));
  183561. /* Function to free memory for zlib */
  183562. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183563. #endif
  183564. /* Free data that was allocated internally */
  183565. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183566. png_infop info_ptr, png_uint_32 free_me, int num));
  183567. #ifdef PNG_FREE_ME_SUPPORTED
  183568. /* Reassign responsibility for freeing existing data, whether allocated
  183569. * by libpng or by the application */
  183570. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183571. png_infop info_ptr, int freer, png_uint_32 mask));
  183572. #endif
  183573. /* assignments for png_data_freer */
  183574. #define PNG_DESTROY_WILL_FREE_DATA 1
  183575. #define PNG_SET_WILL_FREE_DATA 1
  183576. #define PNG_USER_WILL_FREE_DATA 2
  183577. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183578. #define PNG_FREE_HIST 0x0008
  183579. #define PNG_FREE_ICCP 0x0010
  183580. #define PNG_FREE_SPLT 0x0020
  183581. #define PNG_FREE_ROWS 0x0040
  183582. #define PNG_FREE_PCAL 0x0080
  183583. #define PNG_FREE_SCAL 0x0100
  183584. #define PNG_FREE_UNKN 0x0200
  183585. #define PNG_FREE_LIST 0x0400
  183586. #define PNG_FREE_PLTE 0x1000
  183587. #define PNG_FREE_TRNS 0x2000
  183588. #define PNG_FREE_TEXT 0x4000
  183589. #define PNG_FREE_ALL 0x7fff
  183590. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183591. #ifdef PNG_USER_MEM_SUPPORTED
  183592. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183593. png_uint_32 size));
  183594. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183595. png_voidp ptr));
  183596. #endif
  183597. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183598. png_voidp s1, png_voidp s2, png_uint_32 size));
  183599. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183600. png_voidp s1, int value, png_uint_32 size));
  183601. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183602. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183603. int check));
  183604. #endif /* USE_FAR_KEYWORD */
  183605. #ifndef PNG_NO_ERROR_TEXT
  183606. /* Fatal error in PNG image of libpng - can't continue */
  183607. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183608. png_const_charp error_message));
  183609. /* The same, but the chunk name is prepended to the error string. */
  183610. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183611. png_const_charp error_message));
  183612. #else
  183613. /* Fatal error in PNG image of libpng - can't continue */
  183614. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183615. #endif
  183616. #ifndef PNG_NO_WARNINGS
  183617. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183618. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183619. png_const_charp warning_message));
  183620. #ifdef PNG_READ_SUPPORTED
  183621. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183622. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183623. png_const_charp warning_message));
  183624. #endif /* PNG_READ_SUPPORTED */
  183625. #endif /* PNG_NO_WARNINGS */
  183626. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183627. * Similarly, the png_get_<chunk> calls are used to read values from the
  183628. * png_info_struct, either storing the parameters in the passed variables, or
  183629. * setting pointers into the png_info_struct where the data is stored. The
  183630. * png_get_<chunk> functions return a non-zero value if the data was available
  183631. * in info_ptr, or return zero and do not change any of the parameters if the
  183632. * data was not available.
  183633. *
  183634. * These functions should be used instead of directly accessing png_info
  183635. * to avoid problems with future changes in the size and internal layout of
  183636. * png_info_struct.
  183637. */
  183638. /* Returns "flag" if chunk data is valid in info_ptr. */
  183639. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183640. png_infop info_ptr, png_uint_32 flag));
  183641. /* Returns number of bytes needed to hold a transformed row. */
  183642. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183643. png_infop info_ptr));
  183644. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183645. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183646. returned from png_read_png(). */
  183647. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183648. png_infop info_ptr));
  183649. /* Set row_pointers, which is an array of pointers to scanlines for use
  183650. by png_write_png(). */
  183651. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183652. png_infop info_ptr, png_bytepp row_pointers));
  183653. #endif
  183654. /* Returns number of color channels in image. */
  183655. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183656. png_infop info_ptr));
  183657. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183658. /* Returns image width in pixels. */
  183659. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183660. png_ptr, png_infop info_ptr));
  183661. /* Returns image height in pixels. */
  183662. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183663. png_ptr, png_infop info_ptr));
  183664. /* Returns image bit_depth. */
  183665. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183666. png_ptr, png_infop info_ptr));
  183667. /* Returns image color_type. */
  183668. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183669. png_ptr, png_infop info_ptr));
  183670. /* Returns image filter_type. */
  183671. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183672. png_ptr, png_infop info_ptr));
  183673. /* Returns image interlace_type. */
  183674. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183675. png_ptr, png_infop info_ptr));
  183676. /* Returns image compression_type. */
  183677. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183678. png_ptr, png_infop info_ptr));
  183679. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183680. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183681. png_ptr, png_infop info_ptr));
  183682. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183683. png_ptr, png_infop info_ptr));
  183684. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183685. png_ptr, png_infop info_ptr));
  183686. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183687. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183688. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183689. png_ptr, png_infop info_ptr));
  183690. #endif
  183691. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183692. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183693. png_ptr, png_infop info_ptr));
  183694. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183695. png_ptr, png_infop info_ptr));
  183696. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183697. png_ptr, png_infop info_ptr));
  183698. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183699. png_ptr, png_infop info_ptr));
  183700. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183701. /* Returns pointer to signature string read from PNG header */
  183702. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183703. png_infop info_ptr));
  183704. #if defined(PNG_bKGD_SUPPORTED)
  183705. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183706. png_infop info_ptr, png_color_16p *background));
  183707. #endif
  183708. #if defined(PNG_bKGD_SUPPORTED)
  183709. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183710. png_infop info_ptr, png_color_16p background));
  183711. #endif
  183712. #if defined(PNG_cHRM_SUPPORTED)
  183713. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183714. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183715. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183716. double *red_y, double *green_x, double *green_y, double *blue_x,
  183717. double *blue_y));
  183718. #endif
  183719. #ifdef PNG_FIXED_POINT_SUPPORTED
  183720. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183721. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183722. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183723. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183724. *int_blue_x, png_fixed_point *int_blue_y));
  183725. #endif
  183726. #endif
  183727. #if defined(PNG_cHRM_SUPPORTED)
  183728. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183729. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183730. png_infop info_ptr, double white_x, double white_y, double red_x,
  183731. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183732. #endif
  183733. #ifdef PNG_FIXED_POINT_SUPPORTED
  183734. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183735. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183736. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183737. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183738. png_fixed_point int_blue_y));
  183739. #endif
  183740. #endif
  183741. #if defined(PNG_gAMA_SUPPORTED)
  183742. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183743. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183744. png_infop info_ptr, double *file_gamma));
  183745. #endif
  183746. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183747. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183748. #endif
  183749. #if defined(PNG_gAMA_SUPPORTED)
  183750. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183751. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183752. png_infop info_ptr, double file_gamma));
  183753. #endif
  183754. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183755. png_infop info_ptr, png_fixed_point int_file_gamma));
  183756. #endif
  183757. #if defined(PNG_hIST_SUPPORTED)
  183758. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183759. png_infop info_ptr, png_uint_16p *hist));
  183760. #endif
  183761. #if defined(PNG_hIST_SUPPORTED)
  183762. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183763. png_infop info_ptr, png_uint_16p hist));
  183764. #endif
  183765. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183766. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183767. int *bit_depth, int *color_type, int *interlace_method,
  183768. int *compression_method, int *filter_method));
  183769. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183770. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183771. int color_type, int interlace_method, int compression_method,
  183772. int filter_method));
  183773. #if defined(PNG_oFFs_SUPPORTED)
  183774. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183775. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183776. int *unit_type));
  183777. #endif
  183778. #if defined(PNG_oFFs_SUPPORTED)
  183779. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183780. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183781. int unit_type));
  183782. #endif
  183783. #if defined(PNG_pCAL_SUPPORTED)
  183784. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183785. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183786. int *type, int *nparams, png_charp *units, png_charpp *params));
  183787. #endif
  183788. #if defined(PNG_pCAL_SUPPORTED)
  183789. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183790. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183791. int type, int nparams, png_charp units, png_charpp params));
  183792. #endif
  183793. #if defined(PNG_pHYs_SUPPORTED)
  183794. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183795. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183796. #endif
  183797. #if defined(PNG_pHYs_SUPPORTED)
  183798. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183799. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183800. #endif
  183801. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183802. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183803. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183804. png_infop info_ptr, png_colorp palette, int num_palette));
  183805. #if defined(PNG_sBIT_SUPPORTED)
  183806. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183807. png_infop info_ptr, png_color_8p *sig_bit));
  183808. #endif
  183809. #if defined(PNG_sBIT_SUPPORTED)
  183810. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183811. png_infop info_ptr, png_color_8p sig_bit));
  183812. #endif
  183813. #if defined(PNG_sRGB_SUPPORTED)
  183814. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183815. png_infop info_ptr, int *intent));
  183816. #endif
  183817. #if defined(PNG_sRGB_SUPPORTED)
  183818. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183819. png_infop info_ptr, int intent));
  183820. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183821. png_infop info_ptr, int intent));
  183822. #endif
  183823. #if defined(PNG_iCCP_SUPPORTED)
  183824. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183825. png_infop info_ptr, png_charpp name, int *compression_type,
  183826. png_charpp profile, png_uint_32 *proflen));
  183827. /* Note to maintainer: profile should be png_bytepp */
  183828. #endif
  183829. #if defined(PNG_iCCP_SUPPORTED)
  183830. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183831. png_infop info_ptr, png_charp name, int compression_type,
  183832. png_charp profile, png_uint_32 proflen));
  183833. /* Note to maintainer: profile should be png_bytep */
  183834. #endif
  183835. #if defined(PNG_sPLT_SUPPORTED)
  183836. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183837. png_infop info_ptr, png_sPLT_tpp entries));
  183838. #endif
  183839. #if defined(PNG_sPLT_SUPPORTED)
  183840. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183841. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183842. #endif
  183843. #if defined(PNG_TEXT_SUPPORTED)
  183844. /* png_get_text also returns the number of text chunks in *num_text */
  183845. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183846. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183847. #endif
  183848. /*
  183849. * Note while png_set_text() will accept a structure whose text,
  183850. * language, and translated keywords are NULL pointers, the structure
  183851. * returned by png_get_text will always contain regular
  183852. * zero-terminated C strings. They might be empty strings but
  183853. * they will never be NULL pointers.
  183854. */
  183855. #if defined(PNG_TEXT_SUPPORTED)
  183856. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183857. png_infop info_ptr, png_textp text_ptr, int num_text));
  183858. #endif
  183859. #if defined(PNG_tIME_SUPPORTED)
  183860. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183861. png_infop info_ptr, png_timep *mod_time));
  183862. #endif
  183863. #if defined(PNG_tIME_SUPPORTED)
  183864. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183865. png_infop info_ptr, png_timep mod_time));
  183866. #endif
  183867. #if defined(PNG_tRNS_SUPPORTED)
  183868. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183869. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183870. png_color_16p *trans_values));
  183871. #endif
  183872. #if defined(PNG_tRNS_SUPPORTED)
  183873. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183874. png_infop info_ptr, png_bytep trans, int num_trans,
  183875. png_color_16p trans_values));
  183876. #endif
  183877. #if defined(PNG_tRNS_SUPPORTED)
  183878. #endif
  183879. #if defined(PNG_sCAL_SUPPORTED)
  183880. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183881. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183882. png_infop info_ptr, int *unit, double *width, double *height));
  183883. #else
  183884. #ifdef PNG_FIXED_POINT_SUPPORTED
  183885. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183886. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183887. #endif
  183888. #endif
  183889. #endif /* PNG_sCAL_SUPPORTED */
  183890. #if defined(PNG_sCAL_SUPPORTED)
  183891. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183892. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183893. png_infop info_ptr, int unit, double width, double height));
  183894. #else
  183895. #ifdef PNG_FIXED_POINT_SUPPORTED
  183896. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183897. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183898. #endif
  183899. #endif
  183900. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183901. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183902. /* provide a list of chunks and how they are to be handled, if the built-in
  183903. handling or default unknown chunk handling is not desired. Any chunks not
  183904. listed will be handled in the default manner. The IHDR and IEND chunks
  183905. must not be listed.
  183906. keep = 0: follow default behaviour
  183907. = 1: do not keep
  183908. = 2: keep only if safe-to-copy
  183909. = 3: keep even if unsafe-to-copy
  183910. */
  183911. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183912. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183913. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183914. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183915. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183916. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183917. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183918. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183919. #endif
  183920. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183921. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183922. chunk_name));
  183923. #endif
  183924. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183925. If you need to turn it off for a chunk that your application has freed,
  183926. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183927. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183928. png_infop info_ptr, int mask));
  183929. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183930. /* The "params" pointer is currently not used and is for future expansion. */
  183931. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183932. png_infop info_ptr,
  183933. int transforms,
  183934. png_voidp params));
  183935. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183936. png_infop info_ptr,
  183937. int transforms,
  183938. png_voidp params));
  183939. #endif
  183940. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183941. * numbers for PNG_DEBUG mean more debugging information. This has
  183942. * only been added since version 0.95 so it is not implemented throughout
  183943. * libpng yet, but more support will be added as needed.
  183944. */
  183945. #ifdef PNG_DEBUG
  183946. #if (PNG_DEBUG > 0)
  183947. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183948. #include <crtdbg.h>
  183949. #if (PNG_DEBUG > 1)
  183950. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183951. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183952. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183953. #endif
  183954. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183955. #ifndef PNG_DEBUG_FILE
  183956. #define PNG_DEBUG_FILE stderr
  183957. #endif /* PNG_DEBUG_FILE */
  183958. #if (PNG_DEBUG > 1)
  183959. #define png_debug(l,m) \
  183960. { \
  183961. int num_tabs=l; \
  183962. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183963. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183964. }
  183965. #define png_debug1(l,m,p1) \
  183966. { \
  183967. int num_tabs=l; \
  183968. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183969. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183970. }
  183971. #define png_debug2(l,m,p1,p2) \
  183972. { \
  183973. int num_tabs=l; \
  183974. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183975. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183976. }
  183977. #endif /* (PNG_DEBUG > 1) */
  183978. #endif /* _MSC_VER */
  183979. #endif /* (PNG_DEBUG > 0) */
  183980. #endif /* PNG_DEBUG */
  183981. #ifndef png_debug
  183982. #define png_debug(l, m)
  183983. #endif
  183984. #ifndef png_debug1
  183985. #define png_debug1(l, m, p1)
  183986. #endif
  183987. #ifndef png_debug2
  183988. #define png_debug2(l, m, p1, p2)
  183989. #endif
  183990. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183991. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183992. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183993. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183994. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183995. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183996. png_ptr, png_uint_32 mng_features_permitted));
  183997. #endif
  183998. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183999. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  184000. #define PNG_HANDLE_CHUNK_NEVER 1
  184001. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  184002. #define PNG_HANDLE_CHUNK_ALWAYS 3
  184003. /* Added to version 1.2.0 */
  184004. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184005. #if defined(PNG_MMX_CODE_SUPPORTED)
  184006. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  184007. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  184008. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  184009. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  184010. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  184011. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  184012. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  184013. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  184014. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  184015. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  184016. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  184017. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  184018. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  184019. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  184020. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  184021. #define PNG_MMX_WRITE_FLAGS ( 0 )
  184022. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  184023. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  184024. | PNG_MMX_READ_FLAGS \
  184025. | PNG_MMX_WRITE_FLAGS )
  184026. #define PNG_SELECT_READ 1
  184027. #define PNG_SELECT_WRITE 2
  184028. #endif /* PNG_MMX_CODE_SUPPORTED */
  184029. #if !defined(PNG_1_0_X)
  184030. /* pngget.c */
  184031. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  184032. PNGARG((int flag_select, int *compilerID));
  184033. /* pngget.c */
  184034. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  184035. PNGARG((int flag_select));
  184036. /* pngget.c */
  184037. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  184038. PNGARG((png_structp png_ptr));
  184039. /* pngget.c */
  184040. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  184041. PNGARG((png_structp png_ptr));
  184042. /* pngget.c */
  184043. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  184044. PNGARG((png_structp png_ptr));
  184045. /* pngset.c */
  184046. extern PNG_EXPORT(void,png_set_asm_flags)
  184047. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  184048. /* pngset.c */
  184049. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  184050. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  184051. png_uint_32 mmx_rowbytes_threshold));
  184052. #endif /* PNG_1_0_X */
  184053. #if !defined(PNG_1_0_X)
  184054. /* png.c, pnggccrd.c, or pngvcrd.c */
  184055. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  184056. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  184057. /* Strip the prepended error numbers ("#nnn ") from error and warning
  184058. * messages before passing them to the error or warning handler. */
  184059. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184060. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  184061. png_ptr, png_uint_32 strip_mode));
  184062. #endif
  184063. #endif /* PNG_1_0_X */
  184064. /* Added at libpng-1.2.6 */
  184065. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184066. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  184067. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  184068. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  184069. png_ptr));
  184070. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  184071. png_ptr));
  184072. #endif
  184073. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  184074. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  184075. /* With these routines we avoid an integer divide, which will be slower on
  184076. * most machines. However, it does take more operations than the corresponding
  184077. * divide method, so it may be slower on a few RISC systems. There are two
  184078. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  184079. *
  184080. * Note that the rounding factors are NOT supposed to be the same! 128 and
  184081. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  184082. * standard method.
  184083. *
  184084. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  184085. */
  184086. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  184087. # define png_composite(composite, fg, alpha, bg) \
  184088. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  184089. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  184090. (png_uint_16)(alpha)) + (png_uint_16)128); \
  184091. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  184092. # define png_composite_16(composite, fg, alpha, bg) \
  184093. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  184094. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  184095. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  184096. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  184097. #else /* standard method using integer division */
  184098. # define png_composite(composite, fg, alpha, bg) \
  184099. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  184100. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  184101. (png_uint_16)127) / 255)
  184102. # define png_composite_16(composite, fg, alpha, bg) \
  184103. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  184104. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  184105. (png_uint_32)32767) / (png_uint_32)65535L)
  184106. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  184107. /* Inline macros to do direct reads of bytes from the input buffer. These
  184108. * require that you are using an architecture that uses PNG byte ordering
  184109. * (MSB first) and supports unaligned data storage. I think that PowerPC
  184110. * in big-endian mode and 680x0 are the only ones that will support this.
  184111. * The x86 line of processors definitely do not. The png_get_int_32()
  184112. * routine also assumes we are using two's complement format for negative
  184113. * values, which is almost certainly true.
  184114. */
  184115. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  184116. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  184117. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  184118. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  184119. #else
  184120. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  184121. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  184122. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  184123. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  184124. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  184125. PNGARG((png_structp png_ptr, png_bytep buf));
  184126. /* No png_get_int_16 -- may be added if there's a real need for it. */
  184127. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  184128. */
  184129. extern PNG_EXPORT(void,png_save_uint_32)
  184130. PNGARG((png_bytep buf, png_uint_32 i));
  184131. extern PNG_EXPORT(void,png_save_int_32)
  184132. PNGARG((png_bytep buf, png_int_32 i));
  184133. /* Place a 16-bit number into a buffer in PNG byte order.
  184134. * The parameter is declared unsigned int, not png_uint_16,
  184135. * just to avoid potential problems on pre-ANSI C compilers.
  184136. */
  184137. extern PNG_EXPORT(void,png_save_uint_16)
  184138. PNGARG((png_bytep buf, unsigned int i));
  184139. /* No png_save_int_16 -- may be added if there's a real need for it. */
  184140. /* ************************************************************************* */
  184141. /* These next functions are used internally in the code. They generally
  184142. * shouldn't be used unless you are writing code to add or replace some
  184143. * functionality in libpng. More information about most functions can
  184144. * be found in the files where the functions are located.
  184145. */
  184146. /* Various modes of operation, that are visible to applications because
  184147. * they are used for unknown chunk location.
  184148. */
  184149. #define PNG_HAVE_IHDR 0x01
  184150. #define PNG_HAVE_PLTE 0x02
  184151. #define PNG_HAVE_IDAT 0x04
  184152. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  184153. #define PNG_HAVE_IEND 0x10
  184154. #if defined(PNG_INTERNAL)
  184155. /* More modes of operation. Note that after an init, mode is set to
  184156. * zero automatically when the structure is created.
  184157. */
  184158. #define PNG_HAVE_gAMA 0x20
  184159. #define PNG_HAVE_cHRM 0x40
  184160. #define PNG_HAVE_sRGB 0x80
  184161. #define PNG_HAVE_CHUNK_HEADER 0x100
  184162. #define PNG_WROTE_tIME 0x200
  184163. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  184164. #define PNG_BACKGROUND_IS_GRAY 0x800
  184165. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  184166. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  184167. /* flags for the transformations the PNG library does on the image data */
  184168. #define PNG_BGR 0x0001
  184169. #define PNG_INTERLACE 0x0002
  184170. #define PNG_PACK 0x0004
  184171. #define PNG_SHIFT 0x0008
  184172. #define PNG_SWAP_BYTES 0x0010
  184173. #define PNG_INVERT_MONO 0x0020
  184174. #define PNG_DITHER 0x0040
  184175. #define PNG_BACKGROUND 0x0080
  184176. #define PNG_BACKGROUND_EXPAND 0x0100
  184177. /* 0x0200 unused */
  184178. #define PNG_16_TO_8 0x0400
  184179. #define PNG_RGBA 0x0800
  184180. #define PNG_EXPAND 0x1000
  184181. #define PNG_GAMMA 0x2000
  184182. #define PNG_GRAY_TO_RGB 0x4000
  184183. #define PNG_FILLER 0x8000L
  184184. #define PNG_PACKSWAP 0x10000L
  184185. #define PNG_SWAP_ALPHA 0x20000L
  184186. #define PNG_STRIP_ALPHA 0x40000L
  184187. #define PNG_INVERT_ALPHA 0x80000L
  184188. #define PNG_USER_TRANSFORM 0x100000L
  184189. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  184190. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  184191. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  184192. /* 0x800000L Unused */
  184193. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  184194. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  184195. /* 0x4000000L unused */
  184196. /* 0x8000000L unused */
  184197. /* 0x10000000L unused */
  184198. /* 0x20000000L unused */
  184199. /* 0x40000000L unused */
  184200. /* flags for png_create_struct */
  184201. #define PNG_STRUCT_PNG 0x0001
  184202. #define PNG_STRUCT_INFO 0x0002
  184203. /* Scaling factor for filter heuristic weighting calculations */
  184204. #define PNG_WEIGHT_SHIFT 8
  184205. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184206. #define PNG_COST_SHIFT 3
  184207. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184208. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184209. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184210. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184211. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184212. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184213. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184214. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184215. #define PNG_FLAG_ROW_INIT 0x0040
  184216. #define PNG_FLAG_FILLER_AFTER 0x0080
  184217. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184218. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184219. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184220. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184221. #define PNG_FLAG_FREE_PLTE 0x1000
  184222. #define PNG_FLAG_FREE_TRNS 0x2000
  184223. #define PNG_FLAG_FREE_HIST 0x4000
  184224. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184225. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184226. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184227. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184228. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184229. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184230. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184231. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184232. /* 0x800000L unused */
  184233. /* 0x1000000L unused */
  184234. /* 0x2000000L unused */
  184235. /* 0x4000000L unused */
  184236. /* 0x8000000L unused */
  184237. /* 0x10000000L unused */
  184238. /* 0x20000000L unused */
  184239. /* 0x40000000L unused */
  184240. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184241. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184242. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184243. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184244. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184245. PNG_FLAG_CRC_CRITICAL_MASK)
  184246. /* save typing and make code easier to understand */
  184247. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184248. abs((int)((c1).green) - (int)((c2).green)) + \
  184249. abs((int)((c1).blue) - (int)((c2).blue)))
  184250. /* Added to libpng-1.2.6 JB */
  184251. #define PNG_ROWBYTES(pixel_bits, width) \
  184252. ((pixel_bits) >= 8 ? \
  184253. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184254. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184255. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184256. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184257. "ideal" and "delta" should be constants, normally simple
  184258. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184259. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184260. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184261. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184262. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184263. /* place to hold the signature string for a PNG file. */
  184264. #ifdef PNG_USE_GLOBAL_ARRAYS
  184265. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184266. #else
  184267. #endif
  184268. #endif /* PNG_NO_EXTERN */
  184269. /* Constant strings for known chunk types. If you need to add a chunk,
  184270. * define the name here, and add an invocation of the macro in png.c and
  184271. * wherever it's needed.
  184272. */
  184273. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184274. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184275. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184276. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184277. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184278. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184279. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184280. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184281. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184282. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184283. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184284. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184285. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184286. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184287. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184288. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184289. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184290. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184291. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184292. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184293. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184294. #ifdef PNG_USE_GLOBAL_ARRAYS
  184295. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184296. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184297. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184298. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184299. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184300. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184301. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184302. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184303. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184304. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184305. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184306. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184307. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184308. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184309. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184310. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184311. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184312. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184313. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184314. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184315. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184316. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184317. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184318. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184319. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184320. */
  184321. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184322. #undef png_read_init
  184323. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184324. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184325. #endif
  184326. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184327. png_const_charp user_png_ver, png_size_t png_struct_size));
  184328. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184329. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184330. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184331. png_info_size));
  184332. #endif
  184333. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184334. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184335. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184336. */
  184337. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184338. #undef png_write_init
  184339. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184340. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184341. #endif
  184342. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184343. png_const_charp user_png_ver, png_size_t png_struct_size));
  184344. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184345. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184346. png_info_size));
  184347. /* Allocate memory for an internal libpng struct */
  184348. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184349. /* Free memory from internal libpng struct */
  184350. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184351. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184352. malloc_fn, png_voidp mem_ptr));
  184353. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184354. png_free_ptr free_fn, png_voidp mem_ptr));
  184355. /* Free any memory that info_ptr points to and reset struct. */
  184356. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184357. png_infop info_ptr));
  184358. #ifndef PNG_1_0_X
  184359. /* Function to allocate memory for zlib. */
  184360. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184361. /* Function to free memory for zlib */
  184362. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184363. #ifdef PNG_SIZE_T
  184364. /* Function to convert a sizeof an item to png_sizeof item */
  184365. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184366. #endif
  184367. /* Next four functions are used internally as callbacks. PNGAPI is required
  184368. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184369. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184370. png_bytep data, png_size_t length));
  184371. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184372. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184373. png_bytep buffer, png_size_t length));
  184374. #endif
  184375. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184376. png_bytep data, png_size_t length));
  184377. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184378. #if !defined(PNG_NO_STDIO)
  184379. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184380. #endif
  184381. #endif
  184382. #else /* PNG_1_0_X */
  184383. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184384. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184385. png_bytep buffer, png_size_t length));
  184386. #endif
  184387. #endif /* PNG_1_0_X */
  184388. /* Reset the CRC variable */
  184389. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184390. /* Write the "data" buffer to whatever output you are using. */
  184391. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184392. png_size_t length));
  184393. /* Read data from whatever input you are using into the "data" buffer */
  184394. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184395. png_size_t length));
  184396. /* Read bytes into buf, and update png_ptr->crc */
  184397. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184398. png_size_t length));
  184399. /* Decompress data in a chunk that uses compression */
  184400. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184401. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184402. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184403. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184404. png_size_t prefix_length, png_size_t *data_length));
  184405. #endif
  184406. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184407. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184408. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184409. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184410. /* Calculate the CRC over a section of data. Note that we are only
  184411. * passing a maximum of 64K on systems that have this as a memory limit,
  184412. * since this is the maximum buffer size we can specify.
  184413. */
  184414. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184415. png_size_t length));
  184416. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184417. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184418. #endif
  184419. /* simple function to write the signature */
  184420. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184421. /* write various chunks */
  184422. /* Write the IHDR chunk, and update the png_struct with the necessary
  184423. * information.
  184424. */
  184425. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184426. png_uint_32 height,
  184427. int bit_depth, int color_type, int compression_method, int filter_method,
  184428. int interlace_method));
  184429. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184430. png_uint_32 num_pal));
  184431. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184432. png_size_t length));
  184433. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184434. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184435. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184436. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184437. #endif
  184438. #ifdef PNG_FIXED_POINT_SUPPORTED
  184439. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184440. file_gamma));
  184441. #endif
  184442. #endif
  184443. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184444. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184445. int color_type));
  184446. #endif
  184447. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184448. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184449. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184450. double white_x, double white_y,
  184451. double red_x, double red_y, double green_x, double green_y,
  184452. double blue_x, double blue_y));
  184453. #endif
  184454. #ifdef PNG_FIXED_POINT_SUPPORTED
  184455. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184456. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184457. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184458. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184459. png_fixed_point int_blue_y));
  184460. #endif
  184461. #endif
  184462. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184463. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184464. int intent));
  184465. #endif
  184466. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184467. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184468. png_charp name, int compression_type,
  184469. png_charp profile, int proflen));
  184470. /* Note to maintainer: profile should be png_bytep */
  184471. #endif
  184472. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184473. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184474. png_sPLT_tp palette));
  184475. #endif
  184476. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184477. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184478. png_color_16p values, int number, int color_type));
  184479. #endif
  184480. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184481. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184482. png_color_16p values, int color_type));
  184483. #endif
  184484. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184485. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184486. int num_hist));
  184487. #endif
  184488. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184489. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184490. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184491. png_charp key, png_charpp new_key));
  184492. #endif
  184493. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184494. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184495. png_charp text, png_size_t text_len));
  184496. #endif
  184497. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184498. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184499. png_charp text, png_size_t text_len, int compression));
  184500. #endif
  184501. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184502. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184503. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184504. png_charp text));
  184505. #endif
  184506. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184507. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184508. png_infop info_ptr, png_textp text_ptr, int num_text));
  184509. #endif
  184510. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184511. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184512. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184513. #endif
  184514. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184515. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184516. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184517. png_charp units, png_charpp params));
  184518. #endif
  184519. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184520. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184521. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184522. int unit_type));
  184523. #endif
  184524. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184525. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184526. png_timep mod_time));
  184527. #endif
  184528. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184529. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184530. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184531. int unit, double width, double height));
  184532. #else
  184533. #ifdef PNG_FIXED_POINT_SUPPORTED
  184534. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184535. int unit, png_charp width, png_charp height));
  184536. #endif
  184537. #endif
  184538. #endif
  184539. /* Called when finished processing a row of data */
  184540. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184541. /* Internal use only. Called before first row of data */
  184542. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184543. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184544. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184545. #endif
  184546. /* combine a row of data, dealing with alpha, etc. if requested */
  184547. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184548. int mask));
  184549. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184550. /* expand an interlaced row */
  184551. /* OLD pre-1.0.9 interface:
  184552. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184553. png_bytep row, int pass, png_uint_32 transformations));
  184554. */
  184555. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184556. #endif
  184557. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184558. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184559. /* grab pixels out of a row for an interlaced pass */
  184560. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184561. png_bytep row, int pass));
  184562. #endif
  184563. /* unfilter a row */
  184564. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184565. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184566. /* Choose the best filter to use and filter the row data */
  184567. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184568. png_row_infop row_info));
  184569. /* Write out the filtered row. */
  184570. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184571. png_bytep filtered_row));
  184572. /* finish a row while reading, dealing with interlacing passes, etc. */
  184573. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184574. /* initialize the row buffers, etc. */
  184575. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184576. /* optional call to update the users info structure */
  184577. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184578. png_infop info_ptr));
  184579. /* these are the functions that do the transformations */
  184580. #if defined(PNG_READ_FILLER_SUPPORTED)
  184581. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184582. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184583. #endif
  184584. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184585. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184586. png_bytep row));
  184587. #endif
  184588. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184589. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184590. png_bytep row));
  184591. #endif
  184592. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184593. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184594. png_bytep row));
  184595. #endif
  184596. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184597. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184598. png_bytep row));
  184599. #endif
  184600. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184601. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184602. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184603. png_bytep row, png_uint_32 flags));
  184604. #endif
  184605. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184606. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184607. #endif
  184608. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184609. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184610. #endif
  184611. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184612. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184613. row_info, png_bytep row));
  184614. #endif
  184615. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184616. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184617. png_bytep row));
  184618. #endif
  184619. #if defined(PNG_READ_PACK_SUPPORTED)
  184620. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184621. #endif
  184622. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184623. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184624. png_color_8p sig_bits));
  184625. #endif
  184626. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184627. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184628. #endif
  184629. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184630. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184631. #endif
  184632. #if defined(PNG_READ_DITHER_SUPPORTED)
  184633. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184634. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184635. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184636. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184637. png_colorp palette, int num_palette));
  184638. # endif
  184639. #endif
  184640. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184641. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184642. #endif
  184643. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184644. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184645. png_bytep row, png_uint_32 bit_depth));
  184646. #endif
  184647. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184648. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184649. png_color_8p bit_depth));
  184650. #endif
  184651. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184652. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184653. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184654. png_color_16p trans_values, png_color_16p background,
  184655. png_color_16p background_1,
  184656. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184657. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184658. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184659. #else
  184660. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184661. png_color_16p trans_values, png_color_16p background));
  184662. #endif
  184663. #endif
  184664. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184665. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184666. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184667. int gamma_shift));
  184668. #endif
  184669. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184670. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184671. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184672. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184673. png_bytep row, png_color_16p trans_value));
  184674. #endif
  184675. /* The following decodes the appropriate chunks, and does error correction,
  184676. * then calls the appropriate callback for the chunk if it is valid.
  184677. */
  184678. /* decode the IHDR chunk */
  184679. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184680. png_uint_32 length));
  184681. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184682. png_uint_32 length));
  184683. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184684. png_uint_32 length));
  184685. #if defined(PNG_READ_bKGD_SUPPORTED)
  184686. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184687. png_uint_32 length));
  184688. #endif
  184689. #if defined(PNG_READ_cHRM_SUPPORTED)
  184690. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184691. png_uint_32 length));
  184692. #endif
  184693. #if defined(PNG_READ_gAMA_SUPPORTED)
  184694. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184695. png_uint_32 length));
  184696. #endif
  184697. #if defined(PNG_READ_hIST_SUPPORTED)
  184698. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184699. png_uint_32 length));
  184700. #endif
  184701. #if defined(PNG_READ_iCCP_SUPPORTED)
  184702. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184703. png_uint_32 length));
  184704. #endif /* PNG_READ_iCCP_SUPPORTED */
  184705. #if defined(PNG_READ_iTXt_SUPPORTED)
  184706. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184707. png_uint_32 length));
  184708. #endif
  184709. #if defined(PNG_READ_oFFs_SUPPORTED)
  184710. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184711. png_uint_32 length));
  184712. #endif
  184713. #if defined(PNG_READ_pCAL_SUPPORTED)
  184714. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184715. png_uint_32 length));
  184716. #endif
  184717. #if defined(PNG_READ_pHYs_SUPPORTED)
  184718. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184719. png_uint_32 length));
  184720. #endif
  184721. #if defined(PNG_READ_sBIT_SUPPORTED)
  184722. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184723. png_uint_32 length));
  184724. #endif
  184725. #if defined(PNG_READ_sCAL_SUPPORTED)
  184726. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184727. png_uint_32 length));
  184728. #endif
  184729. #if defined(PNG_READ_sPLT_SUPPORTED)
  184730. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184731. png_uint_32 length));
  184732. #endif /* PNG_READ_sPLT_SUPPORTED */
  184733. #if defined(PNG_READ_sRGB_SUPPORTED)
  184734. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184735. png_uint_32 length));
  184736. #endif
  184737. #if defined(PNG_READ_tEXt_SUPPORTED)
  184738. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184739. png_uint_32 length));
  184740. #endif
  184741. #if defined(PNG_READ_tIME_SUPPORTED)
  184742. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184743. png_uint_32 length));
  184744. #endif
  184745. #if defined(PNG_READ_tRNS_SUPPORTED)
  184746. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184747. png_uint_32 length));
  184748. #endif
  184749. #if defined(PNG_READ_zTXt_SUPPORTED)
  184750. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184751. png_uint_32 length));
  184752. #endif
  184753. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184754. png_infop info_ptr, png_uint_32 length));
  184755. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184756. png_bytep chunk_name));
  184757. /* handle the transformations for reading and writing */
  184758. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184759. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184760. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184761. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184762. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184763. png_infop info_ptr));
  184764. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184765. png_infop info_ptr));
  184766. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184767. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184768. png_uint_32 length));
  184769. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184770. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184771. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184772. png_bytep buffer, png_size_t buffer_length));
  184773. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184774. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184775. png_bytep buffer, png_size_t buffer_length));
  184776. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184777. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184778. png_infop info_ptr, png_uint_32 length));
  184779. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184780. png_infop info_ptr));
  184781. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184782. png_infop info_ptr));
  184783. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184784. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184785. png_infop info_ptr));
  184786. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184787. png_infop info_ptr));
  184788. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184789. #if defined(PNG_READ_tEXt_SUPPORTED)
  184790. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184791. png_infop info_ptr, png_uint_32 length));
  184792. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184793. png_infop info_ptr));
  184794. #endif
  184795. #if defined(PNG_READ_zTXt_SUPPORTED)
  184796. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184797. png_infop info_ptr, png_uint_32 length));
  184798. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184799. png_infop info_ptr));
  184800. #endif
  184801. #if defined(PNG_READ_iTXt_SUPPORTED)
  184802. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184803. png_infop info_ptr, png_uint_32 length));
  184804. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184805. png_infop info_ptr));
  184806. #endif
  184807. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184808. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184809. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184810. png_bytep row));
  184811. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184812. png_bytep row));
  184813. #endif
  184814. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184815. #if defined(PNG_MMX_CODE_SUPPORTED)
  184816. /* png.c */ /* PRIVATE */
  184817. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184818. #endif
  184819. #endif
  184820. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184821. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184822. png_infop info_ptr));
  184823. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184824. png_infop info_ptr));
  184825. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184826. png_infop info_ptr));
  184827. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184828. png_infop info_ptr));
  184829. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184830. png_infop info_ptr));
  184831. #if defined(PNG_pHYs_SUPPORTED)
  184832. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184833. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184834. #endif /* PNG_pHYs_SUPPORTED */
  184835. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184836. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184837. #endif /* PNG_INTERNAL */
  184838. #ifdef __cplusplus
  184839. //}
  184840. #endif
  184841. #endif /* PNG_VERSION_INFO_ONLY */
  184842. /* do not put anything past this line */
  184843. #endif /* PNG_H */
  184844. /*** End of inlined file: png.h ***/
  184845. #define PNG_NO_EXTERN
  184846. /*** Start of inlined file: png.c ***/
  184847. /* png.c - location for general purpose libpng functions
  184848. *
  184849. * Last changed in libpng 1.2.21 [October 4, 2007]
  184850. * For conditions of distribution and use, see copyright notice in png.h
  184851. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184852. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184853. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184854. */
  184855. #define PNG_INTERNAL
  184856. #define PNG_NO_EXTERN
  184857. /* Generate a compiler error if there is an old png.h in the search path. */
  184858. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184859. /* Version information for C files. This had better match the version
  184860. * string defined in png.h. */
  184861. #ifdef PNG_USE_GLOBAL_ARRAYS
  184862. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184863. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184864. #ifdef PNG_READ_SUPPORTED
  184865. /* png_sig was changed to a function in version 1.0.5c */
  184866. /* Place to hold the signature string for a PNG file. */
  184867. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184868. #endif /* PNG_READ_SUPPORTED */
  184869. /* Invoke global declarations for constant strings for known chunk types */
  184870. PNG_IHDR;
  184871. PNG_IDAT;
  184872. PNG_IEND;
  184873. PNG_PLTE;
  184874. PNG_bKGD;
  184875. PNG_cHRM;
  184876. PNG_gAMA;
  184877. PNG_hIST;
  184878. PNG_iCCP;
  184879. PNG_iTXt;
  184880. PNG_oFFs;
  184881. PNG_pCAL;
  184882. PNG_sCAL;
  184883. PNG_pHYs;
  184884. PNG_sBIT;
  184885. PNG_sPLT;
  184886. PNG_sRGB;
  184887. PNG_tEXt;
  184888. PNG_tIME;
  184889. PNG_tRNS;
  184890. PNG_zTXt;
  184891. #ifdef PNG_READ_SUPPORTED
  184892. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184893. /* start of interlace block */
  184894. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184895. /* offset to next interlace block */
  184896. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184897. /* start of interlace block in the y direction */
  184898. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184899. /* offset to next interlace block in the y direction */
  184900. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184901. /* Height of interlace block. This is not currently used - if you need
  184902. * it, uncomment it here and in png.h
  184903. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184904. */
  184905. /* Mask to determine which pixels are valid in a pass */
  184906. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184907. /* Mask to determine which pixels to overwrite while displaying */
  184908. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184909. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184910. #endif /* PNG_READ_SUPPORTED */
  184911. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184912. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184913. * of the PNG file signature. If the PNG data is embedded into another
  184914. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184915. * or write any of the magic bytes before it starts on the IHDR.
  184916. */
  184917. #ifdef PNG_READ_SUPPORTED
  184918. void PNGAPI
  184919. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184920. {
  184921. if(png_ptr == NULL) return;
  184922. png_debug(1, "in png_set_sig_bytes\n");
  184923. if (num_bytes > 8)
  184924. png_error(png_ptr, "Too many bytes for PNG signature.");
  184925. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184926. }
  184927. /* Checks whether the supplied bytes match the PNG signature. We allow
  184928. * checking less than the full 8-byte signature so that those apps that
  184929. * already read the first few bytes of a file to determine the file type
  184930. * can simply check the remaining bytes for extra assurance. Returns
  184931. * an integer less than, equal to, or greater than zero if sig is found,
  184932. * respectively, to be less than, to match, or be greater than the correct
  184933. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184934. */
  184935. int PNGAPI
  184936. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184937. {
  184938. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184939. if (num_to_check > 8)
  184940. num_to_check = 8;
  184941. else if (num_to_check < 1)
  184942. return (-1);
  184943. if (start > 7)
  184944. return (-1);
  184945. if (start + num_to_check > 8)
  184946. num_to_check = 8 - start;
  184947. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184948. }
  184949. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184950. /* (Obsolete) function to check signature bytes. It does not allow one
  184951. * to check a partial signature. This function might be removed in the
  184952. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184953. */
  184954. int PNGAPI
  184955. png_check_sig(png_bytep sig, int num)
  184956. {
  184957. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184958. }
  184959. #endif
  184960. #endif /* PNG_READ_SUPPORTED */
  184961. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184962. /* Function to allocate memory for zlib and clear it to 0. */
  184963. #ifdef PNG_1_0_X
  184964. voidpf PNGAPI
  184965. #else
  184966. voidpf /* private */
  184967. #endif
  184968. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184969. {
  184970. png_voidp ptr;
  184971. png_structp p=(png_structp)png_ptr;
  184972. png_uint_32 save_flags=p->flags;
  184973. png_uint_32 num_bytes;
  184974. if(png_ptr == NULL) return (NULL);
  184975. if (items > PNG_UINT_32_MAX/size)
  184976. {
  184977. png_warning (p, "Potential overflow in png_zalloc()");
  184978. return (NULL);
  184979. }
  184980. num_bytes = (png_uint_32)items * size;
  184981. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184982. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184983. p->flags=save_flags;
  184984. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184985. if (ptr == NULL)
  184986. return ((voidpf)ptr);
  184987. if (num_bytes > (png_uint_32)0x8000L)
  184988. {
  184989. png_memset(ptr, 0, (png_size_t)0x8000L);
  184990. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184991. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184992. }
  184993. else
  184994. {
  184995. png_memset(ptr, 0, (png_size_t)num_bytes);
  184996. }
  184997. #endif
  184998. return ((voidpf)ptr);
  184999. }
  185000. /* function to free memory for zlib */
  185001. #ifdef PNG_1_0_X
  185002. void PNGAPI
  185003. #else
  185004. void /* private */
  185005. #endif
  185006. png_zfree(voidpf png_ptr, voidpf ptr)
  185007. {
  185008. png_free((png_structp)png_ptr, (png_voidp)ptr);
  185009. }
  185010. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  185011. * in case CRC is > 32 bits to leave the top bits 0.
  185012. */
  185013. void /* PRIVATE */
  185014. png_reset_crc(png_structp png_ptr)
  185015. {
  185016. png_ptr->crc = crc32(0, Z_NULL, 0);
  185017. }
  185018. /* Calculate the CRC over a section of data. We can only pass as
  185019. * much data to this routine as the largest single buffer size. We
  185020. * also check that this data will actually be used before going to the
  185021. * trouble of calculating it.
  185022. */
  185023. void /* PRIVATE */
  185024. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  185025. {
  185026. int need_crc = 1;
  185027. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  185028. {
  185029. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  185030. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  185031. need_crc = 0;
  185032. }
  185033. else /* critical */
  185034. {
  185035. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  185036. need_crc = 0;
  185037. }
  185038. if (need_crc)
  185039. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  185040. }
  185041. /* Allocate the memory for an info_struct for the application. We don't
  185042. * really need the png_ptr, but it could potentially be useful in the
  185043. * future. This should be used in favour of malloc(png_sizeof(png_info))
  185044. * and png_info_init() so that applications that want to use a shared
  185045. * libpng don't have to be recompiled if png_info changes size.
  185046. */
  185047. png_infop PNGAPI
  185048. png_create_info_struct(png_structp png_ptr)
  185049. {
  185050. png_infop info_ptr;
  185051. png_debug(1, "in png_create_info_struct\n");
  185052. if(png_ptr == NULL) return (NULL);
  185053. #ifdef PNG_USER_MEM_SUPPORTED
  185054. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  185055. png_ptr->malloc_fn, png_ptr->mem_ptr);
  185056. #else
  185057. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185058. #endif
  185059. if (info_ptr != NULL)
  185060. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185061. return (info_ptr);
  185062. }
  185063. /* This function frees the memory associated with a single info struct.
  185064. * Normally, one would use either png_destroy_read_struct() or
  185065. * png_destroy_write_struct() to free an info struct, but this may be
  185066. * useful for some applications.
  185067. */
  185068. void PNGAPI
  185069. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  185070. {
  185071. png_infop info_ptr = NULL;
  185072. if(png_ptr == NULL) return;
  185073. png_debug(1, "in png_destroy_info_struct\n");
  185074. if (info_ptr_ptr != NULL)
  185075. info_ptr = *info_ptr_ptr;
  185076. if (info_ptr != NULL)
  185077. {
  185078. png_info_destroy(png_ptr, info_ptr);
  185079. #ifdef PNG_USER_MEM_SUPPORTED
  185080. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  185081. png_ptr->mem_ptr);
  185082. #else
  185083. png_destroy_struct((png_voidp)info_ptr);
  185084. #endif
  185085. *info_ptr_ptr = NULL;
  185086. }
  185087. }
  185088. /* Initialize the info structure. This is now an internal function (0.89)
  185089. * and applications using it are urged to use png_create_info_struct()
  185090. * instead.
  185091. */
  185092. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185093. #undef png_info_init
  185094. void PNGAPI
  185095. png_info_init(png_infop info_ptr)
  185096. {
  185097. /* We only come here via pre-1.0.12-compiled applications */
  185098. png_info_init_3(&info_ptr, 0);
  185099. }
  185100. #endif
  185101. void PNGAPI
  185102. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  185103. {
  185104. png_infop info_ptr = *ptr_ptr;
  185105. if(info_ptr == NULL) return;
  185106. png_debug(1, "in png_info_init_3\n");
  185107. if(png_sizeof(png_info) > png_info_struct_size)
  185108. {
  185109. png_destroy_struct(info_ptr);
  185110. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185111. *ptr_ptr = info_ptr;
  185112. }
  185113. /* set everything to 0 */
  185114. png_memset(info_ptr, 0, png_sizeof (png_info));
  185115. }
  185116. #ifdef PNG_FREE_ME_SUPPORTED
  185117. void PNGAPI
  185118. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  185119. int freer, png_uint_32 mask)
  185120. {
  185121. png_debug(1, "in png_data_freer\n");
  185122. if (png_ptr == NULL || info_ptr == NULL)
  185123. return;
  185124. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  185125. info_ptr->free_me |= mask;
  185126. else if(freer == PNG_USER_WILL_FREE_DATA)
  185127. info_ptr->free_me &= ~mask;
  185128. else
  185129. png_warning(png_ptr,
  185130. "Unknown freer parameter in png_data_freer.");
  185131. }
  185132. #endif
  185133. void PNGAPI
  185134. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  185135. int num)
  185136. {
  185137. png_debug(1, "in png_free_data\n");
  185138. if (png_ptr == NULL || info_ptr == NULL)
  185139. return;
  185140. #if defined(PNG_TEXT_SUPPORTED)
  185141. /* free text item num or (if num == -1) all text items */
  185142. #ifdef PNG_FREE_ME_SUPPORTED
  185143. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  185144. #else
  185145. if (mask & PNG_FREE_TEXT)
  185146. #endif
  185147. {
  185148. if (num != -1)
  185149. {
  185150. if (info_ptr->text && info_ptr->text[num].key)
  185151. {
  185152. png_free(png_ptr, info_ptr->text[num].key);
  185153. info_ptr->text[num].key = NULL;
  185154. }
  185155. }
  185156. else
  185157. {
  185158. int i;
  185159. for (i = 0; i < info_ptr->num_text; i++)
  185160. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  185161. png_free(png_ptr, info_ptr->text);
  185162. info_ptr->text = NULL;
  185163. info_ptr->num_text=0;
  185164. }
  185165. }
  185166. #endif
  185167. #if defined(PNG_tRNS_SUPPORTED)
  185168. /* free any tRNS entry */
  185169. #ifdef PNG_FREE_ME_SUPPORTED
  185170. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  185171. #else
  185172. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  185173. #endif
  185174. {
  185175. png_free(png_ptr, info_ptr->trans);
  185176. info_ptr->valid &= ~PNG_INFO_tRNS;
  185177. #ifndef PNG_FREE_ME_SUPPORTED
  185178. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185179. #endif
  185180. info_ptr->trans = NULL;
  185181. }
  185182. #endif
  185183. #if defined(PNG_sCAL_SUPPORTED)
  185184. /* free any sCAL entry */
  185185. #ifdef PNG_FREE_ME_SUPPORTED
  185186. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  185187. #else
  185188. if (mask & PNG_FREE_SCAL)
  185189. #endif
  185190. {
  185191. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  185192. png_free(png_ptr, info_ptr->scal_s_width);
  185193. png_free(png_ptr, info_ptr->scal_s_height);
  185194. info_ptr->scal_s_width = NULL;
  185195. info_ptr->scal_s_height = NULL;
  185196. #endif
  185197. info_ptr->valid &= ~PNG_INFO_sCAL;
  185198. }
  185199. #endif
  185200. #if defined(PNG_pCAL_SUPPORTED)
  185201. /* free any pCAL entry */
  185202. #ifdef PNG_FREE_ME_SUPPORTED
  185203. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185204. #else
  185205. if (mask & PNG_FREE_PCAL)
  185206. #endif
  185207. {
  185208. png_free(png_ptr, info_ptr->pcal_purpose);
  185209. png_free(png_ptr, info_ptr->pcal_units);
  185210. info_ptr->pcal_purpose = NULL;
  185211. info_ptr->pcal_units = NULL;
  185212. if (info_ptr->pcal_params != NULL)
  185213. {
  185214. int i;
  185215. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185216. {
  185217. png_free(png_ptr, info_ptr->pcal_params[i]);
  185218. info_ptr->pcal_params[i]=NULL;
  185219. }
  185220. png_free(png_ptr, info_ptr->pcal_params);
  185221. info_ptr->pcal_params = NULL;
  185222. }
  185223. info_ptr->valid &= ~PNG_INFO_pCAL;
  185224. }
  185225. #endif
  185226. #if defined(PNG_iCCP_SUPPORTED)
  185227. /* free any iCCP entry */
  185228. #ifdef PNG_FREE_ME_SUPPORTED
  185229. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185230. #else
  185231. if (mask & PNG_FREE_ICCP)
  185232. #endif
  185233. {
  185234. png_free(png_ptr, info_ptr->iccp_name);
  185235. png_free(png_ptr, info_ptr->iccp_profile);
  185236. info_ptr->iccp_name = NULL;
  185237. info_ptr->iccp_profile = NULL;
  185238. info_ptr->valid &= ~PNG_INFO_iCCP;
  185239. }
  185240. #endif
  185241. #if defined(PNG_sPLT_SUPPORTED)
  185242. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185243. #ifdef PNG_FREE_ME_SUPPORTED
  185244. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185245. #else
  185246. if (mask & PNG_FREE_SPLT)
  185247. #endif
  185248. {
  185249. if (num != -1)
  185250. {
  185251. if(info_ptr->splt_palettes)
  185252. {
  185253. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185254. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185255. info_ptr->splt_palettes[num].name = NULL;
  185256. info_ptr->splt_palettes[num].entries = NULL;
  185257. }
  185258. }
  185259. else
  185260. {
  185261. if(info_ptr->splt_palettes_num)
  185262. {
  185263. int i;
  185264. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185265. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185266. png_free(png_ptr, info_ptr->splt_palettes);
  185267. info_ptr->splt_palettes = NULL;
  185268. info_ptr->splt_palettes_num = 0;
  185269. }
  185270. info_ptr->valid &= ~PNG_INFO_sPLT;
  185271. }
  185272. }
  185273. #endif
  185274. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185275. if(png_ptr->unknown_chunk.data)
  185276. {
  185277. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185278. png_ptr->unknown_chunk.data = NULL;
  185279. }
  185280. #ifdef PNG_FREE_ME_SUPPORTED
  185281. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185282. #else
  185283. if (mask & PNG_FREE_UNKN)
  185284. #endif
  185285. {
  185286. if (num != -1)
  185287. {
  185288. if(info_ptr->unknown_chunks)
  185289. {
  185290. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185291. info_ptr->unknown_chunks[num].data = NULL;
  185292. }
  185293. }
  185294. else
  185295. {
  185296. int i;
  185297. if(info_ptr->unknown_chunks_num)
  185298. {
  185299. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185300. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185301. png_free(png_ptr, info_ptr->unknown_chunks);
  185302. info_ptr->unknown_chunks = NULL;
  185303. info_ptr->unknown_chunks_num = 0;
  185304. }
  185305. }
  185306. }
  185307. #endif
  185308. #if defined(PNG_hIST_SUPPORTED)
  185309. /* free any hIST entry */
  185310. #ifdef PNG_FREE_ME_SUPPORTED
  185311. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185312. #else
  185313. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185314. #endif
  185315. {
  185316. png_free(png_ptr, info_ptr->hist);
  185317. info_ptr->hist = NULL;
  185318. info_ptr->valid &= ~PNG_INFO_hIST;
  185319. #ifndef PNG_FREE_ME_SUPPORTED
  185320. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185321. #endif
  185322. }
  185323. #endif
  185324. /* free any PLTE entry that was internally allocated */
  185325. #ifdef PNG_FREE_ME_SUPPORTED
  185326. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185327. #else
  185328. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185329. #endif
  185330. {
  185331. png_zfree(png_ptr, info_ptr->palette);
  185332. info_ptr->palette = NULL;
  185333. info_ptr->valid &= ~PNG_INFO_PLTE;
  185334. #ifndef PNG_FREE_ME_SUPPORTED
  185335. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185336. #endif
  185337. info_ptr->num_palette = 0;
  185338. }
  185339. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185340. /* free any image bits attached to the info structure */
  185341. #ifdef PNG_FREE_ME_SUPPORTED
  185342. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185343. #else
  185344. if (mask & PNG_FREE_ROWS)
  185345. #endif
  185346. {
  185347. if(info_ptr->row_pointers)
  185348. {
  185349. int row;
  185350. for (row = 0; row < (int)info_ptr->height; row++)
  185351. {
  185352. png_free(png_ptr, info_ptr->row_pointers[row]);
  185353. info_ptr->row_pointers[row]=NULL;
  185354. }
  185355. png_free(png_ptr, info_ptr->row_pointers);
  185356. info_ptr->row_pointers=NULL;
  185357. }
  185358. info_ptr->valid &= ~PNG_INFO_IDAT;
  185359. }
  185360. #endif
  185361. #ifdef PNG_FREE_ME_SUPPORTED
  185362. if(num == -1)
  185363. info_ptr->free_me &= ~mask;
  185364. else
  185365. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185366. #endif
  185367. }
  185368. /* This is an internal routine to free any memory that the info struct is
  185369. * pointing to before re-using it or freeing the struct itself. Recall
  185370. * that png_free() checks for NULL pointers for us.
  185371. */
  185372. void /* PRIVATE */
  185373. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185374. {
  185375. png_debug(1, "in png_info_destroy\n");
  185376. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185377. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185378. if (png_ptr->num_chunk_list)
  185379. {
  185380. png_free(png_ptr, png_ptr->chunk_list);
  185381. png_ptr->chunk_list=NULL;
  185382. png_ptr->num_chunk_list=0;
  185383. }
  185384. #endif
  185385. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185386. }
  185387. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185388. /* This function returns a pointer to the io_ptr associated with the user
  185389. * functions. The application should free any memory associated with this
  185390. * pointer before png_write_destroy() or png_read_destroy() are called.
  185391. */
  185392. png_voidp PNGAPI
  185393. png_get_io_ptr(png_structp png_ptr)
  185394. {
  185395. if(png_ptr == NULL) return (NULL);
  185396. return (png_ptr->io_ptr);
  185397. }
  185398. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185399. #if !defined(PNG_NO_STDIO)
  185400. /* Initialize the default input/output functions for the PNG file. If you
  185401. * use your own read or write routines, you can call either png_set_read_fn()
  185402. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185403. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185404. * necessarily available.
  185405. */
  185406. void PNGAPI
  185407. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185408. {
  185409. png_debug(1, "in png_init_io\n");
  185410. if(png_ptr == NULL) return;
  185411. png_ptr->io_ptr = (png_voidp)fp;
  185412. }
  185413. #endif
  185414. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185415. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185416. * a "Creation Time" or other text-based time string.
  185417. */
  185418. png_charp PNGAPI
  185419. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185420. {
  185421. static PNG_CONST char short_months[12][4] =
  185422. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185423. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185424. if(png_ptr == NULL) return (NULL);
  185425. if (png_ptr->time_buffer == NULL)
  185426. {
  185427. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185428. png_sizeof(char)));
  185429. }
  185430. #if defined(_WIN32_WCE)
  185431. {
  185432. wchar_t time_buf[29];
  185433. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185434. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185435. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185436. ptime->second % 61);
  185437. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185438. NULL, NULL);
  185439. }
  185440. #else
  185441. #ifdef USE_FAR_KEYWORD
  185442. {
  185443. char near_time_buf[29];
  185444. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185445. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185446. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185447. ptime->second % 61);
  185448. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185449. 29*png_sizeof(char));
  185450. }
  185451. #else
  185452. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185453. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185454. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185455. ptime->second % 61);
  185456. #endif
  185457. #endif /* _WIN32_WCE */
  185458. return ((png_charp)png_ptr->time_buffer);
  185459. }
  185460. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185461. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185462. png_charp PNGAPI
  185463. png_get_copyright(png_structp png_ptr)
  185464. {
  185465. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185466. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185467. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185468. Copyright (c) 1996-1997 Andreas Dilger\n\
  185469. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185470. }
  185471. /* The following return the library version as a short string in the
  185472. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185473. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185474. * is defined in png.h.
  185475. * Note: now there is no difference between png_get_libpng_ver() and
  185476. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185477. * it is guaranteed that png.c uses the correct version of png.h.
  185478. */
  185479. png_charp PNGAPI
  185480. png_get_libpng_ver(png_structp png_ptr)
  185481. {
  185482. /* Version of *.c files used when building libpng */
  185483. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185484. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185485. }
  185486. png_charp PNGAPI
  185487. png_get_header_ver(png_structp png_ptr)
  185488. {
  185489. /* Version of *.h files used when building libpng */
  185490. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185491. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185492. }
  185493. png_charp PNGAPI
  185494. png_get_header_version(png_structp png_ptr)
  185495. {
  185496. /* Returns longer string containing both version and date */
  185497. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185498. return ((png_charp) PNG_HEADER_VERSION_STRING
  185499. #ifndef PNG_READ_SUPPORTED
  185500. " (NO READ SUPPORT)"
  185501. #endif
  185502. "\n");
  185503. }
  185504. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185505. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185506. int PNGAPI
  185507. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185508. {
  185509. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185510. int i;
  185511. png_bytep p;
  185512. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185513. return 0;
  185514. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185515. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185516. if (!png_memcmp(chunk_name, p, 4))
  185517. return ((int)*(p+4));
  185518. return 0;
  185519. }
  185520. #endif
  185521. /* This function, added to libpng-1.0.6g, is untested. */
  185522. int PNGAPI
  185523. png_reset_zstream(png_structp png_ptr)
  185524. {
  185525. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185526. return (inflateReset(&png_ptr->zstream));
  185527. }
  185528. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185529. /* This function was added to libpng-1.0.7 */
  185530. png_uint_32 PNGAPI
  185531. png_access_version_number(void)
  185532. {
  185533. /* Version of *.c files used when building libpng */
  185534. return((png_uint_32) PNG_LIBPNG_VER);
  185535. }
  185536. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185537. #if !defined(PNG_1_0_X)
  185538. /* this function was added to libpng 1.2.0 */
  185539. int PNGAPI
  185540. png_mmx_support(void)
  185541. {
  185542. /* obsolete, to be removed from libpng-1.4.0 */
  185543. return -1;
  185544. }
  185545. #endif /* PNG_1_0_X */
  185546. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185547. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185548. #ifdef PNG_SIZE_T
  185549. /* Added at libpng version 1.2.6 */
  185550. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185551. png_size_t PNGAPI
  185552. png_convert_size(size_t size)
  185553. {
  185554. if (size > (png_size_t)-1)
  185555. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185556. return ((png_size_t)size);
  185557. }
  185558. #endif /* PNG_SIZE_T */
  185559. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185560. /*** End of inlined file: png.c ***/
  185561. /*** Start of inlined file: pngerror.c ***/
  185562. /* pngerror.c - stub functions for i/o and memory allocation
  185563. *
  185564. * Last changed in libpng 1.2.20 October 4, 2007
  185565. * For conditions of distribution and use, see copyright notice in png.h
  185566. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185567. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185568. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185569. *
  185570. * This file provides a location for all error handling. Users who
  185571. * need special error handling are expected to write replacement functions
  185572. * and use png_set_error_fn() to use those functions. See the instructions
  185573. * at each function.
  185574. */
  185575. #define PNG_INTERNAL
  185576. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185577. static void /* PRIVATE */
  185578. png_default_error PNGARG((png_structp png_ptr,
  185579. png_const_charp error_message));
  185580. #ifndef PNG_NO_WARNINGS
  185581. static void /* PRIVATE */
  185582. png_default_warning PNGARG((png_structp png_ptr,
  185583. png_const_charp warning_message));
  185584. #endif /* PNG_NO_WARNINGS */
  185585. /* This function is called whenever there is a fatal error. This function
  185586. * should not be changed. If there is a need to handle errors differently,
  185587. * you should supply a replacement error function and use png_set_error_fn()
  185588. * to replace the error function at run-time.
  185589. */
  185590. #ifndef PNG_NO_ERROR_TEXT
  185591. void PNGAPI
  185592. png_error(png_structp png_ptr, png_const_charp error_message)
  185593. {
  185594. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185595. char msg[16];
  185596. if (png_ptr != NULL)
  185597. {
  185598. if (png_ptr->flags&
  185599. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185600. {
  185601. if (*error_message == '#')
  185602. {
  185603. int offset;
  185604. for (offset=1; offset<15; offset++)
  185605. if (*(error_message+offset) == ' ')
  185606. break;
  185607. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185608. {
  185609. int i;
  185610. for (i=0; i<offset-1; i++)
  185611. msg[i]=error_message[i+1];
  185612. msg[i]='\0';
  185613. error_message=msg;
  185614. }
  185615. else
  185616. error_message+=offset;
  185617. }
  185618. else
  185619. {
  185620. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185621. {
  185622. msg[0]='0';
  185623. msg[1]='\0';
  185624. error_message=msg;
  185625. }
  185626. }
  185627. }
  185628. }
  185629. #endif
  185630. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185631. (*(png_ptr->error_fn))(png_ptr, error_message);
  185632. /* If the custom handler doesn't exist, or if it returns,
  185633. use the default handler, which will not return. */
  185634. png_default_error(png_ptr, error_message);
  185635. }
  185636. #else
  185637. void PNGAPI
  185638. png_err(png_structp png_ptr)
  185639. {
  185640. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185641. (*(png_ptr->error_fn))(png_ptr, '\0');
  185642. /* If the custom handler doesn't exist, or if it returns,
  185643. use the default handler, which will not return. */
  185644. png_default_error(png_ptr, '\0');
  185645. }
  185646. #endif /* PNG_NO_ERROR_TEXT */
  185647. #ifndef PNG_NO_WARNINGS
  185648. /* This function is called whenever there is a non-fatal error. This function
  185649. * should not be changed. If there is a need to handle warnings differently,
  185650. * you should supply a replacement warning function and use
  185651. * png_set_error_fn() to replace the warning function at run-time.
  185652. */
  185653. void PNGAPI
  185654. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185655. {
  185656. int offset = 0;
  185657. if (png_ptr != NULL)
  185658. {
  185659. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185660. if (png_ptr->flags&
  185661. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185662. #endif
  185663. {
  185664. if (*warning_message == '#')
  185665. {
  185666. for (offset=1; offset<15; offset++)
  185667. if (*(warning_message+offset) == ' ')
  185668. break;
  185669. }
  185670. }
  185671. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185672. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185673. }
  185674. else
  185675. png_default_warning(png_ptr, warning_message+offset);
  185676. }
  185677. #endif /* PNG_NO_WARNINGS */
  185678. /* These utilities are used internally to build an error message that relates
  185679. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185680. * this is used to prefix the message. The message is limited in length
  185681. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185682. * if the character is invalid.
  185683. */
  185684. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185685. /*static PNG_CONST char png_digit[16] = {
  185686. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185687. 'A', 'B', 'C', 'D', 'E', 'F'
  185688. };*/
  185689. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185690. static void /* PRIVATE */
  185691. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185692. error_message)
  185693. {
  185694. int iout = 0, iin = 0;
  185695. while (iin < 4)
  185696. {
  185697. int c = png_ptr->chunk_name[iin++];
  185698. if (isnonalpha(c))
  185699. {
  185700. buffer[iout++] = '[';
  185701. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185702. buffer[iout++] = png_digit[c & 0x0f];
  185703. buffer[iout++] = ']';
  185704. }
  185705. else
  185706. {
  185707. buffer[iout++] = (png_byte)c;
  185708. }
  185709. }
  185710. if (error_message == NULL)
  185711. buffer[iout] = 0;
  185712. else
  185713. {
  185714. buffer[iout++] = ':';
  185715. buffer[iout++] = ' ';
  185716. png_strncpy(buffer+iout, error_message, 63);
  185717. buffer[iout+63] = 0;
  185718. }
  185719. }
  185720. #ifdef PNG_READ_SUPPORTED
  185721. void PNGAPI
  185722. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185723. {
  185724. char msg[18+64];
  185725. if (png_ptr == NULL)
  185726. png_error(png_ptr, error_message);
  185727. else
  185728. {
  185729. png_format_buffer(png_ptr, msg, error_message);
  185730. png_error(png_ptr, msg);
  185731. }
  185732. }
  185733. #endif /* PNG_READ_SUPPORTED */
  185734. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185735. #ifndef PNG_NO_WARNINGS
  185736. void PNGAPI
  185737. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185738. {
  185739. char msg[18+64];
  185740. if (png_ptr == NULL)
  185741. png_warning(png_ptr, warning_message);
  185742. else
  185743. {
  185744. png_format_buffer(png_ptr, msg, warning_message);
  185745. png_warning(png_ptr, msg);
  185746. }
  185747. }
  185748. #endif /* PNG_NO_WARNINGS */
  185749. /* This is the default error handling function. Note that replacements for
  185750. * this function MUST NOT RETURN, or the program will likely crash. This
  185751. * function is used by default, or if the program supplies NULL for the
  185752. * error function pointer in png_set_error_fn().
  185753. */
  185754. static void /* PRIVATE */
  185755. png_default_error(png_structp, png_const_charp error_message)
  185756. {
  185757. #ifndef PNG_NO_CONSOLE_IO
  185758. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185759. if (*error_message == '#')
  185760. {
  185761. int offset;
  185762. char error_number[16];
  185763. for (offset=0; offset<15; offset++)
  185764. {
  185765. error_number[offset] = *(error_message+offset+1);
  185766. if (*(error_message+offset) == ' ')
  185767. break;
  185768. }
  185769. if((offset > 1) && (offset < 15))
  185770. {
  185771. error_number[offset-1]='\0';
  185772. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185773. error_message+offset);
  185774. }
  185775. else
  185776. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185777. }
  185778. else
  185779. #endif
  185780. fprintf(stderr, "libpng error: %s\n", error_message);
  185781. #endif
  185782. #ifdef PNG_SETJMP_SUPPORTED
  185783. if (png_ptr)
  185784. {
  185785. # ifdef USE_FAR_KEYWORD
  185786. {
  185787. jmp_buf jmpbuf;
  185788. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185789. longjmp(jmpbuf, 1);
  185790. }
  185791. # else
  185792. longjmp(png_ptr->jmpbuf, 1);
  185793. # endif
  185794. }
  185795. #else
  185796. PNG_ABORT();
  185797. #endif
  185798. #ifdef PNG_NO_CONSOLE_IO
  185799. error_message = error_message; /* make compiler happy */
  185800. #endif
  185801. }
  185802. #ifndef PNG_NO_WARNINGS
  185803. /* This function is called when there is a warning, but the library thinks
  185804. * it can continue anyway. Replacement functions don't have to do anything
  185805. * here if you don't want them to. In the default configuration, png_ptr is
  185806. * not used, but it is passed in case it may be useful.
  185807. */
  185808. static void /* PRIVATE */
  185809. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185810. {
  185811. #ifndef PNG_NO_CONSOLE_IO
  185812. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185813. if (*warning_message == '#')
  185814. {
  185815. int offset;
  185816. char warning_number[16];
  185817. for (offset=0; offset<15; offset++)
  185818. {
  185819. warning_number[offset]=*(warning_message+offset+1);
  185820. if (*(warning_message+offset) == ' ')
  185821. break;
  185822. }
  185823. if((offset > 1) && (offset < 15))
  185824. {
  185825. warning_number[offset-1]='\0';
  185826. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185827. warning_message+offset);
  185828. }
  185829. else
  185830. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185831. }
  185832. else
  185833. # endif
  185834. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185835. #else
  185836. warning_message = warning_message; /* make compiler happy */
  185837. #endif
  185838. png_ptr = png_ptr; /* make compiler happy */
  185839. }
  185840. #endif /* PNG_NO_WARNINGS */
  185841. /* This function is called when the application wants to use another method
  185842. * of handling errors and warnings. Note that the error function MUST NOT
  185843. * return to the calling routine or serious problems will occur. The return
  185844. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185845. */
  185846. void PNGAPI
  185847. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185848. png_error_ptr error_fn, png_error_ptr warning_fn)
  185849. {
  185850. if (png_ptr == NULL)
  185851. return;
  185852. png_ptr->error_ptr = error_ptr;
  185853. png_ptr->error_fn = error_fn;
  185854. png_ptr->warning_fn = warning_fn;
  185855. }
  185856. /* This function returns a pointer to the error_ptr associated with the user
  185857. * functions. The application should free any memory associated with this
  185858. * pointer before png_write_destroy and png_read_destroy are called.
  185859. */
  185860. png_voidp PNGAPI
  185861. png_get_error_ptr(png_structp png_ptr)
  185862. {
  185863. if (png_ptr == NULL)
  185864. return NULL;
  185865. return ((png_voidp)png_ptr->error_ptr);
  185866. }
  185867. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185868. void PNGAPI
  185869. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185870. {
  185871. if(png_ptr != NULL)
  185872. {
  185873. png_ptr->flags &=
  185874. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185875. }
  185876. }
  185877. #endif
  185878. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185879. /*** End of inlined file: pngerror.c ***/
  185880. /*** Start of inlined file: pngget.c ***/
  185881. /* pngget.c - retrieval of values from info struct
  185882. *
  185883. * Last changed in libpng 1.2.15 January 5, 2007
  185884. * For conditions of distribution and use, see copyright notice in png.h
  185885. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185886. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185887. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185888. */
  185889. #define PNG_INTERNAL
  185890. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185891. png_uint_32 PNGAPI
  185892. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185893. {
  185894. if (png_ptr != NULL && info_ptr != NULL)
  185895. return(info_ptr->valid & flag);
  185896. else
  185897. return(0);
  185898. }
  185899. png_uint_32 PNGAPI
  185900. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185901. {
  185902. if (png_ptr != NULL && info_ptr != NULL)
  185903. return(info_ptr->rowbytes);
  185904. else
  185905. return(0);
  185906. }
  185907. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185908. png_bytepp PNGAPI
  185909. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185910. {
  185911. if (png_ptr != NULL && info_ptr != NULL)
  185912. return(info_ptr->row_pointers);
  185913. else
  185914. return(0);
  185915. }
  185916. #endif
  185917. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185918. /* easy access to info, added in libpng-0.99 */
  185919. png_uint_32 PNGAPI
  185920. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185921. {
  185922. if (png_ptr != NULL && info_ptr != NULL)
  185923. {
  185924. return info_ptr->width;
  185925. }
  185926. return (0);
  185927. }
  185928. png_uint_32 PNGAPI
  185929. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185930. {
  185931. if (png_ptr != NULL && info_ptr != NULL)
  185932. {
  185933. return info_ptr->height;
  185934. }
  185935. return (0);
  185936. }
  185937. png_byte PNGAPI
  185938. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185939. {
  185940. if (png_ptr != NULL && info_ptr != NULL)
  185941. {
  185942. return info_ptr->bit_depth;
  185943. }
  185944. return (0);
  185945. }
  185946. png_byte PNGAPI
  185947. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185948. {
  185949. if (png_ptr != NULL && info_ptr != NULL)
  185950. {
  185951. return info_ptr->color_type;
  185952. }
  185953. return (0);
  185954. }
  185955. png_byte PNGAPI
  185956. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185957. {
  185958. if (png_ptr != NULL && info_ptr != NULL)
  185959. {
  185960. return info_ptr->filter_type;
  185961. }
  185962. return (0);
  185963. }
  185964. png_byte PNGAPI
  185965. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185966. {
  185967. if (png_ptr != NULL && info_ptr != NULL)
  185968. {
  185969. return info_ptr->interlace_type;
  185970. }
  185971. return (0);
  185972. }
  185973. png_byte PNGAPI
  185974. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185975. {
  185976. if (png_ptr != NULL && info_ptr != NULL)
  185977. {
  185978. return info_ptr->compression_type;
  185979. }
  185980. return (0);
  185981. }
  185982. png_uint_32 PNGAPI
  185983. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185984. {
  185985. if (png_ptr != NULL && info_ptr != NULL)
  185986. #if defined(PNG_pHYs_SUPPORTED)
  185987. if (info_ptr->valid & PNG_INFO_pHYs)
  185988. {
  185989. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185990. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185991. return (0);
  185992. else return (info_ptr->x_pixels_per_unit);
  185993. }
  185994. #else
  185995. return (0);
  185996. #endif
  185997. return (0);
  185998. }
  185999. png_uint_32 PNGAPI
  186000. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186001. {
  186002. if (png_ptr != NULL && info_ptr != NULL)
  186003. #if defined(PNG_pHYs_SUPPORTED)
  186004. if (info_ptr->valid & PNG_INFO_pHYs)
  186005. {
  186006. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  186007. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  186008. return (0);
  186009. else return (info_ptr->y_pixels_per_unit);
  186010. }
  186011. #else
  186012. return (0);
  186013. #endif
  186014. return (0);
  186015. }
  186016. png_uint_32 PNGAPI
  186017. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186018. {
  186019. if (png_ptr != NULL && info_ptr != NULL)
  186020. #if defined(PNG_pHYs_SUPPORTED)
  186021. if (info_ptr->valid & PNG_INFO_pHYs)
  186022. {
  186023. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  186024. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  186025. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  186026. return (0);
  186027. else return (info_ptr->x_pixels_per_unit);
  186028. }
  186029. #else
  186030. return (0);
  186031. #endif
  186032. return (0);
  186033. }
  186034. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186035. float PNGAPI
  186036. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  186037. {
  186038. if (png_ptr != NULL && info_ptr != NULL)
  186039. #if defined(PNG_pHYs_SUPPORTED)
  186040. if (info_ptr->valid & PNG_INFO_pHYs)
  186041. {
  186042. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  186043. if (info_ptr->x_pixels_per_unit == 0)
  186044. return ((float)0.0);
  186045. else
  186046. return ((float)((float)info_ptr->y_pixels_per_unit
  186047. /(float)info_ptr->x_pixels_per_unit));
  186048. }
  186049. #else
  186050. return (0.0);
  186051. #endif
  186052. return ((float)0.0);
  186053. }
  186054. #endif
  186055. png_int_32 PNGAPI
  186056. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186057. {
  186058. if (png_ptr != NULL && info_ptr != NULL)
  186059. #if defined(PNG_oFFs_SUPPORTED)
  186060. if (info_ptr->valid & PNG_INFO_oFFs)
  186061. {
  186062. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186063. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186064. return (0);
  186065. else return (info_ptr->x_offset);
  186066. }
  186067. #else
  186068. return (0);
  186069. #endif
  186070. return (0);
  186071. }
  186072. png_int_32 PNGAPI
  186073. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186074. {
  186075. if (png_ptr != NULL && info_ptr != NULL)
  186076. #if defined(PNG_oFFs_SUPPORTED)
  186077. if (info_ptr->valid & PNG_INFO_oFFs)
  186078. {
  186079. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186080. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186081. return (0);
  186082. else return (info_ptr->y_offset);
  186083. }
  186084. #else
  186085. return (0);
  186086. #endif
  186087. return (0);
  186088. }
  186089. png_int_32 PNGAPI
  186090. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186091. {
  186092. if (png_ptr != NULL && info_ptr != NULL)
  186093. #if defined(PNG_oFFs_SUPPORTED)
  186094. if (info_ptr->valid & PNG_INFO_oFFs)
  186095. {
  186096. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186097. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186098. return (0);
  186099. else return (info_ptr->x_offset);
  186100. }
  186101. #else
  186102. return (0);
  186103. #endif
  186104. return (0);
  186105. }
  186106. png_int_32 PNGAPI
  186107. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186108. {
  186109. if (png_ptr != NULL && info_ptr != NULL)
  186110. #if defined(PNG_oFFs_SUPPORTED)
  186111. if (info_ptr->valid & PNG_INFO_oFFs)
  186112. {
  186113. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186114. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186115. return (0);
  186116. else return (info_ptr->y_offset);
  186117. }
  186118. #else
  186119. return (0);
  186120. #endif
  186121. return (0);
  186122. }
  186123. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186124. png_uint_32 PNGAPI
  186125. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186126. {
  186127. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  186128. *.0254 +.5));
  186129. }
  186130. png_uint_32 PNGAPI
  186131. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186132. {
  186133. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  186134. *.0254 +.5));
  186135. }
  186136. png_uint_32 PNGAPI
  186137. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186138. {
  186139. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  186140. *.0254 +.5));
  186141. }
  186142. float PNGAPI
  186143. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186144. {
  186145. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  186146. *.00003937);
  186147. }
  186148. float PNGAPI
  186149. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186150. {
  186151. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  186152. *.00003937);
  186153. }
  186154. #if defined(PNG_pHYs_SUPPORTED)
  186155. png_uint_32 PNGAPI
  186156. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  186157. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186158. {
  186159. png_uint_32 retval = 0;
  186160. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  186161. {
  186162. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186163. if (res_x != NULL)
  186164. {
  186165. *res_x = info_ptr->x_pixels_per_unit;
  186166. retval |= PNG_INFO_pHYs;
  186167. }
  186168. if (res_y != NULL)
  186169. {
  186170. *res_y = info_ptr->y_pixels_per_unit;
  186171. retval |= PNG_INFO_pHYs;
  186172. }
  186173. if (unit_type != NULL)
  186174. {
  186175. *unit_type = (int)info_ptr->phys_unit_type;
  186176. retval |= PNG_INFO_pHYs;
  186177. if(*unit_type == 1)
  186178. {
  186179. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  186180. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  186181. }
  186182. }
  186183. }
  186184. return (retval);
  186185. }
  186186. #endif /* PNG_pHYs_SUPPORTED */
  186187. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  186188. /* png_get_channels really belongs in here, too, but it's been around longer */
  186189. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  186190. png_byte PNGAPI
  186191. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  186192. {
  186193. if (png_ptr != NULL && info_ptr != NULL)
  186194. return(info_ptr->channels);
  186195. else
  186196. return (0);
  186197. }
  186198. png_bytep PNGAPI
  186199. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186200. {
  186201. if (png_ptr != NULL && info_ptr != NULL)
  186202. return(info_ptr->signature);
  186203. else
  186204. return (NULL);
  186205. }
  186206. #if defined(PNG_bKGD_SUPPORTED)
  186207. png_uint_32 PNGAPI
  186208. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186209. png_color_16p *background)
  186210. {
  186211. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186212. && background != NULL)
  186213. {
  186214. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186215. *background = &(info_ptr->background);
  186216. return (PNG_INFO_bKGD);
  186217. }
  186218. return (0);
  186219. }
  186220. #endif
  186221. #if defined(PNG_cHRM_SUPPORTED)
  186222. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186223. png_uint_32 PNGAPI
  186224. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186225. double *white_x, double *white_y, double *red_x, double *red_y,
  186226. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186227. {
  186228. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186229. {
  186230. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186231. if (white_x != NULL)
  186232. *white_x = (double)info_ptr->x_white;
  186233. if (white_y != NULL)
  186234. *white_y = (double)info_ptr->y_white;
  186235. if (red_x != NULL)
  186236. *red_x = (double)info_ptr->x_red;
  186237. if (red_y != NULL)
  186238. *red_y = (double)info_ptr->y_red;
  186239. if (green_x != NULL)
  186240. *green_x = (double)info_ptr->x_green;
  186241. if (green_y != NULL)
  186242. *green_y = (double)info_ptr->y_green;
  186243. if (blue_x != NULL)
  186244. *blue_x = (double)info_ptr->x_blue;
  186245. if (blue_y != NULL)
  186246. *blue_y = (double)info_ptr->y_blue;
  186247. return (PNG_INFO_cHRM);
  186248. }
  186249. return (0);
  186250. }
  186251. #endif
  186252. #ifdef PNG_FIXED_POINT_SUPPORTED
  186253. png_uint_32 PNGAPI
  186254. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186255. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186256. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186257. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186258. {
  186259. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186260. {
  186261. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186262. if (white_x != NULL)
  186263. *white_x = info_ptr->int_x_white;
  186264. if (white_y != NULL)
  186265. *white_y = info_ptr->int_y_white;
  186266. if (red_x != NULL)
  186267. *red_x = info_ptr->int_x_red;
  186268. if (red_y != NULL)
  186269. *red_y = info_ptr->int_y_red;
  186270. if (green_x != NULL)
  186271. *green_x = info_ptr->int_x_green;
  186272. if (green_y != NULL)
  186273. *green_y = info_ptr->int_y_green;
  186274. if (blue_x != NULL)
  186275. *blue_x = info_ptr->int_x_blue;
  186276. if (blue_y != NULL)
  186277. *blue_y = info_ptr->int_y_blue;
  186278. return (PNG_INFO_cHRM);
  186279. }
  186280. return (0);
  186281. }
  186282. #endif
  186283. #endif
  186284. #if defined(PNG_gAMA_SUPPORTED)
  186285. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186286. png_uint_32 PNGAPI
  186287. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186288. {
  186289. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186290. && file_gamma != NULL)
  186291. {
  186292. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186293. *file_gamma = (double)info_ptr->gamma;
  186294. return (PNG_INFO_gAMA);
  186295. }
  186296. return (0);
  186297. }
  186298. #endif
  186299. #ifdef PNG_FIXED_POINT_SUPPORTED
  186300. png_uint_32 PNGAPI
  186301. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186302. png_fixed_point *int_file_gamma)
  186303. {
  186304. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186305. && int_file_gamma != NULL)
  186306. {
  186307. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186308. *int_file_gamma = info_ptr->int_gamma;
  186309. return (PNG_INFO_gAMA);
  186310. }
  186311. return (0);
  186312. }
  186313. #endif
  186314. #endif
  186315. #if defined(PNG_sRGB_SUPPORTED)
  186316. png_uint_32 PNGAPI
  186317. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186318. {
  186319. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186320. && file_srgb_intent != NULL)
  186321. {
  186322. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186323. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186324. return (PNG_INFO_sRGB);
  186325. }
  186326. return (0);
  186327. }
  186328. #endif
  186329. #if defined(PNG_iCCP_SUPPORTED)
  186330. png_uint_32 PNGAPI
  186331. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186332. png_charpp name, int *compression_type,
  186333. png_charpp profile, png_uint_32 *proflen)
  186334. {
  186335. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186336. && name != NULL && profile != NULL && proflen != NULL)
  186337. {
  186338. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186339. *name = info_ptr->iccp_name;
  186340. *profile = info_ptr->iccp_profile;
  186341. /* compression_type is a dummy so the API won't have to change
  186342. if we introduce multiple compression types later. */
  186343. *proflen = (int)info_ptr->iccp_proflen;
  186344. *compression_type = (int)info_ptr->iccp_compression;
  186345. return (PNG_INFO_iCCP);
  186346. }
  186347. return (0);
  186348. }
  186349. #endif
  186350. #if defined(PNG_sPLT_SUPPORTED)
  186351. png_uint_32 PNGAPI
  186352. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186353. png_sPLT_tpp spalettes)
  186354. {
  186355. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186356. {
  186357. *spalettes = info_ptr->splt_palettes;
  186358. return ((png_uint_32)info_ptr->splt_palettes_num);
  186359. }
  186360. return (0);
  186361. }
  186362. #endif
  186363. #if defined(PNG_hIST_SUPPORTED)
  186364. png_uint_32 PNGAPI
  186365. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186366. {
  186367. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186368. && hist != NULL)
  186369. {
  186370. png_debug1(1, "in %s retrieval function\n", "hIST");
  186371. *hist = info_ptr->hist;
  186372. return (PNG_INFO_hIST);
  186373. }
  186374. return (0);
  186375. }
  186376. #endif
  186377. png_uint_32 PNGAPI
  186378. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186379. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186380. int *color_type, int *interlace_type, int *compression_type,
  186381. int *filter_type)
  186382. {
  186383. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186384. bit_depth != NULL && color_type != NULL)
  186385. {
  186386. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186387. *width = info_ptr->width;
  186388. *height = info_ptr->height;
  186389. *bit_depth = info_ptr->bit_depth;
  186390. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186391. png_error(png_ptr, "Invalid bit depth");
  186392. *color_type = info_ptr->color_type;
  186393. if (info_ptr->color_type > 6)
  186394. png_error(png_ptr, "Invalid color type");
  186395. if (compression_type != NULL)
  186396. *compression_type = info_ptr->compression_type;
  186397. if (filter_type != NULL)
  186398. *filter_type = info_ptr->filter_type;
  186399. if (interlace_type != NULL)
  186400. *interlace_type = info_ptr->interlace_type;
  186401. /* check for potential overflow of rowbytes */
  186402. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186403. png_error(png_ptr, "Invalid image width");
  186404. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186405. png_error(png_ptr, "Invalid image height");
  186406. if (info_ptr->width > (PNG_UINT_32_MAX
  186407. >> 3) /* 8-byte RGBA pixels */
  186408. - 64 /* bigrowbuf hack */
  186409. - 1 /* filter byte */
  186410. - 7*8 /* rounding of width to multiple of 8 pixels */
  186411. - 8) /* extra max_pixel_depth pad */
  186412. {
  186413. png_warning(png_ptr,
  186414. "Width too large for libpng to process image data.");
  186415. }
  186416. return (1);
  186417. }
  186418. return (0);
  186419. }
  186420. #if defined(PNG_oFFs_SUPPORTED)
  186421. png_uint_32 PNGAPI
  186422. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186423. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186424. {
  186425. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186426. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186427. {
  186428. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186429. *offset_x = info_ptr->x_offset;
  186430. *offset_y = info_ptr->y_offset;
  186431. *unit_type = (int)info_ptr->offset_unit_type;
  186432. return (PNG_INFO_oFFs);
  186433. }
  186434. return (0);
  186435. }
  186436. #endif
  186437. #if defined(PNG_pCAL_SUPPORTED)
  186438. png_uint_32 PNGAPI
  186439. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186440. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186441. png_charp *units, png_charpp *params)
  186442. {
  186443. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186444. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186445. nparams != NULL && units != NULL && params != NULL)
  186446. {
  186447. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186448. *purpose = info_ptr->pcal_purpose;
  186449. *X0 = info_ptr->pcal_X0;
  186450. *X1 = info_ptr->pcal_X1;
  186451. *type = (int)info_ptr->pcal_type;
  186452. *nparams = (int)info_ptr->pcal_nparams;
  186453. *units = info_ptr->pcal_units;
  186454. *params = info_ptr->pcal_params;
  186455. return (PNG_INFO_pCAL);
  186456. }
  186457. return (0);
  186458. }
  186459. #endif
  186460. #if defined(PNG_sCAL_SUPPORTED)
  186461. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186462. png_uint_32 PNGAPI
  186463. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186464. int *unit, double *width, double *height)
  186465. {
  186466. if (png_ptr != NULL && info_ptr != NULL &&
  186467. (info_ptr->valid & PNG_INFO_sCAL))
  186468. {
  186469. *unit = info_ptr->scal_unit;
  186470. *width = info_ptr->scal_pixel_width;
  186471. *height = info_ptr->scal_pixel_height;
  186472. return (PNG_INFO_sCAL);
  186473. }
  186474. return(0);
  186475. }
  186476. #else
  186477. #ifdef PNG_FIXED_POINT_SUPPORTED
  186478. png_uint_32 PNGAPI
  186479. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186480. int *unit, png_charpp width, png_charpp height)
  186481. {
  186482. if (png_ptr != NULL && info_ptr != NULL &&
  186483. (info_ptr->valid & PNG_INFO_sCAL))
  186484. {
  186485. *unit = info_ptr->scal_unit;
  186486. *width = info_ptr->scal_s_width;
  186487. *height = info_ptr->scal_s_height;
  186488. return (PNG_INFO_sCAL);
  186489. }
  186490. return(0);
  186491. }
  186492. #endif
  186493. #endif
  186494. #endif
  186495. #if defined(PNG_pHYs_SUPPORTED)
  186496. png_uint_32 PNGAPI
  186497. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186498. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186499. {
  186500. png_uint_32 retval = 0;
  186501. if (png_ptr != NULL && info_ptr != NULL &&
  186502. (info_ptr->valid & PNG_INFO_pHYs))
  186503. {
  186504. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186505. if (res_x != NULL)
  186506. {
  186507. *res_x = info_ptr->x_pixels_per_unit;
  186508. retval |= PNG_INFO_pHYs;
  186509. }
  186510. if (res_y != NULL)
  186511. {
  186512. *res_y = info_ptr->y_pixels_per_unit;
  186513. retval |= PNG_INFO_pHYs;
  186514. }
  186515. if (unit_type != NULL)
  186516. {
  186517. *unit_type = (int)info_ptr->phys_unit_type;
  186518. retval |= PNG_INFO_pHYs;
  186519. }
  186520. }
  186521. return (retval);
  186522. }
  186523. #endif
  186524. png_uint_32 PNGAPI
  186525. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186526. int *num_palette)
  186527. {
  186528. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186529. && palette != NULL)
  186530. {
  186531. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186532. *palette = info_ptr->palette;
  186533. *num_palette = info_ptr->num_palette;
  186534. png_debug1(3, "num_palette = %d\n", *num_palette);
  186535. return (PNG_INFO_PLTE);
  186536. }
  186537. return (0);
  186538. }
  186539. #if defined(PNG_sBIT_SUPPORTED)
  186540. png_uint_32 PNGAPI
  186541. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186542. {
  186543. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186544. && sig_bit != NULL)
  186545. {
  186546. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186547. *sig_bit = &(info_ptr->sig_bit);
  186548. return (PNG_INFO_sBIT);
  186549. }
  186550. return (0);
  186551. }
  186552. #endif
  186553. #if defined(PNG_TEXT_SUPPORTED)
  186554. png_uint_32 PNGAPI
  186555. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186556. int *num_text)
  186557. {
  186558. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186559. {
  186560. png_debug1(1, "in %s retrieval function\n",
  186561. (png_ptr->chunk_name[0] == '\0' ? "text"
  186562. : (png_const_charp)png_ptr->chunk_name));
  186563. if (text_ptr != NULL)
  186564. *text_ptr = info_ptr->text;
  186565. if (num_text != NULL)
  186566. *num_text = info_ptr->num_text;
  186567. return ((png_uint_32)info_ptr->num_text);
  186568. }
  186569. if (num_text != NULL)
  186570. *num_text = 0;
  186571. return(0);
  186572. }
  186573. #endif
  186574. #if defined(PNG_tIME_SUPPORTED)
  186575. png_uint_32 PNGAPI
  186576. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186577. {
  186578. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186579. && mod_time != NULL)
  186580. {
  186581. png_debug1(1, "in %s retrieval function\n", "tIME");
  186582. *mod_time = &(info_ptr->mod_time);
  186583. return (PNG_INFO_tIME);
  186584. }
  186585. return (0);
  186586. }
  186587. #endif
  186588. #if defined(PNG_tRNS_SUPPORTED)
  186589. png_uint_32 PNGAPI
  186590. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186591. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186592. {
  186593. png_uint_32 retval = 0;
  186594. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186595. {
  186596. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186597. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186598. {
  186599. if (trans != NULL)
  186600. {
  186601. *trans = info_ptr->trans;
  186602. retval |= PNG_INFO_tRNS;
  186603. }
  186604. if (trans_values != NULL)
  186605. *trans_values = &(info_ptr->trans_values);
  186606. }
  186607. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186608. {
  186609. if (trans_values != NULL)
  186610. {
  186611. *trans_values = &(info_ptr->trans_values);
  186612. retval |= PNG_INFO_tRNS;
  186613. }
  186614. if(trans != NULL)
  186615. *trans = NULL;
  186616. }
  186617. if(num_trans != NULL)
  186618. {
  186619. *num_trans = info_ptr->num_trans;
  186620. retval |= PNG_INFO_tRNS;
  186621. }
  186622. }
  186623. return (retval);
  186624. }
  186625. #endif
  186626. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186627. png_uint_32 PNGAPI
  186628. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186629. png_unknown_chunkpp unknowns)
  186630. {
  186631. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186632. {
  186633. *unknowns = info_ptr->unknown_chunks;
  186634. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186635. }
  186636. return (0);
  186637. }
  186638. #endif
  186639. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186640. png_byte PNGAPI
  186641. png_get_rgb_to_gray_status (png_structp png_ptr)
  186642. {
  186643. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186644. }
  186645. #endif
  186646. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186647. png_voidp PNGAPI
  186648. png_get_user_chunk_ptr(png_structp png_ptr)
  186649. {
  186650. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186651. }
  186652. #endif
  186653. #ifdef PNG_WRITE_SUPPORTED
  186654. png_uint_32 PNGAPI
  186655. png_get_compression_buffer_size(png_structp png_ptr)
  186656. {
  186657. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186658. }
  186659. #endif
  186660. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186661. #ifndef PNG_1_0_X
  186662. /* this function was added to libpng 1.2.0 and should exist by default */
  186663. png_uint_32 PNGAPI
  186664. png_get_asm_flags (png_structp png_ptr)
  186665. {
  186666. /* obsolete, to be removed from libpng-1.4.0 */
  186667. return (png_ptr? 0L: 0L);
  186668. }
  186669. /* this function was added to libpng 1.2.0 and should exist by default */
  186670. png_uint_32 PNGAPI
  186671. png_get_asm_flagmask (int flag_select)
  186672. {
  186673. /* obsolete, to be removed from libpng-1.4.0 */
  186674. flag_select=flag_select;
  186675. return 0L;
  186676. }
  186677. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186678. /* this function was added to libpng 1.2.0 */
  186679. png_uint_32 PNGAPI
  186680. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186681. {
  186682. /* obsolete, to be removed from libpng-1.4.0 */
  186683. flag_select=flag_select;
  186684. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186685. return 0L;
  186686. }
  186687. /* this function was added to libpng 1.2.0 */
  186688. png_byte PNGAPI
  186689. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186690. {
  186691. /* obsolete, to be removed from libpng-1.4.0 */
  186692. return (png_ptr? 0: 0);
  186693. }
  186694. /* this function was added to libpng 1.2.0 */
  186695. png_uint_32 PNGAPI
  186696. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186697. {
  186698. /* obsolete, to be removed from libpng-1.4.0 */
  186699. return (png_ptr? 0L: 0L);
  186700. }
  186701. #endif /* ?PNG_1_0_X */
  186702. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186703. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186704. /* these functions were added to libpng 1.2.6 */
  186705. png_uint_32 PNGAPI
  186706. png_get_user_width_max (png_structp png_ptr)
  186707. {
  186708. return (png_ptr? png_ptr->user_width_max : 0);
  186709. }
  186710. png_uint_32 PNGAPI
  186711. png_get_user_height_max (png_structp png_ptr)
  186712. {
  186713. return (png_ptr? png_ptr->user_height_max : 0);
  186714. }
  186715. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186716. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186717. /*** End of inlined file: pngget.c ***/
  186718. /*** Start of inlined file: pngmem.c ***/
  186719. /* pngmem.c - stub functions for memory allocation
  186720. *
  186721. * Last changed in libpng 1.2.13 November 13, 2006
  186722. * For conditions of distribution and use, see copyright notice in png.h
  186723. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186724. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186725. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186726. *
  186727. * This file provides a location for all memory allocation. Users who
  186728. * need special memory handling are expected to supply replacement
  186729. * functions for png_malloc() and png_free(), and to use
  186730. * png_create_read_struct_2() and png_create_write_struct_2() to
  186731. * identify the replacement functions.
  186732. */
  186733. #define PNG_INTERNAL
  186734. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186735. /* Borland DOS special memory handler */
  186736. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186737. /* if you change this, be sure to change the one in png.h also */
  186738. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186739. by a single call to calloc() if this is thought to improve performance. */
  186740. png_voidp /* PRIVATE */
  186741. png_create_struct(int type)
  186742. {
  186743. #ifdef PNG_USER_MEM_SUPPORTED
  186744. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186745. }
  186746. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186747. png_voidp /* PRIVATE */
  186748. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186749. {
  186750. #endif /* PNG_USER_MEM_SUPPORTED */
  186751. png_size_t size;
  186752. png_voidp struct_ptr;
  186753. if (type == PNG_STRUCT_INFO)
  186754. size = png_sizeof(png_info);
  186755. else if (type == PNG_STRUCT_PNG)
  186756. size = png_sizeof(png_struct);
  186757. else
  186758. return (png_get_copyright(NULL));
  186759. #ifdef PNG_USER_MEM_SUPPORTED
  186760. if(malloc_fn != NULL)
  186761. {
  186762. png_struct dummy_struct;
  186763. png_structp png_ptr = &dummy_struct;
  186764. png_ptr->mem_ptr=mem_ptr;
  186765. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186766. }
  186767. else
  186768. #endif /* PNG_USER_MEM_SUPPORTED */
  186769. struct_ptr = (png_voidp)farmalloc(size);
  186770. if (struct_ptr != NULL)
  186771. png_memset(struct_ptr, 0, size);
  186772. return (struct_ptr);
  186773. }
  186774. /* Free memory allocated by a png_create_struct() call */
  186775. void /* PRIVATE */
  186776. png_destroy_struct(png_voidp struct_ptr)
  186777. {
  186778. #ifdef PNG_USER_MEM_SUPPORTED
  186779. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186780. }
  186781. /* Free memory allocated by a png_create_struct() call */
  186782. void /* PRIVATE */
  186783. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186784. png_voidp mem_ptr)
  186785. {
  186786. #endif
  186787. if (struct_ptr != NULL)
  186788. {
  186789. #ifdef PNG_USER_MEM_SUPPORTED
  186790. if(free_fn != NULL)
  186791. {
  186792. png_struct dummy_struct;
  186793. png_structp png_ptr = &dummy_struct;
  186794. png_ptr->mem_ptr=mem_ptr;
  186795. (*(free_fn))(png_ptr, struct_ptr);
  186796. return;
  186797. }
  186798. #endif /* PNG_USER_MEM_SUPPORTED */
  186799. farfree (struct_ptr);
  186800. }
  186801. }
  186802. /* Allocate memory. For reasonable files, size should never exceed
  186803. * 64K. However, zlib may allocate more then 64K if you don't tell
  186804. * it not to. See zconf.h and png.h for more information. zlib does
  186805. * need to allocate exactly 64K, so whatever you call here must
  186806. * have the ability to do that.
  186807. *
  186808. * Borland seems to have a problem in DOS mode for exactly 64K.
  186809. * It gives you a segment with an offset of 8 (perhaps to store its
  186810. * memory stuff). zlib doesn't like this at all, so we have to
  186811. * detect and deal with it. This code should not be needed in
  186812. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186813. * been updated by Alexander Lehmann for version 0.89 to waste less
  186814. * memory.
  186815. *
  186816. * Note that we can't use png_size_t for the "size" declaration,
  186817. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186818. * result, we would be truncating potentially larger memory requests
  186819. * (which should cause a fatal error) and introducing major problems.
  186820. */
  186821. png_voidp PNGAPI
  186822. png_malloc(png_structp png_ptr, png_uint_32 size)
  186823. {
  186824. png_voidp ret;
  186825. if (png_ptr == NULL || size == 0)
  186826. return (NULL);
  186827. #ifdef PNG_USER_MEM_SUPPORTED
  186828. if(png_ptr->malloc_fn != NULL)
  186829. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186830. else
  186831. ret = (png_malloc_default(png_ptr, size));
  186832. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186833. png_error(png_ptr, "Out of memory!");
  186834. return (ret);
  186835. }
  186836. png_voidp PNGAPI
  186837. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186838. {
  186839. png_voidp ret;
  186840. #endif /* PNG_USER_MEM_SUPPORTED */
  186841. if (png_ptr == NULL || size == 0)
  186842. return (NULL);
  186843. #ifdef PNG_MAX_MALLOC_64K
  186844. if (size > (png_uint_32)65536L)
  186845. {
  186846. png_warning(png_ptr, "Cannot Allocate > 64K");
  186847. ret = NULL;
  186848. }
  186849. else
  186850. #endif
  186851. if (size != (size_t)size)
  186852. ret = NULL;
  186853. else if (size == (png_uint_32)65536L)
  186854. {
  186855. if (png_ptr->offset_table == NULL)
  186856. {
  186857. /* try to see if we need to do any of this fancy stuff */
  186858. ret = farmalloc(size);
  186859. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186860. {
  186861. int num_blocks;
  186862. png_uint_32 total_size;
  186863. png_bytep table;
  186864. int i;
  186865. png_byte huge * hptr;
  186866. if (ret != NULL)
  186867. {
  186868. farfree(ret);
  186869. ret = NULL;
  186870. }
  186871. if(png_ptr->zlib_window_bits > 14)
  186872. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186873. else
  186874. num_blocks = 1;
  186875. if (png_ptr->zlib_mem_level >= 7)
  186876. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186877. else
  186878. num_blocks++;
  186879. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186880. table = farmalloc(total_size);
  186881. if (table == NULL)
  186882. {
  186883. #ifndef PNG_USER_MEM_SUPPORTED
  186884. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186885. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186886. else
  186887. png_warning(png_ptr, "Out Of Memory.");
  186888. #endif
  186889. return (NULL);
  186890. }
  186891. if ((png_size_t)table & 0xfff0)
  186892. {
  186893. #ifndef PNG_USER_MEM_SUPPORTED
  186894. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186895. png_error(png_ptr,
  186896. "Farmalloc didn't return normalized pointer");
  186897. else
  186898. png_warning(png_ptr,
  186899. "Farmalloc didn't return normalized pointer");
  186900. #endif
  186901. return (NULL);
  186902. }
  186903. png_ptr->offset_table = table;
  186904. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186905. png_sizeof (png_bytep));
  186906. if (png_ptr->offset_table_ptr == NULL)
  186907. {
  186908. #ifndef PNG_USER_MEM_SUPPORTED
  186909. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186910. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186911. else
  186912. png_warning(png_ptr, "Out Of memory.");
  186913. #endif
  186914. return (NULL);
  186915. }
  186916. hptr = (png_byte huge *)table;
  186917. if ((png_size_t)hptr & 0xf)
  186918. {
  186919. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186920. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186921. }
  186922. for (i = 0; i < num_blocks; i++)
  186923. {
  186924. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186925. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186926. }
  186927. png_ptr->offset_table_number = num_blocks;
  186928. png_ptr->offset_table_count = 0;
  186929. png_ptr->offset_table_count_free = 0;
  186930. }
  186931. }
  186932. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186933. {
  186934. #ifndef PNG_USER_MEM_SUPPORTED
  186935. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186936. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186937. else
  186938. png_warning(png_ptr, "Out of Memory.");
  186939. #endif
  186940. return (NULL);
  186941. }
  186942. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186943. }
  186944. else
  186945. ret = farmalloc(size);
  186946. #ifndef PNG_USER_MEM_SUPPORTED
  186947. if (ret == NULL)
  186948. {
  186949. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186950. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186951. else
  186952. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186953. }
  186954. #endif
  186955. return (ret);
  186956. }
  186957. /* free a pointer allocated by png_malloc(). In the default
  186958. configuration, png_ptr is not used, but is passed in case it
  186959. is needed. If ptr is NULL, return without taking any action. */
  186960. void PNGAPI
  186961. png_free(png_structp png_ptr, png_voidp ptr)
  186962. {
  186963. if (png_ptr == NULL || ptr == NULL)
  186964. return;
  186965. #ifdef PNG_USER_MEM_SUPPORTED
  186966. if (png_ptr->free_fn != NULL)
  186967. {
  186968. (*(png_ptr->free_fn))(png_ptr, ptr);
  186969. return;
  186970. }
  186971. else png_free_default(png_ptr, ptr);
  186972. }
  186973. void PNGAPI
  186974. png_free_default(png_structp png_ptr, png_voidp ptr)
  186975. {
  186976. #endif /* PNG_USER_MEM_SUPPORTED */
  186977. if(png_ptr == NULL) return;
  186978. if (png_ptr->offset_table != NULL)
  186979. {
  186980. int i;
  186981. for (i = 0; i < png_ptr->offset_table_count; i++)
  186982. {
  186983. if (ptr == png_ptr->offset_table_ptr[i])
  186984. {
  186985. ptr = NULL;
  186986. png_ptr->offset_table_count_free++;
  186987. break;
  186988. }
  186989. }
  186990. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186991. {
  186992. farfree(png_ptr->offset_table);
  186993. farfree(png_ptr->offset_table_ptr);
  186994. png_ptr->offset_table = NULL;
  186995. png_ptr->offset_table_ptr = NULL;
  186996. }
  186997. }
  186998. if (ptr != NULL)
  186999. {
  187000. farfree(ptr);
  187001. }
  187002. }
  187003. #else /* Not the Borland DOS special memory handler */
  187004. /* Allocate memory for a png_struct or a png_info. The malloc and
  187005. memset can be replaced by a single call to calloc() if this is thought
  187006. to improve performance noticably. */
  187007. png_voidp /* PRIVATE */
  187008. png_create_struct(int type)
  187009. {
  187010. #ifdef PNG_USER_MEM_SUPPORTED
  187011. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  187012. }
  187013. /* Allocate memory for a png_struct or a png_info. The malloc and
  187014. memset can be replaced by a single call to calloc() if this is thought
  187015. to improve performance noticably. */
  187016. png_voidp /* PRIVATE */
  187017. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  187018. {
  187019. #endif /* PNG_USER_MEM_SUPPORTED */
  187020. png_size_t size;
  187021. png_voidp struct_ptr;
  187022. if (type == PNG_STRUCT_INFO)
  187023. size = png_sizeof(png_info);
  187024. else if (type == PNG_STRUCT_PNG)
  187025. size = png_sizeof(png_struct);
  187026. else
  187027. return (NULL);
  187028. #ifdef PNG_USER_MEM_SUPPORTED
  187029. if(malloc_fn != NULL)
  187030. {
  187031. png_struct dummy_struct;
  187032. png_structp png_ptr = &dummy_struct;
  187033. png_ptr->mem_ptr=mem_ptr;
  187034. struct_ptr = (*(malloc_fn))(png_ptr, size);
  187035. if (struct_ptr != NULL)
  187036. png_memset(struct_ptr, 0, size);
  187037. return (struct_ptr);
  187038. }
  187039. #endif /* PNG_USER_MEM_SUPPORTED */
  187040. #if defined(__TURBOC__) && !defined(__FLAT__)
  187041. struct_ptr = (png_voidp)farmalloc(size);
  187042. #else
  187043. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187044. struct_ptr = (png_voidp)halloc(size,1);
  187045. # else
  187046. struct_ptr = (png_voidp)malloc(size);
  187047. # endif
  187048. #endif
  187049. if (struct_ptr != NULL)
  187050. png_memset(struct_ptr, 0, size);
  187051. return (struct_ptr);
  187052. }
  187053. /* Free memory allocated by a png_create_struct() call */
  187054. void /* PRIVATE */
  187055. png_destroy_struct(png_voidp struct_ptr)
  187056. {
  187057. #ifdef PNG_USER_MEM_SUPPORTED
  187058. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  187059. }
  187060. /* Free memory allocated by a png_create_struct() call */
  187061. void /* PRIVATE */
  187062. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  187063. png_voidp mem_ptr)
  187064. {
  187065. #endif /* PNG_USER_MEM_SUPPORTED */
  187066. if (struct_ptr != NULL)
  187067. {
  187068. #ifdef PNG_USER_MEM_SUPPORTED
  187069. if(free_fn != NULL)
  187070. {
  187071. png_struct dummy_struct;
  187072. png_structp png_ptr = &dummy_struct;
  187073. png_ptr->mem_ptr=mem_ptr;
  187074. (*(free_fn))(png_ptr, struct_ptr);
  187075. return;
  187076. }
  187077. #endif /* PNG_USER_MEM_SUPPORTED */
  187078. #if defined(__TURBOC__) && !defined(__FLAT__)
  187079. farfree(struct_ptr);
  187080. #else
  187081. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187082. hfree(struct_ptr);
  187083. # else
  187084. free(struct_ptr);
  187085. # endif
  187086. #endif
  187087. }
  187088. }
  187089. /* Allocate memory. For reasonable files, size should never exceed
  187090. 64K. However, zlib may allocate more then 64K if you don't tell
  187091. it not to. See zconf.h and png.h for more information. zlib does
  187092. need to allocate exactly 64K, so whatever you call here must
  187093. have the ability to do that. */
  187094. png_voidp PNGAPI
  187095. png_malloc(png_structp png_ptr, png_uint_32 size)
  187096. {
  187097. png_voidp ret;
  187098. #ifdef PNG_USER_MEM_SUPPORTED
  187099. if (png_ptr == NULL || size == 0)
  187100. return (NULL);
  187101. if(png_ptr->malloc_fn != NULL)
  187102. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  187103. else
  187104. ret = (png_malloc_default(png_ptr, size));
  187105. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187106. png_error(png_ptr, "Out of Memory!");
  187107. return (ret);
  187108. }
  187109. png_voidp PNGAPI
  187110. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  187111. {
  187112. png_voidp ret;
  187113. #endif /* PNG_USER_MEM_SUPPORTED */
  187114. if (png_ptr == NULL || size == 0)
  187115. return (NULL);
  187116. #ifdef PNG_MAX_MALLOC_64K
  187117. if (size > (png_uint_32)65536L)
  187118. {
  187119. #ifndef PNG_USER_MEM_SUPPORTED
  187120. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187121. png_error(png_ptr, "Cannot Allocate > 64K");
  187122. else
  187123. #endif
  187124. return NULL;
  187125. }
  187126. #endif
  187127. /* Check for overflow */
  187128. #if defined(__TURBOC__) && !defined(__FLAT__)
  187129. if (size != (unsigned long)size)
  187130. ret = NULL;
  187131. else
  187132. ret = farmalloc(size);
  187133. #else
  187134. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187135. if (size != (unsigned long)size)
  187136. ret = NULL;
  187137. else
  187138. ret = halloc(size, 1);
  187139. # else
  187140. if (size != (size_t)size)
  187141. ret = NULL;
  187142. else
  187143. ret = malloc((size_t)size);
  187144. # endif
  187145. #endif
  187146. #ifndef PNG_USER_MEM_SUPPORTED
  187147. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187148. png_error(png_ptr, "Out of Memory");
  187149. #endif
  187150. return (ret);
  187151. }
  187152. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  187153. without taking any action. */
  187154. void PNGAPI
  187155. png_free(png_structp png_ptr, png_voidp ptr)
  187156. {
  187157. if (png_ptr == NULL || ptr == NULL)
  187158. return;
  187159. #ifdef PNG_USER_MEM_SUPPORTED
  187160. if (png_ptr->free_fn != NULL)
  187161. {
  187162. (*(png_ptr->free_fn))(png_ptr, ptr);
  187163. return;
  187164. }
  187165. else png_free_default(png_ptr, ptr);
  187166. }
  187167. void PNGAPI
  187168. png_free_default(png_structp png_ptr, png_voidp ptr)
  187169. {
  187170. if (png_ptr == NULL || ptr == NULL)
  187171. return;
  187172. #endif /* PNG_USER_MEM_SUPPORTED */
  187173. #if defined(__TURBOC__) && !defined(__FLAT__)
  187174. farfree(ptr);
  187175. #else
  187176. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187177. hfree(ptr);
  187178. # else
  187179. free(ptr);
  187180. # endif
  187181. #endif
  187182. }
  187183. #endif /* Not Borland DOS special memory handler */
  187184. #if defined(PNG_1_0_X)
  187185. # define png_malloc_warn png_malloc
  187186. #else
  187187. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  187188. * function will set up png_malloc() to issue a png_warning and return NULL
  187189. * instead of issuing a png_error, if it fails to allocate the requested
  187190. * memory.
  187191. */
  187192. png_voidp PNGAPI
  187193. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  187194. {
  187195. png_voidp ptr;
  187196. png_uint_32 save_flags;
  187197. if(png_ptr == NULL) return (NULL);
  187198. save_flags=png_ptr->flags;
  187199. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187200. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187201. png_ptr->flags=save_flags;
  187202. return(ptr);
  187203. }
  187204. #endif
  187205. png_voidp PNGAPI
  187206. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187207. png_uint_32 length)
  187208. {
  187209. png_size_t size;
  187210. size = (png_size_t)length;
  187211. if ((png_uint_32)size != length)
  187212. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187213. return(png_memcpy (s1, s2, size));
  187214. }
  187215. png_voidp PNGAPI
  187216. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187217. png_uint_32 length)
  187218. {
  187219. png_size_t size;
  187220. size = (png_size_t)length;
  187221. if ((png_uint_32)size != length)
  187222. png_error(png_ptr,"Overflow in png_memset_check.");
  187223. return (png_memset (s1, value, size));
  187224. }
  187225. #ifdef PNG_USER_MEM_SUPPORTED
  187226. /* This function is called when the application wants to use another method
  187227. * of allocating and freeing memory.
  187228. */
  187229. void PNGAPI
  187230. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187231. malloc_fn, png_free_ptr free_fn)
  187232. {
  187233. if(png_ptr != NULL) {
  187234. png_ptr->mem_ptr = mem_ptr;
  187235. png_ptr->malloc_fn = malloc_fn;
  187236. png_ptr->free_fn = free_fn;
  187237. }
  187238. }
  187239. /* This function returns a pointer to the mem_ptr associated with the user
  187240. * functions. The application should free any memory associated with this
  187241. * pointer before png_write_destroy and png_read_destroy are called.
  187242. */
  187243. png_voidp PNGAPI
  187244. png_get_mem_ptr(png_structp png_ptr)
  187245. {
  187246. if(png_ptr == NULL) return (NULL);
  187247. return ((png_voidp)png_ptr->mem_ptr);
  187248. }
  187249. #endif /* PNG_USER_MEM_SUPPORTED */
  187250. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187251. /*** End of inlined file: pngmem.c ***/
  187252. /*** Start of inlined file: pngread.c ***/
  187253. /* pngread.c - read a PNG file
  187254. *
  187255. * Last changed in libpng 1.2.20 September 7, 2007
  187256. * For conditions of distribution and use, see copyright notice in png.h
  187257. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187258. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187259. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187260. *
  187261. * This file contains routines that an application calls directly to
  187262. * read a PNG file or stream.
  187263. */
  187264. #define PNG_INTERNAL
  187265. #if defined(PNG_READ_SUPPORTED)
  187266. /* Create a PNG structure for reading, and allocate any memory needed. */
  187267. png_structp PNGAPI
  187268. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187269. png_error_ptr error_fn, png_error_ptr warn_fn)
  187270. {
  187271. #ifdef PNG_USER_MEM_SUPPORTED
  187272. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187273. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187274. }
  187275. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187276. png_structp PNGAPI
  187277. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187278. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187279. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187280. {
  187281. #endif /* PNG_USER_MEM_SUPPORTED */
  187282. png_structp png_ptr;
  187283. #ifdef PNG_SETJMP_SUPPORTED
  187284. #ifdef USE_FAR_KEYWORD
  187285. jmp_buf jmpbuf;
  187286. #endif
  187287. #endif
  187288. int i;
  187289. png_debug(1, "in png_create_read_struct\n");
  187290. #ifdef PNG_USER_MEM_SUPPORTED
  187291. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187292. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187293. #else
  187294. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187295. #endif
  187296. if (png_ptr == NULL)
  187297. return (NULL);
  187298. /* added at libpng-1.2.6 */
  187299. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187300. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187301. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187302. #endif
  187303. #ifdef PNG_SETJMP_SUPPORTED
  187304. #ifdef USE_FAR_KEYWORD
  187305. if (setjmp(jmpbuf))
  187306. #else
  187307. if (setjmp(png_ptr->jmpbuf))
  187308. #endif
  187309. {
  187310. png_free(png_ptr, png_ptr->zbuf);
  187311. png_ptr->zbuf=NULL;
  187312. #ifdef PNG_USER_MEM_SUPPORTED
  187313. png_destroy_struct_2((png_voidp)png_ptr,
  187314. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187315. #else
  187316. png_destroy_struct((png_voidp)png_ptr);
  187317. #endif
  187318. return (NULL);
  187319. }
  187320. #ifdef USE_FAR_KEYWORD
  187321. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187322. #endif
  187323. #endif
  187324. #ifdef PNG_USER_MEM_SUPPORTED
  187325. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187326. #endif
  187327. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187328. i=0;
  187329. do
  187330. {
  187331. if(user_png_ver[i] != png_libpng_ver[i])
  187332. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187333. } while (png_libpng_ver[i++]);
  187334. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187335. {
  187336. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187337. * we must recompile any applications that use any older library version.
  187338. * For versions after libpng 1.0, we will be compatible, so we need
  187339. * only check the first digit.
  187340. */
  187341. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187342. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187343. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187344. {
  187345. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187346. char msg[80];
  187347. if (user_png_ver)
  187348. {
  187349. png_snprintf(msg, 80,
  187350. "Application was compiled with png.h from libpng-%.20s",
  187351. user_png_ver);
  187352. png_warning(png_ptr, msg);
  187353. }
  187354. png_snprintf(msg, 80,
  187355. "Application is running with png.c from libpng-%.20s",
  187356. png_libpng_ver);
  187357. png_warning(png_ptr, msg);
  187358. #endif
  187359. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187360. png_ptr->flags=0;
  187361. #endif
  187362. png_error(png_ptr,
  187363. "Incompatible libpng version in application and library");
  187364. }
  187365. }
  187366. /* initialize zbuf - compression buffer */
  187367. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187368. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187369. (png_uint_32)png_ptr->zbuf_size);
  187370. png_ptr->zstream.zalloc = png_zalloc;
  187371. png_ptr->zstream.zfree = png_zfree;
  187372. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187373. switch (inflateInit(&png_ptr->zstream))
  187374. {
  187375. case Z_OK: /* Do nothing */ break;
  187376. case Z_MEM_ERROR:
  187377. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187378. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187379. default: png_error(png_ptr, "Unknown zlib error");
  187380. }
  187381. png_ptr->zstream.next_out = png_ptr->zbuf;
  187382. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187383. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187384. #ifdef PNG_SETJMP_SUPPORTED
  187385. /* Applications that neglect to set up their own setjmp() and then encounter
  187386. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187387. abort instead of returning. */
  187388. #ifdef USE_FAR_KEYWORD
  187389. if (setjmp(jmpbuf))
  187390. PNG_ABORT();
  187391. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187392. #else
  187393. if (setjmp(png_ptr->jmpbuf))
  187394. PNG_ABORT();
  187395. #endif
  187396. #endif
  187397. return (png_ptr);
  187398. }
  187399. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187400. /* Initialize PNG structure for reading, and allocate any memory needed.
  187401. This interface is deprecated in favour of the png_create_read_struct(),
  187402. and it will disappear as of libpng-1.3.0. */
  187403. #undef png_read_init
  187404. void PNGAPI
  187405. png_read_init(png_structp png_ptr)
  187406. {
  187407. /* We only come here via pre-1.0.7-compiled applications */
  187408. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187409. }
  187410. void PNGAPI
  187411. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187412. png_size_t png_struct_size, png_size_t png_info_size)
  187413. {
  187414. /* We only come here via pre-1.0.12-compiled applications */
  187415. if(png_ptr == NULL) return;
  187416. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187417. if(png_sizeof(png_struct) > png_struct_size ||
  187418. png_sizeof(png_info) > png_info_size)
  187419. {
  187420. char msg[80];
  187421. png_ptr->warning_fn=NULL;
  187422. if (user_png_ver)
  187423. {
  187424. png_snprintf(msg, 80,
  187425. "Application was compiled with png.h from libpng-%.20s",
  187426. user_png_ver);
  187427. png_warning(png_ptr, msg);
  187428. }
  187429. png_snprintf(msg, 80,
  187430. "Application is running with png.c from libpng-%.20s",
  187431. png_libpng_ver);
  187432. png_warning(png_ptr, msg);
  187433. }
  187434. #endif
  187435. if(png_sizeof(png_struct) > png_struct_size)
  187436. {
  187437. png_ptr->error_fn=NULL;
  187438. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187439. png_ptr->flags=0;
  187440. #endif
  187441. png_error(png_ptr,
  187442. "The png struct allocated by the application for reading is too small.");
  187443. }
  187444. if(png_sizeof(png_info) > png_info_size)
  187445. {
  187446. png_ptr->error_fn=NULL;
  187447. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187448. png_ptr->flags=0;
  187449. #endif
  187450. png_error(png_ptr,
  187451. "The info struct allocated by application for reading is too small.");
  187452. }
  187453. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187454. }
  187455. #endif /* PNG_1_0_X || PNG_1_2_X */
  187456. void PNGAPI
  187457. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187458. png_size_t png_struct_size)
  187459. {
  187460. #ifdef PNG_SETJMP_SUPPORTED
  187461. jmp_buf tmp_jmp; /* to save current jump buffer */
  187462. #endif
  187463. int i=0;
  187464. png_structp png_ptr=*ptr_ptr;
  187465. if(png_ptr == NULL) return;
  187466. do
  187467. {
  187468. if(user_png_ver[i] != png_libpng_ver[i])
  187469. {
  187470. #ifdef PNG_LEGACY_SUPPORTED
  187471. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187472. #else
  187473. png_ptr->warning_fn=NULL;
  187474. png_warning(png_ptr,
  187475. "Application uses deprecated png_read_init() and should be recompiled.");
  187476. break;
  187477. #endif
  187478. }
  187479. } while (png_libpng_ver[i++]);
  187480. png_debug(1, "in png_read_init_3\n");
  187481. #ifdef PNG_SETJMP_SUPPORTED
  187482. /* save jump buffer and error functions */
  187483. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187484. #endif
  187485. if(png_sizeof(png_struct) > png_struct_size)
  187486. {
  187487. png_destroy_struct(png_ptr);
  187488. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187489. png_ptr = *ptr_ptr;
  187490. }
  187491. /* reset all variables to 0 */
  187492. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187493. #ifdef PNG_SETJMP_SUPPORTED
  187494. /* restore jump buffer */
  187495. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187496. #endif
  187497. /* added at libpng-1.2.6 */
  187498. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187499. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187500. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187501. #endif
  187502. /* initialize zbuf - compression buffer */
  187503. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187504. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187505. (png_uint_32)png_ptr->zbuf_size);
  187506. png_ptr->zstream.zalloc = png_zalloc;
  187507. png_ptr->zstream.zfree = png_zfree;
  187508. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187509. switch (inflateInit(&png_ptr->zstream))
  187510. {
  187511. case Z_OK: /* Do nothing */ break;
  187512. case Z_MEM_ERROR:
  187513. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187514. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187515. default: png_error(png_ptr, "Unknown zlib error");
  187516. }
  187517. png_ptr->zstream.next_out = png_ptr->zbuf;
  187518. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187519. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187520. }
  187521. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187522. /* Read the information before the actual image data. This has been
  187523. * changed in v0.90 to allow reading a file that already has the magic
  187524. * bytes read from the stream. You can tell libpng how many bytes have
  187525. * been read from the beginning of the stream (up to the maximum of 8)
  187526. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187527. * here. The application can then have access to the signature bytes we
  187528. * read if it is determined that this isn't a valid PNG file.
  187529. */
  187530. void PNGAPI
  187531. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187532. {
  187533. if(png_ptr == NULL) return;
  187534. png_debug(1, "in png_read_info\n");
  187535. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187536. if (png_ptr->sig_bytes < 8)
  187537. {
  187538. png_size_t num_checked = png_ptr->sig_bytes,
  187539. num_to_check = 8 - num_checked;
  187540. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187541. png_ptr->sig_bytes = 8;
  187542. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187543. {
  187544. if (num_checked < 4 &&
  187545. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187546. png_error(png_ptr, "Not a PNG file");
  187547. else
  187548. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187549. }
  187550. if (num_checked < 3)
  187551. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187552. }
  187553. for(;;)
  187554. {
  187555. #ifdef PNG_USE_LOCAL_ARRAYS
  187556. PNG_CONST PNG_IHDR;
  187557. PNG_CONST PNG_IDAT;
  187558. PNG_CONST PNG_IEND;
  187559. PNG_CONST PNG_PLTE;
  187560. #if defined(PNG_READ_bKGD_SUPPORTED)
  187561. PNG_CONST PNG_bKGD;
  187562. #endif
  187563. #if defined(PNG_READ_cHRM_SUPPORTED)
  187564. PNG_CONST PNG_cHRM;
  187565. #endif
  187566. #if defined(PNG_READ_gAMA_SUPPORTED)
  187567. PNG_CONST PNG_gAMA;
  187568. #endif
  187569. #if defined(PNG_READ_hIST_SUPPORTED)
  187570. PNG_CONST PNG_hIST;
  187571. #endif
  187572. #if defined(PNG_READ_iCCP_SUPPORTED)
  187573. PNG_CONST PNG_iCCP;
  187574. #endif
  187575. #if defined(PNG_READ_iTXt_SUPPORTED)
  187576. PNG_CONST PNG_iTXt;
  187577. #endif
  187578. #if defined(PNG_READ_oFFs_SUPPORTED)
  187579. PNG_CONST PNG_oFFs;
  187580. #endif
  187581. #if defined(PNG_READ_pCAL_SUPPORTED)
  187582. PNG_CONST PNG_pCAL;
  187583. #endif
  187584. #if defined(PNG_READ_pHYs_SUPPORTED)
  187585. PNG_CONST PNG_pHYs;
  187586. #endif
  187587. #if defined(PNG_READ_sBIT_SUPPORTED)
  187588. PNG_CONST PNG_sBIT;
  187589. #endif
  187590. #if defined(PNG_READ_sCAL_SUPPORTED)
  187591. PNG_CONST PNG_sCAL;
  187592. #endif
  187593. #if defined(PNG_READ_sPLT_SUPPORTED)
  187594. PNG_CONST PNG_sPLT;
  187595. #endif
  187596. #if defined(PNG_READ_sRGB_SUPPORTED)
  187597. PNG_CONST PNG_sRGB;
  187598. #endif
  187599. #if defined(PNG_READ_tEXt_SUPPORTED)
  187600. PNG_CONST PNG_tEXt;
  187601. #endif
  187602. #if defined(PNG_READ_tIME_SUPPORTED)
  187603. PNG_CONST PNG_tIME;
  187604. #endif
  187605. #if defined(PNG_READ_tRNS_SUPPORTED)
  187606. PNG_CONST PNG_tRNS;
  187607. #endif
  187608. #if defined(PNG_READ_zTXt_SUPPORTED)
  187609. PNG_CONST PNG_zTXt;
  187610. #endif
  187611. #endif /* PNG_USE_LOCAL_ARRAYS */
  187612. png_byte chunk_length[4];
  187613. png_uint_32 length;
  187614. png_read_data(png_ptr, chunk_length, 4);
  187615. length = png_get_uint_31(png_ptr,chunk_length);
  187616. png_reset_crc(png_ptr);
  187617. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187618. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187619. length);
  187620. /* This should be a binary subdivision search or a hash for
  187621. * matching the chunk name rather than a linear search.
  187622. */
  187623. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187624. if(png_ptr->mode & PNG_AFTER_IDAT)
  187625. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187626. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187627. png_handle_IHDR(png_ptr, info_ptr, length);
  187628. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187629. png_handle_IEND(png_ptr, info_ptr, length);
  187630. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187631. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187632. {
  187633. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187634. png_ptr->mode |= PNG_HAVE_IDAT;
  187635. png_handle_unknown(png_ptr, info_ptr, length);
  187636. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187637. png_ptr->mode |= PNG_HAVE_PLTE;
  187638. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187639. {
  187640. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187641. png_error(png_ptr, "Missing IHDR before IDAT");
  187642. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187643. !(png_ptr->mode & PNG_HAVE_PLTE))
  187644. png_error(png_ptr, "Missing PLTE before IDAT");
  187645. break;
  187646. }
  187647. }
  187648. #endif
  187649. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187650. png_handle_PLTE(png_ptr, info_ptr, length);
  187651. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187652. {
  187653. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187654. png_error(png_ptr, "Missing IHDR before IDAT");
  187655. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187656. !(png_ptr->mode & PNG_HAVE_PLTE))
  187657. png_error(png_ptr, "Missing PLTE before IDAT");
  187658. png_ptr->idat_size = length;
  187659. png_ptr->mode |= PNG_HAVE_IDAT;
  187660. break;
  187661. }
  187662. #if defined(PNG_READ_bKGD_SUPPORTED)
  187663. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187664. png_handle_bKGD(png_ptr, info_ptr, length);
  187665. #endif
  187666. #if defined(PNG_READ_cHRM_SUPPORTED)
  187667. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187668. png_handle_cHRM(png_ptr, info_ptr, length);
  187669. #endif
  187670. #if defined(PNG_READ_gAMA_SUPPORTED)
  187671. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187672. png_handle_gAMA(png_ptr, info_ptr, length);
  187673. #endif
  187674. #if defined(PNG_READ_hIST_SUPPORTED)
  187675. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187676. png_handle_hIST(png_ptr, info_ptr, length);
  187677. #endif
  187678. #if defined(PNG_READ_oFFs_SUPPORTED)
  187679. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187680. png_handle_oFFs(png_ptr, info_ptr, length);
  187681. #endif
  187682. #if defined(PNG_READ_pCAL_SUPPORTED)
  187683. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187684. png_handle_pCAL(png_ptr, info_ptr, length);
  187685. #endif
  187686. #if defined(PNG_READ_sCAL_SUPPORTED)
  187687. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187688. png_handle_sCAL(png_ptr, info_ptr, length);
  187689. #endif
  187690. #if defined(PNG_READ_pHYs_SUPPORTED)
  187691. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187692. png_handle_pHYs(png_ptr, info_ptr, length);
  187693. #endif
  187694. #if defined(PNG_READ_sBIT_SUPPORTED)
  187695. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187696. png_handle_sBIT(png_ptr, info_ptr, length);
  187697. #endif
  187698. #if defined(PNG_READ_sRGB_SUPPORTED)
  187699. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187700. png_handle_sRGB(png_ptr, info_ptr, length);
  187701. #endif
  187702. #if defined(PNG_READ_iCCP_SUPPORTED)
  187703. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187704. png_handle_iCCP(png_ptr, info_ptr, length);
  187705. #endif
  187706. #if defined(PNG_READ_sPLT_SUPPORTED)
  187707. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187708. png_handle_sPLT(png_ptr, info_ptr, length);
  187709. #endif
  187710. #if defined(PNG_READ_tEXt_SUPPORTED)
  187711. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187712. png_handle_tEXt(png_ptr, info_ptr, length);
  187713. #endif
  187714. #if defined(PNG_READ_tIME_SUPPORTED)
  187715. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187716. png_handle_tIME(png_ptr, info_ptr, length);
  187717. #endif
  187718. #if defined(PNG_READ_tRNS_SUPPORTED)
  187719. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187720. png_handle_tRNS(png_ptr, info_ptr, length);
  187721. #endif
  187722. #if defined(PNG_READ_zTXt_SUPPORTED)
  187723. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187724. png_handle_zTXt(png_ptr, info_ptr, length);
  187725. #endif
  187726. #if defined(PNG_READ_iTXt_SUPPORTED)
  187727. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187728. png_handle_iTXt(png_ptr, info_ptr, length);
  187729. #endif
  187730. else
  187731. png_handle_unknown(png_ptr, info_ptr, length);
  187732. }
  187733. }
  187734. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187735. /* optional call to update the users info_ptr structure */
  187736. void PNGAPI
  187737. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187738. {
  187739. png_debug(1, "in png_read_update_info\n");
  187740. if(png_ptr == NULL) return;
  187741. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187742. png_read_start_row(png_ptr);
  187743. else
  187744. png_warning(png_ptr,
  187745. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187746. png_read_transform_info(png_ptr, info_ptr);
  187747. }
  187748. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187749. /* Initialize palette, background, etc, after transformations
  187750. * are set, but before any reading takes place. This allows
  187751. * the user to obtain a gamma-corrected palette, for example.
  187752. * If the user doesn't call this, we will do it ourselves.
  187753. */
  187754. void PNGAPI
  187755. png_start_read_image(png_structp png_ptr)
  187756. {
  187757. png_debug(1, "in png_start_read_image\n");
  187758. if(png_ptr == NULL) return;
  187759. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187760. png_read_start_row(png_ptr);
  187761. }
  187762. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187763. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187764. void PNGAPI
  187765. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187766. {
  187767. #ifdef PNG_USE_LOCAL_ARRAYS
  187768. PNG_CONST PNG_IDAT;
  187769. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187770. 0xff};
  187771. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187772. #endif
  187773. int ret;
  187774. if(png_ptr == NULL) return;
  187775. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187776. png_ptr->row_number, png_ptr->pass);
  187777. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187778. png_read_start_row(png_ptr);
  187779. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187780. {
  187781. /* check for transforms that have been set but were defined out */
  187782. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187783. if (png_ptr->transformations & PNG_INVERT_MONO)
  187784. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187785. #endif
  187786. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187787. if (png_ptr->transformations & PNG_FILLER)
  187788. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187789. #endif
  187790. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187791. if (png_ptr->transformations & PNG_PACKSWAP)
  187792. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187793. #endif
  187794. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187795. if (png_ptr->transformations & PNG_PACK)
  187796. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187797. #endif
  187798. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187799. if (png_ptr->transformations & PNG_SHIFT)
  187800. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187801. #endif
  187802. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187803. if (png_ptr->transformations & PNG_BGR)
  187804. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187805. #endif
  187806. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187807. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187808. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187809. #endif
  187810. }
  187811. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187812. /* if interlaced and we do not need a new row, combine row and return */
  187813. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187814. {
  187815. switch (png_ptr->pass)
  187816. {
  187817. case 0:
  187818. if (png_ptr->row_number & 0x07)
  187819. {
  187820. if (dsp_row != NULL)
  187821. png_combine_row(png_ptr, dsp_row,
  187822. png_pass_dsp_mask[png_ptr->pass]);
  187823. png_read_finish_row(png_ptr);
  187824. return;
  187825. }
  187826. break;
  187827. case 1:
  187828. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187829. {
  187830. if (dsp_row != NULL)
  187831. png_combine_row(png_ptr, dsp_row,
  187832. png_pass_dsp_mask[png_ptr->pass]);
  187833. png_read_finish_row(png_ptr);
  187834. return;
  187835. }
  187836. break;
  187837. case 2:
  187838. if ((png_ptr->row_number & 0x07) != 4)
  187839. {
  187840. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187841. png_combine_row(png_ptr, dsp_row,
  187842. png_pass_dsp_mask[png_ptr->pass]);
  187843. png_read_finish_row(png_ptr);
  187844. return;
  187845. }
  187846. break;
  187847. case 3:
  187848. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187849. {
  187850. if (dsp_row != NULL)
  187851. png_combine_row(png_ptr, dsp_row,
  187852. png_pass_dsp_mask[png_ptr->pass]);
  187853. png_read_finish_row(png_ptr);
  187854. return;
  187855. }
  187856. break;
  187857. case 4:
  187858. if ((png_ptr->row_number & 3) != 2)
  187859. {
  187860. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187861. png_combine_row(png_ptr, dsp_row,
  187862. png_pass_dsp_mask[png_ptr->pass]);
  187863. png_read_finish_row(png_ptr);
  187864. return;
  187865. }
  187866. break;
  187867. case 5:
  187868. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187869. {
  187870. if (dsp_row != NULL)
  187871. png_combine_row(png_ptr, dsp_row,
  187872. png_pass_dsp_mask[png_ptr->pass]);
  187873. png_read_finish_row(png_ptr);
  187874. return;
  187875. }
  187876. break;
  187877. case 6:
  187878. if (!(png_ptr->row_number & 1))
  187879. {
  187880. png_read_finish_row(png_ptr);
  187881. return;
  187882. }
  187883. break;
  187884. }
  187885. }
  187886. #endif
  187887. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187888. png_error(png_ptr, "Invalid attempt to read row data");
  187889. png_ptr->zstream.next_out = png_ptr->row_buf;
  187890. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187891. do
  187892. {
  187893. if (!(png_ptr->zstream.avail_in))
  187894. {
  187895. while (!png_ptr->idat_size)
  187896. {
  187897. png_byte chunk_length[4];
  187898. png_crc_finish(png_ptr, 0);
  187899. png_read_data(png_ptr, chunk_length, 4);
  187900. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187901. png_reset_crc(png_ptr);
  187902. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187903. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187904. png_error(png_ptr, "Not enough image data");
  187905. }
  187906. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187907. png_ptr->zstream.next_in = png_ptr->zbuf;
  187908. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187909. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187910. png_crc_read(png_ptr, png_ptr->zbuf,
  187911. (png_size_t)png_ptr->zstream.avail_in);
  187912. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187913. }
  187914. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187915. if (ret == Z_STREAM_END)
  187916. {
  187917. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187918. png_ptr->idat_size)
  187919. png_error(png_ptr, "Extra compressed data");
  187920. png_ptr->mode |= PNG_AFTER_IDAT;
  187921. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187922. break;
  187923. }
  187924. if (ret != Z_OK)
  187925. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187926. "Decompression error");
  187927. } while (png_ptr->zstream.avail_out);
  187928. png_ptr->row_info.color_type = png_ptr->color_type;
  187929. png_ptr->row_info.width = png_ptr->iwidth;
  187930. png_ptr->row_info.channels = png_ptr->channels;
  187931. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187932. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187933. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187934. png_ptr->row_info.width);
  187935. if(png_ptr->row_buf[0])
  187936. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187937. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187938. (int)(png_ptr->row_buf[0]));
  187939. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187940. png_ptr->rowbytes + 1);
  187941. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187942. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187943. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187944. {
  187945. /* Intrapixel differencing */
  187946. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187947. }
  187948. #endif
  187949. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187950. png_do_read_transformations(png_ptr);
  187951. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187952. /* blow up interlaced rows to full size */
  187953. if (png_ptr->interlaced &&
  187954. (png_ptr->transformations & PNG_INTERLACE))
  187955. {
  187956. if (png_ptr->pass < 6)
  187957. /* old interface (pre-1.0.9):
  187958. png_do_read_interlace(&(png_ptr->row_info),
  187959. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187960. */
  187961. png_do_read_interlace(png_ptr);
  187962. if (dsp_row != NULL)
  187963. png_combine_row(png_ptr, dsp_row,
  187964. png_pass_dsp_mask[png_ptr->pass]);
  187965. if (row != NULL)
  187966. png_combine_row(png_ptr, row,
  187967. png_pass_mask[png_ptr->pass]);
  187968. }
  187969. else
  187970. #endif
  187971. {
  187972. if (row != NULL)
  187973. png_combine_row(png_ptr, row, 0xff);
  187974. if (dsp_row != NULL)
  187975. png_combine_row(png_ptr, dsp_row, 0xff);
  187976. }
  187977. png_read_finish_row(png_ptr);
  187978. if (png_ptr->read_row_fn != NULL)
  187979. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187980. }
  187981. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187982. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187983. /* Read one or more rows of image data. If the image is interlaced,
  187984. * and png_set_interlace_handling() has been called, the rows need to
  187985. * contain the contents of the rows from the previous pass. If the
  187986. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187987. * called, the rows contents must be initialized to the contents of the
  187988. * screen.
  187989. *
  187990. * "row" holds the actual image, and pixels are placed in it
  187991. * as they arrive. If the image is displayed after each pass, it will
  187992. * appear to "sparkle" in. "display_row" can be used to display a
  187993. * "chunky" progressive image, with finer detail added as it becomes
  187994. * available. If you do not want this "chunky" display, you may pass
  187995. * NULL for display_row. If you do not want the sparkle display, and
  187996. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187997. * If you have called png_handle_alpha(), and the image has either an
  187998. * alpha channel or a transparency chunk, you must provide a buffer for
  187999. * rows. In this case, you do not have to provide a display_row buffer
  188000. * also, but you may. If the image is not interlaced, or if you have
  188001. * not called png_set_interlace_handling(), the display_row buffer will
  188002. * be ignored, so pass NULL to it.
  188003. *
  188004. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188005. */
  188006. void PNGAPI
  188007. png_read_rows(png_structp png_ptr, png_bytepp row,
  188008. png_bytepp display_row, png_uint_32 num_rows)
  188009. {
  188010. png_uint_32 i;
  188011. png_bytepp rp;
  188012. png_bytepp dp;
  188013. png_debug(1, "in png_read_rows\n");
  188014. if(png_ptr == NULL) return;
  188015. rp = row;
  188016. dp = display_row;
  188017. if (rp != NULL && dp != NULL)
  188018. for (i = 0; i < num_rows; i++)
  188019. {
  188020. png_bytep rptr = *rp++;
  188021. png_bytep dptr = *dp++;
  188022. png_read_row(png_ptr, rptr, dptr);
  188023. }
  188024. else if(rp != NULL)
  188025. for (i = 0; i < num_rows; i++)
  188026. {
  188027. png_bytep rptr = *rp;
  188028. png_read_row(png_ptr, rptr, png_bytep_NULL);
  188029. rp++;
  188030. }
  188031. else if(dp != NULL)
  188032. for (i = 0; i < num_rows; i++)
  188033. {
  188034. png_bytep dptr = *dp;
  188035. png_read_row(png_ptr, png_bytep_NULL, dptr);
  188036. dp++;
  188037. }
  188038. }
  188039. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188040. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188041. /* Read the entire image. If the image has an alpha channel or a tRNS
  188042. * chunk, and you have called png_handle_alpha()[*], you will need to
  188043. * initialize the image to the current image that PNG will be overlaying.
  188044. * We set the num_rows again here, in case it was incorrectly set in
  188045. * png_read_start_row() by a call to png_read_update_info() or
  188046. * png_start_read_image() if png_set_interlace_handling() wasn't called
  188047. * prior to either of these functions like it should have been. You can
  188048. * only call this function once. If you desire to have an image for
  188049. * each pass of a interlaced image, use png_read_rows() instead.
  188050. *
  188051. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188052. */
  188053. void PNGAPI
  188054. png_read_image(png_structp png_ptr, png_bytepp image)
  188055. {
  188056. png_uint_32 i,image_height;
  188057. int pass, j;
  188058. png_bytepp rp;
  188059. png_debug(1, "in png_read_image\n");
  188060. if(png_ptr == NULL) return;
  188061. #ifdef PNG_READ_INTERLACING_SUPPORTED
  188062. pass = png_set_interlace_handling(png_ptr);
  188063. #else
  188064. if (png_ptr->interlaced)
  188065. png_error(png_ptr,
  188066. "Cannot read interlaced image -- interlace handler disabled.");
  188067. pass = 1;
  188068. #endif
  188069. image_height=png_ptr->height;
  188070. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  188071. for (j = 0; j < pass; j++)
  188072. {
  188073. rp = image;
  188074. for (i = 0; i < image_height; i++)
  188075. {
  188076. png_read_row(png_ptr, *rp, png_bytep_NULL);
  188077. rp++;
  188078. }
  188079. }
  188080. }
  188081. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188082. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188083. /* Read the end of the PNG file. Will not read past the end of the
  188084. * file, will verify the end is accurate, and will read any comments
  188085. * or time information at the end of the file, if info is not NULL.
  188086. */
  188087. void PNGAPI
  188088. png_read_end(png_structp png_ptr, png_infop info_ptr)
  188089. {
  188090. png_byte chunk_length[4];
  188091. png_uint_32 length;
  188092. png_debug(1, "in png_read_end\n");
  188093. if(png_ptr == NULL) return;
  188094. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  188095. do
  188096. {
  188097. #ifdef PNG_USE_LOCAL_ARRAYS
  188098. PNG_CONST PNG_IHDR;
  188099. PNG_CONST PNG_IDAT;
  188100. PNG_CONST PNG_IEND;
  188101. PNG_CONST PNG_PLTE;
  188102. #if defined(PNG_READ_bKGD_SUPPORTED)
  188103. PNG_CONST PNG_bKGD;
  188104. #endif
  188105. #if defined(PNG_READ_cHRM_SUPPORTED)
  188106. PNG_CONST PNG_cHRM;
  188107. #endif
  188108. #if defined(PNG_READ_gAMA_SUPPORTED)
  188109. PNG_CONST PNG_gAMA;
  188110. #endif
  188111. #if defined(PNG_READ_hIST_SUPPORTED)
  188112. PNG_CONST PNG_hIST;
  188113. #endif
  188114. #if defined(PNG_READ_iCCP_SUPPORTED)
  188115. PNG_CONST PNG_iCCP;
  188116. #endif
  188117. #if defined(PNG_READ_iTXt_SUPPORTED)
  188118. PNG_CONST PNG_iTXt;
  188119. #endif
  188120. #if defined(PNG_READ_oFFs_SUPPORTED)
  188121. PNG_CONST PNG_oFFs;
  188122. #endif
  188123. #if defined(PNG_READ_pCAL_SUPPORTED)
  188124. PNG_CONST PNG_pCAL;
  188125. #endif
  188126. #if defined(PNG_READ_pHYs_SUPPORTED)
  188127. PNG_CONST PNG_pHYs;
  188128. #endif
  188129. #if defined(PNG_READ_sBIT_SUPPORTED)
  188130. PNG_CONST PNG_sBIT;
  188131. #endif
  188132. #if defined(PNG_READ_sCAL_SUPPORTED)
  188133. PNG_CONST PNG_sCAL;
  188134. #endif
  188135. #if defined(PNG_READ_sPLT_SUPPORTED)
  188136. PNG_CONST PNG_sPLT;
  188137. #endif
  188138. #if defined(PNG_READ_sRGB_SUPPORTED)
  188139. PNG_CONST PNG_sRGB;
  188140. #endif
  188141. #if defined(PNG_READ_tEXt_SUPPORTED)
  188142. PNG_CONST PNG_tEXt;
  188143. #endif
  188144. #if defined(PNG_READ_tIME_SUPPORTED)
  188145. PNG_CONST PNG_tIME;
  188146. #endif
  188147. #if defined(PNG_READ_tRNS_SUPPORTED)
  188148. PNG_CONST PNG_tRNS;
  188149. #endif
  188150. #if defined(PNG_READ_zTXt_SUPPORTED)
  188151. PNG_CONST PNG_zTXt;
  188152. #endif
  188153. #endif /* PNG_USE_LOCAL_ARRAYS */
  188154. png_read_data(png_ptr, chunk_length, 4);
  188155. length = png_get_uint_31(png_ptr,chunk_length);
  188156. png_reset_crc(png_ptr);
  188157. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188158. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  188159. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188160. png_handle_IHDR(png_ptr, info_ptr, length);
  188161. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188162. png_handle_IEND(png_ptr, info_ptr, length);
  188163. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188164. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188165. {
  188166. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188167. {
  188168. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188169. png_error(png_ptr, "Too many IDAT's found");
  188170. }
  188171. png_handle_unknown(png_ptr, info_ptr, length);
  188172. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188173. png_ptr->mode |= PNG_HAVE_PLTE;
  188174. }
  188175. #endif
  188176. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188177. {
  188178. /* Zero length IDATs are legal after the last IDAT has been
  188179. * read, but not after other chunks have been read.
  188180. */
  188181. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188182. png_error(png_ptr, "Too many IDAT's found");
  188183. png_crc_finish(png_ptr, length);
  188184. }
  188185. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188186. png_handle_PLTE(png_ptr, info_ptr, length);
  188187. #if defined(PNG_READ_bKGD_SUPPORTED)
  188188. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188189. png_handle_bKGD(png_ptr, info_ptr, length);
  188190. #endif
  188191. #if defined(PNG_READ_cHRM_SUPPORTED)
  188192. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188193. png_handle_cHRM(png_ptr, info_ptr, length);
  188194. #endif
  188195. #if defined(PNG_READ_gAMA_SUPPORTED)
  188196. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188197. png_handle_gAMA(png_ptr, info_ptr, length);
  188198. #endif
  188199. #if defined(PNG_READ_hIST_SUPPORTED)
  188200. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188201. png_handle_hIST(png_ptr, info_ptr, length);
  188202. #endif
  188203. #if defined(PNG_READ_oFFs_SUPPORTED)
  188204. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188205. png_handle_oFFs(png_ptr, info_ptr, length);
  188206. #endif
  188207. #if defined(PNG_READ_pCAL_SUPPORTED)
  188208. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188209. png_handle_pCAL(png_ptr, info_ptr, length);
  188210. #endif
  188211. #if defined(PNG_READ_sCAL_SUPPORTED)
  188212. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188213. png_handle_sCAL(png_ptr, info_ptr, length);
  188214. #endif
  188215. #if defined(PNG_READ_pHYs_SUPPORTED)
  188216. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188217. png_handle_pHYs(png_ptr, info_ptr, length);
  188218. #endif
  188219. #if defined(PNG_READ_sBIT_SUPPORTED)
  188220. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188221. png_handle_sBIT(png_ptr, info_ptr, length);
  188222. #endif
  188223. #if defined(PNG_READ_sRGB_SUPPORTED)
  188224. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188225. png_handle_sRGB(png_ptr, info_ptr, length);
  188226. #endif
  188227. #if defined(PNG_READ_iCCP_SUPPORTED)
  188228. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188229. png_handle_iCCP(png_ptr, info_ptr, length);
  188230. #endif
  188231. #if defined(PNG_READ_sPLT_SUPPORTED)
  188232. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188233. png_handle_sPLT(png_ptr, info_ptr, length);
  188234. #endif
  188235. #if defined(PNG_READ_tEXt_SUPPORTED)
  188236. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188237. png_handle_tEXt(png_ptr, info_ptr, length);
  188238. #endif
  188239. #if defined(PNG_READ_tIME_SUPPORTED)
  188240. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188241. png_handle_tIME(png_ptr, info_ptr, length);
  188242. #endif
  188243. #if defined(PNG_READ_tRNS_SUPPORTED)
  188244. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188245. png_handle_tRNS(png_ptr, info_ptr, length);
  188246. #endif
  188247. #if defined(PNG_READ_zTXt_SUPPORTED)
  188248. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188249. png_handle_zTXt(png_ptr, info_ptr, length);
  188250. #endif
  188251. #if defined(PNG_READ_iTXt_SUPPORTED)
  188252. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188253. png_handle_iTXt(png_ptr, info_ptr, length);
  188254. #endif
  188255. else
  188256. png_handle_unknown(png_ptr, info_ptr, length);
  188257. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188258. }
  188259. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188260. /* free all memory used by the read */
  188261. void PNGAPI
  188262. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188263. png_infopp end_info_ptr_ptr)
  188264. {
  188265. png_structp png_ptr = NULL;
  188266. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188267. #ifdef PNG_USER_MEM_SUPPORTED
  188268. png_free_ptr free_fn;
  188269. png_voidp mem_ptr;
  188270. #endif
  188271. png_debug(1, "in png_destroy_read_struct\n");
  188272. if (png_ptr_ptr != NULL)
  188273. png_ptr = *png_ptr_ptr;
  188274. if (info_ptr_ptr != NULL)
  188275. info_ptr = *info_ptr_ptr;
  188276. if (end_info_ptr_ptr != NULL)
  188277. end_info_ptr = *end_info_ptr_ptr;
  188278. #ifdef PNG_USER_MEM_SUPPORTED
  188279. free_fn = png_ptr->free_fn;
  188280. mem_ptr = png_ptr->mem_ptr;
  188281. #endif
  188282. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188283. if (info_ptr != NULL)
  188284. {
  188285. #if defined(PNG_TEXT_SUPPORTED)
  188286. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188287. #endif
  188288. #ifdef PNG_USER_MEM_SUPPORTED
  188289. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188290. (png_voidp)mem_ptr);
  188291. #else
  188292. png_destroy_struct((png_voidp)info_ptr);
  188293. #endif
  188294. *info_ptr_ptr = NULL;
  188295. }
  188296. if (end_info_ptr != NULL)
  188297. {
  188298. #if defined(PNG_READ_TEXT_SUPPORTED)
  188299. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188300. #endif
  188301. #ifdef PNG_USER_MEM_SUPPORTED
  188302. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188303. (png_voidp)mem_ptr);
  188304. #else
  188305. png_destroy_struct((png_voidp)end_info_ptr);
  188306. #endif
  188307. *end_info_ptr_ptr = NULL;
  188308. }
  188309. if (png_ptr != NULL)
  188310. {
  188311. #ifdef PNG_USER_MEM_SUPPORTED
  188312. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188313. (png_voidp)mem_ptr);
  188314. #else
  188315. png_destroy_struct((png_voidp)png_ptr);
  188316. #endif
  188317. *png_ptr_ptr = NULL;
  188318. }
  188319. }
  188320. /* free all memory used by the read (old method) */
  188321. void /* PRIVATE */
  188322. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188323. {
  188324. #ifdef PNG_SETJMP_SUPPORTED
  188325. jmp_buf tmp_jmp;
  188326. #endif
  188327. png_error_ptr error_fn;
  188328. png_error_ptr warning_fn;
  188329. png_voidp error_ptr;
  188330. #ifdef PNG_USER_MEM_SUPPORTED
  188331. png_free_ptr free_fn;
  188332. #endif
  188333. png_debug(1, "in png_read_destroy\n");
  188334. if (info_ptr != NULL)
  188335. png_info_destroy(png_ptr, info_ptr);
  188336. if (end_info_ptr != NULL)
  188337. png_info_destroy(png_ptr, end_info_ptr);
  188338. png_free(png_ptr, png_ptr->zbuf);
  188339. png_free(png_ptr, png_ptr->big_row_buf);
  188340. png_free(png_ptr, png_ptr->prev_row);
  188341. #if defined(PNG_READ_DITHER_SUPPORTED)
  188342. png_free(png_ptr, png_ptr->palette_lookup);
  188343. png_free(png_ptr, png_ptr->dither_index);
  188344. #endif
  188345. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188346. png_free(png_ptr, png_ptr->gamma_table);
  188347. #endif
  188348. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188349. png_free(png_ptr, png_ptr->gamma_from_1);
  188350. png_free(png_ptr, png_ptr->gamma_to_1);
  188351. #endif
  188352. #ifdef PNG_FREE_ME_SUPPORTED
  188353. if (png_ptr->free_me & PNG_FREE_PLTE)
  188354. png_zfree(png_ptr, png_ptr->palette);
  188355. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188356. #else
  188357. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188358. png_zfree(png_ptr, png_ptr->palette);
  188359. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188360. #endif
  188361. #if defined(PNG_tRNS_SUPPORTED) || \
  188362. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188363. #ifdef PNG_FREE_ME_SUPPORTED
  188364. if (png_ptr->free_me & PNG_FREE_TRNS)
  188365. png_free(png_ptr, png_ptr->trans);
  188366. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188367. #else
  188368. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188369. png_free(png_ptr, png_ptr->trans);
  188370. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188371. #endif
  188372. #endif
  188373. #if defined(PNG_READ_hIST_SUPPORTED)
  188374. #ifdef PNG_FREE_ME_SUPPORTED
  188375. if (png_ptr->free_me & PNG_FREE_HIST)
  188376. png_free(png_ptr, png_ptr->hist);
  188377. png_ptr->free_me &= ~PNG_FREE_HIST;
  188378. #else
  188379. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188380. png_free(png_ptr, png_ptr->hist);
  188381. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188382. #endif
  188383. #endif
  188384. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188385. if (png_ptr->gamma_16_table != NULL)
  188386. {
  188387. int i;
  188388. int istop = (1 << (8 - png_ptr->gamma_shift));
  188389. for (i = 0; i < istop; i++)
  188390. {
  188391. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188392. }
  188393. png_free(png_ptr, png_ptr->gamma_16_table);
  188394. }
  188395. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188396. if (png_ptr->gamma_16_from_1 != NULL)
  188397. {
  188398. int i;
  188399. int istop = (1 << (8 - png_ptr->gamma_shift));
  188400. for (i = 0; i < istop; i++)
  188401. {
  188402. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188403. }
  188404. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188405. }
  188406. if (png_ptr->gamma_16_to_1 != NULL)
  188407. {
  188408. int i;
  188409. int istop = (1 << (8 - png_ptr->gamma_shift));
  188410. for (i = 0; i < istop; i++)
  188411. {
  188412. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188413. }
  188414. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188415. }
  188416. #endif
  188417. #endif
  188418. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188419. png_free(png_ptr, png_ptr->time_buffer);
  188420. #endif
  188421. inflateEnd(&png_ptr->zstream);
  188422. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188423. png_free(png_ptr, png_ptr->save_buffer);
  188424. #endif
  188425. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188426. #ifdef PNG_TEXT_SUPPORTED
  188427. png_free(png_ptr, png_ptr->current_text);
  188428. #endif /* PNG_TEXT_SUPPORTED */
  188429. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188430. /* Save the important info out of the png_struct, in case it is
  188431. * being used again.
  188432. */
  188433. #ifdef PNG_SETJMP_SUPPORTED
  188434. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188435. #endif
  188436. error_fn = png_ptr->error_fn;
  188437. warning_fn = png_ptr->warning_fn;
  188438. error_ptr = png_ptr->error_ptr;
  188439. #ifdef PNG_USER_MEM_SUPPORTED
  188440. free_fn = png_ptr->free_fn;
  188441. #endif
  188442. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188443. png_ptr->error_fn = error_fn;
  188444. png_ptr->warning_fn = warning_fn;
  188445. png_ptr->error_ptr = error_ptr;
  188446. #ifdef PNG_USER_MEM_SUPPORTED
  188447. png_ptr->free_fn = free_fn;
  188448. #endif
  188449. #ifdef PNG_SETJMP_SUPPORTED
  188450. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188451. #endif
  188452. }
  188453. void PNGAPI
  188454. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188455. {
  188456. if(png_ptr == NULL) return;
  188457. png_ptr->read_row_fn = read_row_fn;
  188458. }
  188459. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188460. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188461. void PNGAPI
  188462. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188463. int transforms,
  188464. voidp params)
  188465. {
  188466. int row;
  188467. if(png_ptr == NULL) return;
  188468. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188469. /* invert the alpha channel from opacity to transparency
  188470. */
  188471. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188472. png_set_invert_alpha(png_ptr);
  188473. #endif
  188474. /* png_read_info() gives us all of the information from the
  188475. * PNG file before the first IDAT (image data chunk).
  188476. */
  188477. png_read_info(png_ptr, info_ptr);
  188478. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188479. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188480. /* -------------- image transformations start here ------------------- */
  188481. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188482. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188483. */
  188484. if (transforms & PNG_TRANSFORM_STRIP_16)
  188485. png_set_strip_16(png_ptr);
  188486. #endif
  188487. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188488. /* Strip alpha bytes from the input data without combining with
  188489. * the background (not recommended).
  188490. */
  188491. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188492. png_set_strip_alpha(png_ptr);
  188493. #endif
  188494. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188495. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188496. * byte into separate bytes (useful for paletted and grayscale images).
  188497. */
  188498. if (transforms & PNG_TRANSFORM_PACKING)
  188499. png_set_packing(png_ptr);
  188500. #endif
  188501. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188502. /* Change the order of packed pixels to least significant bit first
  188503. * (not useful if you are using png_set_packing).
  188504. */
  188505. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188506. png_set_packswap(png_ptr);
  188507. #endif
  188508. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188509. /* Expand paletted colors into true RGB triplets
  188510. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188511. * Expand paletted or RGB images with transparency to full alpha
  188512. * channels so the data will be available as RGBA quartets.
  188513. */
  188514. if (transforms & PNG_TRANSFORM_EXPAND)
  188515. if ((png_ptr->bit_depth < 8) ||
  188516. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188517. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188518. png_set_expand(png_ptr);
  188519. #endif
  188520. /* We don't handle background color or gamma transformation or dithering.
  188521. */
  188522. #if defined(PNG_READ_INVERT_SUPPORTED)
  188523. /* invert monochrome files to have 0 as white and 1 as black
  188524. */
  188525. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188526. png_set_invert_mono(png_ptr);
  188527. #endif
  188528. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188529. /* If you want to shift the pixel values from the range [0,255] or
  188530. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188531. * colors were originally in:
  188532. */
  188533. if ((transforms & PNG_TRANSFORM_SHIFT)
  188534. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188535. {
  188536. png_color_8p sig_bit;
  188537. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188538. png_set_shift(png_ptr, sig_bit);
  188539. }
  188540. #endif
  188541. #if defined(PNG_READ_BGR_SUPPORTED)
  188542. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188543. */
  188544. if (transforms & PNG_TRANSFORM_BGR)
  188545. png_set_bgr(png_ptr);
  188546. #endif
  188547. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188548. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188549. */
  188550. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188551. png_set_swap_alpha(png_ptr);
  188552. #endif
  188553. #if defined(PNG_READ_SWAP_SUPPORTED)
  188554. /* swap bytes of 16 bit files to least significant byte first
  188555. */
  188556. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188557. png_set_swap(png_ptr);
  188558. #endif
  188559. /* We don't handle adding filler bytes */
  188560. /* Optional call to gamma correct and add the background to the palette
  188561. * and update info structure. REQUIRED if you are expecting libpng to
  188562. * update the palette for you (i.e., you selected such a transform above).
  188563. */
  188564. png_read_update_info(png_ptr, info_ptr);
  188565. /* -------------- image transformations end here ------------------- */
  188566. #ifdef PNG_FREE_ME_SUPPORTED
  188567. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188568. #endif
  188569. if(info_ptr->row_pointers == NULL)
  188570. {
  188571. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188572. info_ptr->height * png_sizeof(png_bytep));
  188573. #ifdef PNG_FREE_ME_SUPPORTED
  188574. info_ptr->free_me |= PNG_FREE_ROWS;
  188575. #endif
  188576. for (row = 0; row < (int)info_ptr->height; row++)
  188577. {
  188578. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188579. png_get_rowbytes(png_ptr, info_ptr));
  188580. }
  188581. }
  188582. png_read_image(png_ptr, info_ptr->row_pointers);
  188583. info_ptr->valid |= PNG_INFO_IDAT;
  188584. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188585. png_read_end(png_ptr, info_ptr);
  188586. transforms = transforms; /* quiet compiler warnings */
  188587. params = params;
  188588. }
  188589. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188590. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188591. #endif /* PNG_READ_SUPPORTED */
  188592. /*** End of inlined file: pngread.c ***/
  188593. /*** Start of inlined file: pngpread.c ***/
  188594. /* pngpread.c - read a png file in push mode
  188595. *
  188596. * Last changed in libpng 1.2.21 October 4, 2007
  188597. * For conditions of distribution and use, see copyright notice in png.h
  188598. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188599. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188600. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188601. */
  188602. #define PNG_INTERNAL
  188603. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188604. /* push model modes */
  188605. #define PNG_READ_SIG_MODE 0
  188606. #define PNG_READ_CHUNK_MODE 1
  188607. #define PNG_READ_IDAT_MODE 2
  188608. #define PNG_SKIP_MODE 3
  188609. #define PNG_READ_tEXt_MODE 4
  188610. #define PNG_READ_zTXt_MODE 5
  188611. #define PNG_READ_DONE_MODE 6
  188612. #define PNG_READ_iTXt_MODE 7
  188613. #define PNG_ERROR_MODE 8
  188614. void PNGAPI
  188615. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188616. png_bytep buffer, png_size_t buffer_size)
  188617. {
  188618. if(png_ptr == NULL) return;
  188619. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188620. while (png_ptr->buffer_size)
  188621. {
  188622. png_process_some_data(png_ptr, info_ptr);
  188623. }
  188624. }
  188625. /* What we do with the incoming data depends on what we were previously
  188626. * doing before we ran out of data...
  188627. */
  188628. void /* PRIVATE */
  188629. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188630. {
  188631. if(png_ptr == NULL) return;
  188632. switch (png_ptr->process_mode)
  188633. {
  188634. case PNG_READ_SIG_MODE:
  188635. {
  188636. png_push_read_sig(png_ptr, info_ptr);
  188637. break;
  188638. }
  188639. case PNG_READ_CHUNK_MODE:
  188640. {
  188641. png_push_read_chunk(png_ptr, info_ptr);
  188642. break;
  188643. }
  188644. case PNG_READ_IDAT_MODE:
  188645. {
  188646. png_push_read_IDAT(png_ptr);
  188647. break;
  188648. }
  188649. #if defined(PNG_READ_tEXt_SUPPORTED)
  188650. case PNG_READ_tEXt_MODE:
  188651. {
  188652. png_push_read_tEXt(png_ptr, info_ptr);
  188653. break;
  188654. }
  188655. #endif
  188656. #if defined(PNG_READ_zTXt_SUPPORTED)
  188657. case PNG_READ_zTXt_MODE:
  188658. {
  188659. png_push_read_zTXt(png_ptr, info_ptr);
  188660. break;
  188661. }
  188662. #endif
  188663. #if defined(PNG_READ_iTXt_SUPPORTED)
  188664. case PNG_READ_iTXt_MODE:
  188665. {
  188666. png_push_read_iTXt(png_ptr, info_ptr);
  188667. break;
  188668. }
  188669. #endif
  188670. case PNG_SKIP_MODE:
  188671. {
  188672. png_push_crc_finish(png_ptr);
  188673. break;
  188674. }
  188675. default:
  188676. {
  188677. png_ptr->buffer_size = 0;
  188678. break;
  188679. }
  188680. }
  188681. }
  188682. /* Read any remaining signature bytes from the stream and compare them with
  188683. * the correct PNG signature. It is possible that this routine is called
  188684. * with bytes already read from the signature, either because they have been
  188685. * checked by the calling application, or because of multiple calls to this
  188686. * routine.
  188687. */
  188688. void /* PRIVATE */
  188689. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188690. {
  188691. png_size_t num_checked = png_ptr->sig_bytes,
  188692. num_to_check = 8 - num_checked;
  188693. if (png_ptr->buffer_size < num_to_check)
  188694. {
  188695. num_to_check = png_ptr->buffer_size;
  188696. }
  188697. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188698. num_to_check);
  188699. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188700. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188701. {
  188702. if (num_checked < 4 &&
  188703. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188704. png_error(png_ptr, "Not a PNG file");
  188705. else
  188706. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188707. }
  188708. else
  188709. {
  188710. if (png_ptr->sig_bytes >= 8)
  188711. {
  188712. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188713. }
  188714. }
  188715. }
  188716. void /* PRIVATE */
  188717. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188718. {
  188719. #ifdef PNG_USE_LOCAL_ARRAYS
  188720. PNG_CONST PNG_IHDR;
  188721. PNG_CONST PNG_IDAT;
  188722. PNG_CONST PNG_IEND;
  188723. PNG_CONST PNG_PLTE;
  188724. #if defined(PNG_READ_bKGD_SUPPORTED)
  188725. PNG_CONST PNG_bKGD;
  188726. #endif
  188727. #if defined(PNG_READ_cHRM_SUPPORTED)
  188728. PNG_CONST PNG_cHRM;
  188729. #endif
  188730. #if defined(PNG_READ_gAMA_SUPPORTED)
  188731. PNG_CONST PNG_gAMA;
  188732. #endif
  188733. #if defined(PNG_READ_hIST_SUPPORTED)
  188734. PNG_CONST PNG_hIST;
  188735. #endif
  188736. #if defined(PNG_READ_iCCP_SUPPORTED)
  188737. PNG_CONST PNG_iCCP;
  188738. #endif
  188739. #if defined(PNG_READ_iTXt_SUPPORTED)
  188740. PNG_CONST PNG_iTXt;
  188741. #endif
  188742. #if defined(PNG_READ_oFFs_SUPPORTED)
  188743. PNG_CONST PNG_oFFs;
  188744. #endif
  188745. #if defined(PNG_READ_pCAL_SUPPORTED)
  188746. PNG_CONST PNG_pCAL;
  188747. #endif
  188748. #if defined(PNG_READ_pHYs_SUPPORTED)
  188749. PNG_CONST PNG_pHYs;
  188750. #endif
  188751. #if defined(PNG_READ_sBIT_SUPPORTED)
  188752. PNG_CONST PNG_sBIT;
  188753. #endif
  188754. #if defined(PNG_READ_sCAL_SUPPORTED)
  188755. PNG_CONST PNG_sCAL;
  188756. #endif
  188757. #if defined(PNG_READ_sRGB_SUPPORTED)
  188758. PNG_CONST PNG_sRGB;
  188759. #endif
  188760. #if defined(PNG_READ_sPLT_SUPPORTED)
  188761. PNG_CONST PNG_sPLT;
  188762. #endif
  188763. #if defined(PNG_READ_tEXt_SUPPORTED)
  188764. PNG_CONST PNG_tEXt;
  188765. #endif
  188766. #if defined(PNG_READ_tIME_SUPPORTED)
  188767. PNG_CONST PNG_tIME;
  188768. #endif
  188769. #if defined(PNG_READ_tRNS_SUPPORTED)
  188770. PNG_CONST PNG_tRNS;
  188771. #endif
  188772. #if defined(PNG_READ_zTXt_SUPPORTED)
  188773. PNG_CONST PNG_zTXt;
  188774. #endif
  188775. #endif /* PNG_USE_LOCAL_ARRAYS */
  188776. /* First we make sure we have enough data for the 4 byte chunk name
  188777. * and the 4 byte chunk length before proceeding with decoding the
  188778. * chunk data. To fully decode each of these chunks, we also make
  188779. * sure we have enough data in the buffer for the 4 byte CRC at the
  188780. * end of every chunk (except IDAT, which is handled separately).
  188781. */
  188782. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188783. {
  188784. png_byte chunk_length[4];
  188785. if (png_ptr->buffer_size < 8)
  188786. {
  188787. png_push_save_buffer(png_ptr);
  188788. return;
  188789. }
  188790. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188791. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188792. png_reset_crc(png_ptr);
  188793. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188794. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188795. }
  188796. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188797. if(png_ptr->mode & PNG_AFTER_IDAT)
  188798. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188799. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188800. {
  188801. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188802. {
  188803. png_push_save_buffer(png_ptr);
  188804. return;
  188805. }
  188806. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188807. }
  188808. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188809. {
  188810. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188811. {
  188812. png_push_save_buffer(png_ptr);
  188813. return;
  188814. }
  188815. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188816. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188817. png_push_have_end(png_ptr, info_ptr);
  188818. }
  188819. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188820. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188821. {
  188822. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188823. {
  188824. png_push_save_buffer(png_ptr);
  188825. return;
  188826. }
  188827. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188828. png_ptr->mode |= PNG_HAVE_IDAT;
  188829. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188830. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188831. png_ptr->mode |= PNG_HAVE_PLTE;
  188832. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188833. {
  188834. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188835. png_error(png_ptr, "Missing IHDR before IDAT");
  188836. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188837. !(png_ptr->mode & PNG_HAVE_PLTE))
  188838. png_error(png_ptr, "Missing PLTE before IDAT");
  188839. }
  188840. }
  188841. #endif
  188842. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188843. {
  188844. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188845. {
  188846. png_push_save_buffer(png_ptr);
  188847. return;
  188848. }
  188849. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188850. }
  188851. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188852. {
  188853. /* If we reach an IDAT chunk, this means we have read all of the
  188854. * header chunks, and we can start reading the image (or if this
  188855. * is called after the image has been read - we have an error).
  188856. */
  188857. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188858. png_error(png_ptr, "Missing IHDR before IDAT");
  188859. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188860. !(png_ptr->mode & PNG_HAVE_PLTE))
  188861. png_error(png_ptr, "Missing PLTE before IDAT");
  188862. if (png_ptr->mode & PNG_HAVE_IDAT)
  188863. {
  188864. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188865. if (png_ptr->push_length == 0)
  188866. return;
  188867. if (png_ptr->mode & PNG_AFTER_IDAT)
  188868. png_error(png_ptr, "Too many IDAT's found");
  188869. }
  188870. png_ptr->idat_size = png_ptr->push_length;
  188871. png_ptr->mode |= PNG_HAVE_IDAT;
  188872. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188873. png_push_have_info(png_ptr, info_ptr);
  188874. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188875. png_ptr->zstream.next_out = png_ptr->row_buf;
  188876. return;
  188877. }
  188878. #if defined(PNG_READ_gAMA_SUPPORTED)
  188879. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188880. {
  188881. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188882. {
  188883. png_push_save_buffer(png_ptr);
  188884. return;
  188885. }
  188886. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188887. }
  188888. #endif
  188889. #if defined(PNG_READ_sBIT_SUPPORTED)
  188890. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188891. {
  188892. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188893. {
  188894. png_push_save_buffer(png_ptr);
  188895. return;
  188896. }
  188897. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188898. }
  188899. #endif
  188900. #if defined(PNG_READ_cHRM_SUPPORTED)
  188901. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188902. {
  188903. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188904. {
  188905. png_push_save_buffer(png_ptr);
  188906. return;
  188907. }
  188908. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188909. }
  188910. #endif
  188911. #if defined(PNG_READ_sRGB_SUPPORTED)
  188912. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188913. {
  188914. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188915. {
  188916. png_push_save_buffer(png_ptr);
  188917. return;
  188918. }
  188919. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188920. }
  188921. #endif
  188922. #if defined(PNG_READ_iCCP_SUPPORTED)
  188923. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188924. {
  188925. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188926. {
  188927. png_push_save_buffer(png_ptr);
  188928. return;
  188929. }
  188930. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188931. }
  188932. #endif
  188933. #if defined(PNG_READ_sPLT_SUPPORTED)
  188934. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188935. {
  188936. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188937. {
  188938. png_push_save_buffer(png_ptr);
  188939. return;
  188940. }
  188941. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188942. }
  188943. #endif
  188944. #if defined(PNG_READ_tRNS_SUPPORTED)
  188945. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188946. {
  188947. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188948. {
  188949. png_push_save_buffer(png_ptr);
  188950. return;
  188951. }
  188952. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188953. }
  188954. #endif
  188955. #if defined(PNG_READ_bKGD_SUPPORTED)
  188956. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188957. {
  188958. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188959. {
  188960. png_push_save_buffer(png_ptr);
  188961. return;
  188962. }
  188963. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188964. }
  188965. #endif
  188966. #if defined(PNG_READ_hIST_SUPPORTED)
  188967. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188968. {
  188969. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188970. {
  188971. png_push_save_buffer(png_ptr);
  188972. return;
  188973. }
  188974. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188975. }
  188976. #endif
  188977. #if defined(PNG_READ_pHYs_SUPPORTED)
  188978. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188979. {
  188980. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188981. {
  188982. png_push_save_buffer(png_ptr);
  188983. return;
  188984. }
  188985. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188986. }
  188987. #endif
  188988. #if defined(PNG_READ_oFFs_SUPPORTED)
  188989. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188990. {
  188991. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188992. {
  188993. png_push_save_buffer(png_ptr);
  188994. return;
  188995. }
  188996. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188997. }
  188998. #endif
  188999. #if defined(PNG_READ_pCAL_SUPPORTED)
  189000. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  189001. {
  189002. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189003. {
  189004. png_push_save_buffer(png_ptr);
  189005. return;
  189006. }
  189007. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  189008. }
  189009. #endif
  189010. #if defined(PNG_READ_sCAL_SUPPORTED)
  189011. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  189012. {
  189013. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189014. {
  189015. png_push_save_buffer(png_ptr);
  189016. return;
  189017. }
  189018. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  189019. }
  189020. #endif
  189021. #if defined(PNG_READ_tIME_SUPPORTED)
  189022. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  189023. {
  189024. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189025. {
  189026. png_push_save_buffer(png_ptr);
  189027. return;
  189028. }
  189029. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  189030. }
  189031. #endif
  189032. #if defined(PNG_READ_tEXt_SUPPORTED)
  189033. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  189034. {
  189035. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189036. {
  189037. png_push_save_buffer(png_ptr);
  189038. return;
  189039. }
  189040. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  189041. }
  189042. #endif
  189043. #if defined(PNG_READ_zTXt_SUPPORTED)
  189044. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  189045. {
  189046. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189047. {
  189048. png_push_save_buffer(png_ptr);
  189049. return;
  189050. }
  189051. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  189052. }
  189053. #endif
  189054. #if defined(PNG_READ_iTXt_SUPPORTED)
  189055. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  189056. {
  189057. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189058. {
  189059. png_push_save_buffer(png_ptr);
  189060. return;
  189061. }
  189062. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  189063. }
  189064. #endif
  189065. else
  189066. {
  189067. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189068. {
  189069. png_push_save_buffer(png_ptr);
  189070. return;
  189071. }
  189072. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  189073. }
  189074. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189075. }
  189076. void /* PRIVATE */
  189077. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  189078. {
  189079. png_ptr->process_mode = PNG_SKIP_MODE;
  189080. png_ptr->skip_length = skip;
  189081. }
  189082. void /* PRIVATE */
  189083. png_push_crc_finish(png_structp png_ptr)
  189084. {
  189085. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  189086. {
  189087. png_size_t save_size;
  189088. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  189089. save_size = (png_size_t)png_ptr->skip_length;
  189090. else
  189091. save_size = png_ptr->save_buffer_size;
  189092. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189093. png_ptr->skip_length -= save_size;
  189094. png_ptr->buffer_size -= save_size;
  189095. png_ptr->save_buffer_size -= save_size;
  189096. png_ptr->save_buffer_ptr += save_size;
  189097. }
  189098. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  189099. {
  189100. png_size_t save_size;
  189101. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  189102. save_size = (png_size_t)png_ptr->skip_length;
  189103. else
  189104. save_size = png_ptr->current_buffer_size;
  189105. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189106. png_ptr->skip_length -= save_size;
  189107. png_ptr->buffer_size -= save_size;
  189108. png_ptr->current_buffer_size -= save_size;
  189109. png_ptr->current_buffer_ptr += save_size;
  189110. }
  189111. if (!png_ptr->skip_length)
  189112. {
  189113. if (png_ptr->buffer_size < 4)
  189114. {
  189115. png_push_save_buffer(png_ptr);
  189116. return;
  189117. }
  189118. png_crc_finish(png_ptr, 0);
  189119. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189120. }
  189121. }
  189122. void PNGAPI
  189123. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  189124. {
  189125. png_bytep ptr;
  189126. if(png_ptr == NULL) return;
  189127. ptr = buffer;
  189128. if (png_ptr->save_buffer_size)
  189129. {
  189130. png_size_t save_size;
  189131. if (length < png_ptr->save_buffer_size)
  189132. save_size = length;
  189133. else
  189134. save_size = png_ptr->save_buffer_size;
  189135. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  189136. length -= save_size;
  189137. ptr += save_size;
  189138. png_ptr->buffer_size -= save_size;
  189139. png_ptr->save_buffer_size -= save_size;
  189140. png_ptr->save_buffer_ptr += save_size;
  189141. }
  189142. if (length && png_ptr->current_buffer_size)
  189143. {
  189144. png_size_t save_size;
  189145. if (length < png_ptr->current_buffer_size)
  189146. save_size = length;
  189147. else
  189148. save_size = png_ptr->current_buffer_size;
  189149. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  189150. png_ptr->buffer_size -= save_size;
  189151. png_ptr->current_buffer_size -= save_size;
  189152. png_ptr->current_buffer_ptr += save_size;
  189153. }
  189154. }
  189155. void /* PRIVATE */
  189156. png_push_save_buffer(png_structp png_ptr)
  189157. {
  189158. if (png_ptr->save_buffer_size)
  189159. {
  189160. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  189161. {
  189162. png_size_t i,istop;
  189163. png_bytep sp;
  189164. png_bytep dp;
  189165. istop = png_ptr->save_buffer_size;
  189166. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  189167. i < istop; i++, sp++, dp++)
  189168. {
  189169. *dp = *sp;
  189170. }
  189171. }
  189172. }
  189173. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  189174. png_ptr->save_buffer_max)
  189175. {
  189176. png_size_t new_max;
  189177. png_bytep old_buffer;
  189178. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  189179. (png_ptr->current_buffer_size + 256))
  189180. {
  189181. png_error(png_ptr, "Potential overflow of save_buffer");
  189182. }
  189183. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  189184. old_buffer = png_ptr->save_buffer;
  189185. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  189186. (png_uint_32)new_max);
  189187. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  189188. png_free(png_ptr, old_buffer);
  189189. png_ptr->save_buffer_max = new_max;
  189190. }
  189191. if (png_ptr->current_buffer_size)
  189192. {
  189193. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  189194. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  189195. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189196. png_ptr->current_buffer_size = 0;
  189197. }
  189198. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189199. png_ptr->buffer_size = 0;
  189200. }
  189201. void /* PRIVATE */
  189202. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189203. png_size_t buffer_length)
  189204. {
  189205. png_ptr->current_buffer = buffer;
  189206. png_ptr->current_buffer_size = buffer_length;
  189207. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189208. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189209. }
  189210. void /* PRIVATE */
  189211. png_push_read_IDAT(png_structp png_ptr)
  189212. {
  189213. #ifdef PNG_USE_LOCAL_ARRAYS
  189214. PNG_CONST PNG_IDAT;
  189215. #endif
  189216. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189217. {
  189218. png_byte chunk_length[4];
  189219. if (png_ptr->buffer_size < 8)
  189220. {
  189221. png_push_save_buffer(png_ptr);
  189222. return;
  189223. }
  189224. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189225. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189226. png_reset_crc(png_ptr);
  189227. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189228. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189229. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189230. {
  189231. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189232. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189233. png_error(png_ptr, "Not enough compressed data");
  189234. return;
  189235. }
  189236. png_ptr->idat_size = png_ptr->push_length;
  189237. }
  189238. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189239. {
  189240. png_size_t save_size;
  189241. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189242. {
  189243. save_size = (png_size_t)png_ptr->idat_size;
  189244. /* check for overflow */
  189245. if((png_uint_32)save_size != png_ptr->idat_size)
  189246. png_error(png_ptr, "save_size overflowed in pngpread");
  189247. }
  189248. else
  189249. save_size = png_ptr->save_buffer_size;
  189250. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189251. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189252. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189253. png_ptr->idat_size -= save_size;
  189254. png_ptr->buffer_size -= save_size;
  189255. png_ptr->save_buffer_size -= save_size;
  189256. png_ptr->save_buffer_ptr += save_size;
  189257. }
  189258. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189259. {
  189260. png_size_t save_size;
  189261. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189262. {
  189263. save_size = (png_size_t)png_ptr->idat_size;
  189264. /* check for overflow */
  189265. if((png_uint_32)save_size != png_ptr->idat_size)
  189266. png_error(png_ptr, "save_size overflowed in pngpread");
  189267. }
  189268. else
  189269. save_size = png_ptr->current_buffer_size;
  189270. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189271. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189272. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189273. png_ptr->idat_size -= save_size;
  189274. png_ptr->buffer_size -= save_size;
  189275. png_ptr->current_buffer_size -= save_size;
  189276. png_ptr->current_buffer_ptr += save_size;
  189277. }
  189278. if (!png_ptr->idat_size)
  189279. {
  189280. if (png_ptr->buffer_size < 4)
  189281. {
  189282. png_push_save_buffer(png_ptr);
  189283. return;
  189284. }
  189285. png_crc_finish(png_ptr, 0);
  189286. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189287. png_ptr->mode |= PNG_AFTER_IDAT;
  189288. }
  189289. }
  189290. void /* PRIVATE */
  189291. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189292. png_size_t buffer_length)
  189293. {
  189294. int ret;
  189295. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189296. png_error(png_ptr, "Extra compression data");
  189297. png_ptr->zstream.next_in = buffer;
  189298. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189299. for(;;)
  189300. {
  189301. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189302. if (ret != Z_OK)
  189303. {
  189304. if (ret == Z_STREAM_END)
  189305. {
  189306. if (png_ptr->zstream.avail_in)
  189307. png_error(png_ptr, "Extra compressed data");
  189308. if (!(png_ptr->zstream.avail_out))
  189309. {
  189310. png_push_process_row(png_ptr);
  189311. }
  189312. png_ptr->mode |= PNG_AFTER_IDAT;
  189313. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189314. break;
  189315. }
  189316. else if (ret == Z_BUF_ERROR)
  189317. break;
  189318. else
  189319. png_error(png_ptr, "Decompression Error");
  189320. }
  189321. if (!(png_ptr->zstream.avail_out))
  189322. {
  189323. if ((
  189324. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189325. png_ptr->interlaced && png_ptr->pass > 6) ||
  189326. (!png_ptr->interlaced &&
  189327. #endif
  189328. png_ptr->row_number == png_ptr->num_rows))
  189329. {
  189330. if (png_ptr->zstream.avail_in)
  189331. {
  189332. png_warning(png_ptr, "Too much data in IDAT chunks");
  189333. }
  189334. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189335. break;
  189336. }
  189337. png_push_process_row(png_ptr);
  189338. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189339. png_ptr->zstream.next_out = png_ptr->row_buf;
  189340. }
  189341. else
  189342. break;
  189343. }
  189344. }
  189345. void /* PRIVATE */
  189346. png_push_process_row(png_structp png_ptr)
  189347. {
  189348. png_ptr->row_info.color_type = png_ptr->color_type;
  189349. png_ptr->row_info.width = png_ptr->iwidth;
  189350. png_ptr->row_info.channels = png_ptr->channels;
  189351. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189352. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189353. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189354. png_ptr->row_info.width);
  189355. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189356. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189357. (int)(png_ptr->row_buf[0]));
  189358. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189359. png_ptr->rowbytes + 1);
  189360. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189361. png_do_read_transformations(png_ptr);
  189362. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189363. /* blow up interlaced rows to full size */
  189364. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189365. {
  189366. if (png_ptr->pass < 6)
  189367. /* old interface (pre-1.0.9):
  189368. png_do_read_interlace(&(png_ptr->row_info),
  189369. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189370. */
  189371. png_do_read_interlace(png_ptr);
  189372. switch (png_ptr->pass)
  189373. {
  189374. case 0:
  189375. {
  189376. int i;
  189377. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189378. {
  189379. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189380. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189381. }
  189382. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189383. {
  189384. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189385. {
  189386. png_push_have_row(png_ptr, png_bytep_NULL);
  189387. png_read_push_finish_row(png_ptr);
  189388. }
  189389. }
  189390. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189391. {
  189392. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189393. {
  189394. png_push_have_row(png_ptr, png_bytep_NULL);
  189395. png_read_push_finish_row(png_ptr);
  189396. }
  189397. }
  189398. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189399. {
  189400. png_push_have_row(png_ptr, png_bytep_NULL);
  189401. png_read_push_finish_row(png_ptr);
  189402. }
  189403. break;
  189404. }
  189405. case 1:
  189406. {
  189407. int i;
  189408. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189409. {
  189410. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189411. png_read_push_finish_row(png_ptr);
  189412. }
  189413. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189414. {
  189415. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189416. {
  189417. png_push_have_row(png_ptr, png_bytep_NULL);
  189418. png_read_push_finish_row(png_ptr);
  189419. }
  189420. }
  189421. break;
  189422. }
  189423. case 2:
  189424. {
  189425. int i;
  189426. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189427. {
  189428. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189429. png_read_push_finish_row(png_ptr);
  189430. }
  189431. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189432. {
  189433. png_push_have_row(png_ptr, png_bytep_NULL);
  189434. png_read_push_finish_row(png_ptr);
  189435. }
  189436. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189437. {
  189438. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189439. {
  189440. png_push_have_row(png_ptr, png_bytep_NULL);
  189441. png_read_push_finish_row(png_ptr);
  189442. }
  189443. }
  189444. break;
  189445. }
  189446. case 3:
  189447. {
  189448. int i;
  189449. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189450. {
  189451. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189452. png_read_push_finish_row(png_ptr);
  189453. }
  189454. if (png_ptr->pass == 4) /* skip top two generated rows */
  189455. {
  189456. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189457. {
  189458. png_push_have_row(png_ptr, png_bytep_NULL);
  189459. png_read_push_finish_row(png_ptr);
  189460. }
  189461. }
  189462. break;
  189463. }
  189464. case 4:
  189465. {
  189466. int i;
  189467. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189468. {
  189469. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189470. png_read_push_finish_row(png_ptr);
  189471. }
  189472. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189473. {
  189474. png_push_have_row(png_ptr, png_bytep_NULL);
  189475. png_read_push_finish_row(png_ptr);
  189476. }
  189477. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189478. {
  189479. png_push_have_row(png_ptr, png_bytep_NULL);
  189480. png_read_push_finish_row(png_ptr);
  189481. }
  189482. break;
  189483. }
  189484. case 5:
  189485. {
  189486. int i;
  189487. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189488. {
  189489. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189490. png_read_push_finish_row(png_ptr);
  189491. }
  189492. if (png_ptr->pass == 6) /* skip top generated row */
  189493. {
  189494. png_push_have_row(png_ptr, png_bytep_NULL);
  189495. png_read_push_finish_row(png_ptr);
  189496. }
  189497. break;
  189498. }
  189499. case 6:
  189500. {
  189501. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189502. png_read_push_finish_row(png_ptr);
  189503. if (png_ptr->pass != 6)
  189504. break;
  189505. png_push_have_row(png_ptr, png_bytep_NULL);
  189506. png_read_push_finish_row(png_ptr);
  189507. }
  189508. }
  189509. }
  189510. else
  189511. #endif
  189512. {
  189513. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189514. png_read_push_finish_row(png_ptr);
  189515. }
  189516. }
  189517. void /* PRIVATE */
  189518. png_read_push_finish_row(png_structp png_ptr)
  189519. {
  189520. #ifdef PNG_USE_LOCAL_ARRAYS
  189521. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189522. /* start of interlace block */
  189523. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189524. /* offset to next interlace block */
  189525. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189526. /* start of interlace block in the y direction */
  189527. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189528. /* offset to next interlace block in the y direction */
  189529. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189530. /* Height of interlace block. This is not currently used - if you need
  189531. * it, uncomment it here and in png.h
  189532. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189533. */
  189534. #endif
  189535. png_ptr->row_number++;
  189536. if (png_ptr->row_number < png_ptr->num_rows)
  189537. return;
  189538. if (png_ptr->interlaced)
  189539. {
  189540. png_ptr->row_number = 0;
  189541. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189542. png_ptr->rowbytes + 1);
  189543. do
  189544. {
  189545. png_ptr->pass++;
  189546. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189547. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189548. (png_ptr->pass == 5 && png_ptr->width < 2))
  189549. png_ptr->pass++;
  189550. if (png_ptr->pass > 7)
  189551. png_ptr->pass--;
  189552. if (png_ptr->pass >= 7)
  189553. break;
  189554. png_ptr->iwidth = (png_ptr->width +
  189555. png_pass_inc[png_ptr->pass] - 1 -
  189556. png_pass_start[png_ptr->pass]) /
  189557. png_pass_inc[png_ptr->pass];
  189558. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189559. png_ptr->iwidth) + 1;
  189560. if (png_ptr->transformations & PNG_INTERLACE)
  189561. break;
  189562. png_ptr->num_rows = (png_ptr->height +
  189563. png_pass_yinc[png_ptr->pass] - 1 -
  189564. png_pass_ystart[png_ptr->pass]) /
  189565. png_pass_yinc[png_ptr->pass];
  189566. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189567. }
  189568. }
  189569. #if defined(PNG_READ_tEXt_SUPPORTED)
  189570. void /* PRIVATE */
  189571. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189572. length)
  189573. {
  189574. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189575. {
  189576. png_error(png_ptr, "Out of place tEXt");
  189577. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189578. }
  189579. #ifdef PNG_MAX_MALLOC_64K
  189580. png_ptr->skip_length = 0; /* This may not be necessary */
  189581. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189582. {
  189583. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189584. png_ptr->skip_length = length - (png_uint_32)65535L;
  189585. length = (png_uint_32)65535L;
  189586. }
  189587. #endif
  189588. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189589. (png_uint_32)(length+1));
  189590. png_ptr->current_text[length] = '\0';
  189591. png_ptr->current_text_ptr = png_ptr->current_text;
  189592. png_ptr->current_text_size = (png_size_t)length;
  189593. png_ptr->current_text_left = (png_size_t)length;
  189594. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189595. }
  189596. void /* PRIVATE */
  189597. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189598. {
  189599. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189600. {
  189601. png_size_t text_size;
  189602. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189603. text_size = png_ptr->buffer_size;
  189604. else
  189605. text_size = png_ptr->current_text_left;
  189606. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189607. png_ptr->current_text_left -= text_size;
  189608. png_ptr->current_text_ptr += text_size;
  189609. }
  189610. if (!(png_ptr->current_text_left))
  189611. {
  189612. png_textp text_ptr;
  189613. png_charp text;
  189614. png_charp key;
  189615. int ret;
  189616. if (png_ptr->buffer_size < 4)
  189617. {
  189618. png_push_save_buffer(png_ptr);
  189619. return;
  189620. }
  189621. png_push_crc_finish(png_ptr);
  189622. #if defined(PNG_MAX_MALLOC_64K)
  189623. if (png_ptr->skip_length)
  189624. return;
  189625. #endif
  189626. key = png_ptr->current_text;
  189627. for (text = key; *text; text++)
  189628. /* empty loop */ ;
  189629. if (text < key + png_ptr->current_text_size)
  189630. text++;
  189631. text_ptr = (png_textp)png_malloc(png_ptr,
  189632. (png_uint_32)png_sizeof(png_text));
  189633. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189634. text_ptr->key = key;
  189635. #ifdef PNG_iTXt_SUPPORTED
  189636. text_ptr->lang = NULL;
  189637. text_ptr->lang_key = NULL;
  189638. #endif
  189639. text_ptr->text = text;
  189640. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189641. png_free(png_ptr, key);
  189642. png_free(png_ptr, text_ptr);
  189643. png_ptr->current_text = NULL;
  189644. if (ret)
  189645. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189646. }
  189647. }
  189648. #endif
  189649. #if defined(PNG_READ_zTXt_SUPPORTED)
  189650. void /* PRIVATE */
  189651. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189652. length)
  189653. {
  189654. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189655. {
  189656. png_error(png_ptr, "Out of place zTXt");
  189657. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189658. }
  189659. #ifdef PNG_MAX_MALLOC_64K
  189660. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189661. * to be able to store the uncompressed data. Actually, the threshold
  189662. * is probably around 32K, but it isn't as definite as 64K is.
  189663. */
  189664. if (length > (png_uint_32)65535L)
  189665. {
  189666. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189667. png_push_crc_skip(png_ptr, length);
  189668. return;
  189669. }
  189670. #endif
  189671. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189672. (png_uint_32)(length+1));
  189673. png_ptr->current_text[length] = '\0';
  189674. png_ptr->current_text_ptr = png_ptr->current_text;
  189675. png_ptr->current_text_size = (png_size_t)length;
  189676. png_ptr->current_text_left = (png_size_t)length;
  189677. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189678. }
  189679. void /* PRIVATE */
  189680. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189681. {
  189682. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189683. {
  189684. png_size_t text_size;
  189685. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189686. text_size = png_ptr->buffer_size;
  189687. else
  189688. text_size = png_ptr->current_text_left;
  189689. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189690. png_ptr->current_text_left -= text_size;
  189691. png_ptr->current_text_ptr += text_size;
  189692. }
  189693. if (!(png_ptr->current_text_left))
  189694. {
  189695. png_textp text_ptr;
  189696. png_charp text;
  189697. png_charp key;
  189698. int ret;
  189699. png_size_t text_size, key_size;
  189700. if (png_ptr->buffer_size < 4)
  189701. {
  189702. png_push_save_buffer(png_ptr);
  189703. return;
  189704. }
  189705. png_push_crc_finish(png_ptr);
  189706. key = png_ptr->current_text;
  189707. for (text = key; *text; text++)
  189708. /* empty loop */ ;
  189709. /* zTXt can't have zero text */
  189710. if (text >= key + png_ptr->current_text_size)
  189711. {
  189712. png_ptr->current_text = NULL;
  189713. png_free(png_ptr, key);
  189714. return;
  189715. }
  189716. text++;
  189717. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189718. {
  189719. png_ptr->current_text = NULL;
  189720. png_free(png_ptr, key);
  189721. return;
  189722. }
  189723. text++;
  189724. png_ptr->zstream.next_in = (png_bytep )text;
  189725. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189726. (text - key));
  189727. png_ptr->zstream.next_out = png_ptr->zbuf;
  189728. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189729. key_size = text - key;
  189730. text_size = 0;
  189731. text = NULL;
  189732. ret = Z_STREAM_END;
  189733. while (png_ptr->zstream.avail_in)
  189734. {
  189735. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189736. if (ret != Z_OK && ret != Z_STREAM_END)
  189737. {
  189738. inflateReset(&png_ptr->zstream);
  189739. png_ptr->zstream.avail_in = 0;
  189740. png_ptr->current_text = NULL;
  189741. png_free(png_ptr, key);
  189742. png_free(png_ptr, text);
  189743. return;
  189744. }
  189745. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189746. {
  189747. if (text == NULL)
  189748. {
  189749. text = (png_charp)png_malloc(png_ptr,
  189750. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189751. + key_size + 1));
  189752. png_memcpy(text + key_size, png_ptr->zbuf,
  189753. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189754. png_memcpy(text, key, key_size);
  189755. text_size = key_size + png_ptr->zbuf_size -
  189756. png_ptr->zstream.avail_out;
  189757. *(text + text_size) = '\0';
  189758. }
  189759. else
  189760. {
  189761. png_charp tmp;
  189762. tmp = text;
  189763. text = (png_charp)png_malloc(png_ptr, text_size +
  189764. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189765. + 1));
  189766. png_memcpy(text, tmp, text_size);
  189767. png_free(png_ptr, tmp);
  189768. png_memcpy(text + text_size, png_ptr->zbuf,
  189769. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189770. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189771. *(text + text_size) = '\0';
  189772. }
  189773. if (ret != Z_STREAM_END)
  189774. {
  189775. png_ptr->zstream.next_out = png_ptr->zbuf;
  189776. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189777. }
  189778. }
  189779. else
  189780. {
  189781. break;
  189782. }
  189783. if (ret == Z_STREAM_END)
  189784. break;
  189785. }
  189786. inflateReset(&png_ptr->zstream);
  189787. png_ptr->zstream.avail_in = 0;
  189788. if (ret != Z_STREAM_END)
  189789. {
  189790. png_ptr->current_text = NULL;
  189791. png_free(png_ptr, key);
  189792. png_free(png_ptr, text);
  189793. return;
  189794. }
  189795. png_ptr->current_text = NULL;
  189796. png_free(png_ptr, key);
  189797. key = text;
  189798. text += key_size;
  189799. text_ptr = (png_textp)png_malloc(png_ptr,
  189800. (png_uint_32)png_sizeof(png_text));
  189801. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189802. text_ptr->key = key;
  189803. #ifdef PNG_iTXt_SUPPORTED
  189804. text_ptr->lang = NULL;
  189805. text_ptr->lang_key = NULL;
  189806. #endif
  189807. text_ptr->text = text;
  189808. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189809. png_free(png_ptr, key);
  189810. png_free(png_ptr, text_ptr);
  189811. if (ret)
  189812. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189813. }
  189814. }
  189815. #endif
  189816. #if defined(PNG_READ_iTXt_SUPPORTED)
  189817. void /* PRIVATE */
  189818. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189819. length)
  189820. {
  189821. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189822. {
  189823. png_error(png_ptr, "Out of place iTXt");
  189824. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189825. }
  189826. #ifdef PNG_MAX_MALLOC_64K
  189827. png_ptr->skip_length = 0; /* This may not be necessary */
  189828. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189829. {
  189830. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189831. png_ptr->skip_length = length - (png_uint_32)65535L;
  189832. length = (png_uint_32)65535L;
  189833. }
  189834. #endif
  189835. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189836. (png_uint_32)(length+1));
  189837. png_ptr->current_text[length] = '\0';
  189838. png_ptr->current_text_ptr = png_ptr->current_text;
  189839. png_ptr->current_text_size = (png_size_t)length;
  189840. png_ptr->current_text_left = (png_size_t)length;
  189841. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189842. }
  189843. void /* PRIVATE */
  189844. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189845. {
  189846. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189847. {
  189848. png_size_t text_size;
  189849. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189850. text_size = png_ptr->buffer_size;
  189851. else
  189852. text_size = png_ptr->current_text_left;
  189853. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189854. png_ptr->current_text_left -= text_size;
  189855. png_ptr->current_text_ptr += text_size;
  189856. }
  189857. if (!(png_ptr->current_text_left))
  189858. {
  189859. png_textp text_ptr;
  189860. png_charp key;
  189861. int comp_flag;
  189862. png_charp lang;
  189863. png_charp lang_key;
  189864. png_charp text;
  189865. int ret;
  189866. if (png_ptr->buffer_size < 4)
  189867. {
  189868. png_push_save_buffer(png_ptr);
  189869. return;
  189870. }
  189871. png_push_crc_finish(png_ptr);
  189872. #if defined(PNG_MAX_MALLOC_64K)
  189873. if (png_ptr->skip_length)
  189874. return;
  189875. #endif
  189876. key = png_ptr->current_text;
  189877. for (lang = key; *lang; lang++)
  189878. /* empty loop */ ;
  189879. if (lang < key + png_ptr->current_text_size - 3)
  189880. lang++;
  189881. comp_flag = *lang++;
  189882. lang++; /* skip comp_type, always zero */
  189883. for (lang_key = lang; *lang_key; lang_key++)
  189884. /* empty loop */ ;
  189885. lang_key++; /* skip NUL separator */
  189886. text=lang_key;
  189887. if (lang_key < key + png_ptr->current_text_size - 1)
  189888. {
  189889. for (; *text; text++)
  189890. /* empty loop */ ;
  189891. }
  189892. if (text < key + png_ptr->current_text_size)
  189893. text++;
  189894. text_ptr = (png_textp)png_malloc(png_ptr,
  189895. (png_uint_32)png_sizeof(png_text));
  189896. text_ptr->compression = comp_flag + 2;
  189897. text_ptr->key = key;
  189898. text_ptr->lang = lang;
  189899. text_ptr->lang_key = lang_key;
  189900. text_ptr->text = text;
  189901. text_ptr->text_length = 0;
  189902. text_ptr->itxt_length = png_strlen(text);
  189903. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189904. png_ptr->current_text = NULL;
  189905. png_free(png_ptr, text_ptr);
  189906. if (ret)
  189907. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189908. }
  189909. }
  189910. #endif
  189911. /* This function is called when we haven't found a handler for this
  189912. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189913. * name or a critical chunk), the chunk is (currently) silently ignored.
  189914. */
  189915. void /* PRIVATE */
  189916. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189917. length)
  189918. {
  189919. png_uint_32 skip=0;
  189920. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189921. if (!(png_ptr->chunk_name[0] & 0x20))
  189922. {
  189923. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189924. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189925. PNG_HANDLE_CHUNK_ALWAYS
  189926. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189927. && png_ptr->read_user_chunk_fn == NULL
  189928. #endif
  189929. )
  189930. #endif
  189931. png_chunk_error(png_ptr, "unknown critical chunk");
  189932. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189933. }
  189934. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189935. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189936. {
  189937. #ifdef PNG_MAX_MALLOC_64K
  189938. if (length > (png_uint_32)65535L)
  189939. {
  189940. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189941. skip = length - (png_uint_32)65535L;
  189942. length = (png_uint_32)65535L;
  189943. }
  189944. #endif
  189945. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189946. (png_charp)png_ptr->chunk_name, 5);
  189947. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189948. png_ptr->unknown_chunk.size = (png_size_t)length;
  189949. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189950. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189951. if(png_ptr->read_user_chunk_fn != NULL)
  189952. {
  189953. /* callback to user unknown chunk handler */
  189954. int ret;
  189955. ret = (*(png_ptr->read_user_chunk_fn))
  189956. (png_ptr, &png_ptr->unknown_chunk);
  189957. if (ret < 0)
  189958. png_chunk_error(png_ptr, "error in user chunk");
  189959. if (ret == 0)
  189960. {
  189961. if (!(png_ptr->chunk_name[0] & 0x20))
  189962. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189963. PNG_HANDLE_CHUNK_ALWAYS)
  189964. png_chunk_error(png_ptr, "unknown critical chunk");
  189965. png_set_unknown_chunks(png_ptr, info_ptr,
  189966. &png_ptr->unknown_chunk, 1);
  189967. }
  189968. }
  189969. #else
  189970. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189971. #endif
  189972. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189973. png_ptr->unknown_chunk.data = NULL;
  189974. }
  189975. else
  189976. #endif
  189977. skip=length;
  189978. png_push_crc_skip(png_ptr, skip);
  189979. }
  189980. void /* PRIVATE */
  189981. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189982. {
  189983. if (png_ptr->info_fn != NULL)
  189984. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189985. }
  189986. void /* PRIVATE */
  189987. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189988. {
  189989. if (png_ptr->end_fn != NULL)
  189990. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189991. }
  189992. void /* PRIVATE */
  189993. png_push_have_row(png_structp png_ptr, png_bytep row)
  189994. {
  189995. if (png_ptr->row_fn != NULL)
  189996. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189997. (int)png_ptr->pass);
  189998. }
  189999. void PNGAPI
  190000. png_progressive_combine_row (png_structp png_ptr,
  190001. png_bytep old_row, png_bytep new_row)
  190002. {
  190003. #ifdef PNG_USE_LOCAL_ARRAYS
  190004. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  190005. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  190006. #endif
  190007. if(png_ptr == NULL) return;
  190008. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  190009. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  190010. }
  190011. void PNGAPI
  190012. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  190013. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  190014. png_progressive_end_ptr end_fn)
  190015. {
  190016. if(png_ptr == NULL) return;
  190017. png_ptr->info_fn = info_fn;
  190018. png_ptr->row_fn = row_fn;
  190019. png_ptr->end_fn = end_fn;
  190020. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  190021. }
  190022. png_voidp PNGAPI
  190023. png_get_progressive_ptr(png_structp png_ptr)
  190024. {
  190025. if(png_ptr == NULL) return (NULL);
  190026. return png_ptr->io_ptr;
  190027. }
  190028. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  190029. /*** End of inlined file: pngpread.c ***/
  190030. /*** Start of inlined file: pngrio.c ***/
  190031. /* pngrio.c - functions for data input
  190032. *
  190033. * Last changed in libpng 1.2.13 November 13, 2006
  190034. * For conditions of distribution and use, see copyright notice in png.h
  190035. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  190036. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190037. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190038. *
  190039. * This file provides a location for all input. Users who need
  190040. * special handling are expected to write a function that has the same
  190041. * arguments as this and performs a similar function, but that possibly
  190042. * has a different input method. Note that you shouldn't change this
  190043. * function, but rather write a replacement function and then make
  190044. * libpng use it at run time with png_set_read_fn(...).
  190045. */
  190046. #define PNG_INTERNAL
  190047. #if defined(PNG_READ_SUPPORTED)
  190048. /* Read the data from whatever input you are using. The default routine
  190049. reads from a file pointer. Note that this routine sometimes gets called
  190050. with very small lengths, so you should implement some kind of simple
  190051. buffering if you are using unbuffered reads. This should never be asked
  190052. to read more then 64K on a 16 bit machine. */
  190053. void /* PRIVATE */
  190054. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190055. {
  190056. png_debug1(4,"reading %d bytes\n", (int)length);
  190057. if (png_ptr->read_data_fn != NULL)
  190058. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  190059. else
  190060. png_error(png_ptr, "Call to NULL read function");
  190061. }
  190062. #if !defined(PNG_NO_STDIO)
  190063. /* This is the function that does the actual reading of data. If you are
  190064. not reading from a standard C stream, you should create a replacement
  190065. read_data function and use it at run time with png_set_read_fn(), rather
  190066. than changing the library. */
  190067. #ifndef USE_FAR_KEYWORD
  190068. void PNGAPI
  190069. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190070. {
  190071. png_size_t check;
  190072. if(png_ptr == NULL) return;
  190073. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  190074. * instead of an int, which is what fread() actually returns.
  190075. */
  190076. #if defined(_WIN32_WCE)
  190077. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190078. check = 0;
  190079. #else
  190080. check = (png_size_t)fread(data, (png_size_t)1, length,
  190081. (png_FILE_p)png_ptr->io_ptr);
  190082. #endif
  190083. if (check != length)
  190084. png_error(png_ptr, "Read Error");
  190085. }
  190086. #else
  190087. /* this is the model-independent version. Since the standard I/O library
  190088. can't handle far buffers in the medium and small models, we have to copy
  190089. the data.
  190090. */
  190091. #define NEAR_BUF_SIZE 1024
  190092. #define MIN(a,b) (a <= b ? a : b)
  190093. static void PNGAPI
  190094. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190095. {
  190096. int check;
  190097. png_byte *n_data;
  190098. png_FILE_p io_ptr;
  190099. if(png_ptr == NULL) return;
  190100. /* Check if data really is near. If so, use usual code. */
  190101. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  190102. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  190103. if ((png_bytep)n_data == data)
  190104. {
  190105. #if defined(_WIN32_WCE)
  190106. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190107. check = 0;
  190108. #else
  190109. check = fread(n_data, 1, length, io_ptr);
  190110. #endif
  190111. }
  190112. else
  190113. {
  190114. png_byte buf[NEAR_BUF_SIZE];
  190115. png_size_t read, remaining, err;
  190116. check = 0;
  190117. remaining = length;
  190118. do
  190119. {
  190120. read = MIN(NEAR_BUF_SIZE, remaining);
  190121. #if defined(_WIN32_WCE)
  190122. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  190123. err = 0;
  190124. #else
  190125. err = fread(buf, (png_size_t)1, read, io_ptr);
  190126. #endif
  190127. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  190128. if(err != read)
  190129. break;
  190130. else
  190131. check += err;
  190132. data += read;
  190133. remaining -= read;
  190134. }
  190135. while (remaining != 0);
  190136. }
  190137. if ((png_uint_32)check != (png_uint_32)length)
  190138. png_error(png_ptr, "read Error");
  190139. }
  190140. #endif
  190141. #endif
  190142. /* This function allows the application to supply a new input function
  190143. for libpng if standard C streams aren't being used.
  190144. This function takes as its arguments:
  190145. png_ptr - pointer to a png input data structure
  190146. io_ptr - pointer to user supplied structure containing info about
  190147. the input functions. May be NULL.
  190148. read_data_fn - pointer to a new input function that takes as its
  190149. arguments a pointer to a png_struct, a pointer to
  190150. a location where input data can be stored, and a 32-bit
  190151. unsigned int that is the number of bytes to be read.
  190152. To exit and output any fatal error messages the new write
  190153. function should call png_error(png_ptr, "Error msg"). */
  190154. void PNGAPI
  190155. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  190156. png_rw_ptr read_data_fn)
  190157. {
  190158. if(png_ptr == NULL) return;
  190159. png_ptr->io_ptr = io_ptr;
  190160. #if !defined(PNG_NO_STDIO)
  190161. if (read_data_fn != NULL)
  190162. png_ptr->read_data_fn = read_data_fn;
  190163. else
  190164. png_ptr->read_data_fn = png_default_read_data;
  190165. #else
  190166. png_ptr->read_data_fn = read_data_fn;
  190167. #endif
  190168. /* It is an error to write to a read device */
  190169. if (png_ptr->write_data_fn != NULL)
  190170. {
  190171. png_ptr->write_data_fn = NULL;
  190172. png_warning(png_ptr,
  190173. "It's an error to set both read_data_fn and write_data_fn in the ");
  190174. png_warning(png_ptr,
  190175. "same structure. Resetting write_data_fn to NULL.");
  190176. }
  190177. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  190178. png_ptr->output_flush_fn = NULL;
  190179. #endif
  190180. }
  190181. #endif /* PNG_READ_SUPPORTED */
  190182. /*** End of inlined file: pngrio.c ***/
  190183. /*** Start of inlined file: pngrtran.c ***/
  190184. /* pngrtran.c - transforms the data in a row for PNG readers
  190185. *
  190186. * Last changed in libpng 1.2.21 [October 4, 2007]
  190187. * For conditions of distribution and use, see copyright notice in png.h
  190188. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190189. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190190. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190191. *
  190192. * This file contains functions optionally called by an application
  190193. * in order to tell libpng how to handle data when reading a PNG.
  190194. * Transformations that are used in both reading and writing are
  190195. * in pngtrans.c.
  190196. */
  190197. #define PNG_INTERNAL
  190198. #if defined(PNG_READ_SUPPORTED)
  190199. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190200. void PNGAPI
  190201. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190202. {
  190203. png_debug(1, "in png_set_crc_action\n");
  190204. /* Tell libpng how we react to CRC errors in critical chunks */
  190205. if(png_ptr == NULL) return;
  190206. switch (crit_action)
  190207. {
  190208. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190209. break;
  190210. case PNG_CRC_WARN_USE: /* warn/use data */
  190211. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190212. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190213. break;
  190214. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190215. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190216. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190217. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190218. break;
  190219. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190220. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190221. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190222. case PNG_CRC_DEFAULT:
  190223. default:
  190224. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190225. break;
  190226. }
  190227. switch (ancil_action)
  190228. {
  190229. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190230. break;
  190231. case PNG_CRC_WARN_USE: /* warn/use data */
  190232. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190233. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190234. break;
  190235. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190236. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190237. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190238. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190239. break;
  190240. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190241. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190242. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190243. break;
  190244. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190245. case PNG_CRC_DEFAULT:
  190246. default:
  190247. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190248. break;
  190249. }
  190250. }
  190251. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190252. defined(PNG_FLOATING_POINT_SUPPORTED)
  190253. /* handle alpha and tRNS via a background color */
  190254. void PNGAPI
  190255. png_set_background(png_structp png_ptr,
  190256. png_color_16p background_color, int background_gamma_code,
  190257. int need_expand, double background_gamma)
  190258. {
  190259. png_debug(1, "in png_set_background\n");
  190260. if(png_ptr == NULL) return;
  190261. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190262. {
  190263. png_warning(png_ptr, "Application must supply a known background gamma");
  190264. return;
  190265. }
  190266. png_ptr->transformations |= PNG_BACKGROUND;
  190267. png_memcpy(&(png_ptr->background), background_color,
  190268. png_sizeof(png_color_16));
  190269. png_ptr->background_gamma = (float)background_gamma;
  190270. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190271. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190272. }
  190273. #endif
  190274. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190275. /* strip 16 bit depth files to 8 bit depth */
  190276. void PNGAPI
  190277. png_set_strip_16(png_structp png_ptr)
  190278. {
  190279. png_debug(1, "in png_set_strip_16\n");
  190280. if(png_ptr == NULL) return;
  190281. png_ptr->transformations |= PNG_16_TO_8;
  190282. }
  190283. #endif
  190284. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190285. void PNGAPI
  190286. png_set_strip_alpha(png_structp png_ptr)
  190287. {
  190288. png_debug(1, "in png_set_strip_alpha\n");
  190289. if(png_ptr == NULL) return;
  190290. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190291. }
  190292. #endif
  190293. #if defined(PNG_READ_DITHER_SUPPORTED)
  190294. /* Dither file to 8 bit. Supply a palette, the current number
  190295. * of elements in the palette, the maximum number of elements
  190296. * allowed, and a histogram if possible. If the current number
  190297. * of colors is greater then the maximum number, the palette will be
  190298. * modified to fit in the maximum number. "full_dither" indicates
  190299. * whether we need a dithering cube set up for RGB images, or if we
  190300. * simply are reducing the number of colors in a paletted image.
  190301. */
  190302. typedef struct png_dsort_struct
  190303. {
  190304. struct png_dsort_struct FAR * next;
  190305. png_byte left;
  190306. png_byte right;
  190307. } png_dsort;
  190308. typedef png_dsort FAR * png_dsortp;
  190309. typedef png_dsort FAR * FAR * png_dsortpp;
  190310. void PNGAPI
  190311. png_set_dither(png_structp png_ptr, png_colorp palette,
  190312. int num_palette, int maximum_colors, png_uint_16p histogram,
  190313. int full_dither)
  190314. {
  190315. png_debug(1, "in png_set_dither\n");
  190316. if(png_ptr == NULL) return;
  190317. png_ptr->transformations |= PNG_DITHER;
  190318. if (!full_dither)
  190319. {
  190320. int i;
  190321. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190322. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190323. for (i = 0; i < num_palette; i++)
  190324. png_ptr->dither_index[i] = (png_byte)i;
  190325. }
  190326. if (num_palette > maximum_colors)
  190327. {
  190328. if (histogram != NULL)
  190329. {
  190330. /* This is easy enough, just throw out the least used colors.
  190331. Perhaps not the best solution, but good enough. */
  190332. int i;
  190333. /* initialize an array to sort colors */
  190334. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190335. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190336. /* initialize the dither_sort array */
  190337. for (i = 0; i < num_palette; i++)
  190338. png_ptr->dither_sort[i] = (png_byte)i;
  190339. /* Find the least used palette entries by starting a
  190340. bubble sort, and running it until we have sorted
  190341. out enough colors. Note that we don't care about
  190342. sorting all the colors, just finding which are
  190343. least used. */
  190344. for (i = num_palette - 1; i >= maximum_colors; i--)
  190345. {
  190346. int done; /* to stop early if the list is pre-sorted */
  190347. int j;
  190348. done = 1;
  190349. for (j = 0; j < i; j++)
  190350. {
  190351. if (histogram[png_ptr->dither_sort[j]]
  190352. < histogram[png_ptr->dither_sort[j + 1]])
  190353. {
  190354. png_byte t;
  190355. t = png_ptr->dither_sort[j];
  190356. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190357. png_ptr->dither_sort[j + 1] = t;
  190358. done = 0;
  190359. }
  190360. }
  190361. if (done)
  190362. break;
  190363. }
  190364. /* swap the palette around, and set up a table, if necessary */
  190365. if (full_dither)
  190366. {
  190367. int j = num_palette;
  190368. /* put all the useful colors within the max, but don't
  190369. move the others */
  190370. for (i = 0; i < maximum_colors; i++)
  190371. {
  190372. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190373. {
  190374. do
  190375. j--;
  190376. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190377. palette[i] = palette[j];
  190378. }
  190379. }
  190380. }
  190381. else
  190382. {
  190383. int j = num_palette;
  190384. /* move all the used colors inside the max limit, and
  190385. develop a translation table */
  190386. for (i = 0; i < maximum_colors; i++)
  190387. {
  190388. /* only move the colors we need to */
  190389. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190390. {
  190391. png_color tmp_color;
  190392. do
  190393. j--;
  190394. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190395. tmp_color = palette[j];
  190396. palette[j] = palette[i];
  190397. palette[i] = tmp_color;
  190398. /* indicate where the color went */
  190399. png_ptr->dither_index[j] = (png_byte)i;
  190400. png_ptr->dither_index[i] = (png_byte)j;
  190401. }
  190402. }
  190403. /* find closest color for those colors we are not using */
  190404. for (i = 0; i < num_palette; i++)
  190405. {
  190406. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190407. {
  190408. int min_d, k, min_k, d_index;
  190409. /* find the closest color to one we threw out */
  190410. d_index = png_ptr->dither_index[i];
  190411. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190412. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190413. {
  190414. int d;
  190415. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190416. if (d < min_d)
  190417. {
  190418. min_d = d;
  190419. min_k = k;
  190420. }
  190421. }
  190422. /* point to closest color */
  190423. png_ptr->dither_index[i] = (png_byte)min_k;
  190424. }
  190425. }
  190426. }
  190427. png_free(png_ptr, png_ptr->dither_sort);
  190428. png_ptr->dither_sort=NULL;
  190429. }
  190430. else
  190431. {
  190432. /* This is much harder to do simply (and quickly). Perhaps
  190433. we need to go through a median cut routine, but those
  190434. don't always behave themselves with only a few colors
  190435. as input. So we will just find the closest two colors,
  190436. and throw out one of them (chosen somewhat randomly).
  190437. [We don't understand this at all, so if someone wants to
  190438. work on improving it, be our guest - AED, GRP]
  190439. */
  190440. int i;
  190441. int max_d;
  190442. int num_new_palette;
  190443. png_dsortp t;
  190444. png_dsortpp hash;
  190445. t=NULL;
  190446. /* initialize palette index arrays */
  190447. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190448. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190449. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190450. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190451. /* initialize the sort array */
  190452. for (i = 0; i < num_palette; i++)
  190453. {
  190454. png_ptr->index_to_palette[i] = (png_byte)i;
  190455. png_ptr->palette_to_index[i] = (png_byte)i;
  190456. }
  190457. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190458. png_sizeof (png_dsortp)));
  190459. for (i = 0; i < 769; i++)
  190460. hash[i] = NULL;
  190461. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190462. num_new_palette = num_palette;
  190463. /* initial wild guess at how far apart the farthest pixel
  190464. pair we will be eliminating will be. Larger
  190465. numbers mean more areas will be allocated, Smaller
  190466. numbers run the risk of not saving enough data, and
  190467. having to do this all over again.
  190468. I have not done extensive checking on this number.
  190469. */
  190470. max_d = 96;
  190471. while (num_new_palette > maximum_colors)
  190472. {
  190473. for (i = 0; i < num_new_palette - 1; i++)
  190474. {
  190475. int j;
  190476. for (j = i + 1; j < num_new_palette; j++)
  190477. {
  190478. int d;
  190479. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190480. if (d <= max_d)
  190481. {
  190482. t = (png_dsortp)png_malloc_warn(png_ptr,
  190483. (png_uint_32)(png_sizeof(png_dsort)));
  190484. if (t == NULL)
  190485. break;
  190486. t->next = hash[d];
  190487. t->left = (png_byte)i;
  190488. t->right = (png_byte)j;
  190489. hash[d] = t;
  190490. }
  190491. }
  190492. if (t == NULL)
  190493. break;
  190494. }
  190495. if (t != NULL)
  190496. for (i = 0; i <= max_d; i++)
  190497. {
  190498. if (hash[i] != NULL)
  190499. {
  190500. png_dsortp p;
  190501. for (p = hash[i]; p; p = p->next)
  190502. {
  190503. if ((int)png_ptr->index_to_palette[p->left]
  190504. < num_new_palette &&
  190505. (int)png_ptr->index_to_palette[p->right]
  190506. < num_new_palette)
  190507. {
  190508. int j, next_j;
  190509. if (num_new_palette & 0x01)
  190510. {
  190511. j = p->left;
  190512. next_j = p->right;
  190513. }
  190514. else
  190515. {
  190516. j = p->right;
  190517. next_j = p->left;
  190518. }
  190519. num_new_palette--;
  190520. palette[png_ptr->index_to_palette[j]]
  190521. = palette[num_new_palette];
  190522. if (!full_dither)
  190523. {
  190524. int k;
  190525. for (k = 0; k < num_palette; k++)
  190526. {
  190527. if (png_ptr->dither_index[k] ==
  190528. png_ptr->index_to_palette[j])
  190529. png_ptr->dither_index[k] =
  190530. png_ptr->index_to_palette[next_j];
  190531. if ((int)png_ptr->dither_index[k] ==
  190532. num_new_palette)
  190533. png_ptr->dither_index[k] =
  190534. png_ptr->index_to_palette[j];
  190535. }
  190536. }
  190537. png_ptr->index_to_palette[png_ptr->palette_to_index
  190538. [num_new_palette]] = png_ptr->index_to_palette[j];
  190539. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190540. = png_ptr->palette_to_index[num_new_palette];
  190541. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190542. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190543. }
  190544. if (num_new_palette <= maximum_colors)
  190545. break;
  190546. }
  190547. if (num_new_palette <= maximum_colors)
  190548. break;
  190549. }
  190550. }
  190551. for (i = 0; i < 769; i++)
  190552. {
  190553. if (hash[i] != NULL)
  190554. {
  190555. png_dsortp p = hash[i];
  190556. while (p)
  190557. {
  190558. t = p->next;
  190559. png_free(png_ptr, p);
  190560. p = t;
  190561. }
  190562. }
  190563. hash[i] = 0;
  190564. }
  190565. max_d += 96;
  190566. }
  190567. png_free(png_ptr, hash);
  190568. png_free(png_ptr, png_ptr->palette_to_index);
  190569. png_free(png_ptr, png_ptr->index_to_palette);
  190570. png_ptr->palette_to_index=NULL;
  190571. png_ptr->index_to_palette=NULL;
  190572. }
  190573. num_palette = maximum_colors;
  190574. }
  190575. if (png_ptr->palette == NULL)
  190576. {
  190577. png_ptr->palette = palette;
  190578. }
  190579. png_ptr->num_palette = (png_uint_16)num_palette;
  190580. if (full_dither)
  190581. {
  190582. int i;
  190583. png_bytep distance;
  190584. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190585. PNG_DITHER_BLUE_BITS;
  190586. int num_red = (1 << PNG_DITHER_RED_BITS);
  190587. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190588. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190589. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190590. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190591. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190592. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190593. png_sizeof (png_byte));
  190594. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190595. png_sizeof(png_byte)));
  190596. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190597. for (i = 0; i < num_palette; i++)
  190598. {
  190599. int ir, ig, ib;
  190600. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190601. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190602. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190603. for (ir = 0; ir < num_red; ir++)
  190604. {
  190605. /* int dr = abs(ir - r); */
  190606. int dr = ((ir > r) ? ir - r : r - ir);
  190607. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190608. for (ig = 0; ig < num_green; ig++)
  190609. {
  190610. /* int dg = abs(ig - g); */
  190611. int dg = ((ig > g) ? ig - g : g - ig);
  190612. int dt = dr + dg;
  190613. int dm = ((dr > dg) ? dr : dg);
  190614. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190615. for (ib = 0; ib < num_blue; ib++)
  190616. {
  190617. int d_index = index_g | ib;
  190618. /* int db = abs(ib - b); */
  190619. int db = ((ib > b) ? ib - b : b - ib);
  190620. int dmax = ((dm > db) ? dm : db);
  190621. int d = dmax + dt + db;
  190622. if (d < (int)distance[d_index])
  190623. {
  190624. distance[d_index] = (png_byte)d;
  190625. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190626. }
  190627. }
  190628. }
  190629. }
  190630. }
  190631. png_free(png_ptr, distance);
  190632. }
  190633. }
  190634. #endif
  190635. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190636. /* Transform the image from the file_gamma to the screen_gamma. We
  190637. * only do transformations on images where the file_gamma and screen_gamma
  190638. * are not close reciprocals, otherwise it slows things down slightly, and
  190639. * also needlessly introduces small errors.
  190640. *
  190641. * We will turn off gamma transformation later if no semitransparent entries
  190642. * are present in the tRNS array for palette images. We can't do it here
  190643. * because we don't necessarily have the tRNS chunk yet.
  190644. */
  190645. void PNGAPI
  190646. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190647. {
  190648. png_debug(1, "in png_set_gamma\n");
  190649. if(png_ptr == NULL) return;
  190650. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190651. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190652. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190653. png_ptr->transformations |= PNG_GAMMA;
  190654. png_ptr->gamma = (float)file_gamma;
  190655. png_ptr->screen_gamma = (float)scrn_gamma;
  190656. }
  190657. #endif
  190658. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190659. /* Expand paletted images to RGB, expand grayscale images of
  190660. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190661. * to alpha channels.
  190662. */
  190663. void PNGAPI
  190664. png_set_expand(png_structp png_ptr)
  190665. {
  190666. png_debug(1, "in png_set_expand\n");
  190667. if(png_ptr == NULL) return;
  190668. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190669. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190670. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190671. #endif
  190672. }
  190673. /* GRR 19990627: the following three functions currently are identical
  190674. * to png_set_expand(). However, it is entirely reasonable that someone
  190675. * might wish to expand an indexed image to RGB but *not* expand a single,
  190676. * fully transparent palette entry to a full alpha channel--perhaps instead
  190677. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190678. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190679. * IOW, a future version of the library may make the transformations flag
  190680. * a bit more fine-grained, with separate bits for each of these three
  190681. * functions.
  190682. *
  190683. * More to the point, these functions make it obvious what libpng will be
  190684. * doing, whereas "expand" can (and does) mean any number of things.
  190685. *
  190686. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190687. * to expand only the sample depth but not to expand the tRNS to alpha.
  190688. */
  190689. /* Expand paletted images to RGB. */
  190690. void PNGAPI
  190691. png_set_palette_to_rgb(png_structp png_ptr)
  190692. {
  190693. png_debug(1, "in png_set_palette_to_rgb\n");
  190694. if(png_ptr == NULL) return;
  190695. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190696. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190697. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190698. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190699. #endif
  190700. }
  190701. #if !defined(PNG_1_0_X)
  190702. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190703. void PNGAPI
  190704. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190705. {
  190706. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190707. if(png_ptr == NULL) return;
  190708. png_ptr->transformations |= PNG_EXPAND;
  190709. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190710. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190711. #endif
  190712. }
  190713. #endif
  190714. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190715. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190716. /* Deprecated as of libpng-1.2.9 */
  190717. void PNGAPI
  190718. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190719. {
  190720. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190721. if(png_ptr == NULL) return;
  190722. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190723. }
  190724. #endif
  190725. /* Expand tRNS chunks to alpha channels. */
  190726. void PNGAPI
  190727. png_set_tRNS_to_alpha(png_structp png_ptr)
  190728. {
  190729. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190730. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190731. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190732. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190733. #endif
  190734. }
  190735. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190736. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190737. void PNGAPI
  190738. png_set_gray_to_rgb(png_structp png_ptr)
  190739. {
  190740. png_debug(1, "in png_set_gray_to_rgb\n");
  190741. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190742. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190743. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190744. #endif
  190745. }
  190746. #endif
  190747. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190748. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190749. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190750. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190751. */
  190752. void PNGAPI
  190753. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190754. double green)
  190755. {
  190756. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190757. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190758. if(png_ptr == NULL) return;
  190759. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190760. }
  190761. #endif
  190762. void PNGAPI
  190763. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190764. png_fixed_point red, png_fixed_point green)
  190765. {
  190766. png_debug(1, "in png_set_rgb_to_gray\n");
  190767. if(png_ptr == NULL) return;
  190768. switch(error_action)
  190769. {
  190770. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190771. break;
  190772. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190773. break;
  190774. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190775. }
  190776. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190777. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190778. png_ptr->transformations |= PNG_EXPAND;
  190779. #else
  190780. {
  190781. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190782. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190783. }
  190784. #endif
  190785. {
  190786. png_uint_16 red_int, green_int;
  190787. if(red < 0 || green < 0)
  190788. {
  190789. red_int = 6968; /* .212671 * 32768 + .5 */
  190790. green_int = 23434; /* .715160 * 32768 + .5 */
  190791. }
  190792. else if(red + green < 100000L)
  190793. {
  190794. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190795. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190796. }
  190797. else
  190798. {
  190799. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190800. red_int = 6968;
  190801. green_int = 23434;
  190802. }
  190803. png_ptr->rgb_to_gray_red_coeff = red_int;
  190804. png_ptr->rgb_to_gray_green_coeff = green_int;
  190805. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190806. }
  190807. }
  190808. #endif
  190809. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190810. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190811. defined(PNG_LEGACY_SUPPORTED)
  190812. void PNGAPI
  190813. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190814. read_user_transform_fn)
  190815. {
  190816. png_debug(1, "in png_set_read_user_transform_fn\n");
  190817. if(png_ptr == NULL) return;
  190818. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190819. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190820. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190821. #endif
  190822. #ifdef PNG_LEGACY_SUPPORTED
  190823. if(read_user_transform_fn)
  190824. png_warning(png_ptr,
  190825. "This version of libpng does not support user transforms");
  190826. #endif
  190827. }
  190828. #endif
  190829. /* Initialize everything needed for the read. This includes modifying
  190830. * the palette.
  190831. */
  190832. void /* PRIVATE */
  190833. png_init_read_transformations(png_structp png_ptr)
  190834. {
  190835. png_debug(1, "in png_init_read_transformations\n");
  190836. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190837. if(png_ptr != NULL)
  190838. #endif
  190839. {
  190840. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190841. || defined(PNG_READ_GAMMA_SUPPORTED)
  190842. int color_type = png_ptr->color_type;
  190843. #endif
  190844. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190845. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190846. /* Detect gray background and attempt to enable optimization
  190847. * for gray --> RGB case */
  190848. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190849. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190850. * background color might actually be gray yet not be flagged as such.
  190851. * This is not a problem for the current code, which uses
  190852. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190853. * png_do_gray_to_rgb() transformation.
  190854. */
  190855. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190856. !(color_type & PNG_COLOR_MASK_COLOR))
  190857. {
  190858. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190859. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190860. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190861. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190862. png_ptr->background.red == png_ptr->background.green &&
  190863. png_ptr->background.red == png_ptr->background.blue)
  190864. {
  190865. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190866. png_ptr->background.gray = png_ptr->background.red;
  190867. }
  190868. #endif
  190869. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190870. (png_ptr->transformations & PNG_EXPAND))
  190871. {
  190872. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190873. {
  190874. /* expand background and tRNS chunks */
  190875. switch (png_ptr->bit_depth)
  190876. {
  190877. case 1:
  190878. png_ptr->background.gray *= (png_uint_16)0xff;
  190879. png_ptr->background.red = png_ptr->background.green
  190880. = png_ptr->background.blue = png_ptr->background.gray;
  190881. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190882. {
  190883. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190884. png_ptr->trans_values.red = png_ptr->trans_values.green
  190885. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190886. }
  190887. break;
  190888. case 2:
  190889. png_ptr->background.gray *= (png_uint_16)0x55;
  190890. png_ptr->background.red = png_ptr->background.green
  190891. = png_ptr->background.blue = png_ptr->background.gray;
  190892. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190893. {
  190894. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190895. png_ptr->trans_values.red = png_ptr->trans_values.green
  190896. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190897. }
  190898. break;
  190899. case 4:
  190900. png_ptr->background.gray *= (png_uint_16)0x11;
  190901. png_ptr->background.red = png_ptr->background.green
  190902. = png_ptr->background.blue = png_ptr->background.gray;
  190903. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190904. {
  190905. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190906. png_ptr->trans_values.red = png_ptr->trans_values.green
  190907. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190908. }
  190909. break;
  190910. case 8:
  190911. case 16:
  190912. png_ptr->background.red = png_ptr->background.green
  190913. = png_ptr->background.blue = png_ptr->background.gray;
  190914. break;
  190915. }
  190916. }
  190917. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190918. {
  190919. png_ptr->background.red =
  190920. png_ptr->palette[png_ptr->background.index].red;
  190921. png_ptr->background.green =
  190922. png_ptr->palette[png_ptr->background.index].green;
  190923. png_ptr->background.blue =
  190924. png_ptr->palette[png_ptr->background.index].blue;
  190925. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190926. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190927. {
  190928. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190929. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190930. #endif
  190931. {
  190932. /* invert the alpha channel (in tRNS) unless the pixels are
  190933. going to be expanded, in which case leave it for later */
  190934. int i,istop;
  190935. istop=(int)png_ptr->num_trans;
  190936. for (i=0; i<istop; i++)
  190937. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190938. }
  190939. }
  190940. #endif
  190941. }
  190942. }
  190943. #endif
  190944. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190945. png_ptr->background_1 = png_ptr->background;
  190946. #endif
  190947. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190948. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190949. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190950. < PNG_GAMMA_THRESHOLD))
  190951. {
  190952. int i,k;
  190953. k=0;
  190954. for (i=0; i<png_ptr->num_trans; i++)
  190955. {
  190956. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190957. k=1; /* partial transparency is present */
  190958. }
  190959. if (k == 0)
  190960. png_ptr->transformations &= (~PNG_GAMMA);
  190961. }
  190962. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190963. png_ptr->gamma != 0.0)
  190964. {
  190965. png_build_gamma_table(png_ptr);
  190966. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190967. if (png_ptr->transformations & PNG_BACKGROUND)
  190968. {
  190969. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190970. {
  190971. /* could skip if no transparency and
  190972. */
  190973. png_color back, back_1;
  190974. png_colorp palette = png_ptr->palette;
  190975. int num_palette = png_ptr->num_palette;
  190976. int i;
  190977. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190978. {
  190979. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190980. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190981. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190982. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190983. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190984. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190985. }
  190986. else
  190987. {
  190988. double g, gs;
  190989. switch (png_ptr->background_gamma_type)
  190990. {
  190991. case PNG_BACKGROUND_GAMMA_SCREEN:
  190992. g = (png_ptr->screen_gamma);
  190993. gs = 1.0;
  190994. break;
  190995. case PNG_BACKGROUND_GAMMA_FILE:
  190996. g = 1.0 / (png_ptr->gamma);
  190997. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190998. break;
  190999. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191000. g = 1.0 / (png_ptr->background_gamma);
  191001. gs = 1.0 / (png_ptr->background_gamma *
  191002. png_ptr->screen_gamma);
  191003. break;
  191004. default:
  191005. g = 1.0; /* back_1 */
  191006. gs = 1.0; /* back */
  191007. }
  191008. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  191009. {
  191010. back.red = (png_byte)png_ptr->background.red;
  191011. back.green = (png_byte)png_ptr->background.green;
  191012. back.blue = (png_byte)png_ptr->background.blue;
  191013. }
  191014. else
  191015. {
  191016. back.red = (png_byte)(pow(
  191017. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  191018. back.green = (png_byte)(pow(
  191019. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  191020. back.blue = (png_byte)(pow(
  191021. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  191022. }
  191023. back_1.red = (png_byte)(pow(
  191024. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  191025. back_1.green = (png_byte)(pow(
  191026. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  191027. back_1.blue = (png_byte)(pow(
  191028. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  191029. }
  191030. for (i = 0; i < num_palette; i++)
  191031. {
  191032. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191033. {
  191034. if (png_ptr->trans[i] == 0)
  191035. {
  191036. palette[i] = back;
  191037. }
  191038. else /* if (png_ptr->trans[i] != 0xff) */
  191039. {
  191040. png_byte v, w;
  191041. v = png_ptr->gamma_to_1[palette[i].red];
  191042. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191043. palette[i].red = png_ptr->gamma_from_1[w];
  191044. v = png_ptr->gamma_to_1[palette[i].green];
  191045. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191046. palette[i].green = png_ptr->gamma_from_1[w];
  191047. v = png_ptr->gamma_to_1[palette[i].blue];
  191048. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191049. palette[i].blue = png_ptr->gamma_from_1[w];
  191050. }
  191051. }
  191052. else
  191053. {
  191054. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191055. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191056. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191057. }
  191058. }
  191059. }
  191060. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  191061. else
  191062. /* color_type != PNG_COLOR_TYPE_PALETTE */
  191063. {
  191064. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  191065. double g = 1.0;
  191066. double gs = 1.0;
  191067. switch (png_ptr->background_gamma_type)
  191068. {
  191069. case PNG_BACKGROUND_GAMMA_SCREEN:
  191070. g = (png_ptr->screen_gamma);
  191071. gs = 1.0;
  191072. break;
  191073. case PNG_BACKGROUND_GAMMA_FILE:
  191074. g = 1.0 / (png_ptr->gamma);
  191075. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191076. break;
  191077. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191078. g = 1.0 / (png_ptr->background_gamma);
  191079. gs = 1.0 / (png_ptr->background_gamma *
  191080. png_ptr->screen_gamma);
  191081. break;
  191082. }
  191083. png_ptr->background_1.gray = (png_uint_16)(pow(
  191084. (double)png_ptr->background.gray / m, g) * m + .5);
  191085. png_ptr->background.gray = (png_uint_16)(pow(
  191086. (double)png_ptr->background.gray / m, gs) * m + .5);
  191087. if ((png_ptr->background.red != png_ptr->background.green) ||
  191088. (png_ptr->background.red != png_ptr->background.blue) ||
  191089. (png_ptr->background.red != png_ptr->background.gray))
  191090. {
  191091. /* RGB or RGBA with color background */
  191092. png_ptr->background_1.red = (png_uint_16)(pow(
  191093. (double)png_ptr->background.red / m, g) * m + .5);
  191094. png_ptr->background_1.green = (png_uint_16)(pow(
  191095. (double)png_ptr->background.green / m, g) * m + .5);
  191096. png_ptr->background_1.blue = (png_uint_16)(pow(
  191097. (double)png_ptr->background.blue / m, g) * m + .5);
  191098. png_ptr->background.red = (png_uint_16)(pow(
  191099. (double)png_ptr->background.red / m, gs) * m + .5);
  191100. png_ptr->background.green = (png_uint_16)(pow(
  191101. (double)png_ptr->background.green / m, gs) * m + .5);
  191102. png_ptr->background.blue = (png_uint_16)(pow(
  191103. (double)png_ptr->background.blue / m, gs) * m + .5);
  191104. }
  191105. else
  191106. {
  191107. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  191108. png_ptr->background_1.red = png_ptr->background_1.green
  191109. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  191110. png_ptr->background.red = png_ptr->background.green
  191111. = png_ptr->background.blue = png_ptr->background.gray;
  191112. }
  191113. }
  191114. }
  191115. else
  191116. /* transformation does not include PNG_BACKGROUND */
  191117. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191118. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191119. {
  191120. png_colorp palette = png_ptr->palette;
  191121. int num_palette = png_ptr->num_palette;
  191122. int i;
  191123. for (i = 0; i < num_palette; i++)
  191124. {
  191125. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191126. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191127. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191128. }
  191129. }
  191130. }
  191131. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191132. else
  191133. #endif
  191134. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  191135. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191136. /* No GAMMA transformation */
  191137. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191138. (color_type == PNG_COLOR_TYPE_PALETTE))
  191139. {
  191140. int i;
  191141. int istop = (int)png_ptr->num_trans;
  191142. png_color back;
  191143. png_colorp palette = png_ptr->palette;
  191144. back.red = (png_byte)png_ptr->background.red;
  191145. back.green = (png_byte)png_ptr->background.green;
  191146. back.blue = (png_byte)png_ptr->background.blue;
  191147. for (i = 0; i < istop; i++)
  191148. {
  191149. if (png_ptr->trans[i] == 0)
  191150. {
  191151. palette[i] = back;
  191152. }
  191153. else if (png_ptr->trans[i] != 0xff)
  191154. {
  191155. /* The png_composite() macro is defined in png.h */
  191156. png_composite(palette[i].red, palette[i].red,
  191157. png_ptr->trans[i], back.red);
  191158. png_composite(palette[i].green, palette[i].green,
  191159. png_ptr->trans[i], back.green);
  191160. png_composite(palette[i].blue, palette[i].blue,
  191161. png_ptr->trans[i], back.blue);
  191162. }
  191163. }
  191164. }
  191165. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191166. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191167. if ((png_ptr->transformations & PNG_SHIFT) &&
  191168. (color_type == PNG_COLOR_TYPE_PALETTE))
  191169. {
  191170. png_uint_16 i;
  191171. png_uint_16 istop = png_ptr->num_palette;
  191172. int sr = 8 - png_ptr->sig_bit.red;
  191173. int sg = 8 - png_ptr->sig_bit.green;
  191174. int sb = 8 - png_ptr->sig_bit.blue;
  191175. if (sr < 0 || sr > 8)
  191176. sr = 0;
  191177. if (sg < 0 || sg > 8)
  191178. sg = 0;
  191179. if (sb < 0 || sb > 8)
  191180. sb = 0;
  191181. for (i = 0; i < istop; i++)
  191182. {
  191183. png_ptr->palette[i].red >>= sr;
  191184. png_ptr->palette[i].green >>= sg;
  191185. png_ptr->palette[i].blue >>= sb;
  191186. }
  191187. }
  191188. #endif /* PNG_READ_SHIFT_SUPPORTED */
  191189. }
  191190. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  191191. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  191192. if(png_ptr)
  191193. return;
  191194. #endif
  191195. }
  191196. /* Modify the info structure to reflect the transformations. The
  191197. * info should be updated so a PNG file could be written with it,
  191198. * assuming the transformations result in valid PNG data.
  191199. */
  191200. void /* PRIVATE */
  191201. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191202. {
  191203. png_debug(1, "in png_read_transform_info\n");
  191204. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191205. if (png_ptr->transformations & PNG_EXPAND)
  191206. {
  191207. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191208. {
  191209. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191210. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191211. else
  191212. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191213. info_ptr->bit_depth = 8;
  191214. info_ptr->num_trans = 0;
  191215. }
  191216. else
  191217. {
  191218. if (png_ptr->num_trans)
  191219. {
  191220. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191221. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191222. else
  191223. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191224. }
  191225. if (info_ptr->bit_depth < 8)
  191226. info_ptr->bit_depth = 8;
  191227. info_ptr->num_trans = 0;
  191228. }
  191229. }
  191230. #endif
  191231. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191232. if (png_ptr->transformations & PNG_BACKGROUND)
  191233. {
  191234. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191235. info_ptr->num_trans = 0;
  191236. info_ptr->background = png_ptr->background;
  191237. }
  191238. #endif
  191239. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191240. if (png_ptr->transformations & PNG_GAMMA)
  191241. {
  191242. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191243. info_ptr->gamma = png_ptr->gamma;
  191244. #endif
  191245. #ifdef PNG_FIXED_POINT_SUPPORTED
  191246. info_ptr->int_gamma = png_ptr->int_gamma;
  191247. #endif
  191248. }
  191249. #endif
  191250. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191251. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191252. info_ptr->bit_depth = 8;
  191253. #endif
  191254. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191255. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191256. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191257. #endif
  191258. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191259. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191260. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191261. #endif
  191262. #if defined(PNG_READ_DITHER_SUPPORTED)
  191263. if (png_ptr->transformations & PNG_DITHER)
  191264. {
  191265. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191266. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191267. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191268. {
  191269. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191270. }
  191271. }
  191272. #endif
  191273. #if defined(PNG_READ_PACK_SUPPORTED)
  191274. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191275. info_ptr->bit_depth = 8;
  191276. #endif
  191277. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191278. info_ptr->channels = 1;
  191279. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191280. info_ptr->channels = 3;
  191281. else
  191282. info_ptr->channels = 1;
  191283. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191284. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191285. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191286. #endif
  191287. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191288. info_ptr->channels++;
  191289. #if defined(PNG_READ_FILLER_SUPPORTED)
  191290. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191291. if ((png_ptr->transformations & PNG_FILLER) &&
  191292. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191293. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191294. {
  191295. info_ptr->channels++;
  191296. /* if adding a true alpha channel not just filler */
  191297. #if !defined(PNG_1_0_X)
  191298. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191299. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191300. #endif
  191301. }
  191302. #endif
  191303. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191304. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191305. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191306. {
  191307. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191308. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191309. if(info_ptr->channels < png_ptr->user_transform_channels)
  191310. info_ptr->channels = png_ptr->user_transform_channels;
  191311. }
  191312. #endif
  191313. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191314. info_ptr->bit_depth);
  191315. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191316. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191317. if(png_ptr)
  191318. return;
  191319. #endif
  191320. }
  191321. /* Transform the row. The order of transformations is significant,
  191322. * and is very touchy. If you add a transformation, take care to
  191323. * decide how it fits in with the other transformations here.
  191324. */
  191325. void /* PRIVATE */
  191326. png_do_read_transformations(png_structp png_ptr)
  191327. {
  191328. png_debug(1, "in png_do_read_transformations\n");
  191329. if (png_ptr->row_buf == NULL)
  191330. {
  191331. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191332. char msg[50];
  191333. png_snprintf2(msg, 50,
  191334. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191335. png_ptr->pass);
  191336. png_error(png_ptr, msg);
  191337. #else
  191338. png_error(png_ptr, "NULL row buffer");
  191339. #endif
  191340. }
  191341. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191342. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191343. /* Application has failed to call either png_read_start_image()
  191344. * or png_read_update_info() after setting transforms that expand
  191345. * pixels. This check added to libpng-1.2.19 */
  191346. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191347. png_error(png_ptr, "Uninitialized row");
  191348. #else
  191349. png_warning(png_ptr, "Uninitialized row");
  191350. #endif
  191351. #endif
  191352. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191353. if (png_ptr->transformations & PNG_EXPAND)
  191354. {
  191355. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191356. {
  191357. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191358. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191359. }
  191360. else
  191361. {
  191362. if (png_ptr->num_trans &&
  191363. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191364. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191365. &(png_ptr->trans_values));
  191366. else
  191367. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191368. NULL);
  191369. }
  191370. }
  191371. #endif
  191372. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191373. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191374. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191375. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191376. #endif
  191377. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191378. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191379. {
  191380. int rgb_error =
  191381. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191382. if(rgb_error)
  191383. {
  191384. png_ptr->rgb_to_gray_status=1;
  191385. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191386. PNG_RGB_TO_GRAY_WARN)
  191387. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191388. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191389. PNG_RGB_TO_GRAY_ERR)
  191390. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191391. }
  191392. }
  191393. #endif
  191394. /*
  191395. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191396. In most cases, the "simple transparency" should be done prior to doing
  191397. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191398. pixel is transparent. You would also need to make sure that the
  191399. transparency information is upgraded to RGB.
  191400. To summarize, the current flow is:
  191401. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191402. with background "in place" if transparent,
  191403. convert to RGB if necessary
  191404. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191405. convert to RGB if necessary
  191406. To support RGB backgrounds for gray images we need:
  191407. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191408. 3 or 6 bytes and composite with background
  191409. "in place" if transparent (3x compare/pixel
  191410. compared to doing composite with gray bkgrnd)
  191411. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191412. remove alpha bytes (3x float operations/pixel
  191413. compared with composite on gray background)
  191414. Greg's change will do this. The reason it wasn't done before is for
  191415. performance, as this increases the per-pixel operations. If we would check
  191416. in advance if the background was gray or RGB, and position the gray-to-RGB
  191417. transform appropriately, then it would save a lot of work/time.
  191418. */
  191419. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191420. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191421. * for performance reasons */
  191422. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191423. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191424. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191425. #endif
  191426. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191427. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191428. ((png_ptr->num_trans != 0 ) ||
  191429. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191430. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191431. &(png_ptr->trans_values), &(png_ptr->background)
  191432. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191433. , &(png_ptr->background_1),
  191434. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191435. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191436. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191437. png_ptr->gamma_shift
  191438. #endif
  191439. );
  191440. #endif
  191441. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191442. if ((png_ptr->transformations & PNG_GAMMA) &&
  191443. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191444. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191445. ((png_ptr->num_trans != 0) ||
  191446. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191447. #endif
  191448. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191449. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191450. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191451. png_ptr->gamma_shift);
  191452. #endif
  191453. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191454. if (png_ptr->transformations & PNG_16_TO_8)
  191455. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191456. #endif
  191457. #if defined(PNG_READ_DITHER_SUPPORTED)
  191458. if (png_ptr->transformations & PNG_DITHER)
  191459. {
  191460. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191461. png_ptr->palette_lookup, png_ptr->dither_index);
  191462. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191463. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191464. }
  191465. #endif
  191466. #if defined(PNG_READ_INVERT_SUPPORTED)
  191467. if (png_ptr->transformations & PNG_INVERT_MONO)
  191468. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191469. #endif
  191470. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191471. if (png_ptr->transformations & PNG_SHIFT)
  191472. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191473. &(png_ptr->shift));
  191474. #endif
  191475. #if defined(PNG_READ_PACK_SUPPORTED)
  191476. if (png_ptr->transformations & PNG_PACK)
  191477. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191478. #endif
  191479. #if defined(PNG_READ_BGR_SUPPORTED)
  191480. if (png_ptr->transformations & PNG_BGR)
  191481. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191482. #endif
  191483. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191484. if (png_ptr->transformations & PNG_PACKSWAP)
  191485. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191486. #endif
  191487. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191488. /* if gray -> RGB, do so now only if we did not do so above */
  191489. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191490. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191491. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191492. #endif
  191493. #if defined(PNG_READ_FILLER_SUPPORTED)
  191494. if (png_ptr->transformations & PNG_FILLER)
  191495. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191496. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191497. #endif
  191498. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191499. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191500. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191501. #endif
  191502. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191503. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191504. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191505. #endif
  191506. #if defined(PNG_READ_SWAP_SUPPORTED)
  191507. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191508. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191509. #endif
  191510. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191511. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191512. {
  191513. if(png_ptr->read_user_transform_fn != NULL)
  191514. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191515. (png_ptr, /* png_ptr */
  191516. &(png_ptr->row_info), /* row_info: */
  191517. /* png_uint_32 width; width of row */
  191518. /* png_uint_32 rowbytes; number of bytes in row */
  191519. /* png_byte color_type; color type of pixels */
  191520. /* png_byte bit_depth; bit depth of samples */
  191521. /* png_byte channels; number of channels (1-4) */
  191522. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191523. png_ptr->row_buf + 1); /* start of pixel data for row */
  191524. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191525. if(png_ptr->user_transform_depth)
  191526. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191527. if(png_ptr->user_transform_channels)
  191528. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191529. #endif
  191530. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191531. png_ptr->row_info.channels);
  191532. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191533. png_ptr->row_info.width);
  191534. }
  191535. #endif
  191536. }
  191537. #if defined(PNG_READ_PACK_SUPPORTED)
  191538. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191539. * without changing the actual values. Thus, if you had a row with
  191540. * a bit depth of 1, you would end up with bytes that only contained
  191541. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191542. * png_do_shift() after this.
  191543. */
  191544. void /* PRIVATE */
  191545. png_do_unpack(png_row_infop row_info, png_bytep row)
  191546. {
  191547. png_debug(1, "in png_do_unpack\n");
  191548. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191549. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191550. #else
  191551. if (row_info->bit_depth < 8)
  191552. #endif
  191553. {
  191554. png_uint_32 i;
  191555. png_uint_32 row_width=row_info->width;
  191556. switch (row_info->bit_depth)
  191557. {
  191558. case 1:
  191559. {
  191560. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191561. png_bytep dp = row + (png_size_t)row_width - 1;
  191562. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191563. for (i = 0; i < row_width; i++)
  191564. {
  191565. *dp = (png_byte)((*sp >> shift) & 0x01);
  191566. if (shift == 7)
  191567. {
  191568. shift = 0;
  191569. sp--;
  191570. }
  191571. else
  191572. shift++;
  191573. dp--;
  191574. }
  191575. break;
  191576. }
  191577. case 2:
  191578. {
  191579. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191580. png_bytep dp = row + (png_size_t)row_width - 1;
  191581. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191582. for (i = 0; i < row_width; i++)
  191583. {
  191584. *dp = (png_byte)((*sp >> shift) & 0x03);
  191585. if (shift == 6)
  191586. {
  191587. shift = 0;
  191588. sp--;
  191589. }
  191590. else
  191591. shift += 2;
  191592. dp--;
  191593. }
  191594. break;
  191595. }
  191596. case 4:
  191597. {
  191598. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191599. png_bytep dp = row + (png_size_t)row_width - 1;
  191600. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191601. for (i = 0; i < row_width; i++)
  191602. {
  191603. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191604. if (shift == 4)
  191605. {
  191606. shift = 0;
  191607. sp--;
  191608. }
  191609. else
  191610. shift = 4;
  191611. dp--;
  191612. }
  191613. break;
  191614. }
  191615. }
  191616. row_info->bit_depth = 8;
  191617. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191618. row_info->rowbytes = row_width * row_info->channels;
  191619. }
  191620. }
  191621. #endif
  191622. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191623. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191624. * pixels back to their significant bits values. Thus, if you have
  191625. * a row of bit depth 8, but only 5 are significant, this will shift
  191626. * the values back to 0 through 31.
  191627. */
  191628. void /* PRIVATE */
  191629. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191630. {
  191631. png_debug(1, "in png_do_unshift\n");
  191632. if (
  191633. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191634. row != NULL && row_info != NULL && sig_bits != NULL &&
  191635. #endif
  191636. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191637. {
  191638. int shift[4];
  191639. int channels = 0;
  191640. int c;
  191641. png_uint_16 value = 0;
  191642. png_uint_32 row_width = row_info->width;
  191643. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191644. {
  191645. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191646. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191647. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191648. }
  191649. else
  191650. {
  191651. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191652. }
  191653. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191654. {
  191655. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191656. }
  191657. for (c = 0; c < channels; c++)
  191658. {
  191659. if (shift[c] <= 0)
  191660. shift[c] = 0;
  191661. else
  191662. value = 1;
  191663. }
  191664. if (!value)
  191665. return;
  191666. switch (row_info->bit_depth)
  191667. {
  191668. case 2:
  191669. {
  191670. png_bytep bp;
  191671. png_uint_32 i;
  191672. png_uint_32 istop = row_info->rowbytes;
  191673. for (bp = row, i = 0; i < istop; i++)
  191674. {
  191675. *bp >>= 1;
  191676. *bp++ &= 0x55;
  191677. }
  191678. break;
  191679. }
  191680. case 4:
  191681. {
  191682. png_bytep bp = row;
  191683. png_uint_32 i;
  191684. png_uint_32 istop = row_info->rowbytes;
  191685. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191686. (png_byte)((int)0xf >> shift[0]));
  191687. for (i = 0; i < istop; i++)
  191688. {
  191689. *bp >>= shift[0];
  191690. *bp++ &= mask;
  191691. }
  191692. break;
  191693. }
  191694. case 8:
  191695. {
  191696. png_bytep bp = row;
  191697. png_uint_32 i;
  191698. png_uint_32 istop = row_width * channels;
  191699. for (i = 0; i < istop; i++)
  191700. {
  191701. *bp++ >>= shift[i%channels];
  191702. }
  191703. break;
  191704. }
  191705. case 16:
  191706. {
  191707. png_bytep bp = row;
  191708. png_uint_32 i;
  191709. png_uint_32 istop = channels * row_width;
  191710. for (i = 0; i < istop; i++)
  191711. {
  191712. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191713. value >>= shift[i%channels];
  191714. *bp++ = (png_byte)(value >> 8);
  191715. *bp++ = (png_byte)(value & 0xff);
  191716. }
  191717. break;
  191718. }
  191719. }
  191720. }
  191721. }
  191722. #endif
  191723. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191724. /* chop rows of bit depth 16 down to 8 */
  191725. void /* PRIVATE */
  191726. png_do_chop(png_row_infop row_info, png_bytep row)
  191727. {
  191728. png_debug(1, "in png_do_chop\n");
  191729. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191730. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191731. #else
  191732. if (row_info->bit_depth == 16)
  191733. #endif
  191734. {
  191735. png_bytep sp = row;
  191736. png_bytep dp = row;
  191737. png_uint_32 i;
  191738. png_uint_32 istop = row_info->width * row_info->channels;
  191739. for (i = 0; i<istop; i++, sp += 2, dp++)
  191740. {
  191741. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191742. /* This does a more accurate scaling of the 16-bit color
  191743. * value, rather than a simple low-byte truncation.
  191744. *
  191745. * What the ideal calculation should be:
  191746. * *dp = (((((png_uint_32)(*sp) << 8) |
  191747. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191748. *
  191749. * GRR: no, I think this is what it really should be:
  191750. * *dp = (((((png_uint_32)(*sp) << 8) |
  191751. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191752. *
  191753. * GRR: here's the exact calculation with shifts:
  191754. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191755. * *dp = (temp - (temp >> 8)) >> 8;
  191756. *
  191757. * Approximate calculation with shift/add instead of multiply/divide:
  191758. * *dp = ((((png_uint_32)(*sp) << 8) |
  191759. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191760. *
  191761. * What we actually do to avoid extra shifting and conversion:
  191762. */
  191763. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191764. #else
  191765. /* Simply discard the low order byte */
  191766. *dp = *sp;
  191767. #endif
  191768. }
  191769. row_info->bit_depth = 8;
  191770. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191771. row_info->rowbytes = row_info->width * row_info->channels;
  191772. }
  191773. }
  191774. #endif
  191775. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191776. void /* PRIVATE */
  191777. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191778. {
  191779. png_debug(1, "in png_do_read_swap_alpha\n");
  191780. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191781. if (row != NULL && row_info != NULL)
  191782. #endif
  191783. {
  191784. png_uint_32 row_width = row_info->width;
  191785. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191786. {
  191787. /* This converts from RGBA to ARGB */
  191788. if (row_info->bit_depth == 8)
  191789. {
  191790. png_bytep sp = row + row_info->rowbytes;
  191791. png_bytep dp = sp;
  191792. png_byte save;
  191793. png_uint_32 i;
  191794. for (i = 0; i < row_width; i++)
  191795. {
  191796. save = *(--sp);
  191797. *(--dp) = *(--sp);
  191798. *(--dp) = *(--sp);
  191799. *(--dp) = *(--sp);
  191800. *(--dp) = save;
  191801. }
  191802. }
  191803. /* This converts from RRGGBBAA to AARRGGBB */
  191804. else
  191805. {
  191806. png_bytep sp = row + row_info->rowbytes;
  191807. png_bytep dp = sp;
  191808. png_byte save[2];
  191809. png_uint_32 i;
  191810. for (i = 0; i < row_width; i++)
  191811. {
  191812. save[0] = *(--sp);
  191813. save[1] = *(--sp);
  191814. *(--dp) = *(--sp);
  191815. *(--dp) = *(--sp);
  191816. *(--dp) = *(--sp);
  191817. *(--dp) = *(--sp);
  191818. *(--dp) = *(--sp);
  191819. *(--dp) = *(--sp);
  191820. *(--dp) = save[0];
  191821. *(--dp) = save[1];
  191822. }
  191823. }
  191824. }
  191825. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191826. {
  191827. /* This converts from GA to AG */
  191828. if (row_info->bit_depth == 8)
  191829. {
  191830. png_bytep sp = row + row_info->rowbytes;
  191831. png_bytep dp = sp;
  191832. png_byte save;
  191833. png_uint_32 i;
  191834. for (i = 0; i < row_width; i++)
  191835. {
  191836. save = *(--sp);
  191837. *(--dp) = *(--sp);
  191838. *(--dp) = save;
  191839. }
  191840. }
  191841. /* This converts from GGAA to AAGG */
  191842. else
  191843. {
  191844. png_bytep sp = row + row_info->rowbytes;
  191845. png_bytep dp = sp;
  191846. png_byte save[2];
  191847. png_uint_32 i;
  191848. for (i = 0; i < row_width; i++)
  191849. {
  191850. save[0] = *(--sp);
  191851. save[1] = *(--sp);
  191852. *(--dp) = *(--sp);
  191853. *(--dp) = *(--sp);
  191854. *(--dp) = save[0];
  191855. *(--dp) = save[1];
  191856. }
  191857. }
  191858. }
  191859. }
  191860. }
  191861. #endif
  191862. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191863. void /* PRIVATE */
  191864. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191865. {
  191866. png_debug(1, "in png_do_read_invert_alpha\n");
  191867. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191868. if (row != NULL && row_info != NULL)
  191869. #endif
  191870. {
  191871. png_uint_32 row_width = row_info->width;
  191872. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191873. {
  191874. /* This inverts the alpha channel in RGBA */
  191875. if (row_info->bit_depth == 8)
  191876. {
  191877. png_bytep sp = row + row_info->rowbytes;
  191878. png_bytep dp = sp;
  191879. png_uint_32 i;
  191880. for (i = 0; i < row_width; i++)
  191881. {
  191882. *(--dp) = (png_byte)(255 - *(--sp));
  191883. /* This does nothing:
  191884. *(--dp) = *(--sp);
  191885. *(--dp) = *(--sp);
  191886. *(--dp) = *(--sp);
  191887. We can replace it with:
  191888. */
  191889. sp-=3;
  191890. dp=sp;
  191891. }
  191892. }
  191893. /* This inverts the alpha channel in RRGGBBAA */
  191894. else
  191895. {
  191896. png_bytep sp = row + row_info->rowbytes;
  191897. png_bytep dp = sp;
  191898. png_uint_32 i;
  191899. for (i = 0; i < row_width; i++)
  191900. {
  191901. *(--dp) = (png_byte)(255 - *(--sp));
  191902. *(--dp) = (png_byte)(255 - *(--sp));
  191903. /* This does nothing:
  191904. *(--dp) = *(--sp);
  191905. *(--dp) = *(--sp);
  191906. *(--dp) = *(--sp);
  191907. *(--dp) = *(--sp);
  191908. *(--dp) = *(--sp);
  191909. *(--dp) = *(--sp);
  191910. We can replace it with:
  191911. */
  191912. sp-=6;
  191913. dp=sp;
  191914. }
  191915. }
  191916. }
  191917. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191918. {
  191919. /* This inverts the alpha channel in GA */
  191920. if (row_info->bit_depth == 8)
  191921. {
  191922. png_bytep sp = row + row_info->rowbytes;
  191923. png_bytep dp = sp;
  191924. png_uint_32 i;
  191925. for (i = 0; i < row_width; i++)
  191926. {
  191927. *(--dp) = (png_byte)(255 - *(--sp));
  191928. *(--dp) = *(--sp);
  191929. }
  191930. }
  191931. /* This inverts the alpha channel in GGAA */
  191932. else
  191933. {
  191934. png_bytep sp = row + row_info->rowbytes;
  191935. png_bytep dp = sp;
  191936. png_uint_32 i;
  191937. for (i = 0; i < row_width; i++)
  191938. {
  191939. *(--dp) = (png_byte)(255 - *(--sp));
  191940. *(--dp) = (png_byte)(255 - *(--sp));
  191941. /*
  191942. *(--dp) = *(--sp);
  191943. *(--dp) = *(--sp);
  191944. */
  191945. sp-=2;
  191946. dp=sp;
  191947. }
  191948. }
  191949. }
  191950. }
  191951. }
  191952. #endif
  191953. #if defined(PNG_READ_FILLER_SUPPORTED)
  191954. /* Add filler channel if we have RGB color */
  191955. void /* PRIVATE */
  191956. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191957. png_uint_32 filler, png_uint_32 flags)
  191958. {
  191959. png_uint_32 i;
  191960. png_uint_32 row_width = row_info->width;
  191961. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191962. png_byte lo_filler = (png_byte)(filler & 0xff);
  191963. png_debug(1, "in png_do_read_filler\n");
  191964. if (
  191965. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191966. row != NULL && row_info != NULL &&
  191967. #endif
  191968. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191969. {
  191970. if(row_info->bit_depth == 8)
  191971. {
  191972. /* This changes the data from G to GX */
  191973. if (flags & PNG_FLAG_FILLER_AFTER)
  191974. {
  191975. png_bytep sp = row + (png_size_t)row_width;
  191976. png_bytep dp = sp + (png_size_t)row_width;
  191977. for (i = 1; i < row_width; i++)
  191978. {
  191979. *(--dp) = lo_filler;
  191980. *(--dp) = *(--sp);
  191981. }
  191982. *(--dp) = lo_filler;
  191983. row_info->channels = 2;
  191984. row_info->pixel_depth = 16;
  191985. row_info->rowbytes = row_width * 2;
  191986. }
  191987. /* This changes the data from G to XG */
  191988. else
  191989. {
  191990. png_bytep sp = row + (png_size_t)row_width;
  191991. png_bytep dp = sp + (png_size_t)row_width;
  191992. for (i = 0; i < row_width; i++)
  191993. {
  191994. *(--dp) = *(--sp);
  191995. *(--dp) = lo_filler;
  191996. }
  191997. row_info->channels = 2;
  191998. row_info->pixel_depth = 16;
  191999. row_info->rowbytes = row_width * 2;
  192000. }
  192001. }
  192002. else if(row_info->bit_depth == 16)
  192003. {
  192004. /* This changes the data from GG to GGXX */
  192005. if (flags & PNG_FLAG_FILLER_AFTER)
  192006. {
  192007. png_bytep sp = row + (png_size_t)row_width * 2;
  192008. png_bytep dp = sp + (png_size_t)row_width * 2;
  192009. for (i = 1; i < row_width; i++)
  192010. {
  192011. *(--dp) = hi_filler;
  192012. *(--dp) = lo_filler;
  192013. *(--dp) = *(--sp);
  192014. *(--dp) = *(--sp);
  192015. }
  192016. *(--dp) = hi_filler;
  192017. *(--dp) = lo_filler;
  192018. row_info->channels = 2;
  192019. row_info->pixel_depth = 32;
  192020. row_info->rowbytes = row_width * 4;
  192021. }
  192022. /* This changes the data from GG to XXGG */
  192023. else
  192024. {
  192025. png_bytep sp = row + (png_size_t)row_width * 2;
  192026. png_bytep dp = sp + (png_size_t)row_width * 2;
  192027. for (i = 0; i < row_width; i++)
  192028. {
  192029. *(--dp) = *(--sp);
  192030. *(--dp) = *(--sp);
  192031. *(--dp) = hi_filler;
  192032. *(--dp) = lo_filler;
  192033. }
  192034. row_info->channels = 2;
  192035. row_info->pixel_depth = 32;
  192036. row_info->rowbytes = row_width * 4;
  192037. }
  192038. }
  192039. } /* COLOR_TYPE == GRAY */
  192040. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192041. {
  192042. if(row_info->bit_depth == 8)
  192043. {
  192044. /* This changes the data from RGB to RGBX */
  192045. if (flags & PNG_FLAG_FILLER_AFTER)
  192046. {
  192047. png_bytep sp = row + (png_size_t)row_width * 3;
  192048. png_bytep dp = sp + (png_size_t)row_width;
  192049. for (i = 1; i < row_width; i++)
  192050. {
  192051. *(--dp) = lo_filler;
  192052. *(--dp) = *(--sp);
  192053. *(--dp) = *(--sp);
  192054. *(--dp) = *(--sp);
  192055. }
  192056. *(--dp) = lo_filler;
  192057. row_info->channels = 4;
  192058. row_info->pixel_depth = 32;
  192059. row_info->rowbytes = row_width * 4;
  192060. }
  192061. /* This changes the data from RGB to XRGB */
  192062. else
  192063. {
  192064. png_bytep sp = row + (png_size_t)row_width * 3;
  192065. png_bytep dp = sp + (png_size_t)row_width;
  192066. for (i = 0; i < row_width; i++)
  192067. {
  192068. *(--dp) = *(--sp);
  192069. *(--dp) = *(--sp);
  192070. *(--dp) = *(--sp);
  192071. *(--dp) = lo_filler;
  192072. }
  192073. row_info->channels = 4;
  192074. row_info->pixel_depth = 32;
  192075. row_info->rowbytes = row_width * 4;
  192076. }
  192077. }
  192078. else if(row_info->bit_depth == 16)
  192079. {
  192080. /* This changes the data from RRGGBB to RRGGBBXX */
  192081. if (flags & PNG_FLAG_FILLER_AFTER)
  192082. {
  192083. png_bytep sp = row + (png_size_t)row_width * 6;
  192084. png_bytep dp = sp + (png_size_t)row_width * 2;
  192085. for (i = 1; i < row_width; i++)
  192086. {
  192087. *(--dp) = hi_filler;
  192088. *(--dp) = lo_filler;
  192089. *(--dp) = *(--sp);
  192090. *(--dp) = *(--sp);
  192091. *(--dp) = *(--sp);
  192092. *(--dp) = *(--sp);
  192093. *(--dp) = *(--sp);
  192094. *(--dp) = *(--sp);
  192095. }
  192096. *(--dp) = hi_filler;
  192097. *(--dp) = lo_filler;
  192098. row_info->channels = 4;
  192099. row_info->pixel_depth = 64;
  192100. row_info->rowbytes = row_width * 8;
  192101. }
  192102. /* This changes the data from RRGGBB to XXRRGGBB */
  192103. else
  192104. {
  192105. png_bytep sp = row + (png_size_t)row_width * 6;
  192106. png_bytep dp = sp + (png_size_t)row_width * 2;
  192107. for (i = 0; i < row_width; i++)
  192108. {
  192109. *(--dp) = *(--sp);
  192110. *(--dp) = *(--sp);
  192111. *(--dp) = *(--sp);
  192112. *(--dp) = *(--sp);
  192113. *(--dp) = *(--sp);
  192114. *(--dp) = *(--sp);
  192115. *(--dp) = hi_filler;
  192116. *(--dp) = lo_filler;
  192117. }
  192118. row_info->channels = 4;
  192119. row_info->pixel_depth = 64;
  192120. row_info->rowbytes = row_width * 8;
  192121. }
  192122. }
  192123. } /* COLOR_TYPE == RGB */
  192124. }
  192125. #endif
  192126. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192127. /* expand grayscale files to RGB, with or without alpha */
  192128. void /* PRIVATE */
  192129. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  192130. {
  192131. png_uint_32 i;
  192132. png_uint_32 row_width = row_info->width;
  192133. png_debug(1, "in png_do_gray_to_rgb\n");
  192134. if (row_info->bit_depth >= 8 &&
  192135. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192136. row != NULL && row_info != NULL &&
  192137. #endif
  192138. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  192139. {
  192140. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192141. {
  192142. if (row_info->bit_depth == 8)
  192143. {
  192144. png_bytep sp = row + (png_size_t)row_width - 1;
  192145. png_bytep dp = sp + (png_size_t)row_width * 2;
  192146. for (i = 0; i < row_width; i++)
  192147. {
  192148. *(dp--) = *sp;
  192149. *(dp--) = *sp;
  192150. *(dp--) = *(sp--);
  192151. }
  192152. }
  192153. else
  192154. {
  192155. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192156. png_bytep dp = sp + (png_size_t)row_width * 4;
  192157. for (i = 0; i < row_width; i++)
  192158. {
  192159. *(dp--) = *sp;
  192160. *(dp--) = *(sp - 1);
  192161. *(dp--) = *sp;
  192162. *(dp--) = *(sp - 1);
  192163. *(dp--) = *(sp--);
  192164. *(dp--) = *(sp--);
  192165. }
  192166. }
  192167. }
  192168. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192169. {
  192170. if (row_info->bit_depth == 8)
  192171. {
  192172. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192173. png_bytep dp = sp + (png_size_t)row_width * 2;
  192174. for (i = 0; i < row_width; i++)
  192175. {
  192176. *(dp--) = *(sp--);
  192177. *(dp--) = *sp;
  192178. *(dp--) = *sp;
  192179. *(dp--) = *(sp--);
  192180. }
  192181. }
  192182. else
  192183. {
  192184. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  192185. png_bytep dp = sp + (png_size_t)row_width * 4;
  192186. for (i = 0; i < row_width; i++)
  192187. {
  192188. *(dp--) = *(sp--);
  192189. *(dp--) = *(sp--);
  192190. *(dp--) = *sp;
  192191. *(dp--) = *(sp - 1);
  192192. *(dp--) = *sp;
  192193. *(dp--) = *(sp - 1);
  192194. *(dp--) = *(sp--);
  192195. *(dp--) = *(sp--);
  192196. }
  192197. }
  192198. }
  192199. row_info->channels += (png_byte)2;
  192200. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192201. row_info->pixel_depth = (png_byte)(row_info->channels *
  192202. row_info->bit_depth);
  192203. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192204. }
  192205. }
  192206. #endif
  192207. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192208. /* reduce RGB files to grayscale, with or without alpha
  192209. * using the equation given in Poynton's ColorFAQ at
  192210. * <http://www.inforamp.net/~poynton/>
  192211. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192212. *
  192213. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192214. *
  192215. * We approximate this with
  192216. *
  192217. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192218. *
  192219. * which can be expressed with integers as
  192220. *
  192221. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192222. *
  192223. * The calculation is to be done in a linear colorspace.
  192224. *
  192225. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192226. */
  192227. int /* PRIVATE */
  192228. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192229. {
  192230. png_uint_32 i;
  192231. png_uint_32 row_width = row_info->width;
  192232. int rgb_error = 0;
  192233. png_debug(1, "in png_do_rgb_to_gray\n");
  192234. if (
  192235. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192236. row != NULL && row_info != NULL &&
  192237. #endif
  192238. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192239. {
  192240. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192241. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192242. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192243. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192244. {
  192245. if (row_info->bit_depth == 8)
  192246. {
  192247. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192248. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192249. {
  192250. png_bytep sp = row;
  192251. png_bytep dp = row;
  192252. for (i = 0; i < row_width; i++)
  192253. {
  192254. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192255. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192256. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192257. if(red != green || red != blue)
  192258. {
  192259. rgb_error |= 1;
  192260. *(dp++) = png_ptr->gamma_from_1[
  192261. (rc*red+gc*green+bc*blue)>>15];
  192262. }
  192263. else
  192264. *(dp++) = *(sp-1);
  192265. }
  192266. }
  192267. else
  192268. #endif
  192269. {
  192270. png_bytep sp = row;
  192271. png_bytep dp = row;
  192272. for (i = 0; i < row_width; i++)
  192273. {
  192274. png_byte red = *(sp++);
  192275. png_byte green = *(sp++);
  192276. png_byte blue = *(sp++);
  192277. if(red != green || red != blue)
  192278. {
  192279. rgb_error |= 1;
  192280. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192281. }
  192282. else
  192283. *(dp++) = *(sp-1);
  192284. }
  192285. }
  192286. }
  192287. else /* RGB bit_depth == 16 */
  192288. {
  192289. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192290. if (png_ptr->gamma_16_to_1 != NULL &&
  192291. png_ptr->gamma_16_from_1 != NULL)
  192292. {
  192293. png_bytep sp = row;
  192294. png_bytep dp = row;
  192295. for (i = 0; i < row_width; i++)
  192296. {
  192297. png_uint_16 red, green, blue, w;
  192298. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192299. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192300. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192301. if(red == green && red == blue)
  192302. w = red;
  192303. else
  192304. {
  192305. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192306. png_ptr->gamma_shift][red>>8];
  192307. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192308. png_ptr->gamma_shift][green>>8];
  192309. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192310. png_ptr->gamma_shift][blue>>8];
  192311. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192312. + bc*blue_1)>>15);
  192313. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192314. png_ptr->gamma_shift][gray16 >> 8];
  192315. rgb_error |= 1;
  192316. }
  192317. *(dp++) = (png_byte)((w>>8) & 0xff);
  192318. *(dp++) = (png_byte)(w & 0xff);
  192319. }
  192320. }
  192321. else
  192322. #endif
  192323. {
  192324. png_bytep sp = row;
  192325. png_bytep dp = row;
  192326. for (i = 0; i < row_width; i++)
  192327. {
  192328. png_uint_16 red, green, blue, gray16;
  192329. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192330. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192331. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192332. if(red != green || red != blue)
  192333. rgb_error |= 1;
  192334. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192335. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192336. *(dp++) = (png_byte)(gray16 & 0xff);
  192337. }
  192338. }
  192339. }
  192340. }
  192341. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192342. {
  192343. if (row_info->bit_depth == 8)
  192344. {
  192345. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192346. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192347. {
  192348. png_bytep sp = row;
  192349. png_bytep dp = row;
  192350. for (i = 0; i < row_width; i++)
  192351. {
  192352. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192353. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192354. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192355. if(red != green || red != blue)
  192356. rgb_error |= 1;
  192357. *(dp++) = png_ptr->gamma_from_1
  192358. [(rc*red + gc*green + bc*blue)>>15];
  192359. *(dp++) = *(sp++); /* alpha */
  192360. }
  192361. }
  192362. else
  192363. #endif
  192364. {
  192365. png_bytep sp = row;
  192366. png_bytep dp = row;
  192367. for (i = 0; i < row_width; i++)
  192368. {
  192369. png_byte red = *(sp++);
  192370. png_byte green = *(sp++);
  192371. png_byte blue = *(sp++);
  192372. if(red != green || red != blue)
  192373. rgb_error |= 1;
  192374. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192375. *(dp++) = *(sp++); /* alpha */
  192376. }
  192377. }
  192378. }
  192379. else /* RGBA bit_depth == 16 */
  192380. {
  192381. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192382. if (png_ptr->gamma_16_to_1 != NULL &&
  192383. png_ptr->gamma_16_from_1 != NULL)
  192384. {
  192385. png_bytep sp = row;
  192386. png_bytep dp = row;
  192387. for (i = 0; i < row_width; i++)
  192388. {
  192389. png_uint_16 red, green, blue, w;
  192390. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192391. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192392. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192393. if(red == green && red == blue)
  192394. w = red;
  192395. else
  192396. {
  192397. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192398. png_ptr->gamma_shift][red>>8];
  192399. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192400. png_ptr->gamma_shift][green>>8];
  192401. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192402. png_ptr->gamma_shift][blue>>8];
  192403. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192404. + gc * green_1 + bc * blue_1)>>15);
  192405. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192406. png_ptr->gamma_shift][gray16 >> 8];
  192407. rgb_error |= 1;
  192408. }
  192409. *(dp++) = (png_byte)((w>>8) & 0xff);
  192410. *(dp++) = (png_byte)(w & 0xff);
  192411. *(dp++) = *(sp++); /* alpha */
  192412. *(dp++) = *(sp++);
  192413. }
  192414. }
  192415. else
  192416. #endif
  192417. {
  192418. png_bytep sp = row;
  192419. png_bytep dp = row;
  192420. for (i = 0; i < row_width; i++)
  192421. {
  192422. png_uint_16 red, green, blue, gray16;
  192423. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192424. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192425. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192426. if(red != green || red != blue)
  192427. rgb_error |= 1;
  192428. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192429. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192430. *(dp++) = (png_byte)(gray16 & 0xff);
  192431. *(dp++) = *(sp++); /* alpha */
  192432. *(dp++) = *(sp++);
  192433. }
  192434. }
  192435. }
  192436. }
  192437. row_info->channels -= (png_byte)2;
  192438. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192439. row_info->pixel_depth = (png_byte)(row_info->channels *
  192440. row_info->bit_depth);
  192441. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192442. }
  192443. return rgb_error;
  192444. }
  192445. #endif
  192446. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192447. * large of png_color. This lets grayscale images be treated as
  192448. * paletted. Most useful for gamma correction and simplification
  192449. * of code.
  192450. */
  192451. void PNGAPI
  192452. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192453. {
  192454. int num_palette;
  192455. int color_inc;
  192456. int i;
  192457. int v;
  192458. png_debug(1, "in png_do_build_grayscale_palette\n");
  192459. if (palette == NULL)
  192460. return;
  192461. switch (bit_depth)
  192462. {
  192463. case 1:
  192464. num_palette = 2;
  192465. color_inc = 0xff;
  192466. break;
  192467. case 2:
  192468. num_palette = 4;
  192469. color_inc = 0x55;
  192470. break;
  192471. case 4:
  192472. num_palette = 16;
  192473. color_inc = 0x11;
  192474. break;
  192475. case 8:
  192476. num_palette = 256;
  192477. color_inc = 1;
  192478. break;
  192479. default:
  192480. num_palette = 0;
  192481. color_inc = 0;
  192482. break;
  192483. }
  192484. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192485. {
  192486. palette[i].red = (png_byte)v;
  192487. palette[i].green = (png_byte)v;
  192488. palette[i].blue = (png_byte)v;
  192489. }
  192490. }
  192491. /* This function is currently unused. Do we really need it? */
  192492. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192493. void /* PRIVATE */
  192494. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192495. int num_palette)
  192496. {
  192497. png_debug(1, "in png_correct_palette\n");
  192498. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192499. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192500. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192501. {
  192502. png_color back, back_1;
  192503. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192504. {
  192505. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192506. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192507. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192508. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192509. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192510. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192511. }
  192512. else
  192513. {
  192514. double g;
  192515. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192516. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192517. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192518. {
  192519. back.red = png_ptr->background.red;
  192520. back.green = png_ptr->background.green;
  192521. back.blue = png_ptr->background.blue;
  192522. }
  192523. else
  192524. {
  192525. back.red =
  192526. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192527. 255.0 + 0.5);
  192528. back.green =
  192529. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192530. 255.0 + 0.5);
  192531. back.blue =
  192532. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192533. 255.0 + 0.5);
  192534. }
  192535. g = 1.0 / png_ptr->background_gamma;
  192536. back_1.red =
  192537. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192538. 255.0 + 0.5);
  192539. back_1.green =
  192540. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192541. 255.0 + 0.5);
  192542. back_1.blue =
  192543. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192544. 255.0 + 0.5);
  192545. }
  192546. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192547. {
  192548. png_uint_32 i;
  192549. for (i = 0; i < (png_uint_32)num_palette; i++)
  192550. {
  192551. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192552. {
  192553. palette[i] = back;
  192554. }
  192555. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192556. {
  192557. png_byte v, w;
  192558. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192559. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192560. palette[i].red = png_ptr->gamma_from_1[w];
  192561. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192562. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192563. palette[i].green = png_ptr->gamma_from_1[w];
  192564. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192565. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192566. palette[i].blue = png_ptr->gamma_from_1[w];
  192567. }
  192568. else
  192569. {
  192570. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192571. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192572. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192573. }
  192574. }
  192575. }
  192576. else
  192577. {
  192578. int i;
  192579. for (i = 0; i < num_palette; i++)
  192580. {
  192581. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192582. {
  192583. palette[i] = back;
  192584. }
  192585. else
  192586. {
  192587. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192588. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192589. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192590. }
  192591. }
  192592. }
  192593. }
  192594. else
  192595. #endif
  192596. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192597. if (png_ptr->transformations & PNG_GAMMA)
  192598. {
  192599. int i;
  192600. for (i = 0; i < num_palette; i++)
  192601. {
  192602. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192603. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192604. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192605. }
  192606. }
  192607. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192608. else
  192609. #endif
  192610. #endif
  192611. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192612. if (png_ptr->transformations & PNG_BACKGROUND)
  192613. {
  192614. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192615. {
  192616. png_color back;
  192617. back.red = (png_byte)png_ptr->background.red;
  192618. back.green = (png_byte)png_ptr->background.green;
  192619. back.blue = (png_byte)png_ptr->background.blue;
  192620. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192621. {
  192622. if (png_ptr->trans[i] == 0)
  192623. {
  192624. palette[i].red = back.red;
  192625. palette[i].green = back.green;
  192626. palette[i].blue = back.blue;
  192627. }
  192628. else if (png_ptr->trans[i] != 0xff)
  192629. {
  192630. png_composite(palette[i].red, png_ptr->palette[i].red,
  192631. png_ptr->trans[i], back.red);
  192632. png_composite(palette[i].green, png_ptr->palette[i].green,
  192633. png_ptr->trans[i], back.green);
  192634. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192635. png_ptr->trans[i], back.blue);
  192636. }
  192637. }
  192638. }
  192639. else /* assume grayscale palette (what else could it be?) */
  192640. {
  192641. int i;
  192642. for (i = 0; i < num_palette; i++)
  192643. {
  192644. if (i == (png_byte)png_ptr->trans_values.gray)
  192645. {
  192646. palette[i].red = (png_byte)png_ptr->background.red;
  192647. palette[i].green = (png_byte)png_ptr->background.green;
  192648. palette[i].blue = (png_byte)png_ptr->background.blue;
  192649. }
  192650. }
  192651. }
  192652. }
  192653. #endif
  192654. }
  192655. #endif
  192656. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192657. /* Replace any alpha or transparency with the supplied background color.
  192658. * "background" is already in the screen gamma, while "background_1" is
  192659. * at a gamma of 1.0. Paletted files have already been taken care of.
  192660. */
  192661. void /* PRIVATE */
  192662. png_do_background(png_row_infop row_info, png_bytep row,
  192663. png_color_16p trans_values, png_color_16p background
  192664. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192665. , png_color_16p background_1,
  192666. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192667. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192668. png_uint_16pp gamma_16_to_1, int gamma_shift
  192669. #endif
  192670. )
  192671. {
  192672. png_bytep sp, dp;
  192673. png_uint_32 i;
  192674. png_uint_32 row_width=row_info->width;
  192675. int shift;
  192676. png_debug(1, "in png_do_background\n");
  192677. if (background != NULL &&
  192678. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192679. row != NULL && row_info != NULL &&
  192680. #endif
  192681. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192682. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192683. {
  192684. switch (row_info->color_type)
  192685. {
  192686. case PNG_COLOR_TYPE_GRAY:
  192687. {
  192688. switch (row_info->bit_depth)
  192689. {
  192690. case 1:
  192691. {
  192692. sp = row;
  192693. shift = 7;
  192694. for (i = 0; i < row_width; i++)
  192695. {
  192696. if ((png_uint_16)((*sp >> shift) & 0x01)
  192697. == trans_values->gray)
  192698. {
  192699. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192700. *sp |= (png_byte)(background->gray << shift);
  192701. }
  192702. if (!shift)
  192703. {
  192704. shift = 7;
  192705. sp++;
  192706. }
  192707. else
  192708. shift--;
  192709. }
  192710. break;
  192711. }
  192712. case 2:
  192713. {
  192714. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192715. if (gamma_table != NULL)
  192716. {
  192717. sp = row;
  192718. shift = 6;
  192719. for (i = 0; i < row_width; i++)
  192720. {
  192721. if ((png_uint_16)((*sp >> shift) & 0x03)
  192722. == trans_values->gray)
  192723. {
  192724. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192725. *sp |= (png_byte)(background->gray << shift);
  192726. }
  192727. else
  192728. {
  192729. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192730. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192731. (p << 4) | (p << 6)] >> 6) & 0x03);
  192732. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192733. *sp |= (png_byte)(g << shift);
  192734. }
  192735. if (!shift)
  192736. {
  192737. shift = 6;
  192738. sp++;
  192739. }
  192740. else
  192741. shift -= 2;
  192742. }
  192743. }
  192744. else
  192745. #endif
  192746. {
  192747. sp = row;
  192748. shift = 6;
  192749. for (i = 0; i < row_width; i++)
  192750. {
  192751. if ((png_uint_16)((*sp >> shift) & 0x03)
  192752. == trans_values->gray)
  192753. {
  192754. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192755. *sp |= (png_byte)(background->gray << shift);
  192756. }
  192757. if (!shift)
  192758. {
  192759. shift = 6;
  192760. sp++;
  192761. }
  192762. else
  192763. shift -= 2;
  192764. }
  192765. }
  192766. break;
  192767. }
  192768. case 4:
  192769. {
  192770. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192771. if (gamma_table != NULL)
  192772. {
  192773. sp = row;
  192774. shift = 4;
  192775. for (i = 0; i < row_width; i++)
  192776. {
  192777. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192778. == trans_values->gray)
  192779. {
  192780. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192781. *sp |= (png_byte)(background->gray << shift);
  192782. }
  192783. else
  192784. {
  192785. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192786. png_byte g = (png_byte)((gamma_table[p |
  192787. (p << 4)] >> 4) & 0x0f);
  192788. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192789. *sp |= (png_byte)(g << shift);
  192790. }
  192791. if (!shift)
  192792. {
  192793. shift = 4;
  192794. sp++;
  192795. }
  192796. else
  192797. shift -= 4;
  192798. }
  192799. }
  192800. else
  192801. #endif
  192802. {
  192803. sp = row;
  192804. shift = 4;
  192805. for (i = 0; i < row_width; i++)
  192806. {
  192807. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192808. == trans_values->gray)
  192809. {
  192810. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192811. *sp |= (png_byte)(background->gray << shift);
  192812. }
  192813. if (!shift)
  192814. {
  192815. shift = 4;
  192816. sp++;
  192817. }
  192818. else
  192819. shift -= 4;
  192820. }
  192821. }
  192822. break;
  192823. }
  192824. case 8:
  192825. {
  192826. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192827. if (gamma_table != NULL)
  192828. {
  192829. sp = row;
  192830. for (i = 0; i < row_width; i++, sp++)
  192831. {
  192832. if (*sp == trans_values->gray)
  192833. {
  192834. *sp = (png_byte)background->gray;
  192835. }
  192836. else
  192837. {
  192838. *sp = gamma_table[*sp];
  192839. }
  192840. }
  192841. }
  192842. else
  192843. #endif
  192844. {
  192845. sp = row;
  192846. for (i = 0; i < row_width; i++, sp++)
  192847. {
  192848. if (*sp == trans_values->gray)
  192849. {
  192850. *sp = (png_byte)background->gray;
  192851. }
  192852. }
  192853. }
  192854. break;
  192855. }
  192856. case 16:
  192857. {
  192858. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192859. if (gamma_16 != NULL)
  192860. {
  192861. sp = row;
  192862. for (i = 0; i < row_width; i++, sp += 2)
  192863. {
  192864. png_uint_16 v;
  192865. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192866. if (v == trans_values->gray)
  192867. {
  192868. /* background is already in screen gamma */
  192869. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192870. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192871. }
  192872. else
  192873. {
  192874. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192875. *sp = (png_byte)((v >> 8) & 0xff);
  192876. *(sp + 1) = (png_byte)(v & 0xff);
  192877. }
  192878. }
  192879. }
  192880. else
  192881. #endif
  192882. {
  192883. sp = row;
  192884. for (i = 0; i < row_width; i++, sp += 2)
  192885. {
  192886. png_uint_16 v;
  192887. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192888. if (v == trans_values->gray)
  192889. {
  192890. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192891. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192892. }
  192893. }
  192894. }
  192895. break;
  192896. }
  192897. }
  192898. break;
  192899. }
  192900. case PNG_COLOR_TYPE_RGB:
  192901. {
  192902. if (row_info->bit_depth == 8)
  192903. {
  192904. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192905. if (gamma_table != NULL)
  192906. {
  192907. sp = row;
  192908. for (i = 0; i < row_width; i++, sp += 3)
  192909. {
  192910. if (*sp == trans_values->red &&
  192911. *(sp + 1) == trans_values->green &&
  192912. *(sp + 2) == trans_values->blue)
  192913. {
  192914. *sp = (png_byte)background->red;
  192915. *(sp + 1) = (png_byte)background->green;
  192916. *(sp + 2) = (png_byte)background->blue;
  192917. }
  192918. else
  192919. {
  192920. *sp = gamma_table[*sp];
  192921. *(sp + 1) = gamma_table[*(sp + 1)];
  192922. *(sp + 2) = gamma_table[*(sp + 2)];
  192923. }
  192924. }
  192925. }
  192926. else
  192927. #endif
  192928. {
  192929. sp = row;
  192930. for (i = 0; i < row_width; i++, sp += 3)
  192931. {
  192932. if (*sp == trans_values->red &&
  192933. *(sp + 1) == trans_values->green &&
  192934. *(sp + 2) == trans_values->blue)
  192935. {
  192936. *sp = (png_byte)background->red;
  192937. *(sp + 1) = (png_byte)background->green;
  192938. *(sp + 2) = (png_byte)background->blue;
  192939. }
  192940. }
  192941. }
  192942. }
  192943. else /* if (row_info->bit_depth == 16) */
  192944. {
  192945. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192946. if (gamma_16 != NULL)
  192947. {
  192948. sp = row;
  192949. for (i = 0; i < row_width; i++, sp += 6)
  192950. {
  192951. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192952. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192953. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192954. if (r == trans_values->red && g == trans_values->green &&
  192955. b == trans_values->blue)
  192956. {
  192957. /* background is already in screen gamma */
  192958. *sp = (png_byte)((background->red >> 8) & 0xff);
  192959. *(sp + 1) = (png_byte)(background->red & 0xff);
  192960. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192961. *(sp + 3) = (png_byte)(background->green & 0xff);
  192962. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192963. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192964. }
  192965. else
  192966. {
  192967. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192968. *sp = (png_byte)((v >> 8) & 0xff);
  192969. *(sp + 1) = (png_byte)(v & 0xff);
  192970. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192971. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192972. *(sp + 3) = (png_byte)(v & 0xff);
  192973. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192974. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192975. *(sp + 5) = (png_byte)(v & 0xff);
  192976. }
  192977. }
  192978. }
  192979. else
  192980. #endif
  192981. {
  192982. sp = row;
  192983. for (i = 0; i < row_width; i++, sp += 6)
  192984. {
  192985. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192986. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192987. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192988. if (r == trans_values->red && g == trans_values->green &&
  192989. b == trans_values->blue)
  192990. {
  192991. *sp = (png_byte)((background->red >> 8) & 0xff);
  192992. *(sp + 1) = (png_byte)(background->red & 0xff);
  192993. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192994. *(sp + 3) = (png_byte)(background->green & 0xff);
  192995. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192996. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192997. }
  192998. }
  192999. }
  193000. }
  193001. break;
  193002. }
  193003. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193004. {
  193005. if (row_info->bit_depth == 8)
  193006. {
  193007. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193008. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193009. gamma_table != NULL)
  193010. {
  193011. sp = row;
  193012. dp = row;
  193013. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193014. {
  193015. png_uint_16 a = *(sp + 1);
  193016. if (a == 0xff)
  193017. {
  193018. *dp = gamma_table[*sp];
  193019. }
  193020. else if (a == 0)
  193021. {
  193022. /* background is already in screen gamma */
  193023. *dp = (png_byte)background->gray;
  193024. }
  193025. else
  193026. {
  193027. png_byte v, w;
  193028. v = gamma_to_1[*sp];
  193029. png_composite(w, v, a, background_1->gray);
  193030. *dp = gamma_from_1[w];
  193031. }
  193032. }
  193033. }
  193034. else
  193035. #endif
  193036. {
  193037. sp = row;
  193038. dp = row;
  193039. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193040. {
  193041. png_byte a = *(sp + 1);
  193042. if (a == 0xff)
  193043. {
  193044. *dp = *sp;
  193045. }
  193046. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193047. else if (a == 0)
  193048. {
  193049. *dp = (png_byte)background->gray;
  193050. }
  193051. else
  193052. {
  193053. png_composite(*dp, *sp, a, background_1->gray);
  193054. }
  193055. #else
  193056. *dp = (png_byte)background->gray;
  193057. #endif
  193058. }
  193059. }
  193060. }
  193061. else /* if (png_ptr->bit_depth == 16) */
  193062. {
  193063. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193064. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193065. gamma_16_to_1 != NULL)
  193066. {
  193067. sp = row;
  193068. dp = row;
  193069. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193070. {
  193071. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193072. if (a == (png_uint_16)0xffff)
  193073. {
  193074. png_uint_16 v;
  193075. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193076. *dp = (png_byte)((v >> 8) & 0xff);
  193077. *(dp + 1) = (png_byte)(v & 0xff);
  193078. }
  193079. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193080. else if (a == 0)
  193081. #else
  193082. else
  193083. #endif
  193084. {
  193085. /* background is already in screen gamma */
  193086. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193087. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193088. }
  193089. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193090. else
  193091. {
  193092. png_uint_16 g, v, w;
  193093. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193094. png_composite_16(v, g, a, background_1->gray);
  193095. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  193096. *dp = (png_byte)((w >> 8) & 0xff);
  193097. *(dp + 1) = (png_byte)(w & 0xff);
  193098. }
  193099. #endif
  193100. }
  193101. }
  193102. else
  193103. #endif
  193104. {
  193105. sp = row;
  193106. dp = row;
  193107. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193108. {
  193109. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193110. if (a == (png_uint_16)0xffff)
  193111. {
  193112. png_memcpy(dp, sp, 2);
  193113. }
  193114. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193115. else if (a == 0)
  193116. #else
  193117. else
  193118. #endif
  193119. {
  193120. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193121. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193122. }
  193123. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193124. else
  193125. {
  193126. png_uint_16 g, v;
  193127. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193128. png_composite_16(v, g, a, background_1->gray);
  193129. *dp = (png_byte)((v >> 8) & 0xff);
  193130. *(dp + 1) = (png_byte)(v & 0xff);
  193131. }
  193132. #endif
  193133. }
  193134. }
  193135. }
  193136. break;
  193137. }
  193138. case PNG_COLOR_TYPE_RGB_ALPHA:
  193139. {
  193140. if (row_info->bit_depth == 8)
  193141. {
  193142. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193143. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193144. gamma_table != NULL)
  193145. {
  193146. sp = row;
  193147. dp = row;
  193148. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193149. {
  193150. png_byte a = *(sp + 3);
  193151. if (a == 0xff)
  193152. {
  193153. *dp = gamma_table[*sp];
  193154. *(dp + 1) = gamma_table[*(sp + 1)];
  193155. *(dp + 2) = gamma_table[*(sp + 2)];
  193156. }
  193157. else if (a == 0)
  193158. {
  193159. /* background is already in screen gamma */
  193160. *dp = (png_byte)background->red;
  193161. *(dp + 1) = (png_byte)background->green;
  193162. *(dp + 2) = (png_byte)background->blue;
  193163. }
  193164. else
  193165. {
  193166. png_byte v, w;
  193167. v = gamma_to_1[*sp];
  193168. png_composite(w, v, a, background_1->red);
  193169. *dp = gamma_from_1[w];
  193170. v = gamma_to_1[*(sp + 1)];
  193171. png_composite(w, v, a, background_1->green);
  193172. *(dp + 1) = gamma_from_1[w];
  193173. v = gamma_to_1[*(sp + 2)];
  193174. png_composite(w, v, a, background_1->blue);
  193175. *(dp + 2) = gamma_from_1[w];
  193176. }
  193177. }
  193178. }
  193179. else
  193180. #endif
  193181. {
  193182. sp = row;
  193183. dp = row;
  193184. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193185. {
  193186. png_byte a = *(sp + 3);
  193187. if (a == 0xff)
  193188. {
  193189. *dp = *sp;
  193190. *(dp + 1) = *(sp + 1);
  193191. *(dp + 2) = *(sp + 2);
  193192. }
  193193. else if (a == 0)
  193194. {
  193195. *dp = (png_byte)background->red;
  193196. *(dp + 1) = (png_byte)background->green;
  193197. *(dp + 2) = (png_byte)background->blue;
  193198. }
  193199. else
  193200. {
  193201. png_composite(*dp, *sp, a, background->red);
  193202. png_composite(*(dp + 1), *(sp + 1), a,
  193203. background->green);
  193204. png_composite(*(dp + 2), *(sp + 2), a,
  193205. background->blue);
  193206. }
  193207. }
  193208. }
  193209. }
  193210. else /* if (row_info->bit_depth == 16) */
  193211. {
  193212. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193213. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193214. gamma_16_to_1 != NULL)
  193215. {
  193216. sp = row;
  193217. dp = row;
  193218. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193219. {
  193220. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193221. << 8) + (png_uint_16)(*(sp + 7)));
  193222. if (a == (png_uint_16)0xffff)
  193223. {
  193224. png_uint_16 v;
  193225. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193226. *dp = (png_byte)((v >> 8) & 0xff);
  193227. *(dp + 1) = (png_byte)(v & 0xff);
  193228. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193229. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193230. *(dp + 3) = (png_byte)(v & 0xff);
  193231. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193232. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193233. *(dp + 5) = (png_byte)(v & 0xff);
  193234. }
  193235. else if (a == 0)
  193236. {
  193237. /* background is already in screen gamma */
  193238. *dp = (png_byte)((background->red >> 8) & 0xff);
  193239. *(dp + 1) = (png_byte)(background->red & 0xff);
  193240. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193241. *(dp + 3) = (png_byte)(background->green & 0xff);
  193242. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193243. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193244. }
  193245. else
  193246. {
  193247. png_uint_16 v, w, x;
  193248. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193249. png_composite_16(w, v, a, background_1->red);
  193250. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193251. *dp = (png_byte)((x >> 8) & 0xff);
  193252. *(dp + 1) = (png_byte)(x & 0xff);
  193253. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193254. png_composite_16(w, v, a, background_1->green);
  193255. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193256. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193257. *(dp + 3) = (png_byte)(x & 0xff);
  193258. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193259. png_composite_16(w, v, a, background_1->blue);
  193260. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193261. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193262. *(dp + 5) = (png_byte)(x & 0xff);
  193263. }
  193264. }
  193265. }
  193266. else
  193267. #endif
  193268. {
  193269. sp = row;
  193270. dp = row;
  193271. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193272. {
  193273. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193274. << 8) + (png_uint_16)(*(sp + 7)));
  193275. if (a == (png_uint_16)0xffff)
  193276. {
  193277. png_memcpy(dp, sp, 6);
  193278. }
  193279. else if (a == 0)
  193280. {
  193281. *dp = (png_byte)((background->red >> 8) & 0xff);
  193282. *(dp + 1) = (png_byte)(background->red & 0xff);
  193283. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193284. *(dp + 3) = (png_byte)(background->green & 0xff);
  193285. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193286. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193287. }
  193288. else
  193289. {
  193290. png_uint_16 v;
  193291. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193292. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193293. + *(sp + 3));
  193294. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193295. + *(sp + 5));
  193296. png_composite_16(v, r, a, background->red);
  193297. *dp = (png_byte)((v >> 8) & 0xff);
  193298. *(dp + 1) = (png_byte)(v & 0xff);
  193299. png_composite_16(v, g, a, background->green);
  193300. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193301. *(dp + 3) = (png_byte)(v & 0xff);
  193302. png_composite_16(v, b, a, background->blue);
  193303. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193304. *(dp + 5) = (png_byte)(v & 0xff);
  193305. }
  193306. }
  193307. }
  193308. }
  193309. break;
  193310. }
  193311. }
  193312. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193313. {
  193314. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193315. row_info->channels--;
  193316. row_info->pixel_depth = (png_byte)(row_info->channels *
  193317. row_info->bit_depth);
  193318. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193319. }
  193320. }
  193321. }
  193322. #endif
  193323. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193324. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193325. * you do this after you deal with the transparency issue on grayscale
  193326. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193327. * is 16, use gamma_16_table and gamma_shift. Build these with
  193328. * build_gamma_table().
  193329. */
  193330. void /* PRIVATE */
  193331. png_do_gamma(png_row_infop row_info, png_bytep row,
  193332. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193333. int gamma_shift)
  193334. {
  193335. png_bytep sp;
  193336. png_uint_32 i;
  193337. png_uint_32 row_width=row_info->width;
  193338. png_debug(1, "in png_do_gamma\n");
  193339. if (
  193340. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193341. row != NULL && row_info != NULL &&
  193342. #endif
  193343. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193344. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193345. {
  193346. switch (row_info->color_type)
  193347. {
  193348. case PNG_COLOR_TYPE_RGB:
  193349. {
  193350. if (row_info->bit_depth == 8)
  193351. {
  193352. sp = row;
  193353. for (i = 0; i < row_width; i++)
  193354. {
  193355. *sp = gamma_table[*sp];
  193356. sp++;
  193357. *sp = gamma_table[*sp];
  193358. sp++;
  193359. *sp = gamma_table[*sp];
  193360. sp++;
  193361. }
  193362. }
  193363. else /* if (row_info->bit_depth == 16) */
  193364. {
  193365. sp = row;
  193366. for (i = 0; i < row_width; i++)
  193367. {
  193368. png_uint_16 v;
  193369. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193370. *sp = (png_byte)((v >> 8) & 0xff);
  193371. *(sp + 1) = (png_byte)(v & 0xff);
  193372. sp += 2;
  193373. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193374. *sp = (png_byte)((v >> 8) & 0xff);
  193375. *(sp + 1) = (png_byte)(v & 0xff);
  193376. sp += 2;
  193377. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193378. *sp = (png_byte)((v >> 8) & 0xff);
  193379. *(sp + 1) = (png_byte)(v & 0xff);
  193380. sp += 2;
  193381. }
  193382. }
  193383. break;
  193384. }
  193385. case PNG_COLOR_TYPE_RGB_ALPHA:
  193386. {
  193387. if (row_info->bit_depth == 8)
  193388. {
  193389. sp = row;
  193390. for (i = 0; i < row_width; i++)
  193391. {
  193392. *sp = gamma_table[*sp];
  193393. sp++;
  193394. *sp = gamma_table[*sp];
  193395. sp++;
  193396. *sp = gamma_table[*sp];
  193397. sp++;
  193398. sp++;
  193399. }
  193400. }
  193401. else /* if (row_info->bit_depth == 16) */
  193402. {
  193403. sp = row;
  193404. for (i = 0; i < row_width; i++)
  193405. {
  193406. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193407. *sp = (png_byte)((v >> 8) & 0xff);
  193408. *(sp + 1) = (png_byte)(v & 0xff);
  193409. sp += 2;
  193410. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193411. *sp = (png_byte)((v >> 8) & 0xff);
  193412. *(sp + 1) = (png_byte)(v & 0xff);
  193413. sp += 2;
  193414. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193415. *sp = (png_byte)((v >> 8) & 0xff);
  193416. *(sp + 1) = (png_byte)(v & 0xff);
  193417. sp += 4;
  193418. }
  193419. }
  193420. break;
  193421. }
  193422. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193423. {
  193424. if (row_info->bit_depth == 8)
  193425. {
  193426. sp = row;
  193427. for (i = 0; i < row_width; i++)
  193428. {
  193429. *sp = gamma_table[*sp];
  193430. sp += 2;
  193431. }
  193432. }
  193433. else /* if (row_info->bit_depth == 16) */
  193434. {
  193435. sp = row;
  193436. for (i = 0; i < row_width; i++)
  193437. {
  193438. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193439. *sp = (png_byte)((v >> 8) & 0xff);
  193440. *(sp + 1) = (png_byte)(v & 0xff);
  193441. sp += 4;
  193442. }
  193443. }
  193444. break;
  193445. }
  193446. case PNG_COLOR_TYPE_GRAY:
  193447. {
  193448. if (row_info->bit_depth == 2)
  193449. {
  193450. sp = row;
  193451. for (i = 0; i < row_width; i += 4)
  193452. {
  193453. int a = *sp & 0xc0;
  193454. int b = *sp & 0x30;
  193455. int c = *sp & 0x0c;
  193456. int d = *sp & 0x03;
  193457. *sp = (png_byte)(
  193458. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193459. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193460. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193461. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193462. sp++;
  193463. }
  193464. }
  193465. if (row_info->bit_depth == 4)
  193466. {
  193467. sp = row;
  193468. for (i = 0; i < row_width; i += 2)
  193469. {
  193470. int msb = *sp & 0xf0;
  193471. int lsb = *sp & 0x0f;
  193472. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193473. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193474. sp++;
  193475. }
  193476. }
  193477. else if (row_info->bit_depth == 8)
  193478. {
  193479. sp = row;
  193480. for (i = 0; i < row_width; i++)
  193481. {
  193482. *sp = gamma_table[*sp];
  193483. sp++;
  193484. }
  193485. }
  193486. else if (row_info->bit_depth == 16)
  193487. {
  193488. sp = row;
  193489. for (i = 0; i < row_width; i++)
  193490. {
  193491. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193492. *sp = (png_byte)((v >> 8) & 0xff);
  193493. *(sp + 1) = (png_byte)(v & 0xff);
  193494. sp += 2;
  193495. }
  193496. }
  193497. break;
  193498. }
  193499. }
  193500. }
  193501. }
  193502. #endif
  193503. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193504. /* Expands a palette row to an RGB or RGBA row depending
  193505. * upon whether you supply trans and num_trans.
  193506. */
  193507. void /* PRIVATE */
  193508. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193509. png_colorp palette, png_bytep trans, int num_trans)
  193510. {
  193511. int shift, value;
  193512. png_bytep sp, dp;
  193513. png_uint_32 i;
  193514. png_uint_32 row_width=row_info->width;
  193515. png_debug(1, "in png_do_expand_palette\n");
  193516. if (
  193517. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193518. row != NULL && row_info != NULL &&
  193519. #endif
  193520. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193521. {
  193522. if (row_info->bit_depth < 8)
  193523. {
  193524. switch (row_info->bit_depth)
  193525. {
  193526. case 1:
  193527. {
  193528. sp = row + (png_size_t)((row_width - 1) >> 3);
  193529. dp = row + (png_size_t)row_width - 1;
  193530. shift = 7 - (int)((row_width + 7) & 0x07);
  193531. for (i = 0; i < row_width; i++)
  193532. {
  193533. if ((*sp >> shift) & 0x01)
  193534. *dp = 1;
  193535. else
  193536. *dp = 0;
  193537. if (shift == 7)
  193538. {
  193539. shift = 0;
  193540. sp--;
  193541. }
  193542. else
  193543. shift++;
  193544. dp--;
  193545. }
  193546. break;
  193547. }
  193548. case 2:
  193549. {
  193550. sp = row + (png_size_t)((row_width - 1) >> 2);
  193551. dp = row + (png_size_t)row_width - 1;
  193552. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193553. for (i = 0; i < row_width; i++)
  193554. {
  193555. value = (*sp >> shift) & 0x03;
  193556. *dp = (png_byte)value;
  193557. if (shift == 6)
  193558. {
  193559. shift = 0;
  193560. sp--;
  193561. }
  193562. else
  193563. shift += 2;
  193564. dp--;
  193565. }
  193566. break;
  193567. }
  193568. case 4:
  193569. {
  193570. sp = row + (png_size_t)((row_width - 1) >> 1);
  193571. dp = row + (png_size_t)row_width - 1;
  193572. shift = (int)((row_width & 0x01) << 2);
  193573. for (i = 0; i < row_width; i++)
  193574. {
  193575. value = (*sp >> shift) & 0x0f;
  193576. *dp = (png_byte)value;
  193577. if (shift == 4)
  193578. {
  193579. shift = 0;
  193580. sp--;
  193581. }
  193582. else
  193583. shift += 4;
  193584. dp--;
  193585. }
  193586. break;
  193587. }
  193588. }
  193589. row_info->bit_depth = 8;
  193590. row_info->pixel_depth = 8;
  193591. row_info->rowbytes = row_width;
  193592. }
  193593. switch (row_info->bit_depth)
  193594. {
  193595. case 8:
  193596. {
  193597. if (trans != NULL)
  193598. {
  193599. sp = row + (png_size_t)row_width - 1;
  193600. dp = row + (png_size_t)(row_width << 2) - 1;
  193601. for (i = 0; i < row_width; i++)
  193602. {
  193603. if ((int)(*sp) >= num_trans)
  193604. *dp-- = 0xff;
  193605. else
  193606. *dp-- = trans[*sp];
  193607. *dp-- = palette[*sp].blue;
  193608. *dp-- = palette[*sp].green;
  193609. *dp-- = palette[*sp].red;
  193610. sp--;
  193611. }
  193612. row_info->bit_depth = 8;
  193613. row_info->pixel_depth = 32;
  193614. row_info->rowbytes = row_width * 4;
  193615. row_info->color_type = 6;
  193616. row_info->channels = 4;
  193617. }
  193618. else
  193619. {
  193620. sp = row + (png_size_t)row_width - 1;
  193621. dp = row + (png_size_t)(row_width * 3) - 1;
  193622. for (i = 0; i < row_width; i++)
  193623. {
  193624. *dp-- = palette[*sp].blue;
  193625. *dp-- = palette[*sp].green;
  193626. *dp-- = palette[*sp].red;
  193627. sp--;
  193628. }
  193629. row_info->bit_depth = 8;
  193630. row_info->pixel_depth = 24;
  193631. row_info->rowbytes = row_width * 3;
  193632. row_info->color_type = 2;
  193633. row_info->channels = 3;
  193634. }
  193635. break;
  193636. }
  193637. }
  193638. }
  193639. }
  193640. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193641. * expanded transparency value is supplied, an alpha channel is built.
  193642. */
  193643. void /* PRIVATE */
  193644. png_do_expand(png_row_infop row_info, png_bytep row,
  193645. png_color_16p trans_value)
  193646. {
  193647. int shift, value;
  193648. png_bytep sp, dp;
  193649. png_uint_32 i;
  193650. png_uint_32 row_width=row_info->width;
  193651. png_debug(1, "in png_do_expand\n");
  193652. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193653. if (row != NULL && row_info != NULL)
  193654. #endif
  193655. {
  193656. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193657. {
  193658. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193659. if (row_info->bit_depth < 8)
  193660. {
  193661. switch (row_info->bit_depth)
  193662. {
  193663. case 1:
  193664. {
  193665. gray = (png_uint_16)((gray&0x01)*0xff);
  193666. sp = row + (png_size_t)((row_width - 1) >> 3);
  193667. dp = row + (png_size_t)row_width - 1;
  193668. shift = 7 - (int)((row_width + 7) & 0x07);
  193669. for (i = 0; i < row_width; i++)
  193670. {
  193671. if ((*sp >> shift) & 0x01)
  193672. *dp = 0xff;
  193673. else
  193674. *dp = 0;
  193675. if (shift == 7)
  193676. {
  193677. shift = 0;
  193678. sp--;
  193679. }
  193680. else
  193681. shift++;
  193682. dp--;
  193683. }
  193684. break;
  193685. }
  193686. case 2:
  193687. {
  193688. gray = (png_uint_16)((gray&0x03)*0x55);
  193689. sp = row + (png_size_t)((row_width - 1) >> 2);
  193690. dp = row + (png_size_t)row_width - 1;
  193691. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193692. for (i = 0; i < row_width; i++)
  193693. {
  193694. value = (*sp >> shift) & 0x03;
  193695. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193696. (value << 6));
  193697. if (shift == 6)
  193698. {
  193699. shift = 0;
  193700. sp--;
  193701. }
  193702. else
  193703. shift += 2;
  193704. dp--;
  193705. }
  193706. break;
  193707. }
  193708. case 4:
  193709. {
  193710. gray = (png_uint_16)((gray&0x0f)*0x11);
  193711. sp = row + (png_size_t)((row_width - 1) >> 1);
  193712. dp = row + (png_size_t)row_width - 1;
  193713. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193714. for (i = 0; i < row_width; i++)
  193715. {
  193716. value = (*sp >> shift) & 0x0f;
  193717. *dp = (png_byte)(value | (value << 4));
  193718. if (shift == 4)
  193719. {
  193720. shift = 0;
  193721. sp--;
  193722. }
  193723. else
  193724. shift = 4;
  193725. dp--;
  193726. }
  193727. break;
  193728. }
  193729. }
  193730. row_info->bit_depth = 8;
  193731. row_info->pixel_depth = 8;
  193732. row_info->rowbytes = row_width;
  193733. }
  193734. if (trans_value != NULL)
  193735. {
  193736. if (row_info->bit_depth == 8)
  193737. {
  193738. gray = gray & 0xff;
  193739. sp = row + (png_size_t)row_width - 1;
  193740. dp = row + (png_size_t)(row_width << 1) - 1;
  193741. for (i = 0; i < row_width; i++)
  193742. {
  193743. if (*sp == gray)
  193744. *dp-- = 0;
  193745. else
  193746. *dp-- = 0xff;
  193747. *dp-- = *sp--;
  193748. }
  193749. }
  193750. else if (row_info->bit_depth == 16)
  193751. {
  193752. png_byte gray_high = (gray >> 8) & 0xff;
  193753. png_byte gray_low = gray & 0xff;
  193754. sp = row + row_info->rowbytes - 1;
  193755. dp = row + (row_info->rowbytes << 1) - 1;
  193756. for (i = 0; i < row_width; i++)
  193757. {
  193758. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193759. {
  193760. *dp-- = 0;
  193761. *dp-- = 0;
  193762. }
  193763. else
  193764. {
  193765. *dp-- = 0xff;
  193766. *dp-- = 0xff;
  193767. }
  193768. *dp-- = *sp--;
  193769. *dp-- = *sp--;
  193770. }
  193771. }
  193772. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193773. row_info->channels = 2;
  193774. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193775. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193776. row_width);
  193777. }
  193778. }
  193779. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193780. {
  193781. if (row_info->bit_depth == 8)
  193782. {
  193783. png_byte red = trans_value->red & 0xff;
  193784. png_byte green = trans_value->green & 0xff;
  193785. png_byte blue = trans_value->blue & 0xff;
  193786. sp = row + (png_size_t)row_info->rowbytes - 1;
  193787. dp = row + (png_size_t)(row_width << 2) - 1;
  193788. for (i = 0; i < row_width; i++)
  193789. {
  193790. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193791. *dp-- = 0;
  193792. else
  193793. *dp-- = 0xff;
  193794. *dp-- = *sp--;
  193795. *dp-- = *sp--;
  193796. *dp-- = *sp--;
  193797. }
  193798. }
  193799. else if (row_info->bit_depth == 16)
  193800. {
  193801. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193802. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193803. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193804. png_byte red_low = trans_value->red & 0xff;
  193805. png_byte green_low = trans_value->green & 0xff;
  193806. png_byte blue_low = trans_value->blue & 0xff;
  193807. sp = row + row_info->rowbytes - 1;
  193808. dp = row + (png_size_t)(row_width << 3) - 1;
  193809. for (i = 0; i < row_width; i++)
  193810. {
  193811. if (*(sp - 5) == red_high &&
  193812. *(sp - 4) == red_low &&
  193813. *(sp - 3) == green_high &&
  193814. *(sp - 2) == green_low &&
  193815. *(sp - 1) == blue_high &&
  193816. *(sp ) == blue_low)
  193817. {
  193818. *dp-- = 0;
  193819. *dp-- = 0;
  193820. }
  193821. else
  193822. {
  193823. *dp-- = 0xff;
  193824. *dp-- = 0xff;
  193825. }
  193826. *dp-- = *sp--;
  193827. *dp-- = *sp--;
  193828. *dp-- = *sp--;
  193829. *dp-- = *sp--;
  193830. *dp-- = *sp--;
  193831. *dp-- = *sp--;
  193832. }
  193833. }
  193834. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193835. row_info->channels = 4;
  193836. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193837. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193838. }
  193839. }
  193840. }
  193841. #endif
  193842. #if defined(PNG_READ_DITHER_SUPPORTED)
  193843. void /* PRIVATE */
  193844. png_do_dither(png_row_infop row_info, png_bytep row,
  193845. png_bytep palette_lookup, png_bytep dither_lookup)
  193846. {
  193847. png_bytep sp, dp;
  193848. png_uint_32 i;
  193849. png_uint_32 row_width=row_info->width;
  193850. png_debug(1, "in png_do_dither\n");
  193851. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193852. if (row != NULL && row_info != NULL)
  193853. #endif
  193854. {
  193855. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193856. palette_lookup && row_info->bit_depth == 8)
  193857. {
  193858. int r, g, b, p;
  193859. sp = row;
  193860. dp = row;
  193861. for (i = 0; i < row_width; i++)
  193862. {
  193863. r = *sp++;
  193864. g = *sp++;
  193865. b = *sp++;
  193866. /* this looks real messy, but the compiler will reduce
  193867. it down to a reasonable formula. For example, with
  193868. 5 bits per color, we get:
  193869. p = (((r >> 3) & 0x1f) << 10) |
  193870. (((g >> 3) & 0x1f) << 5) |
  193871. ((b >> 3) & 0x1f);
  193872. */
  193873. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193874. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193875. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193876. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193877. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193878. (PNG_DITHER_BLUE_BITS)) |
  193879. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193880. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193881. *dp++ = palette_lookup[p];
  193882. }
  193883. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193884. row_info->channels = 1;
  193885. row_info->pixel_depth = row_info->bit_depth;
  193886. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193887. }
  193888. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193889. palette_lookup != NULL && row_info->bit_depth == 8)
  193890. {
  193891. int r, g, b, p;
  193892. sp = row;
  193893. dp = row;
  193894. for (i = 0; i < row_width; i++)
  193895. {
  193896. r = *sp++;
  193897. g = *sp++;
  193898. b = *sp++;
  193899. sp++;
  193900. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193901. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193902. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193903. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193904. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193905. (PNG_DITHER_BLUE_BITS)) |
  193906. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193907. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193908. *dp++ = palette_lookup[p];
  193909. }
  193910. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193911. row_info->channels = 1;
  193912. row_info->pixel_depth = row_info->bit_depth;
  193913. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193914. }
  193915. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193916. dither_lookup && row_info->bit_depth == 8)
  193917. {
  193918. sp = row;
  193919. for (i = 0; i < row_width; i++, sp++)
  193920. {
  193921. *sp = dither_lookup[*sp];
  193922. }
  193923. }
  193924. }
  193925. }
  193926. #endif
  193927. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193928. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193929. static PNG_CONST int png_gamma_shift[] =
  193930. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193931. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193932. * tables, we don't make a full table if we are reducing to 8-bit in
  193933. * the future. Note also how the gamma_16 tables are segmented so that
  193934. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193935. */
  193936. void /* PRIVATE */
  193937. png_build_gamma_table(png_structp png_ptr)
  193938. {
  193939. png_debug(1, "in png_build_gamma_table\n");
  193940. if (png_ptr->bit_depth <= 8)
  193941. {
  193942. int i;
  193943. double g;
  193944. if (png_ptr->screen_gamma > .000001)
  193945. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193946. else
  193947. g = 1.0;
  193948. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193949. (png_uint_32)256);
  193950. for (i = 0; i < 256; i++)
  193951. {
  193952. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193953. g) * 255.0 + .5);
  193954. }
  193955. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193956. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193957. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193958. {
  193959. g = 1.0 / (png_ptr->gamma);
  193960. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193961. (png_uint_32)256);
  193962. for (i = 0; i < 256; i++)
  193963. {
  193964. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193965. g) * 255.0 + .5);
  193966. }
  193967. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193968. (png_uint_32)256);
  193969. if(png_ptr->screen_gamma > 0.000001)
  193970. g = 1.0 / png_ptr->screen_gamma;
  193971. else
  193972. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193973. for (i = 0; i < 256; i++)
  193974. {
  193975. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193976. g) * 255.0 + .5);
  193977. }
  193978. }
  193979. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193980. }
  193981. else
  193982. {
  193983. double g;
  193984. int i, j, shift, num;
  193985. int sig_bit;
  193986. png_uint_32 ig;
  193987. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193988. {
  193989. sig_bit = (int)png_ptr->sig_bit.red;
  193990. if ((int)png_ptr->sig_bit.green > sig_bit)
  193991. sig_bit = png_ptr->sig_bit.green;
  193992. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193993. sig_bit = png_ptr->sig_bit.blue;
  193994. }
  193995. else
  193996. {
  193997. sig_bit = (int)png_ptr->sig_bit.gray;
  193998. }
  193999. if (sig_bit > 0)
  194000. shift = 16 - sig_bit;
  194001. else
  194002. shift = 0;
  194003. if (png_ptr->transformations & PNG_16_TO_8)
  194004. {
  194005. if (shift < (16 - PNG_MAX_GAMMA_8))
  194006. shift = (16 - PNG_MAX_GAMMA_8);
  194007. }
  194008. if (shift > 8)
  194009. shift = 8;
  194010. if (shift < 0)
  194011. shift = 0;
  194012. png_ptr->gamma_shift = (png_byte)shift;
  194013. num = (1 << (8 - shift));
  194014. if (png_ptr->screen_gamma > .000001)
  194015. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  194016. else
  194017. g = 1.0;
  194018. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  194019. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194020. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  194021. {
  194022. double fin, fout;
  194023. png_uint_32 last, max;
  194024. for (i = 0; i < num; i++)
  194025. {
  194026. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194027. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194028. }
  194029. g = 1.0 / g;
  194030. last = 0;
  194031. for (i = 0; i < 256; i++)
  194032. {
  194033. fout = ((double)i + 0.5) / 256.0;
  194034. fin = pow(fout, g);
  194035. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  194036. while (last <= max)
  194037. {
  194038. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194039. [(int)(last >> (8 - shift))] = (png_uint_16)(
  194040. (png_uint_16)i | ((png_uint_16)i << 8));
  194041. last++;
  194042. }
  194043. }
  194044. while (last < ((png_uint_32)num << 8))
  194045. {
  194046. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194047. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  194048. last++;
  194049. }
  194050. }
  194051. else
  194052. {
  194053. for (i = 0; i < num; i++)
  194054. {
  194055. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194056. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194057. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  194058. for (j = 0; j < 256; j++)
  194059. {
  194060. png_ptr->gamma_16_table[i][j] =
  194061. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194062. 65535.0, g) * 65535.0 + .5);
  194063. }
  194064. }
  194065. }
  194066. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  194067. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  194068. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  194069. {
  194070. g = 1.0 / (png_ptr->gamma);
  194071. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  194072. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  194073. for (i = 0; i < num; i++)
  194074. {
  194075. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194076. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194077. ig = (((png_uint_32)i *
  194078. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194079. for (j = 0; j < 256; j++)
  194080. {
  194081. png_ptr->gamma_16_to_1[i][j] =
  194082. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194083. 65535.0, g) * 65535.0 + .5);
  194084. }
  194085. }
  194086. if(png_ptr->screen_gamma > 0.000001)
  194087. g = 1.0 / png_ptr->screen_gamma;
  194088. else
  194089. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  194090. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  194091. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194092. for (i = 0; i < num; i++)
  194093. {
  194094. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194095. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194096. ig = (((png_uint_32)i *
  194097. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194098. for (j = 0; j < 256; j++)
  194099. {
  194100. png_ptr->gamma_16_from_1[i][j] =
  194101. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194102. 65535.0, g) * 65535.0 + .5);
  194103. }
  194104. }
  194105. }
  194106. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  194107. }
  194108. }
  194109. #endif
  194110. /* To do: install integer version of png_build_gamma_table here */
  194111. #endif
  194112. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194113. /* undoes intrapixel differencing */
  194114. void /* PRIVATE */
  194115. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  194116. {
  194117. png_debug(1, "in png_do_read_intrapixel\n");
  194118. if (
  194119. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194120. row != NULL && row_info != NULL &&
  194121. #endif
  194122. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194123. {
  194124. int bytes_per_pixel;
  194125. png_uint_32 row_width = row_info->width;
  194126. if (row_info->bit_depth == 8)
  194127. {
  194128. png_bytep rp;
  194129. png_uint_32 i;
  194130. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194131. bytes_per_pixel = 3;
  194132. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194133. bytes_per_pixel = 4;
  194134. else
  194135. return;
  194136. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194137. {
  194138. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  194139. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  194140. }
  194141. }
  194142. else if (row_info->bit_depth == 16)
  194143. {
  194144. png_bytep rp;
  194145. png_uint_32 i;
  194146. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194147. bytes_per_pixel = 6;
  194148. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194149. bytes_per_pixel = 8;
  194150. else
  194151. return;
  194152. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194153. {
  194154. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194155. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194156. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194157. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  194158. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  194159. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194160. *(rp+1) = (png_byte)(red & 0xff);
  194161. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194162. *(rp+5) = (png_byte)(blue & 0xff);
  194163. }
  194164. }
  194165. }
  194166. }
  194167. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194168. #endif /* PNG_READ_SUPPORTED */
  194169. /*** End of inlined file: pngrtran.c ***/
  194170. /*** Start of inlined file: pngrutil.c ***/
  194171. /* pngrutil.c - utilities to read a PNG file
  194172. *
  194173. * Last changed in libpng 1.2.21 [October 4, 2007]
  194174. * For conditions of distribution and use, see copyright notice in png.h
  194175. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194176. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194177. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194178. *
  194179. * This file contains routines that are only called from within
  194180. * libpng itself during the course of reading an image.
  194181. */
  194182. #define PNG_INTERNAL
  194183. #if defined(PNG_READ_SUPPORTED)
  194184. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  194185. # define WIN32_WCE_OLD
  194186. #endif
  194187. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194188. # if defined(WIN32_WCE_OLD)
  194189. /* strtod() function is not supported on WindowsCE */
  194190. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  194191. {
  194192. double result = 0;
  194193. int len;
  194194. wchar_t *str, *end;
  194195. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194196. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194197. if ( NULL != str )
  194198. {
  194199. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194200. result = wcstod(str, &end);
  194201. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194202. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194203. png_free(png_ptr, str);
  194204. }
  194205. return result;
  194206. }
  194207. # else
  194208. # define png_strtod(p,a,b) strtod(a,b)
  194209. # endif
  194210. #endif
  194211. png_uint_32 PNGAPI
  194212. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194213. {
  194214. png_uint_32 i = png_get_uint_32(buf);
  194215. if (i > PNG_UINT_31_MAX)
  194216. png_error(png_ptr, "PNG unsigned integer out of range.");
  194217. return (i);
  194218. }
  194219. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194220. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194221. png_uint_32 PNGAPI
  194222. png_get_uint_32(png_bytep buf)
  194223. {
  194224. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194225. ((png_uint_32)(*(buf + 1)) << 16) +
  194226. ((png_uint_32)(*(buf + 2)) << 8) +
  194227. (png_uint_32)(*(buf + 3));
  194228. return (i);
  194229. }
  194230. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194231. * data is stored in the PNG file in two's complement format, and it is
  194232. * assumed that the machine format for signed integers is the same. */
  194233. png_int_32 PNGAPI
  194234. png_get_int_32(png_bytep buf)
  194235. {
  194236. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194237. ((png_int_32)(*(buf + 1)) << 16) +
  194238. ((png_int_32)(*(buf + 2)) << 8) +
  194239. (png_int_32)(*(buf + 3));
  194240. return (i);
  194241. }
  194242. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194243. png_uint_16 PNGAPI
  194244. png_get_uint_16(png_bytep buf)
  194245. {
  194246. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194247. (png_uint_16)(*(buf + 1)));
  194248. return (i);
  194249. }
  194250. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194251. /* Read data, and (optionally) run it through the CRC. */
  194252. void /* PRIVATE */
  194253. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194254. {
  194255. if(png_ptr == NULL) return;
  194256. png_read_data(png_ptr, buf, length);
  194257. png_calculate_crc(png_ptr, buf, length);
  194258. }
  194259. /* Optionally skip data and then check the CRC. Depending on whether we
  194260. are reading a ancillary or critical chunk, and how the program has set
  194261. things up, we may calculate the CRC on the data and print a message.
  194262. Returns '1' if there was a CRC error, '0' otherwise. */
  194263. int /* PRIVATE */
  194264. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194265. {
  194266. png_size_t i;
  194267. png_size_t istop = png_ptr->zbuf_size;
  194268. for (i = (png_size_t)skip; i > istop; i -= istop)
  194269. {
  194270. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194271. }
  194272. if (i)
  194273. {
  194274. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194275. }
  194276. if (png_crc_error(png_ptr))
  194277. {
  194278. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194279. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194280. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194281. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194282. {
  194283. png_chunk_warning(png_ptr, "CRC error");
  194284. }
  194285. else
  194286. {
  194287. png_chunk_error(png_ptr, "CRC error");
  194288. }
  194289. return (1);
  194290. }
  194291. return (0);
  194292. }
  194293. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194294. the data it has read thus far. */
  194295. int /* PRIVATE */
  194296. png_crc_error(png_structp png_ptr)
  194297. {
  194298. png_byte crc_bytes[4];
  194299. png_uint_32 crc;
  194300. int need_crc = 1;
  194301. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194302. {
  194303. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194304. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194305. need_crc = 0;
  194306. }
  194307. else /* critical */
  194308. {
  194309. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194310. need_crc = 0;
  194311. }
  194312. png_read_data(png_ptr, crc_bytes, 4);
  194313. if (need_crc)
  194314. {
  194315. crc = png_get_uint_32(crc_bytes);
  194316. return ((int)(crc != png_ptr->crc));
  194317. }
  194318. else
  194319. return (0);
  194320. }
  194321. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194322. defined(PNG_READ_iCCP_SUPPORTED)
  194323. /*
  194324. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194325. * points at an allocated area holding the contents of a chunk with a
  194326. * trailing compressed part. What we get back is an allocated area
  194327. * holding the original prefix part and an uncompressed version of the
  194328. * trailing part (the malloc area passed in is freed).
  194329. */
  194330. png_charp /* PRIVATE */
  194331. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194332. png_charp chunkdata, png_size_t chunklength,
  194333. png_size_t prefix_size, png_size_t *newlength)
  194334. {
  194335. static PNG_CONST char msg[] = "Error decoding compressed text";
  194336. png_charp text;
  194337. png_size_t text_size;
  194338. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194339. {
  194340. int ret = Z_OK;
  194341. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194342. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194343. png_ptr->zstream.next_out = png_ptr->zbuf;
  194344. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194345. text_size = 0;
  194346. text = NULL;
  194347. while (png_ptr->zstream.avail_in)
  194348. {
  194349. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194350. if (ret != Z_OK && ret != Z_STREAM_END)
  194351. {
  194352. if (png_ptr->zstream.msg != NULL)
  194353. png_warning(png_ptr, png_ptr->zstream.msg);
  194354. else
  194355. png_warning(png_ptr, msg);
  194356. inflateReset(&png_ptr->zstream);
  194357. png_ptr->zstream.avail_in = 0;
  194358. if (text == NULL)
  194359. {
  194360. text_size = prefix_size + png_sizeof(msg) + 1;
  194361. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194362. if (text == NULL)
  194363. {
  194364. png_free(png_ptr,chunkdata);
  194365. png_error(png_ptr,"Not enough memory to decompress chunk");
  194366. }
  194367. png_memcpy(text, chunkdata, prefix_size);
  194368. }
  194369. text[text_size - 1] = 0x00;
  194370. /* Copy what we can of the error message into the text chunk */
  194371. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194372. text_size = png_sizeof(msg) > text_size ? text_size :
  194373. png_sizeof(msg);
  194374. png_memcpy(text + prefix_size, msg, text_size + 1);
  194375. break;
  194376. }
  194377. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194378. {
  194379. if (text == NULL)
  194380. {
  194381. text_size = prefix_size +
  194382. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194383. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194384. if (text == NULL)
  194385. {
  194386. png_free(png_ptr,chunkdata);
  194387. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194388. }
  194389. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194390. text_size - prefix_size);
  194391. png_memcpy(text, chunkdata, prefix_size);
  194392. *(text + text_size) = 0x00;
  194393. }
  194394. else
  194395. {
  194396. png_charp tmp;
  194397. tmp = text;
  194398. text = (png_charp)png_malloc_warn(png_ptr,
  194399. (png_uint_32)(text_size +
  194400. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194401. if (text == NULL)
  194402. {
  194403. png_free(png_ptr, tmp);
  194404. png_free(png_ptr, chunkdata);
  194405. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194406. }
  194407. png_memcpy(text, tmp, text_size);
  194408. png_free(png_ptr, tmp);
  194409. png_memcpy(text + text_size, png_ptr->zbuf,
  194410. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194411. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194412. *(text + text_size) = 0x00;
  194413. }
  194414. if (ret == Z_STREAM_END)
  194415. break;
  194416. else
  194417. {
  194418. png_ptr->zstream.next_out = png_ptr->zbuf;
  194419. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194420. }
  194421. }
  194422. }
  194423. if (ret != Z_STREAM_END)
  194424. {
  194425. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194426. char umsg[52];
  194427. if (ret == Z_BUF_ERROR)
  194428. png_snprintf(umsg, 52,
  194429. "Buffer error in compressed datastream in %s chunk",
  194430. png_ptr->chunk_name);
  194431. else if (ret == Z_DATA_ERROR)
  194432. png_snprintf(umsg, 52,
  194433. "Data error in compressed datastream in %s chunk",
  194434. png_ptr->chunk_name);
  194435. else
  194436. png_snprintf(umsg, 52,
  194437. "Incomplete compressed datastream in %s chunk",
  194438. png_ptr->chunk_name);
  194439. png_warning(png_ptr, umsg);
  194440. #else
  194441. png_warning(png_ptr,
  194442. "Incomplete compressed datastream in chunk other than IDAT");
  194443. #endif
  194444. text_size=prefix_size;
  194445. if (text == NULL)
  194446. {
  194447. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194448. if (text == NULL)
  194449. {
  194450. png_free(png_ptr, chunkdata);
  194451. png_error(png_ptr,"Not enough memory for text.");
  194452. }
  194453. png_memcpy(text, chunkdata, prefix_size);
  194454. }
  194455. *(text + text_size) = 0x00;
  194456. }
  194457. inflateReset(&png_ptr->zstream);
  194458. png_ptr->zstream.avail_in = 0;
  194459. png_free(png_ptr, chunkdata);
  194460. chunkdata = text;
  194461. *newlength=text_size;
  194462. }
  194463. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194464. {
  194465. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194466. char umsg[50];
  194467. png_snprintf(umsg, 50,
  194468. "Unknown zTXt compression type %d", comp_type);
  194469. png_warning(png_ptr, umsg);
  194470. #else
  194471. png_warning(png_ptr, "Unknown zTXt compression type");
  194472. #endif
  194473. *(chunkdata + prefix_size) = 0x00;
  194474. *newlength=prefix_size;
  194475. }
  194476. return chunkdata;
  194477. }
  194478. #endif
  194479. /* read and check the IDHR chunk */
  194480. void /* PRIVATE */
  194481. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194482. {
  194483. png_byte buf[13];
  194484. png_uint_32 width, height;
  194485. int bit_depth, color_type, compression_type, filter_type;
  194486. int interlace_type;
  194487. png_debug(1, "in png_handle_IHDR\n");
  194488. if (png_ptr->mode & PNG_HAVE_IHDR)
  194489. png_error(png_ptr, "Out of place IHDR");
  194490. /* check the length */
  194491. if (length != 13)
  194492. png_error(png_ptr, "Invalid IHDR chunk");
  194493. png_ptr->mode |= PNG_HAVE_IHDR;
  194494. png_crc_read(png_ptr, buf, 13);
  194495. png_crc_finish(png_ptr, 0);
  194496. width = png_get_uint_31(png_ptr, buf);
  194497. height = png_get_uint_31(png_ptr, buf + 4);
  194498. bit_depth = buf[8];
  194499. color_type = buf[9];
  194500. compression_type = buf[10];
  194501. filter_type = buf[11];
  194502. interlace_type = buf[12];
  194503. /* set internal variables */
  194504. png_ptr->width = width;
  194505. png_ptr->height = height;
  194506. png_ptr->bit_depth = (png_byte)bit_depth;
  194507. png_ptr->interlaced = (png_byte)interlace_type;
  194508. png_ptr->color_type = (png_byte)color_type;
  194509. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194510. png_ptr->filter_type = (png_byte)filter_type;
  194511. #endif
  194512. png_ptr->compression_type = (png_byte)compression_type;
  194513. /* find number of channels */
  194514. switch (png_ptr->color_type)
  194515. {
  194516. case PNG_COLOR_TYPE_GRAY:
  194517. case PNG_COLOR_TYPE_PALETTE:
  194518. png_ptr->channels = 1;
  194519. break;
  194520. case PNG_COLOR_TYPE_RGB:
  194521. png_ptr->channels = 3;
  194522. break;
  194523. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194524. png_ptr->channels = 2;
  194525. break;
  194526. case PNG_COLOR_TYPE_RGB_ALPHA:
  194527. png_ptr->channels = 4;
  194528. break;
  194529. }
  194530. /* set up other useful info */
  194531. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194532. png_ptr->channels);
  194533. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194534. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194535. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194536. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194537. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194538. color_type, interlace_type, compression_type, filter_type);
  194539. }
  194540. /* read and check the palette */
  194541. void /* PRIVATE */
  194542. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194543. {
  194544. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194545. int num, i;
  194546. #ifndef PNG_NO_POINTER_INDEXING
  194547. png_colorp pal_ptr;
  194548. #endif
  194549. png_debug(1, "in png_handle_PLTE\n");
  194550. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194551. png_error(png_ptr, "Missing IHDR before PLTE");
  194552. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194553. {
  194554. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194555. png_crc_finish(png_ptr, length);
  194556. return;
  194557. }
  194558. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194559. png_error(png_ptr, "Duplicate PLTE chunk");
  194560. png_ptr->mode |= PNG_HAVE_PLTE;
  194561. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194562. {
  194563. png_warning(png_ptr,
  194564. "Ignoring PLTE chunk in grayscale PNG");
  194565. png_crc_finish(png_ptr, length);
  194566. return;
  194567. }
  194568. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194569. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194570. {
  194571. png_crc_finish(png_ptr, length);
  194572. return;
  194573. }
  194574. #endif
  194575. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194576. {
  194577. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194578. {
  194579. png_warning(png_ptr, "Invalid palette chunk");
  194580. png_crc_finish(png_ptr, length);
  194581. return;
  194582. }
  194583. else
  194584. {
  194585. png_error(png_ptr, "Invalid palette chunk");
  194586. }
  194587. }
  194588. num = (int)length / 3;
  194589. #ifndef PNG_NO_POINTER_INDEXING
  194590. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194591. {
  194592. png_byte buf[3];
  194593. png_crc_read(png_ptr, buf, 3);
  194594. pal_ptr->red = buf[0];
  194595. pal_ptr->green = buf[1];
  194596. pal_ptr->blue = buf[2];
  194597. }
  194598. #else
  194599. for (i = 0; i < num; i++)
  194600. {
  194601. png_byte buf[3];
  194602. png_crc_read(png_ptr, buf, 3);
  194603. /* don't depend upon png_color being any order */
  194604. palette[i].red = buf[0];
  194605. palette[i].green = buf[1];
  194606. palette[i].blue = buf[2];
  194607. }
  194608. #endif
  194609. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194610. whatever the normal CRC configuration tells us. However, if we
  194611. have an RGB image, the PLTE can be considered ancillary, so
  194612. we will act as though it is. */
  194613. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194614. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194615. #endif
  194616. {
  194617. png_crc_finish(png_ptr, 0);
  194618. }
  194619. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194620. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194621. {
  194622. /* If we don't want to use the data from an ancillary chunk,
  194623. we have two options: an error abort, or a warning and we
  194624. ignore the data in this chunk (which should be OK, since
  194625. it's considered ancillary for a RGB or RGBA image). */
  194626. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194627. {
  194628. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194629. {
  194630. png_chunk_error(png_ptr, "CRC error");
  194631. }
  194632. else
  194633. {
  194634. png_chunk_warning(png_ptr, "CRC error");
  194635. return;
  194636. }
  194637. }
  194638. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194639. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194640. {
  194641. png_chunk_warning(png_ptr, "CRC error");
  194642. }
  194643. }
  194644. #endif
  194645. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194646. #if defined(PNG_READ_tRNS_SUPPORTED)
  194647. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194648. {
  194649. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194650. {
  194651. if (png_ptr->num_trans > (png_uint_16)num)
  194652. {
  194653. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194654. png_ptr->num_trans = (png_uint_16)num;
  194655. }
  194656. if (info_ptr->num_trans > (png_uint_16)num)
  194657. {
  194658. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194659. info_ptr->num_trans = (png_uint_16)num;
  194660. }
  194661. }
  194662. }
  194663. #endif
  194664. }
  194665. void /* PRIVATE */
  194666. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194667. {
  194668. png_debug(1, "in png_handle_IEND\n");
  194669. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194670. {
  194671. png_error(png_ptr, "No image in file");
  194672. }
  194673. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194674. if (length != 0)
  194675. {
  194676. png_warning(png_ptr, "Incorrect IEND chunk length");
  194677. }
  194678. png_crc_finish(png_ptr, length);
  194679. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194680. }
  194681. #if defined(PNG_READ_gAMA_SUPPORTED)
  194682. void /* PRIVATE */
  194683. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194684. {
  194685. png_fixed_point igamma;
  194686. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194687. float file_gamma;
  194688. #endif
  194689. png_byte buf[4];
  194690. png_debug(1, "in png_handle_gAMA\n");
  194691. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194692. png_error(png_ptr, "Missing IHDR before gAMA");
  194693. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194694. {
  194695. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194696. png_crc_finish(png_ptr, length);
  194697. return;
  194698. }
  194699. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194700. /* Should be an error, but we can cope with it */
  194701. png_warning(png_ptr, "Out of place gAMA chunk");
  194702. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194703. #if defined(PNG_READ_sRGB_SUPPORTED)
  194704. && !(info_ptr->valid & PNG_INFO_sRGB)
  194705. #endif
  194706. )
  194707. {
  194708. png_warning(png_ptr, "Duplicate gAMA chunk");
  194709. png_crc_finish(png_ptr, length);
  194710. return;
  194711. }
  194712. if (length != 4)
  194713. {
  194714. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194715. png_crc_finish(png_ptr, length);
  194716. return;
  194717. }
  194718. png_crc_read(png_ptr, buf, 4);
  194719. if (png_crc_finish(png_ptr, 0))
  194720. return;
  194721. igamma = (png_fixed_point)png_get_uint_32(buf);
  194722. /* check for zero gamma */
  194723. if (igamma == 0)
  194724. {
  194725. png_warning(png_ptr,
  194726. "Ignoring gAMA chunk with gamma=0");
  194727. return;
  194728. }
  194729. #if defined(PNG_READ_sRGB_SUPPORTED)
  194730. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194731. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194732. {
  194733. png_warning(png_ptr,
  194734. "Ignoring incorrect gAMA value when sRGB is also present");
  194735. #ifndef PNG_NO_CONSOLE_IO
  194736. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194737. #endif
  194738. return;
  194739. }
  194740. #endif /* PNG_READ_sRGB_SUPPORTED */
  194741. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194742. file_gamma = (float)igamma / (float)100000.0;
  194743. # ifdef PNG_READ_GAMMA_SUPPORTED
  194744. png_ptr->gamma = file_gamma;
  194745. # endif
  194746. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194747. #endif
  194748. #ifdef PNG_FIXED_POINT_SUPPORTED
  194749. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194750. #endif
  194751. }
  194752. #endif
  194753. #if defined(PNG_READ_sBIT_SUPPORTED)
  194754. void /* PRIVATE */
  194755. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194756. {
  194757. png_size_t truelen;
  194758. png_byte buf[4];
  194759. png_debug(1, "in png_handle_sBIT\n");
  194760. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194761. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194762. png_error(png_ptr, "Missing IHDR before sBIT");
  194763. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194764. {
  194765. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194766. png_crc_finish(png_ptr, length);
  194767. return;
  194768. }
  194769. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194770. {
  194771. /* Should be an error, but we can cope with it */
  194772. png_warning(png_ptr, "Out of place sBIT chunk");
  194773. }
  194774. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194775. {
  194776. png_warning(png_ptr, "Duplicate sBIT chunk");
  194777. png_crc_finish(png_ptr, length);
  194778. return;
  194779. }
  194780. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194781. truelen = 3;
  194782. else
  194783. truelen = (png_size_t)png_ptr->channels;
  194784. if (length != truelen || length > 4)
  194785. {
  194786. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194787. png_crc_finish(png_ptr, length);
  194788. return;
  194789. }
  194790. png_crc_read(png_ptr, buf, truelen);
  194791. if (png_crc_finish(png_ptr, 0))
  194792. return;
  194793. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194794. {
  194795. png_ptr->sig_bit.red = buf[0];
  194796. png_ptr->sig_bit.green = buf[1];
  194797. png_ptr->sig_bit.blue = buf[2];
  194798. png_ptr->sig_bit.alpha = buf[3];
  194799. }
  194800. else
  194801. {
  194802. png_ptr->sig_bit.gray = buf[0];
  194803. png_ptr->sig_bit.red = buf[0];
  194804. png_ptr->sig_bit.green = buf[0];
  194805. png_ptr->sig_bit.blue = buf[0];
  194806. png_ptr->sig_bit.alpha = buf[1];
  194807. }
  194808. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194809. }
  194810. #endif
  194811. #if defined(PNG_READ_cHRM_SUPPORTED)
  194812. void /* PRIVATE */
  194813. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194814. {
  194815. png_byte buf[4];
  194816. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194817. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194818. #endif
  194819. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194820. int_y_green, int_x_blue, int_y_blue;
  194821. png_uint_32 uint_x, uint_y;
  194822. png_debug(1, "in png_handle_cHRM\n");
  194823. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194824. png_error(png_ptr, "Missing IHDR before cHRM");
  194825. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194826. {
  194827. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194828. png_crc_finish(png_ptr, length);
  194829. return;
  194830. }
  194831. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194832. /* Should be an error, but we can cope with it */
  194833. png_warning(png_ptr, "Missing PLTE before cHRM");
  194834. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194835. #if defined(PNG_READ_sRGB_SUPPORTED)
  194836. && !(info_ptr->valid & PNG_INFO_sRGB)
  194837. #endif
  194838. )
  194839. {
  194840. png_warning(png_ptr, "Duplicate cHRM chunk");
  194841. png_crc_finish(png_ptr, length);
  194842. return;
  194843. }
  194844. if (length != 32)
  194845. {
  194846. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194847. png_crc_finish(png_ptr, length);
  194848. return;
  194849. }
  194850. png_crc_read(png_ptr, buf, 4);
  194851. uint_x = png_get_uint_32(buf);
  194852. png_crc_read(png_ptr, buf, 4);
  194853. uint_y = png_get_uint_32(buf);
  194854. if (uint_x > 80000L || uint_y > 80000L ||
  194855. uint_x + uint_y > 100000L)
  194856. {
  194857. png_warning(png_ptr, "Invalid cHRM white point");
  194858. png_crc_finish(png_ptr, 24);
  194859. return;
  194860. }
  194861. int_x_white = (png_fixed_point)uint_x;
  194862. int_y_white = (png_fixed_point)uint_y;
  194863. png_crc_read(png_ptr, buf, 4);
  194864. uint_x = png_get_uint_32(buf);
  194865. png_crc_read(png_ptr, buf, 4);
  194866. uint_y = png_get_uint_32(buf);
  194867. if (uint_x + uint_y > 100000L)
  194868. {
  194869. png_warning(png_ptr, "Invalid cHRM red point");
  194870. png_crc_finish(png_ptr, 16);
  194871. return;
  194872. }
  194873. int_x_red = (png_fixed_point)uint_x;
  194874. int_y_red = (png_fixed_point)uint_y;
  194875. png_crc_read(png_ptr, buf, 4);
  194876. uint_x = png_get_uint_32(buf);
  194877. png_crc_read(png_ptr, buf, 4);
  194878. uint_y = png_get_uint_32(buf);
  194879. if (uint_x + uint_y > 100000L)
  194880. {
  194881. png_warning(png_ptr, "Invalid cHRM green point");
  194882. png_crc_finish(png_ptr, 8);
  194883. return;
  194884. }
  194885. int_x_green = (png_fixed_point)uint_x;
  194886. int_y_green = (png_fixed_point)uint_y;
  194887. png_crc_read(png_ptr, buf, 4);
  194888. uint_x = png_get_uint_32(buf);
  194889. png_crc_read(png_ptr, buf, 4);
  194890. uint_y = png_get_uint_32(buf);
  194891. if (uint_x + uint_y > 100000L)
  194892. {
  194893. png_warning(png_ptr, "Invalid cHRM blue point");
  194894. png_crc_finish(png_ptr, 0);
  194895. return;
  194896. }
  194897. int_x_blue = (png_fixed_point)uint_x;
  194898. int_y_blue = (png_fixed_point)uint_y;
  194899. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194900. white_x = (float)int_x_white / (float)100000.0;
  194901. white_y = (float)int_y_white / (float)100000.0;
  194902. red_x = (float)int_x_red / (float)100000.0;
  194903. red_y = (float)int_y_red / (float)100000.0;
  194904. green_x = (float)int_x_green / (float)100000.0;
  194905. green_y = (float)int_y_green / (float)100000.0;
  194906. blue_x = (float)int_x_blue / (float)100000.0;
  194907. blue_y = (float)int_y_blue / (float)100000.0;
  194908. #endif
  194909. #if defined(PNG_READ_sRGB_SUPPORTED)
  194910. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194911. {
  194912. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194913. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194914. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194915. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194916. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194917. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194918. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194919. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194920. {
  194921. png_warning(png_ptr,
  194922. "Ignoring incorrect cHRM value when sRGB is also present");
  194923. #ifndef PNG_NO_CONSOLE_IO
  194924. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194925. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194926. white_x, white_y, red_x, red_y);
  194927. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194928. green_x, green_y, blue_x, blue_y);
  194929. #else
  194930. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194931. int_x_white, int_y_white, int_x_red, int_y_red);
  194932. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194933. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194934. #endif
  194935. #endif /* PNG_NO_CONSOLE_IO */
  194936. }
  194937. png_crc_finish(png_ptr, 0);
  194938. return;
  194939. }
  194940. #endif /* PNG_READ_sRGB_SUPPORTED */
  194941. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194942. png_set_cHRM(png_ptr, info_ptr,
  194943. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194944. #endif
  194945. #ifdef PNG_FIXED_POINT_SUPPORTED
  194946. png_set_cHRM_fixed(png_ptr, info_ptr,
  194947. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194948. int_y_green, int_x_blue, int_y_blue);
  194949. #endif
  194950. if (png_crc_finish(png_ptr, 0))
  194951. return;
  194952. }
  194953. #endif
  194954. #if defined(PNG_READ_sRGB_SUPPORTED)
  194955. void /* PRIVATE */
  194956. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194957. {
  194958. int intent;
  194959. png_byte buf[1];
  194960. png_debug(1, "in png_handle_sRGB\n");
  194961. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194962. png_error(png_ptr, "Missing IHDR before sRGB");
  194963. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194964. {
  194965. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194966. png_crc_finish(png_ptr, length);
  194967. return;
  194968. }
  194969. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194970. /* Should be an error, but we can cope with it */
  194971. png_warning(png_ptr, "Out of place sRGB chunk");
  194972. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194973. {
  194974. png_warning(png_ptr, "Duplicate sRGB chunk");
  194975. png_crc_finish(png_ptr, length);
  194976. return;
  194977. }
  194978. if (length != 1)
  194979. {
  194980. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194981. png_crc_finish(png_ptr, length);
  194982. return;
  194983. }
  194984. png_crc_read(png_ptr, buf, 1);
  194985. if (png_crc_finish(png_ptr, 0))
  194986. return;
  194987. intent = buf[0];
  194988. /* check for bad intent */
  194989. if (intent >= PNG_sRGB_INTENT_LAST)
  194990. {
  194991. png_warning(png_ptr, "Unknown sRGB intent");
  194992. return;
  194993. }
  194994. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194995. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194996. {
  194997. png_fixed_point igamma;
  194998. #ifdef PNG_FIXED_POINT_SUPPORTED
  194999. igamma=info_ptr->int_gamma;
  195000. #else
  195001. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195002. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  195003. # endif
  195004. #endif
  195005. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  195006. {
  195007. png_warning(png_ptr,
  195008. "Ignoring incorrect gAMA value when sRGB is also present");
  195009. #ifndef PNG_NO_CONSOLE_IO
  195010. # ifdef PNG_FIXED_POINT_SUPPORTED
  195011. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  195012. # else
  195013. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195014. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  195015. # endif
  195016. # endif
  195017. #endif
  195018. }
  195019. }
  195020. #endif /* PNG_READ_gAMA_SUPPORTED */
  195021. #ifdef PNG_READ_cHRM_SUPPORTED
  195022. #ifdef PNG_FIXED_POINT_SUPPORTED
  195023. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  195024. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  195025. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  195026. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  195027. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  195028. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  195029. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  195030. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  195031. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  195032. {
  195033. png_warning(png_ptr,
  195034. "Ignoring incorrect cHRM value when sRGB is also present");
  195035. }
  195036. #endif /* PNG_FIXED_POINT_SUPPORTED */
  195037. #endif /* PNG_READ_cHRM_SUPPORTED */
  195038. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  195039. }
  195040. #endif /* PNG_READ_sRGB_SUPPORTED */
  195041. #if defined(PNG_READ_iCCP_SUPPORTED)
  195042. void /* PRIVATE */
  195043. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195044. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195045. {
  195046. png_charp chunkdata;
  195047. png_byte compression_type;
  195048. png_bytep pC;
  195049. png_charp profile;
  195050. png_uint_32 skip = 0;
  195051. png_uint_32 profile_size, profile_length;
  195052. png_size_t slength, prefix_length, data_length;
  195053. png_debug(1, "in png_handle_iCCP\n");
  195054. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195055. png_error(png_ptr, "Missing IHDR before iCCP");
  195056. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195057. {
  195058. png_warning(png_ptr, "Invalid iCCP after IDAT");
  195059. png_crc_finish(png_ptr, length);
  195060. return;
  195061. }
  195062. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195063. /* Should be an error, but we can cope with it */
  195064. png_warning(png_ptr, "Out of place iCCP chunk");
  195065. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  195066. {
  195067. png_warning(png_ptr, "Duplicate iCCP chunk");
  195068. png_crc_finish(png_ptr, length);
  195069. return;
  195070. }
  195071. #ifdef PNG_MAX_MALLOC_64K
  195072. if (length > (png_uint_32)65535L)
  195073. {
  195074. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  195075. skip = length - (png_uint_32)65535L;
  195076. length = (png_uint_32)65535L;
  195077. }
  195078. #endif
  195079. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  195080. slength = (png_size_t)length;
  195081. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195082. if (png_crc_finish(png_ptr, skip))
  195083. {
  195084. png_free(png_ptr, chunkdata);
  195085. return;
  195086. }
  195087. chunkdata[slength] = 0x00;
  195088. for (profile = chunkdata; *profile; profile++)
  195089. /* empty loop to find end of name */ ;
  195090. ++profile;
  195091. /* there should be at least one zero (the compression type byte)
  195092. following the separator, and we should be on it */
  195093. if ( profile >= chunkdata + slength - 1)
  195094. {
  195095. png_free(png_ptr, chunkdata);
  195096. png_warning(png_ptr, "Malformed iCCP chunk");
  195097. return;
  195098. }
  195099. /* compression_type should always be zero */
  195100. compression_type = *profile++;
  195101. if (compression_type)
  195102. {
  195103. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  195104. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  195105. wrote nonzero) */
  195106. }
  195107. prefix_length = profile - chunkdata;
  195108. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  195109. slength, prefix_length, &data_length);
  195110. profile_length = data_length - prefix_length;
  195111. if ( prefix_length > data_length || profile_length < 4)
  195112. {
  195113. png_free(png_ptr, chunkdata);
  195114. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  195115. return;
  195116. }
  195117. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  195118. pC = (png_bytep)(chunkdata+prefix_length);
  195119. profile_size = ((*(pC ))<<24) |
  195120. ((*(pC+1))<<16) |
  195121. ((*(pC+2))<< 8) |
  195122. ((*(pC+3)) );
  195123. if(profile_size < profile_length)
  195124. profile_length = profile_size;
  195125. if(profile_size > profile_length)
  195126. {
  195127. png_free(png_ptr, chunkdata);
  195128. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  195129. return;
  195130. }
  195131. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  195132. chunkdata + prefix_length, profile_length);
  195133. png_free(png_ptr, chunkdata);
  195134. }
  195135. #endif /* PNG_READ_iCCP_SUPPORTED */
  195136. #if defined(PNG_READ_sPLT_SUPPORTED)
  195137. void /* PRIVATE */
  195138. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195139. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195140. {
  195141. png_bytep chunkdata;
  195142. png_bytep entry_start;
  195143. png_sPLT_t new_palette;
  195144. #ifdef PNG_NO_POINTER_INDEXING
  195145. png_sPLT_entryp pp;
  195146. #endif
  195147. int data_length, entry_size, i;
  195148. png_uint_32 skip = 0;
  195149. png_size_t slength;
  195150. png_debug(1, "in png_handle_sPLT\n");
  195151. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195152. png_error(png_ptr, "Missing IHDR before sPLT");
  195153. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195154. {
  195155. png_warning(png_ptr, "Invalid sPLT after IDAT");
  195156. png_crc_finish(png_ptr, length);
  195157. return;
  195158. }
  195159. #ifdef PNG_MAX_MALLOC_64K
  195160. if (length > (png_uint_32)65535L)
  195161. {
  195162. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  195163. skip = length - (png_uint_32)65535L;
  195164. length = (png_uint_32)65535L;
  195165. }
  195166. #endif
  195167. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  195168. slength = (png_size_t)length;
  195169. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195170. if (png_crc_finish(png_ptr, skip))
  195171. {
  195172. png_free(png_ptr, chunkdata);
  195173. return;
  195174. }
  195175. chunkdata[slength] = 0x00;
  195176. for (entry_start = chunkdata; *entry_start; entry_start++)
  195177. /* empty loop to find end of name */ ;
  195178. ++entry_start;
  195179. /* a sample depth should follow the separator, and we should be on it */
  195180. if (entry_start > chunkdata + slength - 2)
  195181. {
  195182. png_free(png_ptr, chunkdata);
  195183. png_warning(png_ptr, "malformed sPLT chunk");
  195184. return;
  195185. }
  195186. new_palette.depth = *entry_start++;
  195187. entry_size = (new_palette.depth == 8 ? 6 : 10);
  195188. data_length = (slength - (entry_start - chunkdata));
  195189. /* integrity-check the data length */
  195190. if (data_length % entry_size)
  195191. {
  195192. png_free(png_ptr, chunkdata);
  195193. png_warning(png_ptr, "sPLT chunk has bad length");
  195194. return;
  195195. }
  195196. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195197. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195198. png_sizeof(png_sPLT_entry)))
  195199. {
  195200. png_warning(png_ptr, "sPLT chunk too long");
  195201. return;
  195202. }
  195203. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195204. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195205. if (new_palette.entries == NULL)
  195206. {
  195207. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195208. return;
  195209. }
  195210. #ifndef PNG_NO_POINTER_INDEXING
  195211. for (i = 0; i < new_palette.nentries; i++)
  195212. {
  195213. png_sPLT_entryp pp = new_palette.entries + i;
  195214. if (new_palette.depth == 8)
  195215. {
  195216. pp->red = *entry_start++;
  195217. pp->green = *entry_start++;
  195218. pp->blue = *entry_start++;
  195219. pp->alpha = *entry_start++;
  195220. }
  195221. else
  195222. {
  195223. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195224. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195225. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195226. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195227. }
  195228. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195229. }
  195230. #else
  195231. pp = new_palette.entries;
  195232. for (i = 0; i < new_palette.nentries; i++)
  195233. {
  195234. if (new_palette.depth == 8)
  195235. {
  195236. pp[i].red = *entry_start++;
  195237. pp[i].green = *entry_start++;
  195238. pp[i].blue = *entry_start++;
  195239. pp[i].alpha = *entry_start++;
  195240. }
  195241. else
  195242. {
  195243. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195244. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195245. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195246. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195247. }
  195248. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195249. }
  195250. #endif
  195251. /* discard all chunk data except the name and stash that */
  195252. new_palette.name = (png_charp)chunkdata;
  195253. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195254. png_free(png_ptr, chunkdata);
  195255. png_free(png_ptr, new_palette.entries);
  195256. }
  195257. #endif /* PNG_READ_sPLT_SUPPORTED */
  195258. #if defined(PNG_READ_tRNS_SUPPORTED)
  195259. void /* PRIVATE */
  195260. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195261. {
  195262. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195263. int bit_mask;
  195264. png_debug(1, "in png_handle_tRNS\n");
  195265. /* For non-indexed color, mask off any bits in the tRNS value that
  195266. * exceed the bit depth. Some creators were writing extra bits there.
  195267. * This is not needed for indexed color. */
  195268. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195269. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195270. png_error(png_ptr, "Missing IHDR before tRNS");
  195271. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195272. {
  195273. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195274. png_crc_finish(png_ptr, length);
  195275. return;
  195276. }
  195277. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195278. {
  195279. png_warning(png_ptr, "Duplicate tRNS chunk");
  195280. png_crc_finish(png_ptr, length);
  195281. return;
  195282. }
  195283. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195284. {
  195285. png_byte buf[2];
  195286. if (length != 2)
  195287. {
  195288. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195289. png_crc_finish(png_ptr, length);
  195290. return;
  195291. }
  195292. png_crc_read(png_ptr, buf, 2);
  195293. png_ptr->num_trans = 1;
  195294. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195295. }
  195296. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195297. {
  195298. png_byte buf[6];
  195299. if (length != 6)
  195300. {
  195301. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195302. png_crc_finish(png_ptr, length);
  195303. return;
  195304. }
  195305. png_crc_read(png_ptr, buf, (png_size_t)length);
  195306. png_ptr->num_trans = 1;
  195307. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195308. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195309. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195310. }
  195311. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195312. {
  195313. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195314. {
  195315. /* Should be an error, but we can cope with it. */
  195316. png_warning(png_ptr, "Missing PLTE before tRNS");
  195317. }
  195318. if (length > (png_uint_32)png_ptr->num_palette ||
  195319. length > PNG_MAX_PALETTE_LENGTH)
  195320. {
  195321. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195322. png_crc_finish(png_ptr, length);
  195323. return;
  195324. }
  195325. if (length == 0)
  195326. {
  195327. png_warning(png_ptr, "Zero length tRNS chunk");
  195328. png_crc_finish(png_ptr, length);
  195329. return;
  195330. }
  195331. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195332. png_ptr->num_trans = (png_uint_16)length;
  195333. }
  195334. else
  195335. {
  195336. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195337. png_crc_finish(png_ptr, length);
  195338. return;
  195339. }
  195340. if (png_crc_finish(png_ptr, 0))
  195341. {
  195342. png_ptr->num_trans = 0;
  195343. return;
  195344. }
  195345. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195346. &(png_ptr->trans_values));
  195347. }
  195348. #endif
  195349. #if defined(PNG_READ_bKGD_SUPPORTED)
  195350. void /* PRIVATE */
  195351. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195352. {
  195353. png_size_t truelen;
  195354. png_byte buf[6];
  195355. png_debug(1, "in png_handle_bKGD\n");
  195356. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195357. png_error(png_ptr, "Missing IHDR before bKGD");
  195358. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195359. {
  195360. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195361. png_crc_finish(png_ptr, length);
  195362. return;
  195363. }
  195364. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195365. !(png_ptr->mode & PNG_HAVE_PLTE))
  195366. {
  195367. png_warning(png_ptr, "Missing PLTE before bKGD");
  195368. png_crc_finish(png_ptr, length);
  195369. return;
  195370. }
  195371. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195372. {
  195373. png_warning(png_ptr, "Duplicate bKGD chunk");
  195374. png_crc_finish(png_ptr, length);
  195375. return;
  195376. }
  195377. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195378. truelen = 1;
  195379. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195380. truelen = 6;
  195381. else
  195382. truelen = 2;
  195383. if (length != truelen)
  195384. {
  195385. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195386. png_crc_finish(png_ptr, length);
  195387. return;
  195388. }
  195389. png_crc_read(png_ptr, buf, truelen);
  195390. if (png_crc_finish(png_ptr, 0))
  195391. return;
  195392. /* We convert the index value into RGB components so that we can allow
  195393. * arbitrary RGB values for background when we have transparency, and
  195394. * so it is easy to determine the RGB values of the background color
  195395. * from the info_ptr struct. */
  195396. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195397. {
  195398. png_ptr->background.index = buf[0];
  195399. if(info_ptr->num_palette)
  195400. {
  195401. if(buf[0] > info_ptr->num_palette)
  195402. {
  195403. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195404. return;
  195405. }
  195406. png_ptr->background.red =
  195407. (png_uint_16)png_ptr->palette[buf[0]].red;
  195408. png_ptr->background.green =
  195409. (png_uint_16)png_ptr->palette[buf[0]].green;
  195410. png_ptr->background.blue =
  195411. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195412. }
  195413. }
  195414. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195415. {
  195416. png_ptr->background.red =
  195417. png_ptr->background.green =
  195418. png_ptr->background.blue =
  195419. png_ptr->background.gray = png_get_uint_16(buf);
  195420. }
  195421. else
  195422. {
  195423. png_ptr->background.red = png_get_uint_16(buf);
  195424. png_ptr->background.green = png_get_uint_16(buf + 2);
  195425. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195426. }
  195427. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195428. }
  195429. #endif
  195430. #if defined(PNG_READ_hIST_SUPPORTED)
  195431. void /* PRIVATE */
  195432. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195433. {
  195434. unsigned int num, i;
  195435. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195436. png_debug(1, "in png_handle_hIST\n");
  195437. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195438. png_error(png_ptr, "Missing IHDR before hIST");
  195439. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195440. {
  195441. png_warning(png_ptr, "Invalid hIST after IDAT");
  195442. png_crc_finish(png_ptr, length);
  195443. return;
  195444. }
  195445. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195446. {
  195447. png_warning(png_ptr, "Missing PLTE before hIST");
  195448. png_crc_finish(png_ptr, length);
  195449. return;
  195450. }
  195451. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195452. {
  195453. png_warning(png_ptr, "Duplicate hIST chunk");
  195454. png_crc_finish(png_ptr, length);
  195455. return;
  195456. }
  195457. num = length / 2 ;
  195458. if (num != (unsigned int) png_ptr->num_palette || num >
  195459. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195460. {
  195461. png_warning(png_ptr, "Incorrect hIST chunk length");
  195462. png_crc_finish(png_ptr, length);
  195463. return;
  195464. }
  195465. for (i = 0; i < num; i++)
  195466. {
  195467. png_byte buf[2];
  195468. png_crc_read(png_ptr, buf, 2);
  195469. readbuf[i] = png_get_uint_16(buf);
  195470. }
  195471. if (png_crc_finish(png_ptr, 0))
  195472. return;
  195473. png_set_hIST(png_ptr, info_ptr, readbuf);
  195474. }
  195475. #endif
  195476. #if defined(PNG_READ_pHYs_SUPPORTED)
  195477. void /* PRIVATE */
  195478. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195479. {
  195480. png_byte buf[9];
  195481. png_uint_32 res_x, res_y;
  195482. int unit_type;
  195483. png_debug(1, "in png_handle_pHYs\n");
  195484. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195485. png_error(png_ptr, "Missing IHDR before pHYs");
  195486. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195487. {
  195488. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195489. png_crc_finish(png_ptr, length);
  195490. return;
  195491. }
  195492. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195493. {
  195494. png_warning(png_ptr, "Duplicate pHYs chunk");
  195495. png_crc_finish(png_ptr, length);
  195496. return;
  195497. }
  195498. if (length != 9)
  195499. {
  195500. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195501. png_crc_finish(png_ptr, length);
  195502. return;
  195503. }
  195504. png_crc_read(png_ptr, buf, 9);
  195505. if (png_crc_finish(png_ptr, 0))
  195506. return;
  195507. res_x = png_get_uint_32(buf);
  195508. res_y = png_get_uint_32(buf + 4);
  195509. unit_type = buf[8];
  195510. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195511. }
  195512. #endif
  195513. #if defined(PNG_READ_oFFs_SUPPORTED)
  195514. void /* PRIVATE */
  195515. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195516. {
  195517. png_byte buf[9];
  195518. png_int_32 offset_x, offset_y;
  195519. int unit_type;
  195520. png_debug(1, "in png_handle_oFFs\n");
  195521. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195522. png_error(png_ptr, "Missing IHDR before oFFs");
  195523. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195524. {
  195525. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195526. png_crc_finish(png_ptr, length);
  195527. return;
  195528. }
  195529. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195530. {
  195531. png_warning(png_ptr, "Duplicate oFFs chunk");
  195532. png_crc_finish(png_ptr, length);
  195533. return;
  195534. }
  195535. if (length != 9)
  195536. {
  195537. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195538. png_crc_finish(png_ptr, length);
  195539. return;
  195540. }
  195541. png_crc_read(png_ptr, buf, 9);
  195542. if (png_crc_finish(png_ptr, 0))
  195543. return;
  195544. offset_x = png_get_int_32(buf);
  195545. offset_y = png_get_int_32(buf + 4);
  195546. unit_type = buf[8];
  195547. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195548. }
  195549. #endif
  195550. #if defined(PNG_READ_pCAL_SUPPORTED)
  195551. /* read the pCAL chunk (described in the PNG Extensions document) */
  195552. void /* PRIVATE */
  195553. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195554. {
  195555. png_charp purpose;
  195556. png_int_32 X0, X1;
  195557. png_byte type, nparams;
  195558. png_charp buf, units, endptr;
  195559. png_charpp params;
  195560. png_size_t slength;
  195561. int i;
  195562. png_debug(1, "in png_handle_pCAL\n");
  195563. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195564. png_error(png_ptr, "Missing IHDR before pCAL");
  195565. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195566. {
  195567. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195568. png_crc_finish(png_ptr, length);
  195569. return;
  195570. }
  195571. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195572. {
  195573. png_warning(png_ptr, "Duplicate pCAL chunk");
  195574. png_crc_finish(png_ptr, length);
  195575. return;
  195576. }
  195577. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195578. length + 1);
  195579. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195580. if (purpose == NULL)
  195581. {
  195582. png_warning(png_ptr, "No memory for pCAL purpose.");
  195583. return;
  195584. }
  195585. slength = (png_size_t)length;
  195586. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195587. if (png_crc_finish(png_ptr, 0))
  195588. {
  195589. png_free(png_ptr, purpose);
  195590. return;
  195591. }
  195592. purpose[slength] = 0x00; /* null terminate the last string */
  195593. png_debug(3, "Finding end of pCAL purpose string\n");
  195594. for (buf = purpose; *buf; buf++)
  195595. /* empty loop */ ;
  195596. endptr = purpose + slength;
  195597. /* We need to have at least 12 bytes after the purpose string
  195598. in order to get the parameter information. */
  195599. if (endptr <= buf + 12)
  195600. {
  195601. png_warning(png_ptr, "Invalid pCAL data");
  195602. png_free(png_ptr, purpose);
  195603. return;
  195604. }
  195605. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195606. X0 = png_get_int_32((png_bytep)buf+1);
  195607. X1 = png_get_int_32((png_bytep)buf+5);
  195608. type = buf[9];
  195609. nparams = buf[10];
  195610. units = buf + 11;
  195611. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195612. /* Check that we have the right number of parameters for known
  195613. equation types. */
  195614. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195615. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195616. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195617. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195618. {
  195619. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195620. png_free(png_ptr, purpose);
  195621. return;
  195622. }
  195623. else if (type >= PNG_EQUATION_LAST)
  195624. {
  195625. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195626. }
  195627. for (buf = units; *buf; buf++)
  195628. /* Empty loop to move past the units string. */ ;
  195629. png_debug(3, "Allocating pCAL parameters array\n");
  195630. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195631. *png_sizeof(png_charp))) ;
  195632. if (params == NULL)
  195633. {
  195634. png_free(png_ptr, purpose);
  195635. png_warning(png_ptr, "No memory for pCAL params.");
  195636. return;
  195637. }
  195638. /* Get pointers to the start of each parameter string. */
  195639. for (i = 0; i < (int)nparams; i++)
  195640. {
  195641. buf++; /* Skip the null string terminator from previous parameter. */
  195642. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195643. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195644. /* Empty loop to move past each parameter string */ ;
  195645. /* Make sure we haven't run out of data yet */
  195646. if (buf > endptr)
  195647. {
  195648. png_warning(png_ptr, "Invalid pCAL data");
  195649. png_free(png_ptr, purpose);
  195650. png_free(png_ptr, params);
  195651. return;
  195652. }
  195653. }
  195654. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195655. units, params);
  195656. png_free(png_ptr, purpose);
  195657. png_free(png_ptr, params);
  195658. }
  195659. #endif
  195660. #if defined(PNG_READ_sCAL_SUPPORTED)
  195661. /* read the sCAL chunk */
  195662. void /* PRIVATE */
  195663. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195664. {
  195665. png_charp buffer, ep;
  195666. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195667. double width, height;
  195668. png_charp vp;
  195669. #else
  195670. #ifdef PNG_FIXED_POINT_SUPPORTED
  195671. png_charp swidth, sheight;
  195672. #endif
  195673. #endif
  195674. png_size_t slength;
  195675. png_debug(1, "in png_handle_sCAL\n");
  195676. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195677. png_error(png_ptr, "Missing IHDR before sCAL");
  195678. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195679. {
  195680. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195681. png_crc_finish(png_ptr, length);
  195682. return;
  195683. }
  195684. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195685. {
  195686. png_warning(png_ptr, "Duplicate sCAL chunk");
  195687. png_crc_finish(png_ptr, length);
  195688. return;
  195689. }
  195690. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195691. length + 1);
  195692. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195693. if (buffer == NULL)
  195694. {
  195695. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195696. return;
  195697. }
  195698. slength = (png_size_t)length;
  195699. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195700. if (png_crc_finish(png_ptr, 0))
  195701. {
  195702. png_free(png_ptr, buffer);
  195703. return;
  195704. }
  195705. buffer[slength] = 0x00; /* null terminate the last string */
  195706. ep = buffer + 1; /* skip unit byte */
  195707. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195708. width = png_strtod(png_ptr, ep, &vp);
  195709. if (*vp)
  195710. {
  195711. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195712. return;
  195713. }
  195714. #else
  195715. #ifdef PNG_FIXED_POINT_SUPPORTED
  195716. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195717. if (swidth == NULL)
  195718. {
  195719. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195720. return;
  195721. }
  195722. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195723. #endif
  195724. #endif
  195725. for (ep = buffer; *ep; ep++)
  195726. /* empty loop */ ;
  195727. ep++;
  195728. if (buffer + slength < ep)
  195729. {
  195730. png_warning(png_ptr, "Truncated sCAL chunk");
  195731. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195732. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195733. png_free(png_ptr, swidth);
  195734. #endif
  195735. png_free(png_ptr, buffer);
  195736. return;
  195737. }
  195738. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195739. height = png_strtod(png_ptr, ep, &vp);
  195740. if (*vp)
  195741. {
  195742. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195743. return;
  195744. }
  195745. #else
  195746. #ifdef PNG_FIXED_POINT_SUPPORTED
  195747. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195748. if (swidth == NULL)
  195749. {
  195750. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195751. return;
  195752. }
  195753. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195754. #endif
  195755. #endif
  195756. if (buffer + slength < ep
  195757. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195758. || width <= 0. || height <= 0.
  195759. #endif
  195760. )
  195761. {
  195762. png_warning(png_ptr, "Invalid sCAL data");
  195763. png_free(png_ptr, buffer);
  195764. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195765. png_free(png_ptr, swidth);
  195766. png_free(png_ptr, sheight);
  195767. #endif
  195768. return;
  195769. }
  195770. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195771. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195772. #else
  195773. #ifdef PNG_FIXED_POINT_SUPPORTED
  195774. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195775. #endif
  195776. #endif
  195777. png_free(png_ptr, buffer);
  195778. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195779. png_free(png_ptr, swidth);
  195780. png_free(png_ptr, sheight);
  195781. #endif
  195782. }
  195783. #endif
  195784. #if defined(PNG_READ_tIME_SUPPORTED)
  195785. void /* PRIVATE */
  195786. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195787. {
  195788. png_byte buf[7];
  195789. png_time mod_time;
  195790. png_debug(1, "in png_handle_tIME\n");
  195791. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195792. png_error(png_ptr, "Out of place tIME chunk");
  195793. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195794. {
  195795. png_warning(png_ptr, "Duplicate tIME chunk");
  195796. png_crc_finish(png_ptr, length);
  195797. return;
  195798. }
  195799. if (png_ptr->mode & PNG_HAVE_IDAT)
  195800. png_ptr->mode |= PNG_AFTER_IDAT;
  195801. if (length != 7)
  195802. {
  195803. png_warning(png_ptr, "Incorrect tIME chunk length");
  195804. png_crc_finish(png_ptr, length);
  195805. return;
  195806. }
  195807. png_crc_read(png_ptr, buf, 7);
  195808. if (png_crc_finish(png_ptr, 0))
  195809. return;
  195810. mod_time.second = buf[6];
  195811. mod_time.minute = buf[5];
  195812. mod_time.hour = buf[4];
  195813. mod_time.day = buf[3];
  195814. mod_time.month = buf[2];
  195815. mod_time.year = png_get_uint_16(buf);
  195816. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195817. }
  195818. #endif
  195819. #if defined(PNG_READ_tEXt_SUPPORTED)
  195820. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195821. void /* PRIVATE */
  195822. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195823. {
  195824. png_textp text_ptr;
  195825. png_charp key;
  195826. png_charp text;
  195827. png_uint_32 skip = 0;
  195828. png_size_t slength;
  195829. int ret;
  195830. png_debug(1, "in png_handle_tEXt\n");
  195831. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195832. png_error(png_ptr, "Missing IHDR before tEXt");
  195833. if (png_ptr->mode & PNG_HAVE_IDAT)
  195834. png_ptr->mode |= PNG_AFTER_IDAT;
  195835. #ifdef PNG_MAX_MALLOC_64K
  195836. if (length > (png_uint_32)65535L)
  195837. {
  195838. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195839. skip = length - (png_uint_32)65535L;
  195840. length = (png_uint_32)65535L;
  195841. }
  195842. #endif
  195843. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195844. if (key == NULL)
  195845. {
  195846. png_warning(png_ptr, "No memory to process text chunk.");
  195847. return;
  195848. }
  195849. slength = (png_size_t)length;
  195850. png_crc_read(png_ptr, (png_bytep)key, slength);
  195851. if (png_crc_finish(png_ptr, skip))
  195852. {
  195853. png_free(png_ptr, key);
  195854. return;
  195855. }
  195856. key[slength] = 0x00;
  195857. for (text = key; *text; text++)
  195858. /* empty loop to find end of key */ ;
  195859. if (text != key + slength)
  195860. text++;
  195861. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195862. (png_uint_32)png_sizeof(png_text));
  195863. if (text_ptr == NULL)
  195864. {
  195865. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195866. png_free(png_ptr, key);
  195867. return;
  195868. }
  195869. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195870. text_ptr->key = key;
  195871. #ifdef PNG_iTXt_SUPPORTED
  195872. text_ptr->lang = NULL;
  195873. text_ptr->lang_key = NULL;
  195874. text_ptr->itxt_length = 0;
  195875. #endif
  195876. text_ptr->text = text;
  195877. text_ptr->text_length = png_strlen(text);
  195878. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195879. png_free(png_ptr, key);
  195880. png_free(png_ptr, text_ptr);
  195881. if (ret)
  195882. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195883. }
  195884. #endif
  195885. #if defined(PNG_READ_zTXt_SUPPORTED)
  195886. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195887. void /* PRIVATE */
  195888. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195889. {
  195890. png_textp text_ptr;
  195891. png_charp chunkdata;
  195892. png_charp text;
  195893. int comp_type;
  195894. int ret;
  195895. png_size_t slength, prefix_len, data_len;
  195896. png_debug(1, "in png_handle_zTXt\n");
  195897. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195898. png_error(png_ptr, "Missing IHDR before zTXt");
  195899. if (png_ptr->mode & PNG_HAVE_IDAT)
  195900. png_ptr->mode |= PNG_AFTER_IDAT;
  195901. #ifdef PNG_MAX_MALLOC_64K
  195902. /* We will no doubt have problems with chunks even half this size, but
  195903. there is no hard and fast rule to tell us where to stop. */
  195904. if (length > (png_uint_32)65535L)
  195905. {
  195906. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195907. png_crc_finish(png_ptr, length);
  195908. return;
  195909. }
  195910. #endif
  195911. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195912. if (chunkdata == NULL)
  195913. {
  195914. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195915. return;
  195916. }
  195917. slength = (png_size_t)length;
  195918. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195919. if (png_crc_finish(png_ptr, 0))
  195920. {
  195921. png_free(png_ptr, chunkdata);
  195922. return;
  195923. }
  195924. chunkdata[slength] = 0x00;
  195925. for (text = chunkdata; *text; text++)
  195926. /* empty loop */ ;
  195927. /* zTXt must have some text after the chunkdataword */
  195928. if (text >= chunkdata + slength - 2)
  195929. {
  195930. png_warning(png_ptr, "Truncated zTXt chunk");
  195931. png_free(png_ptr, chunkdata);
  195932. return;
  195933. }
  195934. else
  195935. {
  195936. comp_type = *(++text);
  195937. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195938. {
  195939. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195940. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195941. }
  195942. text++; /* skip the compression_method byte */
  195943. }
  195944. prefix_len = text - chunkdata;
  195945. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195946. (png_size_t)length, prefix_len, &data_len);
  195947. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195948. (png_uint_32)png_sizeof(png_text));
  195949. if (text_ptr == NULL)
  195950. {
  195951. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195952. png_free(png_ptr, chunkdata);
  195953. return;
  195954. }
  195955. text_ptr->compression = comp_type;
  195956. text_ptr->key = chunkdata;
  195957. #ifdef PNG_iTXt_SUPPORTED
  195958. text_ptr->lang = NULL;
  195959. text_ptr->lang_key = NULL;
  195960. text_ptr->itxt_length = 0;
  195961. #endif
  195962. text_ptr->text = chunkdata + prefix_len;
  195963. text_ptr->text_length = data_len;
  195964. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195965. png_free(png_ptr, text_ptr);
  195966. png_free(png_ptr, chunkdata);
  195967. if (ret)
  195968. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195969. }
  195970. #endif
  195971. #if defined(PNG_READ_iTXt_SUPPORTED)
  195972. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195973. void /* PRIVATE */
  195974. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195975. {
  195976. png_textp text_ptr;
  195977. png_charp chunkdata;
  195978. png_charp key, lang, text, lang_key;
  195979. int comp_flag;
  195980. int comp_type = 0;
  195981. int ret;
  195982. png_size_t slength, prefix_len, data_len;
  195983. png_debug(1, "in png_handle_iTXt\n");
  195984. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195985. png_error(png_ptr, "Missing IHDR before iTXt");
  195986. if (png_ptr->mode & PNG_HAVE_IDAT)
  195987. png_ptr->mode |= PNG_AFTER_IDAT;
  195988. #ifdef PNG_MAX_MALLOC_64K
  195989. /* We will no doubt have problems with chunks even half this size, but
  195990. there is no hard and fast rule to tell us where to stop. */
  195991. if (length > (png_uint_32)65535L)
  195992. {
  195993. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195994. png_crc_finish(png_ptr, length);
  195995. return;
  195996. }
  195997. #endif
  195998. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195999. if (chunkdata == NULL)
  196000. {
  196001. png_warning(png_ptr, "No memory to process iTXt chunk.");
  196002. return;
  196003. }
  196004. slength = (png_size_t)length;
  196005. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  196006. if (png_crc_finish(png_ptr, 0))
  196007. {
  196008. png_free(png_ptr, chunkdata);
  196009. return;
  196010. }
  196011. chunkdata[slength] = 0x00;
  196012. for (lang = chunkdata; *lang; lang++)
  196013. /* empty loop */ ;
  196014. lang++; /* skip NUL separator */
  196015. /* iTXt must have a language tag (possibly empty), two compression bytes,
  196016. translated keyword (possibly empty), and possibly some text after the
  196017. keyword */
  196018. if (lang >= chunkdata + slength - 3)
  196019. {
  196020. png_warning(png_ptr, "Truncated iTXt chunk");
  196021. png_free(png_ptr, chunkdata);
  196022. return;
  196023. }
  196024. else
  196025. {
  196026. comp_flag = *lang++;
  196027. comp_type = *lang++;
  196028. }
  196029. for (lang_key = lang; *lang_key; lang_key++)
  196030. /* empty loop */ ;
  196031. lang_key++; /* skip NUL separator */
  196032. if (lang_key >= chunkdata + slength)
  196033. {
  196034. png_warning(png_ptr, "Truncated iTXt chunk");
  196035. png_free(png_ptr, chunkdata);
  196036. return;
  196037. }
  196038. for (text = lang_key; *text; text++)
  196039. /* empty loop */ ;
  196040. text++; /* skip NUL separator */
  196041. if (text >= chunkdata + slength)
  196042. {
  196043. png_warning(png_ptr, "Malformed iTXt chunk");
  196044. png_free(png_ptr, chunkdata);
  196045. return;
  196046. }
  196047. prefix_len = text - chunkdata;
  196048. key=chunkdata;
  196049. if (comp_flag)
  196050. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  196051. (size_t)length, prefix_len, &data_len);
  196052. else
  196053. data_len=png_strlen(chunkdata + prefix_len);
  196054. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  196055. (png_uint_32)png_sizeof(png_text));
  196056. if (text_ptr == NULL)
  196057. {
  196058. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  196059. png_free(png_ptr, chunkdata);
  196060. return;
  196061. }
  196062. text_ptr->compression = (int)comp_flag + 1;
  196063. text_ptr->lang_key = chunkdata+(lang_key-key);
  196064. text_ptr->lang = chunkdata+(lang-key);
  196065. text_ptr->itxt_length = data_len;
  196066. text_ptr->text_length = 0;
  196067. text_ptr->key = chunkdata;
  196068. text_ptr->text = chunkdata + prefix_len;
  196069. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  196070. png_free(png_ptr, text_ptr);
  196071. png_free(png_ptr, chunkdata);
  196072. if (ret)
  196073. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  196074. }
  196075. #endif
  196076. /* This function is called when we haven't found a handler for a
  196077. chunk. If there isn't a problem with the chunk itself (ie bad
  196078. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  196079. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  196080. case it will be saved away to be written out later. */
  196081. void /* PRIVATE */
  196082. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196083. {
  196084. png_uint_32 skip = 0;
  196085. png_debug(1, "in png_handle_unknown\n");
  196086. if (png_ptr->mode & PNG_HAVE_IDAT)
  196087. {
  196088. #ifdef PNG_USE_LOCAL_ARRAYS
  196089. PNG_CONST PNG_IDAT;
  196090. #endif
  196091. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  196092. png_ptr->mode |= PNG_AFTER_IDAT;
  196093. }
  196094. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  196095. if (!(png_ptr->chunk_name[0] & 0x20))
  196096. {
  196097. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196098. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196099. PNG_HANDLE_CHUNK_ALWAYS
  196100. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196101. && png_ptr->read_user_chunk_fn == NULL
  196102. #endif
  196103. )
  196104. #endif
  196105. png_chunk_error(png_ptr, "unknown critical chunk");
  196106. }
  196107. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196108. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  196109. (png_ptr->read_user_chunk_fn != NULL))
  196110. {
  196111. #ifdef PNG_MAX_MALLOC_64K
  196112. if (length > (png_uint_32)65535L)
  196113. {
  196114. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  196115. skip = length - (png_uint_32)65535L;
  196116. length = (png_uint_32)65535L;
  196117. }
  196118. #endif
  196119. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  196120. (png_charp)png_ptr->chunk_name, 5);
  196121. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  196122. png_ptr->unknown_chunk.size = (png_size_t)length;
  196123. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  196124. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196125. if(png_ptr->read_user_chunk_fn != NULL)
  196126. {
  196127. /* callback to user unknown chunk handler */
  196128. int ret;
  196129. ret = (*(png_ptr->read_user_chunk_fn))
  196130. (png_ptr, &png_ptr->unknown_chunk);
  196131. if (ret < 0)
  196132. png_chunk_error(png_ptr, "error in user chunk");
  196133. if (ret == 0)
  196134. {
  196135. if (!(png_ptr->chunk_name[0] & 0x20))
  196136. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196137. PNG_HANDLE_CHUNK_ALWAYS)
  196138. png_chunk_error(png_ptr, "unknown critical chunk");
  196139. png_set_unknown_chunks(png_ptr, info_ptr,
  196140. &png_ptr->unknown_chunk, 1);
  196141. }
  196142. }
  196143. #else
  196144. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  196145. #endif
  196146. png_free(png_ptr, png_ptr->unknown_chunk.data);
  196147. png_ptr->unknown_chunk.data = NULL;
  196148. }
  196149. else
  196150. #endif
  196151. skip = length;
  196152. png_crc_finish(png_ptr, skip);
  196153. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196154. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  196155. #endif
  196156. }
  196157. /* This function is called to verify that a chunk name is valid.
  196158. This function can't have the "critical chunk check" incorporated
  196159. into it, since in the future we will need to be able to call user
  196160. functions to handle unknown critical chunks after we check that
  196161. the chunk name itself is valid. */
  196162. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  196163. void /* PRIVATE */
  196164. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  196165. {
  196166. png_debug(1, "in png_check_chunk_name\n");
  196167. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  196168. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  196169. {
  196170. png_chunk_error(png_ptr, "invalid chunk type");
  196171. }
  196172. }
  196173. /* Combines the row recently read in with the existing pixels in the
  196174. row. This routine takes care of alpha and transparency if requested.
  196175. This routine also handles the two methods of progressive display
  196176. of interlaced images, depending on the mask value.
  196177. The mask value describes which pixels are to be combined with
  196178. the row. The pattern always repeats every 8 pixels, so just 8
  196179. bits are needed. A one indicates the pixel is to be combined,
  196180. a zero indicates the pixel is to be skipped. This is in addition
  196181. to any alpha or transparency value associated with the pixel. If
  196182. you want all pixels to be combined, pass 0xff (255) in mask. */
  196183. void /* PRIVATE */
  196184. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  196185. {
  196186. png_debug(1,"in png_combine_row\n");
  196187. if (mask == 0xff)
  196188. {
  196189. png_memcpy(row, png_ptr->row_buf + 1,
  196190. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  196191. }
  196192. else
  196193. {
  196194. switch (png_ptr->row_info.pixel_depth)
  196195. {
  196196. case 1:
  196197. {
  196198. png_bytep sp = png_ptr->row_buf + 1;
  196199. png_bytep dp = row;
  196200. int s_inc, s_start, s_end;
  196201. int m = 0x80;
  196202. int shift;
  196203. png_uint_32 i;
  196204. png_uint_32 row_width = png_ptr->width;
  196205. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196206. if (png_ptr->transformations & PNG_PACKSWAP)
  196207. {
  196208. s_start = 0;
  196209. s_end = 7;
  196210. s_inc = 1;
  196211. }
  196212. else
  196213. #endif
  196214. {
  196215. s_start = 7;
  196216. s_end = 0;
  196217. s_inc = -1;
  196218. }
  196219. shift = s_start;
  196220. for (i = 0; i < row_width; i++)
  196221. {
  196222. if (m & mask)
  196223. {
  196224. int value;
  196225. value = (*sp >> shift) & 0x01;
  196226. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196227. *dp |= (png_byte)(value << shift);
  196228. }
  196229. if (shift == s_end)
  196230. {
  196231. shift = s_start;
  196232. sp++;
  196233. dp++;
  196234. }
  196235. else
  196236. shift += s_inc;
  196237. if (m == 1)
  196238. m = 0x80;
  196239. else
  196240. m >>= 1;
  196241. }
  196242. break;
  196243. }
  196244. case 2:
  196245. {
  196246. png_bytep sp = png_ptr->row_buf + 1;
  196247. png_bytep dp = row;
  196248. int s_start, s_end, s_inc;
  196249. int m = 0x80;
  196250. int shift;
  196251. png_uint_32 i;
  196252. png_uint_32 row_width = png_ptr->width;
  196253. int value;
  196254. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196255. if (png_ptr->transformations & PNG_PACKSWAP)
  196256. {
  196257. s_start = 0;
  196258. s_end = 6;
  196259. s_inc = 2;
  196260. }
  196261. else
  196262. #endif
  196263. {
  196264. s_start = 6;
  196265. s_end = 0;
  196266. s_inc = -2;
  196267. }
  196268. shift = s_start;
  196269. for (i = 0; i < row_width; i++)
  196270. {
  196271. if (m & mask)
  196272. {
  196273. value = (*sp >> shift) & 0x03;
  196274. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196275. *dp |= (png_byte)(value << shift);
  196276. }
  196277. if (shift == s_end)
  196278. {
  196279. shift = s_start;
  196280. sp++;
  196281. dp++;
  196282. }
  196283. else
  196284. shift += s_inc;
  196285. if (m == 1)
  196286. m = 0x80;
  196287. else
  196288. m >>= 1;
  196289. }
  196290. break;
  196291. }
  196292. case 4:
  196293. {
  196294. png_bytep sp = png_ptr->row_buf + 1;
  196295. png_bytep dp = row;
  196296. int s_start, s_end, s_inc;
  196297. int m = 0x80;
  196298. int shift;
  196299. png_uint_32 i;
  196300. png_uint_32 row_width = png_ptr->width;
  196301. int value;
  196302. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196303. if (png_ptr->transformations & PNG_PACKSWAP)
  196304. {
  196305. s_start = 0;
  196306. s_end = 4;
  196307. s_inc = 4;
  196308. }
  196309. else
  196310. #endif
  196311. {
  196312. s_start = 4;
  196313. s_end = 0;
  196314. s_inc = -4;
  196315. }
  196316. shift = s_start;
  196317. for (i = 0; i < row_width; i++)
  196318. {
  196319. if (m & mask)
  196320. {
  196321. value = (*sp >> shift) & 0xf;
  196322. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196323. *dp |= (png_byte)(value << shift);
  196324. }
  196325. if (shift == s_end)
  196326. {
  196327. shift = s_start;
  196328. sp++;
  196329. dp++;
  196330. }
  196331. else
  196332. shift += s_inc;
  196333. if (m == 1)
  196334. m = 0x80;
  196335. else
  196336. m >>= 1;
  196337. }
  196338. break;
  196339. }
  196340. default:
  196341. {
  196342. png_bytep sp = png_ptr->row_buf + 1;
  196343. png_bytep dp = row;
  196344. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196345. png_uint_32 i;
  196346. png_uint_32 row_width = png_ptr->width;
  196347. png_byte m = 0x80;
  196348. for (i = 0; i < row_width; i++)
  196349. {
  196350. if (m & mask)
  196351. {
  196352. png_memcpy(dp, sp, pixel_bytes);
  196353. }
  196354. sp += pixel_bytes;
  196355. dp += pixel_bytes;
  196356. if (m == 1)
  196357. m = 0x80;
  196358. else
  196359. m >>= 1;
  196360. }
  196361. break;
  196362. }
  196363. }
  196364. }
  196365. }
  196366. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196367. /* OLD pre-1.0.9 interface:
  196368. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196369. png_uint_32 transformations)
  196370. */
  196371. void /* PRIVATE */
  196372. png_do_read_interlace(png_structp png_ptr)
  196373. {
  196374. png_row_infop row_info = &(png_ptr->row_info);
  196375. png_bytep row = png_ptr->row_buf + 1;
  196376. int pass = png_ptr->pass;
  196377. png_uint_32 transformations = png_ptr->transformations;
  196378. #ifdef PNG_USE_LOCAL_ARRAYS
  196379. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196380. /* offset to next interlace block */
  196381. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196382. #endif
  196383. png_debug(1,"in png_do_read_interlace\n");
  196384. if (row != NULL && row_info != NULL)
  196385. {
  196386. png_uint_32 final_width;
  196387. final_width = row_info->width * png_pass_inc[pass];
  196388. switch (row_info->pixel_depth)
  196389. {
  196390. case 1:
  196391. {
  196392. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196393. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196394. int sshift, dshift;
  196395. int s_start, s_end, s_inc;
  196396. int jstop = png_pass_inc[pass];
  196397. png_byte v;
  196398. png_uint_32 i;
  196399. int j;
  196400. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196401. if (transformations & PNG_PACKSWAP)
  196402. {
  196403. sshift = (int)((row_info->width + 7) & 0x07);
  196404. dshift = (int)((final_width + 7) & 0x07);
  196405. s_start = 7;
  196406. s_end = 0;
  196407. s_inc = -1;
  196408. }
  196409. else
  196410. #endif
  196411. {
  196412. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196413. dshift = 7 - (int)((final_width + 7) & 0x07);
  196414. s_start = 0;
  196415. s_end = 7;
  196416. s_inc = 1;
  196417. }
  196418. for (i = 0; i < row_info->width; i++)
  196419. {
  196420. v = (png_byte)((*sp >> sshift) & 0x01);
  196421. for (j = 0; j < jstop; j++)
  196422. {
  196423. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196424. *dp |= (png_byte)(v << dshift);
  196425. if (dshift == s_end)
  196426. {
  196427. dshift = s_start;
  196428. dp--;
  196429. }
  196430. else
  196431. dshift += s_inc;
  196432. }
  196433. if (sshift == s_end)
  196434. {
  196435. sshift = s_start;
  196436. sp--;
  196437. }
  196438. else
  196439. sshift += s_inc;
  196440. }
  196441. break;
  196442. }
  196443. case 2:
  196444. {
  196445. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196446. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196447. int sshift, dshift;
  196448. int s_start, s_end, s_inc;
  196449. int jstop = png_pass_inc[pass];
  196450. png_uint_32 i;
  196451. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196452. if (transformations & PNG_PACKSWAP)
  196453. {
  196454. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196455. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196456. s_start = 6;
  196457. s_end = 0;
  196458. s_inc = -2;
  196459. }
  196460. else
  196461. #endif
  196462. {
  196463. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196464. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196465. s_start = 0;
  196466. s_end = 6;
  196467. s_inc = 2;
  196468. }
  196469. for (i = 0; i < row_info->width; i++)
  196470. {
  196471. png_byte v;
  196472. int j;
  196473. v = (png_byte)((*sp >> sshift) & 0x03);
  196474. for (j = 0; j < jstop; j++)
  196475. {
  196476. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196477. *dp |= (png_byte)(v << dshift);
  196478. if (dshift == s_end)
  196479. {
  196480. dshift = s_start;
  196481. dp--;
  196482. }
  196483. else
  196484. dshift += s_inc;
  196485. }
  196486. if (sshift == s_end)
  196487. {
  196488. sshift = s_start;
  196489. sp--;
  196490. }
  196491. else
  196492. sshift += s_inc;
  196493. }
  196494. break;
  196495. }
  196496. case 4:
  196497. {
  196498. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196499. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196500. int sshift, dshift;
  196501. int s_start, s_end, s_inc;
  196502. png_uint_32 i;
  196503. int jstop = png_pass_inc[pass];
  196504. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196505. if (transformations & PNG_PACKSWAP)
  196506. {
  196507. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196508. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196509. s_start = 4;
  196510. s_end = 0;
  196511. s_inc = -4;
  196512. }
  196513. else
  196514. #endif
  196515. {
  196516. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196517. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196518. s_start = 0;
  196519. s_end = 4;
  196520. s_inc = 4;
  196521. }
  196522. for (i = 0; i < row_info->width; i++)
  196523. {
  196524. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196525. int j;
  196526. for (j = 0; j < jstop; j++)
  196527. {
  196528. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196529. *dp |= (png_byte)(v << dshift);
  196530. if (dshift == s_end)
  196531. {
  196532. dshift = s_start;
  196533. dp--;
  196534. }
  196535. else
  196536. dshift += s_inc;
  196537. }
  196538. if (sshift == s_end)
  196539. {
  196540. sshift = s_start;
  196541. sp--;
  196542. }
  196543. else
  196544. sshift += s_inc;
  196545. }
  196546. break;
  196547. }
  196548. default:
  196549. {
  196550. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196551. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196552. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196553. int jstop = png_pass_inc[pass];
  196554. png_uint_32 i;
  196555. for (i = 0; i < row_info->width; i++)
  196556. {
  196557. png_byte v[8];
  196558. int j;
  196559. png_memcpy(v, sp, pixel_bytes);
  196560. for (j = 0; j < jstop; j++)
  196561. {
  196562. png_memcpy(dp, v, pixel_bytes);
  196563. dp -= pixel_bytes;
  196564. }
  196565. sp -= pixel_bytes;
  196566. }
  196567. break;
  196568. }
  196569. }
  196570. row_info->width = final_width;
  196571. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196572. }
  196573. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196574. transformations = transformations; /* silence compiler warning */
  196575. #endif
  196576. }
  196577. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196578. void /* PRIVATE */
  196579. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196580. png_bytep prev_row, int filter)
  196581. {
  196582. png_debug(1, "in png_read_filter_row\n");
  196583. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196584. switch (filter)
  196585. {
  196586. case PNG_FILTER_VALUE_NONE:
  196587. break;
  196588. case PNG_FILTER_VALUE_SUB:
  196589. {
  196590. png_uint_32 i;
  196591. png_uint_32 istop = row_info->rowbytes;
  196592. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196593. png_bytep rp = row + bpp;
  196594. png_bytep lp = row;
  196595. for (i = bpp; i < istop; i++)
  196596. {
  196597. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196598. rp++;
  196599. }
  196600. break;
  196601. }
  196602. case PNG_FILTER_VALUE_UP:
  196603. {
  196604. png_uint_32 i;
  196605. png_uint_32 istop = row_info->rowbytes;
  196606. png_bytep rp = row;
  196607. png_bytep pp = prev_row;
  196608. for (i = 0; i < istop; i++)
  196609. {
  196610. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196611. rp++;
  196612. }
  196613. break;
  196614. }
  196615. case PNG_FILTER_VALUE_AVG:
  196616. {
  196617. png_uint_32 i;
  196618. png_bytep rp = row;
  196619. png_bytep pp = prev_row;
  196620. png_bytep lp = row;
  196621. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196622. png_uint_32 istop = row_info->rowbytes - bpp;
  196623. for (i = 0; i < bpp; i++)
  196624. {
  196625. *rp = (png_byte)(((int)(*rp) +
  196626. ((int)(*pp++) / 2 )) & 0xff);
  196627. rp++;
  196628. }
  196629. for (i = 0; i < istop; i++)
  196630. {
  196631. *rp = (png_byte)(((int)(*rp) +
  196632. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196633. rp++;
  196634. }
  196635. break;
  196636. }
  196637. case PNG_FILTER_VALUE_PAETH:
  196638. {
  196639. png_uint_32 i;
  196640. png_bytep rp = row;
  196641. png_bytep pp = prev_row;
  196642. png_bytep lp = row;
  196643. png_bytep cp = prev_row;
  196644. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196645. png_uint_32 istop=row_info->rowbytes - bpp;
  196646. for (i = 0; i < bpp; i++)
  196647. {
  196648. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196649. rp++;
  196650. }
  196651. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196652. {
  196653. int a, b, c, pa, pb, pc, p;
  196654. a = *lp++;
  196655. b = *pp++;
  196656. c = *cp++;
  196657. p = b - c;
  196658. pc = a - c;
  196659. #ifdef PNG_USE_ABS
  196660. pa = abs(p);
  196661. pb = abs(pc);
  196662. pc = abs(p + pc);
  196663. #else
  196664. pa = p < 0 ? -p : p;
  196665. pb = pc < 0 ? -pc : pc;
  196666. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196667. #endif
  196668. /*
  196669. if (pa <= pb && pa <= pc)
  196670. p = a;
  196671. else if (pb <= pc)
  196672. p = b;
  196673. else
  196674. p = c;
  196675. */
  196676. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196677. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196678. rp++;
  196679. }
  196680. break;
  196681. }
  196682. default:
  196683. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196684. *row=0;
  196685. break;
  196686. }
  196687. }
  196688. void /* PRIVATE */
  196689. png_read_finish_row(png_structp png_ptr)
  196690. {
  196691. #ifdef PNG_USE_LOCAL_ARRAYS
  196692. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196693. /* start of interlace block */
  196694. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196695. /* offset to next interlace block */
  196696. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196697. /* start of interlace block in the y direction */
  196698. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196699. /* offset to next interlace block in the y direction */
  196700. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196701. #endif
  196702. png_debug(1, "in png_read_finish_row\n");
  196703. png_ptr->row_number++;
  196704. if (png_ptr->row_number < png_ptr->num_rows)
  196705. return;
  196706. if (png_ptr->interlaced)
  196707. {
  196708. png_ptr->row_number = 0;
  196709. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196710. png_ptr->rowbytes + 1);
  196711. do
  196712. {
  196713. png_ptr->pass++;
  196714. if (png_ptr->pass >= 7)
  196715. break;
  196716. png_ptr->iwidth = (png_ptr->width +
  196717. png_pass_inc[png_ptr->pass] - 1 -
  196718. png_pass_start[png_ptr->pass]) /
  196719. png_pass_inc[png_ptr->pass];
  196720. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196721. png_ptr->iwidth) + 1;
  196722. if (!(png_ptr->transformations & PNG_INTERLACE))
  196723. {
  196724. png_ptr->num_rows = (png_ptr->height +
  196725. png_pass_yinc[png_ptr->pass] - 1 -
  196726. png_pass_ystart[png_ptr->pass]) /
  196727. png_pass_yinc[png_ptr->pass];
  196728. if (!(png_ptr->num_rows))
  196729. continue;
  196730. }
  196731. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196732. break;
  196733. } while (png_ptr->iwidth == 0);
  196734. if (png_ptr->pass < 7)
  196735. return;
  196736. }
  196737. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196738. {
  196739. #ifdef PNG_USE_LOCAL_ARRAYS
  196740. PNG_CONST PNG_IDAT;
  196741. #endif
  196742. char extra;
  196743. int ret;
  196744. png_ptr->zstream.next_out = (Bytef *)&extra;
  196745. png_ptr->zstream.avail_out = (uInt)1;
  196746. for(;;)
  196747. {
  196748. if (!(png_ptr->zstream.avail_in))
  196749. {
  196750. while (!png_ptr->idat_size)
  196751. {
  196752. png_byte chunk_length[4];
  196753. png_crc_finish(png_ptr, 0);
  196754. png_read_data(png_ptr, chunk_length, 4);
  196755. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196756. png_reset_crc(png_ptr);
  196757. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196758. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196759. png_error(png_ptr, "Not enough image data");
  196760. }
  196761. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196762. png_ptr->zstream.next_in = png_ptr->zbuf;
  196763. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196764. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196765. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196766. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196767. }
  196768. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196769. if (ret == Z_STREAM_END)
  196770. {
  196771. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196772. png_ptr->idat_size)
  196773. png_warning(png_ptr, "Extra compressed data");
  196774. png_ptr->mode |= PNG_AFTER_IDAT;
  196775. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196776. break;
  196777. }
  196778. if (ret != Z_OK)
  196779. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196780. "Decompression Error");
  196781. if (!(png_ptr->zstream.avail_out))
  196782. {
  196783. png_warning(png_ptr, "Extra compressed data.");
  196784. png_ptr->mode |= PNG_AFTER_IDAT;
  196785. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196786. break;
  196787. }
  196788. }
  196789. png_ptr->zstream.avail_out = 0;
  196790. }
  196791. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196792. png_warning(png_ptr, "Extra compression data");
  196793. inflateReset(&png_ptr->zstream);
  196794. png_ptr->mode |= PNG_AFTER_IDAT;
  196795. }
  196796. void /* PRIVATE */
  196797. png_read_start_row(png_structp png_ptr)
  196798. {
  196799. #ifdef PNG_USE_LOCAL_ARRAYS
  196800. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196801. /* start of interlace block */
  196802. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196803. /* offset to next interlace block */
  196804. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196805. /* start of interlace block in the y direction */
  196806. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196807. /* offset to next interlace block in the y direction */
  196808. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196809. #endif
  196810. int max_pixel_depth;
  196811. png_uint_32 row_bytes;
  196812. png_debug(1, "in png_read_start_row\n");
  196813. png_ptr->zstream.avail_in = 0;
  196814. png_init_read_transformations(png_ptr);
  196815. if (png_ptr->interlaced)
  196816. {
  196817. if (!(png_ptr->transformations & PNG_INTERLACE))
  196818. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196819. png_pass_ystart[0]) / png_pass_yinc[0];
  196820. else
  196821. png_ptr->num_rows = png_ptr->height;
  196822. png_ptr->iwidth = (png_ptr->width +
  196823. png_pass_inc[png_ptr->pass] - 1 -
  196824. png_pass_start[png_ptr->pass]) /
  196825. png_pass_inc[png_ptr->pass];
  196826. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196827. png_ptr->irowbytes = (png_size_t)row_bytes;
  196828. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196829. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196830. }
  196831. else
  196832. {
  196833. png_ptr->num_rows = png_ptr->height;
  196834. png_ptr->iwidth = png_ptr->width;
  196835. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196836. }
  196837. max_pixel_depth = png_ptr->pixel_depth;
  196838. #if defined(PNG_READ_PACK_SUPPORTED)
  196839. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196840. max_pixel_depth = 8;
  196841. #endif
  196842. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196843. if (png_ptr->transformations & PNG_EXPAND)
  196844. {
  196845. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196846. {
  196847. if (png_ptr->num_trans)
  196848. max_pixel_depth = 32;
  196849. else
  196850. max_pixel_depth = 24;
  196851. }
  196852. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196853. {
  196854. if (max_pixel_depth < 8)
  196855. max_pixel_depth = 8;
  196856. if (png_ptr->num_trans)
  196857. max_pixel_depth *= 2;
  196858. }
  196859. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196860. {
  196861. if (png_ptr->num_trans)
  196862. {
  196863. max_pixel_depth *= 4;
  196864. max_pixel_depth /= 3;
  196865. }
  196866. }
  196867. }
  196868. #endif
  196869. #if defined(PNG_READ_FILLER_SUPPORTED)
  196870. if (png_ptr->transformations & (PNG_FILLER))
  196871. {
  196872. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196873. max_pixel_depth = 32;
  196874. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196875. {
  196876. if (max_pixel_depth <= 8)
  196877. max_pixel_depth = 16;
  196878. else
  196879. max_pixel_depth = 32;
  196880. }
  196881. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196882. {
  196883. if (max_pixel_depth <= 32)
  196884. max_pixel_depth = 32;
  196885. else
  196886. max_pixel_depth = 64;
  196887. }
  196888. }
  196889. #endif
  196890. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196891. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196892. {
  196893. if (
  196894. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196895. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196896. #endif
  196897. #if defined(PNG_READ_FILLER_SUPPORTED)
  196898. (png_ptr->transformations & (PNG_FILLER)) ||
  196899. #endif
  196900. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196901. {
  196902. if (max_pixel_depth <= 16)
  196903. max_pixel_depth = 32;
  196904. else
  196905. max_pixel_depth = 64;
  196906. }
  196907. else
  196908. {
  196909. if (max_pixel_depth <= 8)
  196910. {
  196911. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196912. max_pixel_depth = 32;
  196913. else
  196914. max_pixel_depth = 24;
  196915. }
  196916. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196917. max_pixel_depth = 64;
  196918. else
  196919. max_pixel_depth = 48;
  196920. }
  196921. }
  196922. #endif
  196923. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196924. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196925. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196926. {
  196927. int user_pixel_depth=png_ptr->user_transform_depth*
  196928. png_ptr->user_transform_channels;
  196929. if(user_pixel_depth > max_pixel_depth)
  196930. max_pixel_depth=user_pixel_depth;
  196931. }
  196932. #endif
  196933. /* align the width on the next larger 8 pixels. Mainly used
  196934. for interlacing */
  196935. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196936. /* calculate the maximum bytes needed, adding a byte and a pixel
  196937. for safety's sake */
  196938. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196939. 1 + ((max_pixel_depth + 7) >> 3);
  196940. #ifdef PNG_MAX_MALLOC_64K
  196941. if (row_bytes > (png_uint_32)65536L)
  196942. png_error(png_ptr, "This image requires a row greater than 64KB");
  196943. #endif
  196944. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196945. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196946. #ifdef PNG_MAX_MALLOC_64K
  196947. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196948. png_error(png_ptr, "This image requires a row greater than 64KB");
  196949. #endif
  196950. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196951. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196952. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196953. png_ptr->rowbytes + 1));
  196954. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196955. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196956. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196957. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196958. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196959. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196960. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196961. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196962. }
  196963. #endif /* PNG_READ_SUPPORTED */
  196964. /*** End of inlined file: pngrutil.c ***/
  196965. /*** Start of inlined file: pngset.c ***/
  196966. /* pngset.c - storage of image information into info struct
  196967. *
  196968. * Last changed in libpng 1.2.21 [October 4, 2007]
  196969. * For conditions of distribution and use, see copyright notice in png.h
  196970. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196971. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196972. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196973. *
  196974. * The functions here are used during reads to store data from the file
  196975. * into the info struct, and during writes to store application data
  196976. * into the info struct for writing into the file. This abstracts the
  196977. * info struct and allows us to change the structure in the future.
  196978. */
  196979. #define PNG_INTERNAL
  196980. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196981. #if defined(PNG_bKGD_SUPPORTED)
  196982. void PNGAPI
  196983. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196984. {
  196985. png_debug1(1, "in %s storage function\n", "bKGD");
  196986. if (png_ptr == NULL || info_ptr == NULL)
  196987. return;
  196988. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196989. info_ptr->valid |= PNG_INFO_bKGD;
  196990. }
  196991. #endif
  196992. #if defined(PNG_cHRM_SUPPORTED)
  196993. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196994. void PNGAPI
  196995. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196996. double white_x, double white_y, double red_x, double red_y,
  196997. double green_x, double green_y, double blue_x, double blue_y)
  196998. {
  196999. png_debug1(1, "in %s storage function\n", "cHRM");
  197000. if (png_ptr == NULL || info_ptr == NULL)
  197001. return;
  197002. if (white_x < 0.0 || white_y < 0.0 ||
  197003. red_x < 0.0 || red_y < 0.0 ||
  197004. green_x < 0.0 || green_y < 0.0 ||
  197005. blue_x < 0.0 || blue_y < 0.0)
  197006. {
  197007. png_warning(png_ptr,
  197008. "Ignoring attempt to set negative chromaticity value");
  197009. return;
  197010. }
  197011. if (white_x > 21474.83 || white_y > 21474.83 ||
  197012. red_x > 21474.83 || red_y > 21474.83 ||
  197013. green_x > 21474.83 || green_y > 21474.83 ||
  197014. blue_x > 21474.83 || blue_y > 21474.83)
  197015. {
  197016. png_warning(png_ptr,
  197017. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197018. return;
  197019. }
  197020. info_ptr->x_white = (float)white_x;
  197021. info_ptr->y_white = (float)white_y;
  197022. info_ptr->x_red = (float)red_x;
  197023. info_ptr->y_red = (float)red_y;
  197024. info_ptr->x_green = (float)green_x;
  197025. info_ptr->y_green = (float)green_y;
  197026. info_ptr->x_blue = (float)blue_x;
  197027. info_ptr->y_blue = (float)blue_y;
  197028. #ifdef PNG_FIXED_POINT_SUPPORTED
  197029. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  197030. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  197031. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  197032. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  197033. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  197034. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  197035. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  197036. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  197037. #endif
  197038. info_ptr->valid |= PNG_INFO_cHRM;
  197039. }
  197040. #endif
  197041. #ifdef PNG_FIXED_POINT_SUPPORTED
  197042. void PNGAPI
  197043. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  197044. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  197045. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  197046. png_fixed_point blue_x, png_fixed_point blue_y)
  197047. {
  197048. png_debug1(1, "in %s storage function\n", "cHRM");
  197049. if (png_ptr == NULL || info_ptr == NULL)
  197050. return;
  197051. if (white_x < 0 || white_y < 0 ||
  197052. red_x < 0 || red_y < 0 ||
  197053. green_x < 0 || green_y < 0 ||
  197054. blue_x < 0 || blue_y < 0)
  197055. {
  197056. png_warning(png_ptr,
  197057. "Ignoring attempt to set negative chromaticity value");
  197058. return;
  197059. }
  197060. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197061. if (white_x > (double) PNG_UINT_31_MAX ||
  197062. white_y > (double) PNG_UINT_31_MAX ||
  197063. red_x > (double) PNG_UINT_31_MAX ||
  197064. red_y > (double) PNG_UINT_31_MAX ||
  197065. green_x > (double) PNG_UINT_31_MAX ||
  197066. green_y > (double) PNG_UINT_31_MAX ||
  197067. blue_x > (double) PNG_UINT_31_MAX ||
  197068. blue_y > (double) PNG_UINT_31_MAX)
  197069. #else
  197070. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197071. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197072. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197073. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197074. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197075. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197076. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197077. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  197078. #endif
  197079. {
  197080. png_warning(png_ptr,
  197081. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197082. return;
  197083. }
  197084. info_ptr->int_x_white = white_x;
  197085. info_ptr->int_y_white = white_y;
  197086. info_ptr->int_x_red = red_x;
  197087. info_ptr->int_y_red = red_y;
  197088. info_ptr->int_x_green = green_x;
  197089. info_ptr->int_y_green = green_y;
  197090. info_ptr->int_x_blue = blue_x;
  197091. info_ptr->int_y_blue = blue_y;
  197092. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197093. info_ptr->x_white = (float)(white_x/100000.);
  197094. info_ptr->y_white = (float)(white_y/100000.);
  197095. info_ptr->x_red = (float)( red_x/100000.);
  197096. info_ptr->y_red = (float)( red_y/100000.);
  197097. info_ptr->x_green = (float)(green_x/100000.);
  197098. info_ptr->y_green = (float)(green_y/100000.);
  197099. info_ptr->x_blue = (float)( blue_x/100000.);
  197100. info_ptr->y_blue = (float)( blue_y/100000.);
  197101. #endif
  197102. info_ptr->valid |= PNG_INFO_cHRM;
  197103. }
  197104. #endif
  197105. #endif
  197106. #if defined(PNG_gAMA_SUPPORTED)
  197107. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197108. void PNGAPI
  197109. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  197110. {
  197111. double gamma;
  197112. png_debug1(1, "in %s storage function\n", "gAMA");
  197113. if (png_ptr == NULL || info_ptr == NULL)
  197114. return;
  197115. /* Check for overflow */
  197116. if (file_gamma > 21474.83)
  197117. {
  197118. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197119. gamma=21474.83;
  197120. }
  197121. else
  197122. gamma=file_gamma;
  197123. info_ptr->gamma = (float)gamma;
  197124. #ifdef PNG_FIXED_POINT_SUPPORTED
  197125. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  197126. #endif
  197127. info_ptr->valid |= PNG_INFO_gAMA;
  197128. if(gamma == 0.0)
  197129. png_warning(png_ptr, "Setting gamma=0");
  197130. }
  197131. #endif
  197132. void PNGAPI
  197133. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  197134. int_gamma)
  197135. {
  197136. png_fixed_point gamma;
  197137. png_debug1(1, "in %s storage function\n", "gAMA");
  197138. if (png_ptr == NULL || info_ptr == NULL)
  197139. return;
  197140. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  197141. {
  197142. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197143. gamma=PNG_UINT_31_MAX;
  197144. }
  197145. else
  197146. {
  197147. if (int_gamma < 0)
  197148. {
  197149. png_warning(png_ptr, "Setting negative gamma to zero");
  197150. gamma=0;
  197151. }
  197152. else
  197153. gamma=int_gamma;
  197154. }
  197155. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197156. info_ptr->gamma = (float)(gamma/100000.);
  197157. #endif
  197158. #ifdef PNG_FIXED_POINT_SUPPORTED
  197159. info_ptr->int_gamma = gamma;
  197160. #endif
  197161. info_ptr->valid |= PNG_INFO_gAMA;
  197162. if(gamma == 0)
  197163. png_warning(png_ptr, "Setting gamma=0");
  197164. }
  197165. #endif
  197166. #if defined(PNG_hIST_SUPPORTED)
  197167. void PNGAPI
  197168. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  197169. {
  197170. int i;
  197171. png_debug1(1, "in %s storage function\n", "hIST");
  197172. if (png_ptr == NULL || info_ptr == NULL)
  197173. return;
  197174. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  197175. > PNG_MAX_PALETTE_LENGTH)
  197176. {
  197177. png_warning(png_ptr,
  197178. "Invalid palette size, hIST allocation skipped.");
  197179. return;
  197180. }
  197181. #ifdef PNG_FREE_ME_SUPPORTED
  197182. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  197183. #endif
  197184. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  197185. 1.2.1 */
  197186. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  197187. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  197188. if (png_ptr->hist == NULL)
  197189. {
  197190. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  197191. return;
  197192. }
  197193. for (i = 0; i < info_ptr->num_palette; i++)
  197194. png_ptr->hist[i] = hist[i];
  197195. info_ptr->hist = png_ptr->hist;
  197196. info_ptr->valid |= PNG_INFO_hIST;
  197197. #ifdef PNG_FREE_ME_SUPPORTED
  197198. info_ptr->free_me |= PNG_FREE_HIST;
  197199. #else
  197200. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197201. #endif
  197202. }
  197203. #endif
  197204. void PNGAPI
  197205. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197206. png_uint_32 width, png_uint_32 height, int bit_depth,
  197207. int color_type, int interlace_type, int compression_type,
  197208. int filter_type)
  197209. {
  197210. png_debug1(1, "in %s storage function\n", "IHDR");
  197211. if (png_ptr == NULL || info_ptr == NULL)
  197212. return;
  197213. /* check for width and height valid values */
  197214. if (width == 0 || height == 0)
  197215. png_error(png_ptr, "Image width or height is zero in IHDR");
  197216. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197217. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197218. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197219. #else
  197220. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197221. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197222. #endif
  197223. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197224. png_error(png_ptr, "Invalid image size in IHDR");
  197225. if ( width > (PNG_UINT_32_MAX
  197226. >> 3) /* 8-byte RGBA pixels */
  197227. - 64 /* bigrowbuf hack */
  197228. - 1 /* filter byte */
  197229. - 7*8 /* rounding of width to multiple of 8 pixels */
  197230. - 8) /* extra max_pixel_depth pad */
  197231. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197232. /* check other values */
  197233. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197234. bit_depth != 8 && bit_depth != 16)
  197235. png_error(png_ptr, "Invalid bit depth in IHDR");
  197236. if (color_type < 0 || color_type == 1 ||
  197237. color_type == 5 || color_type > 6)
  197238. png_error(png_ptr, "Invalid color type in IHDR");
  197239. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197240. ((color_type == PNG_COLOR_TYPE_RGB ||
  197241. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197242. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197243. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197244. if (interlace_type >= PNG_INTERLACE_LAST)
  197245. png_error(png_ptr, "Unknown interlace method in IHDR");
  197246. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197247. png_error(png_ptr, "Unknown compression method in IHDR");
  197248. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197249. /* Accept filter_method 64 (intrapixel differencing) only if
  197250. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197251. * 2. Libpng did not read a PNG signature (this filter_method is only
  197252. * used in PNG datastreams that are embedded in MNG datastreams) and
  197253. * 3. The application called png_permit_mng_features with a mask that
  197254. * included PNG_FLAG_MNG_FILTER_64 and
  197255. * 4. The filter_method is 64 and
  197256. * 5. The color_type is RGB or RGBA
  197257. */
  197258. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197259. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197260. if(filter_type != PNG_FILTER_TYPE_BASE)
  197261. {
  197262. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197263. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197264. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197265. (color_type == PNG_COLOR_TYPE_RGB ||
  197266. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197267. png_error(png_ptr, "Unknown filter method in IHDR");
  197268. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197269. png_warning(png_ptr, "Invalid filter method in IHDR");
  197270. }
  197271. #else
  197272. if(filter_type != PNG_FILTER_TYPE_BASE)
  197273. png_error(png_ptr, "Unknown filter method in IHDR");
  197274. #endif
  197275. info_ptr->width = width;
  197276. info_ptr->height = height;
  197277. info_ptr->bit_depth = (png_byte)bit_depth;
  197278. info_ptr->color_type =(png_byte) color_type;
  197279. info_ptr->compression_type = (png_byte)compression_type;
  197280. info_ptr->filter_type = (png_byte)filter_type;
  197281. info_ptr->interlace_type = (png_byte)interlace_type;
  197282. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197283. info_ptr->channels = 1;
  197284. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197285. info_ptr->channels = 3;
  197286. else
  197287. info_ptr->channels = 1;
  197288. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197289. info_ptr->channels++;
  197290. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197291. /* check for potential overflow */
  197292. if (width > (PNG_UINT_32_MAX
  197293. >> 3) /* 8-byte RGBA pixels */
  197294. - 64 /* bigrowbuf hack */
  197295. - 1 /* filter byte */
  197296. - 7*8 /* rounding of width to multiple of 8 pixels */
  197297. - 8) /* extra max_pixel_depth pad */
  197298. info_ptr->rowbytes = (png_size_t)0;
  197299. else
  197300. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197301. }
  197302. #if defined(PNG_oFFs_SUPPORTED)
  197303. void PNGAPI
  197304. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197305. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197306. {
  197307. png_debug1(1, "in %s storage function\n", "oFFs");
  197308. if (png_ptr == NULL || info_ptr == NULL)
  197309. return;
  197310. info_ptr->x_offset = offset_x;
  197311. info_ptr->y_offset = offset_y;
  197312. info_ptr->offset_unit_type = (png_byte)unit_type;
  197313. info_ptr->valid |= PNG_INFO_oFFs;
  197314. }
  197315. #endif
  197316. #if defined(PNG_pCAL_SUPPORTED)
  197317. void PNGAPI
  197318. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197319. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197320. png_charp units, png_charpp params)
  197321. {
  197322. png_uint_32 length;
  197323. int i;
  197324. png_debug1(1, "in %s storage function\n", "pCAL");
  197325. if (png_ptr == NULL || info_ptr == NULL)
  197326. return;
  197327. length = png_strlen(purpose) + 1;
  197328. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197329. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197330. if (info_ptr->pcal_purpose == NULL)
  197331. {
  197332. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197333. return;
  197334. }
  197335. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197336. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197337. info_ptr->pcal_X0 = X0;
  197338. info_ptr->pcal_X1 = X1;
  197339. info_ptr->pcal_type = (png_byte)type;
  197340. info_ptr->pcal_nparams = (png_byte)nparams;
  197341. length = png_strlen(units) + 1;
  197342. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197343. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197344. if (info_ptr->pcal_units == NULL)
  197345. {
  197346. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197347. return;
  197348. }
  197349. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197350. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197351. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197352. if (info_ptr->pcal_params == NULL)
  197353. {
  197354. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197355. return;
  197356. }
  197357. info_ptr->pcal_params[nparams] = NULL;
  197358. for (i = 0; i < nparams; i++)
  197359. {
  197360. length = png_strlen(params[i]) + 1;
  197361. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197362. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197363. if (info_ptr->pcal_params[i] == NULL)
  197364. {
  197365. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197366. return;
  197367. }
  197368. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197369. }
  197370. info_ptr->valid |= PNG_INFO_pCAL;
  197371. #ifdef PNG_FREE_ME_SUPPORTED
  197372. info_ptr->free_me |= PNG_FREE_PCAL;
  197373. #endif
  197374. }
  197375. #endif
  197376. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197377. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197378. void PNGAPI
  197379. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197380. int unit, double width, double height)
  197381. {
  197382. png_debug1(1, "in %s storage function\n", "sCAL");
  197383. if (png_ptr == NULL || info_ptr == NULL)
  197384. return;
  197385. info_ptr->scal_unit = (png_byte)unit;
  197386. info_ptr->scal_pixel_width = width;
  197387. info_ptr->scal_pixel_height = height;
  197388. info_ptr->valid |= PNG_INFO_sCAL;
  197389. }
  197390. #else
  197391. #ifdef PNG_FIXED_POINT_SUPPORTED
  197392. void PNGAPI
  197393. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197394. int unit, png_charp swidth, png_charp sheight)
  197395. {
  197396. png_uint_32 length;
  197397. png_debug1(1, "in %s storage function\n", "sCAL");
  197398. if (png_ptr == NULL || info_ptr == NULL)
  197399. return;
  197400. info_ptr->scal_unit = (png_byte)unit;
  197401. length = png_strlen(swidth) + 1;
  197402. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197403. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197404. if (info_ptr->scal_s_width == NULL)
  197405. {
  197406. png_warning(png_ptr,
  197407. "Memory allocation failed while processing sCAL.");
  197408. }
  197409. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197410. length = png_strlen(sheight) + 1;
  197411. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197412. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197413. if (info_ptr->scal_s_height == NULL)
  197414. {
  197415. png_free (png_ptr, info_ptr->scal_s_width);
  197416. png_warning(png_ptr,
  197417. "Memory allocation failed while processing sCAL.");
  197418. }
  197419. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197420. info_ptr->valid |= PNG_INFO_sCAL;
  197421. #ifdef PNG_FREE_ME_SUPPORTED
  197422. info_ptr->free_me |= PNG_FREE_SCAL;
  197423. #endif
  197424. }
  197425. #endif
  197426. #endif
  197427. #endif
  197428. #if defined(PNG_pHYs_SUPPORTED)
  197429. void PNGAPI
  197430. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197431. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197432. {
  197433. png_debug1(1, "in %s storage function\n", "pHYs");
  197434. if (png_ptr == NULL || info_ptr == NULL)
  197435. return;
  197436. info_ptr->x_pixels_per_unit = res_x;
  197437. info_ptr->y_pixels_per_unit = res_y;
  197438. info_ptr->phys_unit_type = (png_byte)unit_type;
  197439. info_ptr->valid |= PNG_INFO_pHYs;
  197440. }
  197441. #endif
  197442. void PNGAPI
  197443. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197444. png_colorp palette, int num_palette)
  197445. {
  197446. png_debug1(1, "in %s storage function\n", "PLTE");
  197447. if (png_ptr == NULL || info_ptr == NULL)
  197448. return;
  197449. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197450. {
  197451. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197452. png_error(png_ptr, "Invalid palette length");
  197453. else
  197454. {
  197455. png_warning(png_ptr, "Invalid palette length");
  197456. return;
  197457. }
  197458. }
  197459. /*
  197460. * It may not actually be necessary to set png_ptr->palette here;
  197461. * we do it for backward compatibility with the way the png_handle_tRNS
  197462. * function used to do the allocation.
  197463. */
  197464. #ifdef PNG_FREE_ME_SUPPORTED
  197465. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197466. #endif
  197467. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197468. of num_palette entries,
  197469. in case of an invalid PNG file that has too-large sample values. */
  197470. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197471. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197472. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197473. png_sizeof(png_color));
  197474. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197475. info_ptr->palette = png_ptr->palette;
  197476. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197477. #ifdef PNG_FREE_ME_SUPPORTED
  197478. info_ptr->free_me |= PNG_FREE_PLTE;
  197479. #else
  197480. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197481. #endif
  197482. info_ptr->valid |= PNG_INFO_PLTE;
  197483. }
  197484. #if defined(PNG_sBIT_SUPPORTED)
  197485. void PNGAPI
  197486. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197487. png_color_8p sig_bit)
  197488. {
  197489. png_debug1(1, "in %s storage function\n", "sBIT");
  197490. if (png_ptr == NULL || info_ptr == NULL)
  197491. return;
  197492. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197493. info_ptr->valid |= PNG_INFO_sBIT;
  197494. }
  197495. #endif
  197496. #if defined(PNG_sRGB_SUPPORTED)
  197497. void PNGAPI
  197498. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197499. {
  197500. png_debug1(1, "in %s storage function\n", "sRGB");
  197501. if (png_ptr == NULL || info_ptr == NULL)
  197502. return;
  197503. info_ptr->srgb_intent = (png_byte)intent;
  197504. info_ptr->valid |= PNG_INFO_sRGB;
  197505. }
  197506. void PNGAPI
  197507. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197508. int intent)
  197509. {
  197510. #if defined(PNG_gAMA_SUPPORTED)
  197511. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197512. float file_gamma;
  197513. #endif
  197514. #ifdef PNG_FIXED_POINT_SUPPORTED
  197515. png_fixed_point int_file_gamma;
  197516. #endif
  197517. #endif
  197518. #if defined(PNG_cHRM_SUPPORTED)
  197519. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197520. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197521. #endif
  197522. #ifdef PNG_FIXED_POINT_SUPPORTED
  197523. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197524. int_green_y, int_blue_x, int_blue_y;
  197525. #endif
  197526. #endif
  197527. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197528. if (png_ptr == NULL || info_ptr == NULL)
  197529. return;
  197530. png_set_sRGB(png_ptr, info_ptr, intent);
  197531. #if defined(PNG_gAMA_SUPPORTED)
  197532. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197533. file_gamma = (float).45455;
  197534. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197535. #endif
  197536. #ifdef PNG_FIXED_POINT_SUPPORTED
  197537. int_file_gamma = 45455L;
  197538. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197539. #endif
  197540. #endif
  197541. #if defined(PNG_cHRM_SUPPORTED)
  197542. #ifdef PNG_FIXED_POINT_SUPPORTED
  197543. int_white_x = 31270L;
  197544. int_white_y = 32900L;
  197545. int_red_x = 64000L;
  197546. int_red_y = 33000L;
  197547. int_green_x = 30000L;
  197548. int_green_y = 60000L;
  197549. int_blue_x = 15000L;
  197550. int_blue_y = 6000L;
  197551. png_set_cHRM_fixed(png_ptr, info_ptr,
  197552. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197553. int_blue_x, int_blue_y);
  197554. #endif
  197555. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197556. white_x = (float).3127;
  197557. white_y = (float).3290;
  197558. red_x = (float).64;
  197559. red_y = (float).33;
  197560. green_x = (float).30;
  197561. green_y = (float).60;
  197562. blue_x = (float).15;
  197563. blue_y = (float).06;
  197564. png_set_cHRM(png_ptr, info_ptr,
  197565. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197566. #endif
  197567. #endif
  197568. }
  197569. #endif
  197570. #if defined(PNG_iCCP_SUPPORTED)
  197571. void PNGAPI
  197572. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197573. png_charp name, int compression_type,
  197574. png_charp profile, png_uint_32 proflen)
  197575. {
  197576. png_charp new_iccp_name;
  197577. png_charp new_iccp_profile;
  197578. png_debug1(1, "in %s storage function\n", "iCCP");
  197579. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197580. return;
  197581. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197582. if (new_iccp_name == NULL)
  197583. {
  197584. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197585. return;
  197586. }
  197587. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197588. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197589. if (new_iccp_profile == NULL)
  197590. {
  197591. png_free (png_ptr, new_iccp_name);
  197592. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197593. return;
  197594. }
  197595. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197596. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197597. info_ptr->iccp_proflen = proflen;
  197598. info_ptr->iccp_name = new_iccp_name;
  197599. info_ptr->iccp_profile = new_iccp_profile;
  197600. /* Compression is always zero but is here so the API and info structure
  197601. * does not have to change if we introduce multiple compression types */
  197602. info_ptr->iccp_compression = (png_byte)compression_type;
  197603. #ifdef PNG_FREE_ME_SUPPORTED
  197604. info_ptr->free_me |= PNG_FREE_ICCP;
  197605. #endif
  197606. info_ptr->valid |= PNG_INFO_iCCP;
  197607. }
  197608. #endif
  197609. #if defined(PNG_TEXT_SUPPORTED)
  197610. void PNGAPI
  197611. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197612. int num_text)
  197613. {
  197614. int ret;
  197615. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197616. if (ret)
  197617. png_error(png_ptr, "Insufficient memory to store text");
  197618. }
  197619. int /* PRIVATE */
  197620. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197621. int num_text)
  197622. {
  197623. int i;
  197624. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197625. "text" : (png_const_charp)png_ptr->chunk_name));
  197626. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197627. return(0);
  197628. /* Make sure we have enough space in the "text" array in info_struct
  197629. * to hold all of the incoming text_ptr objects.
  197630. */
  197631. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197632. {
  197633. if (info_ptr->text != NULL)
  197634. {
  197635. png_textp old_text;
  197636. int old_max;
  197637. old_max = info_ptr->max_text;
  197638. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197639. old_text = info_ptr->text;
  197640. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197641. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197642. if (info_ptr->text == NULL)
  197643. {
  197644. png_free(png_ptr, old_text);
  197645. return(1);
  197646. }
  197647. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197648. png_sizeof(png_text)));
  197649. png_free(png_ptr, old_text);
  197650. }
  197651. else
  197652. {
  197653. info_ptr->max_text = num_text + 8;
  197654. info_ptr->num_text = 0;
  197655. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197656. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197657. if (info_ptr->text == NULL)
  197658. return(1);
  197659. #ifdef PNG_FREE_ME_SUPPORTED
  197660. info_ptr->free_me |= PNG_FREE_TEXT;
  197661. #endif
  197662. }
  197663. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197664. info_ptr->max_text);
  197665. }
  197666. for (i = 0; i < num_text; i++)
  197667. {
  197668. png_size_t text_length,key_len;
  197669. png_size_t lang_len,lang_key_len;
  197670. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197671. if (text_ptr[i].key == NULL)
  197672. continue;
  197673. key_len = png_strlen(text_ptr[i].key);
  197674. if(text_ptr[i].compression <= 0)
  197675. {
  197676. lang_len = 0;
  197677. lang_key_len = 0;
  197678. }
  197679. else
  197680. #ifdef PNG_iTXt_SUPPORTED
  197681. {
  197682. /* set iTXt data */
  197683. if (text_ptr[i].lang != NULL)
  197684. lang_len = png_strlen(text_ptr[i].lang);
  197685. else
  197686. lang_len = 0;
  197687. if (text_ptr[i].lang_key != NULL)
  197688. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197689. else
  197690. lang_key_len = 0;
  197691. }
  197692. #else
  197693. {
  197694. png_warning(png_ptr, "iTXt chunk not supported.");
  197695. continue;
  197696. }
  197697. #endif
  197698. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197699. {
  197700. text_length = 0;
  197701. #ifdef PNG_iTXt_SUPPORTED
  197702. if(text_ptr[i].compression > 0)
  197703. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197704. else
  197705. #endif
  197706. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197707. }
  197708. else
  197709. {
  197710. text_length = png_strlen(text_ptr[i].text);
  197711. textp->compression = text_ptr[i].compression;
  197712. }
  197713. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197714. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197715. if (textp->key == NULL)
  197716. return(1);
  197717. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197718. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197719. (int)textp->key);
  197720. png_memcpy(textp->key, text_ptr[i].key,
  197721. (png_size_t)(key_len));
  197722. *(textp->key+key_len) = '\0';
  197723. #ifdef PNG_iTXt_SUPPORTED
  197724. if (text_ptr[i].compression > 0)
  197725. {
  197726. textp->lang=textp->key + key_len + 1;
  197727. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197728. *(textp->lang+lang_len) = '\0';
  197729. textp->lang_key=textp->lang + lang_len + 1;
  197730. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197731. *(textp->lang_key+lang_key_len) = '\0';
  197732. textp->text=textp->lang_key + lang_key_len + 1;
  197733. }
  197734. else
  197735. #endif
  197736. {
  197737. #ifdef PNG_iTXt_SUPPORTED
  197738. textp->lang=NULL;
  197739. textp->lang_key=NULL;
  197740. #endif
  197741. textp->text=textp->key + key_len + 1;
  197742. }
  197743. if(text_length)
  197744. png_memcpy(textp->text, text_ptr[i].text,
  197745. (png_size_t)(text_length));
  197746. *(textp->text+text_length) = '\0';
  197747. #ifdef PNG_iTXt_SUPPORTED
  197748. if(textp->compression > 0)
  197749. {
  197750. textp->text_length = 0;
  197751. textp->itxt_length = text_length;
  197752. }
  197753. else
  197754. #endif
  197755. {
  197756. textp->text_length = text_length;
  197757. #ifdef PNG_iTXt_SUPPORTED
  197758. textp->itxt_length = 0;
  197759. #endif
  197760. }
  197761. info_ptr->num_text++;
  197762. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197763. }
  197764. return(0);
  197765. }
  197766. #endif
  197767. #if defined(PNG_tIME_SUPPORTED)
  197768. void PNGAPI
  197769. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197770. {
  197771. png_debug1(1, "in %s storage function\n", "tIME");
  197772. if (png_ptr == NULL || info_ptr == NULL ||
  197773. (png_ptr->mode & PNG_WROTE_tIME))
  197774. return;
  197775. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197776. info_ptr->valid |= PNG_INFO_tIME;
  197777. }
  197778. #endif
  197779. #if defined(PNG_tRNS_SUPPORTED)
  197780. void PNGAPI
  197781. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197782. png_bytep trans, int num_trans, png_color_16p trans_values)
  197783. {
  197784. png_debug1(1, "in %s storage function\n", "tRNS");
  197785. if (png_ptr == NULL || info_ptr == NULL)
  197786. return;
  197787. if (trans != NULL)
  197788. {
  197789. /*
  197790. * It may not actually be necessary to set png_ptr->trans here;
  197791. * we do it for backward compatibility with the way the png_handle_tRNS
  197792. * function used to do the allocation.
  197793. */
  197794. #ifdef PNG_FREE_ME_SUPPORTED
  197795. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197796. #endif
  197797. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197798. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197799. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197800. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197801. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197802. #ifdef PNG_FREE_ME_SUPPORTED
  197803. info_ptr->free_me |= PNG_FREE_TRNS;
  197804. #else
  197805. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197806. #endif
  197807. }
  197808. if (trans_values != NULL)
  197809. {
  197810. png_memcpy(&(info_ptr->trans_values), trans_values,
  197811. png_sizeof(png_color_16));
  197812. if (num_trans == 0)
  197813. num_trans = 1;
  197814. }
  197815. info_ptr->num_trans = (png_uint_16)num_trans;
  197816. info_ptr->valid |= PNG_INFO_tRNS;
  197817. }
  197818. #endif
  197819. #if defined(PNG_sPLT_SUPPORTED)
  197820. void PNGAPI
  197821. png_set_sPLT(png_structp png_ptr,
  197822. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197823. {
  197824. png_sPLT_tp np;
  197825. int i;
  197826. if (png_ptr == NULL || info_ptr == NULL)
  197827. return;
  197828. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197829. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197830. if (np == NULL)
  197831. {
  197832. png_warning(png_ptr, "No memory for sPLT palettes.");
  197833. return;
  197834. }
  197835. png_memcpy(np, info_ptr->splt_palettes,
  197836. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197837. png_free(png_ptr, info_ptr->splt_palettes);
  197838. info_ptr->splt_palettes=NULL;
  197839. for (i = 0; i < nentries; i++)
  197840. {
  197841. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197842. png_sPLT_tp from = entries + i;
  197843. to->name = (png_charp)png_malloc_warn(png_ptr,
  197844. png_strlen(from->name) + 1);
  197845. if (to->name == NULL)
  197846. {
  197847. png_warning(png_ptr,
  197848. "Out of memory while processing sPLT chunk");
  197849. }
  197850. /* TODO: use png_malloc_warn */
  197851. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197852. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197853. from->nentries * png_sizeof(png_sPLT_entry));
  197854. /* TODO: use png_malloc_warn */
  197855. png_memcpy(to->entries, from->entries,
  197856. from->nentries * png_sizeof(png_sPLT_entry));
  197857. if (to->entries == NULL)
  197858. {
  197859. png_warning(png_ptr,
  197860. "Out of memory while processing sPLT chunk");
  197861. png_free(png_ptr,to->name);
  197862. to->name = NULL;
  197863. }
  197864. to->nentries = from->nentries;
  197865. to->depth = from->depth;
  197866. }
  197867. info_ptr->splt_palettes = np;
  197868. info_ptr->splt_palettes_num += nentries;
  197869. info_ptr->valid |= PNG_INFO_sPLT;
  197870. #ifdef PNG_FREE_ME_SUPPORTED
  197871. info_ptr->free_me |= PNG_FREE_SPLT;
  197872. #endif
  197873. }
  197874. #endif /* PNG_sPLT_SUPPORTED */
  197875. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197876. void PNGAPI
  197877. png_set_unknown_chunks(png_structp png_ptr,
  197878. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197879. {
  197880. png_unknown_chunkp np;
  197881. int i;
  197882. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197883. return;
  197884. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197885. (info_ptr->unknown_chunks_num + num_unknowns) *
  197886. png_sizeof(png_unknown_chunk));
  197887. if (np == NULL)
  197888. {
  197889. png_warning(png_ptr,
  197890. "Out of memory while processing unknown chunk.");
  197891. return;
  197892. }
  197893. png_memcpy(np, info_ptr->unknown_chunks,
  197894. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197895. png_free(png_ptr, info_ptr->unknown_chunks);
  197896. info_ptr->unknown_chunks=NULL;
  197897. for (i = 0; i < num_unknowns; i++)
  197898. {
  197899. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197900. png_unknown_chunkp from = unknowns + i;
  197901. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197902. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197903. if (to->data == NULL)
  197904. {
  197905. png_warning(png_ptr,
  197906. "Out of memory while processing unknown chunk.");
  197907. }
  197908. else
  197909. {
  197910. png_memcpy(to->data, from->data, from->size);
  197911. to->size = from->size;
  197912. /* note our location in the read or write sequence */
  197913. to->location = (png_byte)(png_ptr->mode & 0xff);
  197914. }
  197915. }
  197916. info_ptr->unknown_chunks = np;
  197917. info_ptr->unknown_chunks_num += num_unknowns;
  197918. #ifdef PNG_FREE_ME_SUPPORTED
  197919. info_ptr->free_me |= PNG_FREE_UNKN;
  197920. #endif
  197921. }
  197922. void PNGAPI
  197923. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197924. int chunk, int location)
  197925. {
  197926. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197927. (int)info_ptr->unknown_chunks_num)
  197928. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197929. }
  197930. #endif
  197931. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197932. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197933. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197934. void PNGAPI
  197935. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197936. {
  197937. /* This function is deprecated in favor of png_permit_mng_features()
  197938. and will be removed from libpng-1.3.0 */
  197939. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197940. if (png_ptr == NULL)
  197941. return;
  197942. png_ptr->mng_features_permitted = (png_byte)
  197943. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197944. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197945. }
  197946. #endif
  197947. #endif
  197948. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197949. png_uint_32 PNGAPI
  197950. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197951. {
  197952. png_debug(1, "in png_permit_mng_features\n");
  197953. if (png_ptr == NULL)
  197954. return (png_uint_32)0;
  197955. png_ptr->mng_features_permitted =
  197956. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197957. return (png_uint_32)png_ptr->mng_features_permitted;
  197958. }
  197959. #endif
  197960. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197961. void PNGAPI
  197962. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197963. chunk_list, int num_chunks)
  197964. {
  197965. png_bytep new_list, p;
  197966. int i, old_num_chunks;
  197967. if (png_ptr == NULL)
  197968. return;
  197969. if (num_chunks == 0)
  197970. {
  197971. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197972. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197973. else
  197974. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197975. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197976. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197977. else
  197978. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197979. return;
  197980. }
  197981. if (chunk_list == NULL)
  197982. return;
  197983. old_num_chunks=png_ptr->num_chunk_list;
  197984. new_list=(png_bytep)png_malloc(png_ptr,
  197985. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197986. if(png_ptr->chunk_list != NULL)
  197987. {
  197988. png_memcpy(new_list, png_ptr->chunk_list,
  197989. (png_size_t)(5*old_num_chunks));
  197990. png_free(png_ptr, png_ptr->chunk_list);
  197991. png_ptr->chunk_list=NULL;
  197992. }
  197993. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197994. (png_size_t)(5*num_chunks));
  197995. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197996. *p=(png_byte)keep;
  197997. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197998. png_ptr->chunk_list=new_list;
  197999. #ifdef PNG_FREE_ME_SUPPORTED
  198000. png_ptr->free_me |= PNG_FREE_LIST;
  198001. #endif
  198002. }
  198003. #endif
  198004. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  198005. void PNGAPI
  198006. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  198007. png_user_chunk_ptr read_user_chunk_fn)
  198008. {
  198009. png_debug(1, "in png_set_read_user_chunk_fn\n");
  198010. if (png_ptr == NULL)
  198011. return;
  198012. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  198013. png_ptr->user_chunk_ptr = user_chunk_ptr;
  198014. }
  198015. #endif
  198016. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  198017. void PNGAPI
  198018. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  198019. {
  198020. png_debug1(1, "in %s storage function\n", "rows");
  198021. if (png_ptr == NULL || info_ptr == NULL)
  198022. return;
  198023. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  198024. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  198025. info_ptr->row_pointers = row_pointers;
  198026. if(row_pointers)
  198027. info_ptr->valid |= PNG_INFO_IDAT;
  198028. }
  198029. #endif
  198030. #ifdef PNG_WRITE_SUPPORTED
  198031. void PNGAPI
  198032. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  198033. {
  198034. if (png_ptr == NULL)
  198035. return;
  198036. if(png_ptr->zbuf)
  198037. png_free(png_ptr, png_ptr->zbuf);
  198038. png_ptr->zbuf_size = (png_size_t)size;
  198039. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  198040. png_ptr->zstream.next_out = png_ptr->zbuf;
  198041. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198042. }
  198043. #endif
  198044. void PNGAPI
  198045. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  198046. {
  198047. if (png_ptr && info_ptr)
  198048. info_ptr->valid &= ~(mask);
  198049. }
  198050. #ifndef PNG_1_0_X
  198051. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  198052. /* function was added to libpng 1.2.0 and should always exist by default */
  198053. void PNGAPI
  198054. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  198055. {
  198056. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198057. if (png_ptr != NULL)
  198058. png_ptr->asm_flags = 0;
  198059. }
  198060. /* this function was added to libpng 1.2.0 */
  198061. void PNGAPI
  198062. png_set_mmx_thresholds (png_structp png_ptr,
  198063. png_byte,
  198064. png_uint_32)
  198065. {
  198066. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198067. if (png_ptr == NULL)
  198068. return;
  198069. }
  198070. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  198071. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198072. /* this function was added to libpng 1.2.6 */
  198073. void PNGAPI
  198074. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  198075. png_uint_32 user_height_max)
  198076. {
  198077. /* Images with dimensions larger than these limits will be
  198078. * rejected by png_set_IHDR(). To accept any PNG datastream
  198079. * regardless of dimensions, set both limits to 0x7ffffffL.
  198080. */
  198081. if(png_ptr == NULL) return;
  198082. png_ptr->user_width_max = user_width_max;
  198083. png_ptr->user_height_max = user_height_max;
  198084. }
  198085. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  198086. #endif /* ?PNG_1_0_X */
  198087. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198088. /*** End of inlined file: pngset.c ***/
  198089. /*** Start of inlined file: pngtrans.c ***/
  198090. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  198091. *
  198092. * Last changed in libpng 1.2.17 May 15, 2007
  198093. * For conditions of distribution and use, see copyright notice in png.h
  198094. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198095. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198096. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198097. */
  198098. #define PNG_INTERNAL
  198099. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  198100. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198101. /* turn on BGR-to-RGB mapping */
  198102. void PNGAPI
  198103. png_set_bgr(png_structp png_ptr)
  198104. {
  198105. png_debug(1, "in png_set_bgr\n");
  198106. if(png_ptr == NULL) return;
  198107. png_ptr->transformations |= PNG_BGR;
  198108. }
  198109. #endif
  198110. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198111. /* turn on 16 bit byte swapping */
  198112. void PNGAPI
  198113. png_set_swap(png_structp png_ptr)
  198114. {
  198115. png_debug(1, "in png_set_swap\n");
  198116. if(png_ptr == NULL) return;
  198117. if (png_ptr->bit_depth == 16)
  198118. png_ptr->transformations |= PNG_SWAP_BYTES;
  198119. }
  198120. #endif
  198121. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  198122. /* turn on pixel packing */
  198123. void PNGAPI
  198124. png_set_packing(png_structp png_ptr)
  198125. {
  198126. png_debug(1, "in png_set_packing\n");
  198127. if(png_ptr == NULL) return;
  198128. if (png_ptr->bit_depth < 8)
  198129. {
  198130. png_ptr->transformations |= PNG_PACK;
  198131. png_ptr->usr_bit_depth = 8;
  198132. }
  198133. }
  198134. #endif
  198135. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198136. /* turn on packed pixel swapping */
  198137. void PNGAPI
  198138. png_set_packswap(png_structp png_ptr)
  198139. {
  198140. png_debug(1, "in png_set_packswap\n");
  198141. if(png_ptr == NULL) return;
  198142. if (png_ptr->bit_depth < 8)
  198143. png_ptr->transformations |= PNG_PACKSWAP;
  198144. }
  198145. #endif
  198146. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  198147. void PNGAPI
  198148. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  198149. {
  198150. png_debug(1, "in png_set_shift\n");
  198151. if(png_ptr == NULL) return;
  198152. png_ptr->transformations |= PNG_SHIFT;
  198153. png_ptr->shift = *true_bits;
  198154. }
  198155. #endif
  198156. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  198157. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198158. int PNGAPI
  198159. png_set_interlace_handling(png_structp png_ptr)
  198160. {
  198161. png_debug(1, "in png_set_interlace handling\n");
  198162. if (png_ptr && png_ptr->interlaced)
  198163. {
  198164. png_ptr->transformations |= PNG_INTERLACE;
  198165. return (7);
  198166. }
  198167. return (1);
  198168. }
  198169. #endif
  198170. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  198171. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  198172. * The filler type has changed in v0.95 to allow future 2-byte fillers
  198173. * for 48-bit input data, as well as to avoid problems with some compilers
  198174. * that don't like bytes as parameters.
  198175. */
  198176. void PNGAPI
  198177. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198178. {
  198179. png_debug(1, "in png_set_filler\n");
  198180. if(png_ptr == NULL) return;
  198181. png_ptr->transformations |= PNG_FILLER;
  198182. png_ptr->filler = (png_byte)filler;
  198183. if (filler_loc == PNG_FILLER_AFTER)
  198184. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  198185. else
  198186. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  198187. /* This should probably go in the "do_read_filler" routine.
  198188. * I attempted to do that in libpng-1.0.1a but that caused problems
  198189. * so I restored it in libpng-1.0.2a
  198190. */
  198191. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  198192. {
  198193. png_ptr->usr_channels = 4;
  198194. }
  198195. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198196. * a less-than-8-bit grayscale to GA? */
  198197. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198198. {
  198199. png_ptr->usr_channels = 2;
  198200. }
  198201. }
  198202. #if !defined(PNG_1_0_X)
  198203. /* Added to libpng-1.2.7 */
  198204. void PNGAPI
  198205. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198206. {
  198207. png_debug(1, "in png_set_add_alpha\n");
  198208. if(png_ptr == NULL) return;
  198209. png_set_filler(png_ptr, filler, filler_loc);
  198210. png_ptr->transformations |= PNG_ADD_ALPHA;
  198211. }
  198212. #endif
  198213. #endif
  198214. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198215. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198216. void PNGAPI
  198217. png_set_swap_alpha(png_structp png_ptr)
  198218. {
  198219. png_debug(1, "in png_set_swap_alpha\n");
  198220. if(png_ptr == NULL) return;
  198221. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198222. }
  198223. #endif
  198224. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198225. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198226. void PNGAPI
  198227. png_set_invert_alpha(png_structp png_ptr)
  198228. {
  198229. png_debug(1, "in png_set_invert_alpha\n");
  198230. if(png_ptr == NULL) return;
  198231. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198232. }
  198233. #endif
  198234. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198235. void PNGAPI
  198236. png_set_invert_mono(png_structp png_ptr)
  198237. {
  198238. png_debug(1, "in png_set_invert_mono\n");
  198239. if(png_ptr == NULL) return;
  198240. png_ptr->transformations |= PNG_INVERT_MONO;
  198241. }
  198242. /* invert monochrome grayscale data */
  198243. void /* PRIVATE */
  198244. png_do_invert(png_row_infop row_info, png_bytep row)
  198245. {
  198246. png_debug(1, "in png_do_invert\n");
  198247. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198248. * if (row_info->bit_depth == 1 &&
  198249. */
  198250. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198251. if (row == NULL || row_info == NULL)
  198252. return;
  198253. #endif
  198254. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198255. {
  198256. png_bytep rp = row;
  198257. png_uint_32 i;
  198258. png_uint_32 istop = row_info->rowbytes;
  198259. for (i = 0; i < istop; i++)
  198260. {
  198261. *rp = (png_byte)(~(*rp));
  198262. rp++;
  198263. }
  198264. }
  198265. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198266. row_info->bit_depth == 8)
  198267. {
  198268. png_bytep rp = row;
  198269. png_uint_32 i;
  198270. png_uint_32 istop = row_info->rowbytes;
  198271. for (i = 0; i < istop; i+=2)
  198272. {
  198273. *rp = (png_byte)(~(*rp));
  198274. rp+=2;
  198275. }
  198276. }
  198277. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198278. row_info->bit_depth == 16)
  198279. {
  198280. png_bytep rp = row;
  198281. png_uint_32 i;
  198282. png_uint_32 istop = row_info->rowbytes;
  198283. for (i = 0; i < istop; i+=4)
  198284. {
  198285. *rp = (png_byte)(~(*rp));
  198286. *(rp+1) = (png_byte)(~(*(rp+1)));
  198287. rp+=4;
  198288. }
  198289. }
  198290. }
  198291. #endif
  198292. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198293. /* swaps byte order on 16 bit depth images */
  198294. void /* PRIVATE */
  198295. png_do_swap(png_row_infop row_info, png_bytep row)
  198296. {
  198297. png_debug(1, "in png_do_swap\n");
  198298. if (
  198299. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198300. row != NULL && row_info != NULL &&
  198301. #endif
  198302. row_info->bit_depth == 16)
  198303. {
  198304. png_bytep rp = row;
  198305. png_uint_32 i;
  198306. png_uint_32 istop= row_info->width * row_info->channels;
  198307. for (i = 0; i < istop; i++, rp += 2)
  198308. {
  198309. png_byte t = *rp;
  198310. *rp = *(rp + 1);
  198311. *(rp + 1) = t;
  198312. }
  198313. }
  198314. }
  198315. #endif
  198316. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198317. static PNG_CONST png_byte onebppswaptable[256] = {
  198318. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198319. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198320. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198321. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198322. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198323. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198324. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198325. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198326. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198327. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198328. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198329. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198330. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198331. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198332. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198333. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198334. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198335. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198336. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198337. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198338. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198339. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198340. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198341. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198342. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198343. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198344. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198345. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198346. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198347. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198348. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198349. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198350. };
  198351. static PNG_CONST png_byte twobppswaptable[256] = {
  198352. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198353. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198354. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198355. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198356. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198357. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198358. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198359. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198360. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198361. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198362. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198363. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198364. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198365. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198366. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198367. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198368. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198369. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198370. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198371. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198372. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198373. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198374. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198375. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198376. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198377. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198378. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198379. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198380. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198381. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198382. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198383. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198384. };
  198385. static PNG_CONST png_byte fourbppswaptable[256] = {
  198386. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198387. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198388. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198389. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198390. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198391. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198392. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198393. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198394. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198395. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198396. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198397. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198398. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198399. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198400. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198401. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198402. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198403. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198404. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198405. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198406. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198407. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198408. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198409. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198410. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198411. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198412. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198413. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198414. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198415. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198416. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198417. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198418. };
  198419. /* swaps pixel packing order within bytes */
  198420. void /* PRIVATE */
  198421. png_do_packswap(png_row_infop row_info, png_bytep row)
  198422. {
  198423. png_debug(1, "in png_do_packswap\n");
  198424. if (
  198425. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198426. row != NULL && row_info != NULL &&
  198427. #endif
  198428. row_info->bit_depth < 8)
  198429. {
  198430. png_bytep rp, end, table;
  198431. end = row + row_info->rowbytes;
  198432. if (row_info->bit_depth == 1)
  198433. table = (png_bytep)onebppswaptable;
  198434. else if (row_info->bit_depth == 2)
  198435. table = (png_bytep)twobppswaptable;
  198436. else if (row_info->bit_depth == 4)
  198437. table = (png_bytep)fourbppswaptable;
  198438. else
  198439. return;
  198440. for (rp = row; rp < end; rp++)
  198441. *rp = table[*rp];
  198442. }
  198443. }
  198444. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198445. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198446. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198447. /* remove filler or alpha byte(s) */
  198448. void /* PRIVATE */
  198449. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198450. {
  198451. png_debug(1, "in png_do_strip_filler\n");
  198452. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198453. if (row != NULL && row_info != NULL)
  198454. #endif
  198455. {
  198456. png_bytep sp=row;
  198457. png_bytep dp=row;
  198458. png_uint_32 row_width=row_info->width;
  198459. png_uint_32 i;
  198460. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198461. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198462. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198463. row_info->channels == 4)
  198464. {
  198465. if (row_info->bit_depth == 8)
  198466. {
  198467. /* This converts from RGBX or RGBA to RGB */
  198468. if (flags & PNG_FLAG_FILLER_AFTER)
  198469. {
  198470. dp+=3; sp+=4;
  198471. for (i = 1; i < row_width; i++)
  198472. {
  198473. *dp++ = *sp++;
  198474. *dp++ = *sp++;
  198475. *dp++ = *sp++;
  198476. sp++;
  198477. }
  198478. }
  198479. /* This converts from XRGB or ARGB to RGB */
  198480. else
  198481. {
  198482. for (i = 0; i < row_width; i++)
  198483. {
  198484. sp++;
  198485. *dp++ = *sp++;
  198486. *dp++ = *sp++;
  198487. *dp++ = *sp++;
  198488. }
  198489. }
  198490. row_info->pixel_depth = 24;
  198491. row_info->rowbytes = row_width * 3;
  198492. }
  198493. else /* if (row_info->bit_depth == 16) */
  198494. {
  198495. if (flags & PNG_FLAG_FILLER_AFTER)
  198496. {
  198497. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198498. sp += 8; dp += 6;
  198499. for (i = 1; i < row_width; i++)
  198500. {
  198501. /* This could be (although png_memcpy is probably slower):
  198502. png_memcpy(dp, sp, 6);
  198503. sp += 8;
  198504. dp += 6;
  198505. */
  198506. *dp++ = *sp++;
  198507. *dp++ = *sp++;
  198508. *dp++ = *sp++;
  198509. *dp++ = *sp++;
  198510. *dp++ = *sp++;
  198511. *dp++ = *sp++;
  198512. sp += 2;
  198513. }
  198514. }
  198515. else
  198516. {
  198517. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198518. for (i = 0; i < row_width; i++)
  198519. {
  198520. /* This could be (although png_memcpy is probably slower):
  198521. png_memcpy(dp, sp, 6);
  198522. sp += 8;
  198523. dp += 6;
  198524. */
  198525. sp+=2;
  198526. *dp++ = *sp++;
  198527. *dp++ = *sp++;
  198528. *dp++ = *sp++;
  198529. *dp++ = *sp++;
  198530. *dp++ = *sp++;
  198531. *dp++ = *sp++;
  198532. }
  198533. }
  198534. row_info->pixel_depth = 48;
  198535. row_info->rowbytes = row_width * 6;
  198536. }
  198537. row_info->channels = 3;
  198538. }
  198539. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198540. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198541. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198542. row_info->channels == 2)
  198543. {
  198544. if (row_info->bit_depth == 8)
  198545. {
  198546. /* This converts from GX or GA to G */
  198547. if (flags & PNG_FLAG_FILLER_AFTER)
  198548. {
  198549. for (i = 0; i < row_width; i++)
  198550. {
  198551. *dp++ = *sp++;
  198552. sp++;
  198553. }
  198554. }
  198555. /* This converts from XG or AG to G */
  198556. else
  198557. {
  198558. for (i = 0; i < row_width; i++)
  198559. {
  198560. sp++;
  198561. *dp++ = *sp++;
  198562. }
  198563. }
  198564. row_info->pixel_depth = 8;
  198565. row_info->rowbytes = row_width;
  198566. }
  198567. else /* if (row_info->bit_depth == 16) */
  198568. {
  198569. if (flags & PNG_FLAG_FILLER_AFTER)
  198570. {
  198571. /* This converts from GGXX or GGAA to GG */
  198572. sp += 4; dp += 2;
  198573. for (i = 1; i < row_width; i++)
  198574. {
  198575. *dp++ = *sp++;
  198576. *dp++ = *sp++;
  198577. sp += 2;
  198578. }
  198579. }
  198580. else
  198581. {
  198582. /* This converts from XXGG or AAGG to GG */
  198583. for (i = 0; i < row_width; i++)
  198584. {
  198585. sp += 2;
  198586. *dp++ = *sp++;
  198587. *dp++ = *sp++;
  198588. }
  198589. }
  198590. row_info->pixel_depth = 16;
  198591. row_info->rowbytes = row_width * 2;
  198592. }
  198593. row_info->channels = 1;
  198594. }
  198595. if (flags & PNG_FLAG_STRIP_ALPHA)
  198596. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198597. }
  198598. }
  198599. #endif
  198600. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198601. /* swaps red and blue bytes within a pixel */
  198602. void /* PRIVATE */
  198603. png_do_bgr(png_row_infop row_info, png_bytep row)
  198604. {
  198605. png_debug(1, "in png_do_bgr\n");
  198606. if (
  198607. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198608. row != NULL && row_info != NULL &&
  198609. #endif
  198610. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198611. {
  198612. png_uint_32 row_width = row_info->width;
  198613. if (row_info->bit_depth == 8)
  198614. {
  198615. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198616. {
  198617. png_bytep rp;
  198618. png_uint_32 i;
  198619. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198620. {
  198621. png_byte save = *rp;
  198622. *rp = *(rp + 2);
  198623. *(rp + 2) = save;
  198624. }
  198625. }
  198626. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198627. {
  198628. png_bytep rp;
  198629. png_uint_32 i;
  198630. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198631. {
  198632. png_byte save = *rp;
  198633. *rp = *(rp + 2);
  198634. *(rp + 2) = save;
  198635. }
  198636. }
  198637. }
  198638. else if (row_info->bit_depth == 16)
  198639. {
  198640. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198641. {
  198642. png_bytep rp;
  198643. png_uint_32 i;
  198644. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198645. {
  198646. png_byte save = *rp;
  198647. *rp = *(rp + 4);
  198648. *(rp + 4) = save;
  198649. save = *(rp + 1);
  198650. *(rp + 1) = *(rp + 5);
  198651. *(rp + 5) = save;
  198652. }
  198653. }
  198654. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198655. {
  198656. png_bytep rp;
  198657. png_uint_32 i;
  198658. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198659. {
  198660. png_byte save = *rp;
  198661. *rp = *(rp + 4);
  198662. *(rp + 4) = save;
  198663. save = *(rp + 1);
  198664. *(rp + 1) = *(rp + 5);
  198665. *(rp + 5) = save;
  198666. }
  198667. }
  198668. }
  198669. }
  198670. }
  198671. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198672. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198673. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198674. defined(PNG_LEGACY_SUPPORTED)
  198675. void PNGAPI
  198676. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198677. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198678. {
  198679. png_debug(1, "in png_set_user_transform_info\n");
  198680. if(png_ptr == NULL) return;
  198681. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198682. png_ptr->user_transform_ptr = user_transform_ptr;
  198683. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198684. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198685. #else
  198686. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198687. png_warning(png_ptr,
  198688. "This version of libpng does not support user transform info");
  198689. #endif
  198690. }
  198691. #endif
  198692. /* This function returns a pointer to the user_transform_ptr associated with
  198693. * the user transform functions. The application should free any memory
  198694. * associated with this pointer before png_write_destroy and png_read_destroy
  198695. * are called.
  198696. */
  198697. png_voidp PNGAPI
  198698. png_get_user_transform_ptr(png_structp png_ptr)
  198699. {
  198700. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198701. if (png_ptr == NULL) return (NULL);
  198702. return ((png_voidp)png_ptr->user_transform_ptr);
  198703. #else
  198704. return (NULL);
  198705. #endif
  198706. }
  198707. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198708. /*** End of inlined file: pngtrans.c ***/
  198709. /*** Start of inlined file: pngwio.c ***/
  198710. /* pngwio.c - functions for data output
  198711. *
  198712. * Last changed in libpng 1.2.13 November 13, 2006
  198713. * For conditions of distribution and use, see copyright notice in png.h
  198714. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198715. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198716. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198717. *
  198718. * This file provides a location for all output. Users who need
  198719. * special handling are expected to write functions that have the same
  198720. * arguments as these and perform similar functions, but that possibly
  198721. * use different output methods. Note that you shouldn't change these
  198722. * functions, but rather write replacement functions and then change
  198723. * them at run time with png_set_write_fn(...).
  198724. */
  198725. #define PNG_INTERNAL
  198726. #ifdef PNG_WRITE_SUPPORTED
  198727. /* Write the data to whatever output you are using. The default routine
  198728. writes to a file pointer. Note that this routine sometimes gets called
  198729. with very small lengths, so you should implement some kind of simple
  198730. buffering if you are using unbuffered writes. This should never be asked
  198731. to write more than 64K on a 16 bit machine. */
  198732. void /* PRIVATE */
  198733. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198734. {
  198735. if (png_ptr->write_data_fn != NULL )
  198736. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198737. else
  198738. png_error(png_ptr, "Call to NULL write function");
  198739. }
  198740. #if !defined(PNG_NO_STDIO)
  198741. /* This is the function that does the actual writing of data. If you are
  198742. not writing to a standard C stream, you should create a replacement
  198743. write_data function and use it at run time with png_set_write_fn(), rather
  198744. than changing the library. */
  198745. #ifndef USE_FAR_KEYWORD
  198746. void PNGAPI
  198747. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198748. {
  198749. png_uint_32 check;
  198750. if(png_ptr == NULL) return;
  198751. #if defined(_WIN32_WCE)
  198752. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198753. check = 0;
  198754. #else
  198755. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198756. #endif
  198757. if (check != length)
  198758. png_error(png_ptr, "Write Error");
  198759. }
  198760. #else
  198761. /* this is the model-independent version. Since the standard I/O library
  198762. can't handle far buffers in the medium and small models, we have to copy
  198763. the data.
  198764. */
  198765. #define NEAR_BUF_SIZE 1024
  198766. #define MIN(a,b) (a <= b ? a : b)
  198767. void PNGAPI
  198768. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198769. {
  198770. png_uint_32 check;
  198771. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198772. png_FILE_p io_ptr;
  198773. if(png_ptr == NULL) return;
  198774. /* Check if data really is near. If so, use usual code. */
  198775. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198776. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198777. if ((png_bytep)near_data == data)
  198778. {
  198779. #if defined(_WIN32_WCE)
  198780. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198781. check = 0;
  198782. #else
  198783. check = fwrite(near_data, 1, length, io_ptr);
  198784. #endif
  198785. }
  198786. else
  198787. {
  198788. png_byte buf[NEAR_BUF_SIZE];
  198789. png_size_t written, remaining, err;
  198790. check = 0;
  198791. remaining = length;
  198792. do
  198793. {
  198794. written = MIN(NEAR_BUF_SIZE, remaining);
  198795. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198796. #if defined(_WIN32_WCE)
  198797. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198798. err = 0;
  198799. #else
  198800. err = fwrite(buf, 1, written, io_ptr);
  198801. #endif
  198802. if (err != written)
  198803. break;
  198804. else
  198805. check += err;
  198806. data += written;
  198807. remaining -= written;
  198808. }
  198809. while (remaining != 0);
  198810. }
  198811. if (check != length)
  198812. png_error(png_ptr, "Write Error");
  198813. }
  198814. #endif
  198815. #endif
  198816. /* This function is called to output any data pending writing (normally
  198817. to disk). After png_flush is called, there should be no data pending
  198818. writing in any buffers. */
  198819. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198820. void /* PRIVATE */
  198821. png_flush(png_structp png_ptr)
  198822. {
  198823. if (png_ptr->output_flush_fn != NULL)
  198824. (*(png_ptr->output_flush_fn))(png_ptr);
  198825. }
  198826. #if !defined(PNG_NO_STDIO)
  198827. void PNGAPI
  198828. png_default_flush(png_structp png_ptr)
  198829. {
  198830. #if !defined(_WIN32_WCE)
  198831. png_FILE_p io_ptr;
  198832. #endif
  198833. if(png_ptr == NULL) return;
  198834. #if !defined(_WIN32_WCE)
  198835. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198836. if (io_ptr != NULL)
  198837. fflush(io_ptr);
  198838. #endif
  198839. }
  198840. #endif
  198841. #endif
  198842. /* This function allows the application to supply new output functions for
  198843. libpng if standard C streams aren't being used.
  198844. This function takes as its arguments:
  198845. png_ptr - pointer to a png output data structure
  198846. io_ptr - pointer to user supplied structure containing info about
  198847. the output functions. May be NULL.
  198848. write_data_fn - pointer to a new output function that takes as its
  198849. arguments a pointer to a png_struct, a pointer to
  198850. data to be written, and a 32-bit unsigned int that is
  198851. the number of bytes to be written. The new write
  198852. function should call png_error(png_ptr, "Error msg")
  198853. to exit and output any fatal error messages.
  198854. flush_data_fn - pointer to a new flush function that takes as its
  198855. arguments a pointer to a png_struct. After a call to
  198856. the flush function, there should be no data in any buffers
  198857. or pending transmission. If the output method doesn't do
  198858. any buffering of ouput, a function prototype must still be
  198859. supplied although it doesn't have to do anything. If
  198860. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198861. time, output_flush_fn will be ignored, although it must be
  198862. supplied for compatibility. */
  198863. void PNGAPI
  198864. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198865. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198866. {
  198867. if(png_ptr == NULL) return;
  198868. png_ptr->io_ptr = io_ptr;
  198869. #if !defined(PNG_NO_STDIO)
  198870. if (write_data_fn != NULL)
  198871. png_ptr->write_data_fn = write_data_fn;
  198872. else
  198873. png_ptr->write_data_fn = png_default_write_data;
  198874. #else
  198875. png_ptr->write_data_fn = write_data_fn;
  198876. #endif
  198877. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198878. #if !defined(PNG_NO_STDIO)
  198879. if (output_flush_fn != NULL)
  198880. png_ptr->output_flush_fn = output_flush_fn;
  198881. else
  198882. png_ptr->output_flush_fn = png_default_flush;
  198883. #else
  198884. png_ptr->output_flush_fn = output_flush_fn;
  198885. #endif
  198886. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198887. /* It is an error to read while writing a png file */
  198888. if (png_ptr->read_data_fn != NULL)
  198889. {
  198890. png_ptr->read_data_fn = NULL;
  198891. png_warning(png_ptr,
  198892. "Attempted to set both read_data_fn and write_data_fn in");
  198893. png_warning(png_ptr,
  198894. "the same structure. Resetting read_data_fn to NULL.");
  198895. }
  198896. }
  198897. #if defined(USE_FAR_KEYWORD)
  198898. #if defined(_MSC_VER)
  198899. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198900. {
  198901. void *near_ptr;
  198902. void FAR *far_ptr;
  198903. FP_OFF(near_ptr) = FP_OFF(ptr);
  198904. far_ptr = (void FAR *)near_ptr;
  198905. if(check != 0)
  198906. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198907. png_error(png_ptr,"segment lost in conversion");
  198908. return(near_ptr);
  198909. }
  198910. # else
  198911. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198912. {
  198913. void *near_ptr;
  198914. void FAR *far_ptr;
  198915. near_ptr = (void FAR *)ptr;
  198916. far_ptr = (void FAR *)near_ptr;
  198917. if(check != 0)
  198918. if(far_ptr != ptr)
  198919. png_error(png_ptr,"segment lost in conversion");
  198920. return(near_ptr);
  198921. }
  198922. # endif
  198923. # endif
  198924. #endif /* PNG_WRITE_SUPPORTED */
  198925. /*** End of inlined file: pngwio.c ***/
  198926. /*** Start of inlined file: pngwrite.c ***/
  198927. /* pngwrite.c - general routines to write a PNG file
  198928. *
  198929. * Last changed in libpng 1.2.15 January 5, 2007
  198930. * For conditions of distribution and use, see copyright notice in png.h
  198931. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198932. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198933. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198934. */
  198935. /* get internal access to png.h */
  198936. #define PNG_INTERNAL
  198937. #ifdef PNG_WRITE_SUPPORTED
  198938. /* Writes all the PNG information. This is the suggested way to use the
  198939. * library. If you have a new chunk to add, make a function to write it,
  198940. * and put it in the correct location here. If you want the chunk written
  198941. * after the image data, put it in png_write_end(). I strongly encourage
  198942. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198943. * the chunk, as that will keep the code from breaking if you want to just
  198944. * write a plain PNG file. If you have long comments, I suggest writing
  198945. * them in png_write_end(), and compressing them.
  198946. */
  198947. void PNGAPI
  198948. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198949. {
  198950. png_debug(1, "in png_write_info_before_PLTE\n");
  198951. if (png_ptr == NULL || info_ptr == NULL)
  198952. return;
  198953. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198954. {
  198955. png_write_sig(png_ptr); /* write PNG signature */
  198956. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198957. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198958. {
  198959. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198960. png_ptr->mng_features_permitted=0;
  198961. }
  198962. #endif
  198963. /* write IHDR information. */
  198964. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198965. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198966. info_ptr->filter_type,
  198967. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198968. info_ptr->interlace_type);
  198969. #else
  198970. 0);
  198971. #endif
  198972. /* the rest of these check to see if the valid field has the appropriate
  198973. flag set, and if it does, writes the chunk. */
  198974. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198975. if (info_ptr->valid & PNG_INFO_gAMA)
  198976. {
  198977. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198978. png_write_gAMA(png_ptr, info_ptr->gamma);
  198979. #else
  198980. #ifdef PNG_FIXED_POINT_SUPPORTED
  198981. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198982. # endif
  198983. #endif
  198984. }
  198985. #endif
  198986. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198987. if (info_ptr->valid & PNG_INFO_sRGB)
  198988. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198989. #endif
  198990. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198991. if (info_ptr->valid & PNG_INFO_iCCP)
  198992. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198993. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198994. #endif
  198995. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198996. if (info_ptr->valid & PNG_INFO_sBIT)
  198997. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198998. #endif
  198999. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  199000. if (info_ptr->valid & PNG_INFO_cHRM)
  199001. {
  199002. #ifdef PNG_FLOATING_POINT_SUPPORTED
  199003. png_write_cHRM(png_ptr,
  199004. info_ptr->x_white, info_ptr->y_white,
  199005. info_ptr->x_red, info_ptr->y_red,
  199006. info_ptr->x_green, info_ptr->y_green,
  199007. info_ptr->x_blue, info_ptr->y_blue);
  199008. #else
  199009. # ifdef PNG_FIXED_POINT_SUPPORTED
  199010. png_write_cHRM_fixed(png_ptr,
  199011. info_ptr->int_x_white, info_ptr->int_y_white,
  199012. info_ptr->int_x_red, info_ptr->int_y_red,
  199013. info_ptr->int_x_green, info_ptr->int_y_green,
  199014. info_ptr->int_x_blue, info_ptr->int_y_blue);
  199015. # endif
  199016. #endif
  199017. }
  199018. #endif
  199019. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199020. if (info_ptr->unknown_chunks_num)
  199021. {
  199022. png_unknown_chunk *up;
  199023. png_debug(5, "writing extra chunks\n");
  199024. for (up = info_ptr->unknown_chunks;
  199025. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199026. up++)
  199027. {
  199028. int keep=png_handle_as_unknown(png_ptr, up->name);
  199029. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199030. up->location && !(up->location & PNG_HAVE_PLTE) &&
  199031. !(up->location & PNG_HAVE_IDAT) &&
  199032. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199033. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199034. {
  199035. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199036. }
  199037. }
  199038. }
  199039. #endif
  199040. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  199041. }
  199042. }
  199043. void PNGAPI
  199044. png_write_info(png_structp png_ptr, png_infop info_ptr)
  199045. {
  199046. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  199047. int i;
  199048. #endif
  199049. png_debug(1, "in png_write_info\n");
  199050. if (png_ptr == NULL || info_ptr == NULL)
  199051. return;
  199052. png_write_info_before_PLTE(png_ptr, info_ptr);
  199053. if (info_ptr->valid & PNG_INFO_PLTE)
  199054. png_write_PLTE(png_ptr, info_ptr->palette,
  199055. (png_uint_32)info_ptr->num_palette);
  199056. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199057. png_error(png_ptr, "Valid palette required for paletted images");
  199058. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  199059. if (info_ptr->valid & PNG_INFO_tRNS)
  199060. {
  199061. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199062. /* invert the alpha channel (in tRNS) */
  199063. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  199064. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199065. {
  199066. int j;
  199067. for (j=0; j<(int)info_ptr->num_trans; j++)
  199068. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  199069. }
  199070. #endif
  199071. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  199072. info_ptr->num_trans, info_ptr->color_type);
  199073. }
  199074. #endif
  199075. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  199076. if (info_ptr->valid & PNG_INFO_bKGD)
  199077. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  199078. #endif
  199079. #if defined(PNG_WRITE_hIST_SUPPORTED)
  199080. if (info_ptr->valid & PNG_INFO_hIST)
  199081. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  199082. #endif
  199083. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  199084. if (info_ptr->valid & PNG_INFO_oFFs)
  199085. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  199086. info_ptr->offset_unit_type);
  199087. #endif
  199088. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  199089. if (info_ptr->valid & PNG_INFO_pCAL)
  199090. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  199091. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  199092. info_ptr->pcal_units, info_ptr->pcal_params);
  199093. #endif
  199094. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  199095. if (info_ptr->valid & PNG_INFO_sCAL)
  199096. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  199097. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  199098. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  199099. #else
  199100. #ifdef PNG_FIXED_POINT_SUPPORTED
  199101. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  199102. info_ptr->scal_s_width, info_ptr->scal_s_height);
  199103. #else
  199104. png_warning(png_ptr,
  199105. "png_write_sCAL not supported; sCAL chunk not written.");
  199106. #endif
  199107. #endif
  199108. #endif
  199109. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  199110. if (info_ptr->valid & PNG_INFO_pHYs)
  199111. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  199112. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  199113. #endif
  199114. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199115. if (info_ptr->valid & PNG_INFO_tIME)
  199116. {
  199117. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199118. png_ptr->mode |= PNG_WROTE_tIME;
  199119. }
  199120. #endif
  199121. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  199122. if (info_ptr->valid & PNG_INFO_sPLT)
  199123. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  199124. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  199125. #endif
  199126. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199127. /* Check to see if we need to write text chunks */
  199128. for (i = 0; i < info_ptr->num_text; i++)
  199129. {
  199130. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  199131. info_ptr->text[i].compression);
  199132. /* an internationalized chunk? */
  199133. if (info_ptr->text[i].compression > 0)
  199134. {
  199135. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199136. /* write international chunk */
  199137. png_write_iTXt(png_ptr,
  199138. info_ptr->text[i].compression,
  199139. info_ptr->text[i].key,
  199140. info_ptr->text[i].lang,
  199141. info_ptr->text[i].lang_key,
  199142. info_ptr->text[i].text);
  199143. #else
  199144. png_warning(png_ptr, "Unable to write international text");
  199145. #endif
  199146. /* Mark this chunk as written */
  199147. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199148. }
  199149. /* If we want a compressed text chunk */
  199150. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  199151. {
  199152. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199153. /* write compressed chunk */
  199154. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199155. info_ptr->text[i].text, 0,
  199156. info_ptr->text[i].compression);
  199157. #else
  199158. png_warning(png_ptr, "Unable to write compressed text");
  199159. #endif
  199160. /* Mark this chunk as written */
  199161. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199162. }
  199163. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199164. {
  199165. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199166. /* write uncompressed chunk */
  199167. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199168. info_ptr->text[i].text,
  199169. 0);
  199170. #else
  199171. png_warning(png_ptr, "Unable to write uncompressed text");
  199172. #endif
  199173. /* Mark this chunk as written */
  199174. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199175. }
  199176. }
  199177. #endif
  199178. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199179. if (info_ptr->unknown_chunks_num)
  199180. {
  199181. png_unknown_chunk *up;
  199182. png_debug(5, "writing extra chunks\n");
  199183. for (up = info_ptr->unknown_chunks;
  199184. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199185. up++)
  199186. {
  199187. int keep=png_handle_as_unknown(png_ptr, up->name);
  199188. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199189. up->location && (up->location & PNG_HAVE_PLTE) &&
  199190. !(up->location & PNG_HAVE_IDAT) &&
  199191. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199192. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199193. {
  199194. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199195. }
  199196. }
  199197. }
  199198. #endif
  199199. }
  199200. /* Writes the end of the PNG file. If you don't want to write comments or
  199201. * time information, you can pass NULL for info. If you already wrote these
  199202. * in png_write_info(), do not write them again here. If you have long
  199203. * comments, I suggest writing them here, and compressing them.
  199204. */
  199205. void PNGAPI
  199206. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199207. {
  199208. png_debug(1, "in png_write_end\n");
  199209. if (png_ptr == NULL)
  199210. return;
  199211. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199212. png_error(png_ptr, "No IDATs written into file");
  199213. /* see if user wants us to write information chunks */
  199214. if (info_ptr != NULL)
  199215. {
  199216. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199217. int i; /* local index variable */
  199218. #endif
  199219. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199220. /* check to see if user has supplied a time chunk */
  199221. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199222. !(png_ptr->mode & PNG_WROTE_tIME))
  199223. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199224. #endif
  199225. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199226. /* loop through comment chunks */
  199227. for (i = 0; i < info_ptr->num_text; i++)
  199228. {
  199229. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199230. info_ptr->text[i].compression);
  199231. /* an internationalized chunk? */
  199232. if (info_ptr->text[i].compression > 0)
  199233. {
  199234. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199235. /* write international chunk */
  199236. png_write_iTXt(png_ptr,
  199237. info_ptr->text[i].compression,
  199238. info_ptr->text[i].key,
  199239. info_ptr->text[i].lang,
  199240. info_ptr->text[i].lang_key,
  199241. info_ptr->text[i].text);
  199242. #else
  199243. png_warning(png_ptr, "Unable to write international text");
  199244. #endif
  199245. /* Mark this chunk as written */
  199246. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199247. }
  199248. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199249. {
  199250. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199251. /* write compressed chunk */
  199252. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199253. info_ptr->text[i].text, 0,
  199254. info_ptr->text[i].compression);
  199255. #else
  199256. png_warning(png_ptr, "Unable to write compressed text");
  199257. #endif
  199258. /* Mark this chunk as written */
  199259. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199260. }
  199261. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199262. {
  199263. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199264. /* write uncompressed chunk */
  199265. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199266. info_ptr->text[i].text, 0);
  199267. #else
  199268. png_warning(png_ptr, "Unable to write uncompressed text");
  199269. #endif
  199270. /* Mark this chunk as written */
  199271. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199272. }
  199273. }
  199274. #endif
  199275. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199276. if (info_ptr->unknown_chunks_num)
  199277. {
  199278. png_unknown_chunk *up;
  199279. png_debug(5, "writing extra chunks\n");
  199280. for (up = info_ptr->unknown_chunks;
  199281. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199282. up++)
  199283. {
  199284. int keep=png_handle_as_unknown(png_ptr, up->name);
  199285. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199286. up->location && (up->location & PNG_AFTER_IDAT) &&
  199287. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199288. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199289. {
  199290. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199291. }
  199292. }
  199293. }
  199294. #endif
  199295. }
  199296. png_ptr->mode |= PNG_AFTER_IDAT;
  199297. /* write end of PNG file */
  199298. png_write_IEND(png_ptr);
  199299. }
  199300. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199301. #if !defined(_WIN32_WCE)
  199302. /* "time.h" functions are not supported on WindowsCE */
  199303. void PNGAPI
  199304. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199305. {
  199306. png_debug(1, "in png_convert_from_struct_tm\n");
  199307. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199308. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199309. ptime->day = (png_byte)ttime->tm_mday;
  199310. ptime->hour = (png_byte)ttime->tm_hour;
  199311. ptime->minute = (png_byte)ttime->tm_min;
  199312. ptime->second = (png_byte)ttime->tm_sec;
  199313. }
  199314. void PNGAPI
  199315. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199316. {
  199317. struct tm *tbuf;
  199318. png_debug(1, "in png_convert_from_time_t\n");
  199319. tbuf = gmtime(&ttime);
  199320. png_convert_from_struct_tm(ptime, tbuf);
  199321. }
  199322. #endif
  199323. #endif
  199324. /* Initialize png_ptr structure, and allocate any memory needed */
  199325. png_structp PNGAPI
  199326. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199327. png_error_ptr error_fn, png_error_ptr warn_fn)
  199328. {
  199329. #ifdef PNG_USER_MEM_SUPPORTED
  199330. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199331. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199332. }
  199333. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199334. png_structp PNGAPI
  199335. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199336. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199337. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199338. {
  199339. #endif /* PNG_USER_MEM_SUPPORTED */
  199340. png_structp png_ptr;
  199341. #ifdef PNG_SETJMP_SUPPORTED
  199342. #ifdef USE_FAR_KEYWORD
  199343. jmp_buf jmpbuf;
  199344. #endif
  199345. #endif
  199346. int i;
  199347. png_debug(1, "in png_create_write_struct\n");
  199348. #ifdef PNG_USER_MEM_SUPPORTED
  199349. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199350. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199351. #else
  199352. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199353. #endif /* PNG_USER_MEM_SUPPORTED */
  199354. if (png_ptr == NULL)
  199355. return (NULL);
  199356. /* added at libpng-1.2.6 */
  199357. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199358. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199359. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199360. #endif
  199361. #ifdef PNG_SETJMP_SUPPORTED
  199362. #ifdef USE_FAR_KEYWORD
  199363. if (setjmp(jmpbuf))
  199364. #else
  199365. if (setjmp(png_ptr->jmpbuf))
  199366. #endif
  199367. {
  199368. png_free(png_ptr, png_ptr->zbuf);
  199369. png_ptr->zbuf=NULL;
  199370. png_destroy_struct(png_ptr);
  199371. return (NULL);
  199372. }
  199373. #ifdef USE_FAR_KEYWORD
  199374. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199375. #endif
  199376. #endif
  199377. #ifdef PNG_USER_MEM_SUPPORTED
  199378. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199379. #endif /* PNG_USER_MEM_SUPPORTED */
  199380. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199381. i=0;
  199382. do
  199383. {
  199384. if(user_png_ver[i] != png_libpng_ver[i])
  199385. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199386. } while (png_libpng_ver[i++]);
  199387. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199388. {
  199389. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199390. * we must recompile any applications that use any older library version.
  199391. * For versions after libpng 1.0, we will be compatible, so we need
  199392. * only check the first digit.
  199393. */
  199394. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199395. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199396. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199397. {
  199398. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199399. char msg[80];
  199400. if (user_png_ver)
  199401. {
  199402. png_snprintf(msg, 80,
  199403. "Application was compiled with png.h from libpng-%.20s",
  199404. user_png_ver);
  199405. png_warning(png_ptr, msg);
  199406. }
  199407. png_snprintf(msg, 80,
  199408. "Application is running with png.c from libpng-%.20s",
  199409. png_libpng_ver);
  199410. png_warning(png_ptr, msg);
  199411. #endif
  199412. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199413. png_ptr->flags=0;
  199414. #endif
  199415. png_error(png_ptr,
  199416. "Incompatible libpng version in application and library");
  199417. }
  199418. }
  199419. /* initialize zbuf - compression buffer */
  199420. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199421. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199422. (png_uint_32)png_ptr->zbuf_size);
  199423. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199424. png_flush_ptr_NULL);
  199425. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199426. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199427. 1, png_doublep_NULL, png_doublep_NULL);
  199428. #endif
  199429. #ifdef PNG_SETJMP_SUPPORTED
  199430. /* Applications that neglect to set up their own setjmp() and then encounter
  199431. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199432. abort instead of returning. */
  199433. #ifdef USE_FAR_KEYWORD
  199434. if (setjmp(jmpbuf))
  199435. PNG_ABORT();
  199436. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199437. #else
  199438. if (setjmp(png_ptr->jmpbuf))
  199439. PNG_ABORT();
  199440. #endif
  199441. #endif
  199442. return (png_ptr);
  199443. }
  199444. /* Initialize png_ptr structure, and allocate any memory needed */
  199445. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199446. /* Deprecated. */
  199447. #undef png_write_init
  199448. void PNGAPI
  199449. png_write_init(png_structp png_ptr)
  199450. {
  199451. /* We only come here via pre-1.0.7-compiled applications */
  199452. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199453. }
  199454. void PNGAPI
  199455. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199456. png_size_t png_struct_size, png_size_t png_info_size)
  199457. {
  199458. /* We only come here via pre-1.0.12-compiled applications */
  199459. if(png_ptr == NULL) return;
  199460. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199461. if(png_sizeof(png_struct) > png_struct_size ||
  199462. png_sizeof(png_info) > png_info_size)
  199463. {
  199464. char msg[80];
  199465. png_ptr->warning_fn=NULL;
  199466. if (user_png_ver)
  199467. {
  199468. png_snprintf(msg, 80,
  199469. "Application was compiled with png.h from libpng-%.20s",
  199470. user_png_ver);
  199471. png_warning(png_ptr, msg);
  199472. }
  199473. png_snprintf(msg, 80,
  199474. "Application is running with png.c from libpng-%.20s",
  199475. png_libpng_ver);
  199476. png_warning(png_ptr, msg);
  199477. }
  199478. #endif
  199479. if(png_sizeof(png_struct) > png_struct_size)
  199480. {
  199481. png_ptr->error_fn=NULL;
  199482. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199483. png_ptr->flags=0;
  199484. #endif
  199485. png_error(png_ptr,
  199486. "The png struct allocated by the application for writing is too small.");
  199487. }
  199488. if(png_sizeof(png_info) > png_info_size)
  199489. {
  199490. png_ptr->error_fn=NULL;
  199491. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199492. png_ptr->flags=0;
  199493. #endif
  199494. png_error(png_ptr,
  199495. "The info struct allocated by the application for writing is too small.");
  199496. }
  199497. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199498. }
  199499. #endif /* PNG_1_0_X || PNG_1_2_X */
  199500. void PNGAPI
  199501. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199502. png_size_t png_struct_size)
  199503. {
  199504. png_structp png_ptr=*ptr_ptr;
  199505. #ifdef PNG_SETJMP_SUPPORTED
  199506. jmp_buf tmp_jmp; /* to save current jump buffer */
  199507. #endif
  199508. int i = 0;
  199509. if (png_ptr == NULL)
  199510. return;
  199511. do
  199512. {
  199513. if (user_png_ver[i] != png_libpng_ver[i])
  199514. {
  199515. #ifdef PNG_LEGACY_SUPPORTED
  199516. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199517. #else
  199518. png_ptr->warning_fn=NULL;
  199519. png_warning(png_ptr,
  199520. "Application uses deprecated png_write_init() and should be recompiled.");
  199521. break;
  199522. #endif
  199523. }
  199524. } while (png_libpng_ver[i++]);
  199525. png_debug(1, "in png_write_init_3\n");
  199526. #ifdef PNG_SETJMP_SUPPORTED
  199527. /* save jump buffer and error functions */
  199528. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199529. #endif
  199530. if (png_sizeof(png_struct) > png_struct_size)
  199531. {
  199532. png_destroy_struct(png_ptr);
  199533. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199534. *ptr_ptr = png_ptr;
  199535. }
  199536. /* reset all variables to 0 */
  199537. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199538. /* added at libpng-1.2.6 */
  199539. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199540. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199541. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199542. #endif
  199543. #ifdef PNG_SETJMP_SUPPORTED
  199544. /* restore jump buffer */
  199545. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199546. #endif
  199547. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199548. png_flush_ptr_NULL);
  199549. /* initialize zbuf - compression buffer */
  199550. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199551. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199552. (png_uint_32)png_ptr->zbuf_size);
  199553. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199554. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199555. 1, png_doublep_NULL, png_doublep_NULL);
  199556. #endif
  199557. }
  199558. /* Write a few rows of image data. If the image is interlaced,
  199559. * either you will have to write the 7 sub images, or, if you
  199560. * have called png_set_interlace_handling(), you will have to
  199561. * "write" the image seven times.
  199562. */
  199563. void PNGAPI
  199564. png_write_rows(png_structp png_ptr, png_bytepp row,
  199565. png_uint_32 num_rows)
  199566. {
  199567. png_uint_32 i; /* row counter */
  199568. png_bytepp rp; /* row pointer */
  199569. png_debug(1, "in png_write_rows\n");
  199570. if (png_ptr == NULL)
  199571. return;
  199572. /* loop through the rows */
  199573. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199574. {
  199575. png_write_row(png_ptr, *rp);
  199576. }
  199577. }
  199578. /* Write the image. You only need to call this function once, even
  199579. * if you are writing an interlaced image.
  199580. */
  199581. void PNGAPI
  199582. png_write_image(png_structp png_ptr, png_bytepp image)
  199583. {
  199584. png_uint_32 i; /* row index */
  199585. int pass, num_pass; /* pass variables */
  199586. png_bytepp rp; /* points to current row */
  199587. if (png_ptr == NULL)
  199588. return;
  199589. png_debug(1, "in png_write_image\n");
  199590. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199591. /* intialize interlace handling. If image is not interlaced,
  199592. this will set pass to 1 */
  199593. num_pass = png_set_interlace_handling(png_ptr);
  199594. #else
  199595. num_pass = 1;
  199596. #endif
  199597. /* loop through passes */
  199598. for (pass = 0; pass < num_pass; pass++)
  199599. {
  199600. /* loop through image */
  199601. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199602. {
  199603. png_write_row(png_ptr, *rp);
  199604. }
  199605. }
  199606. }
  199607. /* called by user to write a row of image data */
  199608. void PNGAPI
  199609. png_write_row(png_structp png_ptr, png_bytep row)
  199610. {
  199611. if (png_ptr == NULL)
  199612. return;
  199613. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199614. png_ptr->row_number, png_ptr->pass);
  199615. /* initialize transformations and other stuff if first time */
  199616. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199617. {
  199618. /* make sure we wrote the header info */
  199619. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199620. png_error(png_ptr,
  199621. "png_write_info was never called before png_write_row.");
  199622. /* check for transforms that have been set but were defined out */
  199623. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199624. if (png_ptr->transformations & PNG_INVERT_MONO)
  199625. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199626. #endif
  199627. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199628. if (png_ptr->transformations & PNG_FILLER)
  199629. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199630. #endif
  199631. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199632. if (png_ptr->transformations & PNG_PACKSWAP)
  199633. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199634. #endif
  199635. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199636. if (png_ptr->transformations & PNG_PACK)
  199637. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199638. #endif
  199639. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199640. if (png_ptr->transformations & PNG_SHIFT)
  199641. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199642. #endif
  199643. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199644. if (png_ptr->transformations & PNG_BGR)
  199645. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199646. #endif
  199647. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199648. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199649. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199650. #endif
  199651. png_write_start_row(png_ptr);
  199652. }
  199653. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199654. /* if interlaced and not interested in row, return */
  199655. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199656. {
  199657. switch (png_ptr->pass)
  199658. {
  199659. case 0:
  199660. if (png_ptr->row_number & 0x07)
  199661. {
  199662. png_write_finish_row(png_ptr);
  199663. return;
  199664. }
  199665. break;
  199666. case 1:
  199667. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199668. {
  199669. png_write_finish_row(png_ptr);
  199670. return;
  199671. }
  199672. break;
  199673. case 2:
  199674. if ((png_ptr->row_number & 0x07) != 4)
  199675. {
  199676. png_write_finish_row(png_ptr);
  199677. return;
  199678. }
  199679. break;
  199680. case 3:
  199681. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199682. {
  199683. png_write_finish_row(png_ptr);
  199684. return;
  199685. }
  199686. break;
  199687. case 4:
  199688. if ((png_ptr->row_number & 0x03) != 2)
  199689. {
  199690. png_write_finish_row(png_ptr);
  199691. return;
  199692. }
  199693. break;
  199694. case 5:
  199695. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199696. {
  199697. png_write_finish_row(png_ptr);
  199698. return;
  199699. }
  199700. break;
  199701. case 6:
  199702. if (!(png_ptr->row_number & 0x01))
  199703. {
  199704. png_write_finish_row(png_ptr);
  199705. return;
  199706. }
  199707. break;
  199708. }
  199709. }
  199710. #endif
  199711. /* set up row info for transformations */
  199712. png_ptr->row_info.color_type = png_ptr->color_type;
  199713. png_ptr->row_info.width = png_ptr->usr_width;
  199714. png_ptr->row_info.channels = png_ptr->usr_channels;
  199715. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199716. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199717. png_ptr->row_info.channels);
  199718. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199719. png_ptr->row_info.width);
  199720. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199721. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199722. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199723. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199724. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199725. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199726. /* Copy user's row into buffer, leaving room for filter byte. */
  199727. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199728. png_ptr->row_info.rowbytes);
  199729. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199730. /* handle interlacing */
  199731. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199732. (png_ptr->transformations & PNG_INTERLACE))
  199733. {
  199734. png_do_write_interlace(&(png_ptr->row_info),
  199735. png_ptr->row_buf + 1, png_ptr->pass);
  199736. /* this should always get caught above, but still ... */
  199737. if (!(png_ptr->row_info.width))
  199738. {
  199739. png_write_finish_row(png_ptr);
  199740. return;
  199741. }
  199742. }
  199743. #endif
  199744. /* handle other transformations */
  199745. if (png_ptr->transformations)
  199746. png_do_write_transformations(png_ptr);
  199747. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199748. /* Write filter_method 64 (intrapixel differencing) only if
  199749. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199750. * 2. Libpng did not write a PNG signature (this filter_method is only
  199751. * used in PNG datastreams that are embedded in MNG datastreams) and
  199752. * 3. The application called png_permit_mng_features with a mask that
  199753. * included PNG_FLAG_MNG_FILTER_64 and
  199754. * 4. The filter_method is 64 and
  199755. * 5. The color_type is RGB or RGBA
  199756. */
  199757. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199758. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199759. {
  199760. /* Intrapixel differencing */
  199761. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199762. }
  199763. #endif
  199764. /* Find a filter if necessary, filter the row and write it out. */
  199765. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199766. if (png_ptr->write_row_fn != NULL)
  199767. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199768. }
  199769. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199770. /* Set the automatic flush interval or 0 to turn flushing off */
  199771. void PNGAPI
  199772. png_set_flush(png_structp png_ptr, int nrows)
  199773. {
  199774. png_debug(1, "in png_set_flush\n");
  199775. if (png_ptr == NULL)
  199776. return;
  199777. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199778. }
  199779. /* flush the current output buffers now */
  199780. void PNGAPI
  199781. png_write_flush(png_structp png_ptr)
  199782. {
  199783. int wrote_IDAT;
  199784. png_debug(1, "in png_write_flush\n");
  199785. if (png_ptr == NULL)
  199786. return;
  199787. /* We have already written out all of the data */
  199788. if (png_ptr->row_number >= png_ptr->num_rows)
  199789. return;
  199790. do
  199791. {
  199792. int ret;
  199793. /* compress the data */
  199794. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199795. wrote_IDAT = 0;
  199796. /* check for compression errors */
  199797. if (ret != Z_OK)
  199798. {
  199799. if (png_ptr->zstream.msg != NULL)
  199800. png_error(png_ptr, png_ptr->zstream.msg);
  199801. else
  199802. png_error(png_ptr, "zlib error");
  199803. }
  199804. if (!(png_ptr->zstream.avail_out))
  199805. {
  199806. /* write the IDAT and reset the zlib output buffer */
  199807. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199808. png_ptr->zbuf_size);
  199809. png_ptr->zstream.next_out = png_ptr->zbuf;
  199810. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199811. wrote_IDAT = 1;
  199812. }
  199813. } while(wrote_IDAT == 1);
  199814. /* If there is any data left to be output, write it into a new IDAT */
  199815. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199816. {
  199817. /* write the IDAT and reset the zlib output buffer */
  199818. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199819. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199820. png_ptr->zstream.next_out = png_ptr->zbuf;
  199821. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199822. }
  199823. png_ptr->flush_rows = 0;
  199824. png_flush(png_ptr);
  199825. }
  199826. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199827. /* free all memory used by the write */
  199828. void PNGAPI
  199829. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199830. {
  199831. png_structp png_ptr = NULL;
  199832. png_infop info_ptr = NULL;
  199833. #ifdef PNG_USER_MEM_SUPPORTED
  199834. png_free_ptr free_fn = NULL;
  199835. png_voidp mem_ptr = NULL;
  199836. #endif
  199837. png_debug(1, "in png_destroy_write_struct\n");
  199838. if (png_ptr_ptr != NULL)
  199839. {
  199840. png_ptr = *png_ptr_ptr;
  199841. #ifdef PNG_USER_MEM_SUPPORTED
  199842. free_fn = png_ptr->free_fn;
  199843. mem_ptr = png_ptr->mem_ptr;
  199844. #endif
  199845. }
  199846. if (info_ptr_ptr != NULL)
  199847. info_ptr = *info_ptr_ptr;
  199848. if (info_ptr != NULL)
  199849. {
  199850. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199851. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199852. if (png_ptr->num_chunk_list)
  199853. {
  199854. png_free(png_ptr, png_ptr->chunk_list);
  199855. png_ptr->chunk_list=NULL;
  199856. png_ptr->num_chunk_list=0;
  199857. }
  199858. #endif
  199859. #ifdef PNG_USER_MEM_SUPPORTED
  199860. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199861. (png_voidp)mem_ptr);
  199862. #else
  199863. png_destroy_struct((png_voidp)info_ptr);
  199864. #endif
  199865. *info_ptr_ptr = NULL;
  199866. }
  199867. if (png_ptr != NULL)
  199868. {
  199869. png_write_destroy(png_ptr);
  199870. #ifdef PNG_USER_MEM_SUPPORTED
  199871. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199872. (png_voidp)mem_ptr);
  199873. #else
  199874. png_destroy_struct((png_voidp)png_ptr);
  199875. #endif
  199876. *png_ptr_ptr = NULL;
  199877. }
  199878. }
  199879. /* Free any memory used in png_ptr struct (old method) */
  199880. void /* PRIVATE */
  199881. png_write_destroy(png_structp png_ptr)
  199882. {
  199883. #ifdef PNG_SETJMP_SUPPORTED
  199884. jmp_buf tmp_jmp; /* save jump buffer */
  199885. #endif
  199886. png_error_ptr error_fn;
  199887. png_error_ptr warning_fn;
  199888. png_voidp error_ptr;
  199889. #ifdef PNG_USER_MEM_SUPPORTED
  199890. png_free_ptr free_fn;
  199891. #endif
  199892. png_debug(1, "in png_write_destroy\n");
  199893. /* free any memory zlib uses */
  199894. deflateEnd(&png_ptr->zstream);
  199895. /* free our memory. png_free checks NULL for us. */
  199896. png_free(png_ptr, png_ptr->zbuf);
  199897. png_free(png_ptr, png_ptr->row_buf);
  199898. png_free(png_ptr, png_ptr->prev_row);
  199899. png_free(png_ptr, png_ptr->sub_row);
  199900. png_free(png_ptr, png_ptr->up_row);
  199901. png_free(png_ptr, png_ptr->avg_row);
  199902. png_free(png_ptr, png_ptr->paeth_row);
  199903. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199904. png_free(png_ptr, png_ptr->time_buffer);
  199905. #endif
  199906. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199907. png_free(png_ptr, png_ptr->prev_filters);
  199908. png_free(png_ptr, png_ptr->filter_weights);
  199909. png_free(png_ptr, png_ptr->inv_filter_weights);
  199910. png_free(png_ptr, png_ptr->filter_costs);
  199911. png_free(png_ptr, png_ptr->inv_filter_costs);
  199912. #endif
  199913. #ifdef PNG_SETJMP_SUPPORTED
  199914. /* reset structure */
  199915. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199916. #endif
  199917. error_fn = png_ptr->error_fn;
  199918. warning_fn = png_ptr->warning_fn;
  199919. error_ptr = png_ptr->error_ptr;
  199920. #ifdef PNG_USER_MEM_SUPPORTED
  199921. free_fn = png_ptr->free_fn;
  199922. #endif
  199923. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199924. png_ptr->error_fn = error_fn;
  199925. png_ptr->warning_fn = warning_fn;
  199926. png_ptr->error_ptr = error_ptr;
  199927. #ifdef PNG_USER_MEM_SUPPORTED
  199928. png_ptr->free_fn = free_fn;
  199929. #endif
  199930. #ifdef PNG_SETJMP_SUPPORTED
  199931. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199932. #endif
  199933. }
  199934. /* Allow the application to select one or more row filters to use. */
  199935. void PNGAPI
  199936. png_set_filter(png_structp png_ptr, int method, int filters)
  199937. {
  199938. png_debug(1, "in png_set_filter\n");
  199939. if (png_ptr == NULL)
  199940. return;
  199941. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199942. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199943. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199944. method = PNG_FILTER_TYPE_BASE;
  199945. #endif
  199946. if (method == PNG_FILTER_TYPE_BASE)
  199947. {
  199948. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199949. {
  199950. #ifndef PNG_NO_WRITE_FILTER
  199951. case 5:
  199952. case 6:
  199953. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199954. #endif /* PNG_NO_WRITE_FILTER */
  199955. case PNG_FILTER_VALUE_NONE:
  199956. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199957. #ifndef PNG_NO_WRITE_FILTER
  199958. case PNG_FILTER_VALUE_SUB:
  199959. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199960. case PNG_FILTER_VALUE_UP:
  199961. png_ptr->do_filter=PNG_FILTER_UP; break;
  199962. case PNG_FILTER_VALUE_AVG:
  199963. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199964. case PNG_FILTER_VALUE_PAETH:
  199965. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199966. default: png_ptr->do_filter = (png_byte)filters; break;
  199967. #else
  199968. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199969. #endif /* PNG_NO_WRITE_FILTER */
  199970. }
  199971. /* If we have allocated the row_buf, this means we have already started
  199972. * with the image and we should have allocated all of the filter buffers
  199973. * that have been selected. If prev_row isn't already allocated, then
  199974. * it is too late to start using the filters that need it, since we
  199975. * will be missing the data in the previous row. If an application
  199976. * wants to start and stop using particular filters during compression,
  199977. * it should start out with all of the filters, and then add and
  199978. * remove them after the start of compression.
  199979. */
  199980. if (png_ptr->row_buf != NULL)
  199981. {
  199982. #ifndef PNG_NO_WRITE_FILTER
  199983. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199984. {
  199985. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199986. (png_ptr->rowbytes + 1));
  199987. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199988. }
  199989. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199990. {
  199991. if (png_ptr->prev_row == NULL)
  199992. {
  199993. png_warning(png_ptr, "Can't add Up filter after starting");
  199994. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199995. }
  199996. else
  199997. {
  199998. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199999. (png_ptr->rowbytes + 1));
  200000. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  200001. }
  200002. }
  200003. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  200004. {
  200005. if (png_ptr->prev_row == NULL)
  200006. {
  200007. png_warning(png_ptr, "Can't add Average filter after starting");
  200008. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  200009. }
  200010. else
  200011. {
  200012. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  200013. (png_ptr->rowbytes + 1));
  200014. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  200015. }
  200016. }
  200017. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  200018. png_ptr->paeth_row == NULL)
  200019. {
  200020. if (png_ptr->prev_row == NULL)
  200021. {
  200022. png_warning(png_ptr, "Can't add Paeth filter after starting");
  200023. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  200024. }
  200025. else
  200026. {
  200027. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  200028. (png_ptr->rowbytes + 1));
  200029. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  200030. }
  200031. }
  200032. if (png_ptr->do_filter == PNG_NO_FILTERS)
  200033. #endif /* PNG_NO_WRITE_FILTER */
  200034. png_ptr->do_filter = PNG_FILTER_NONE;
  200035. }
  200036. }
  200037. else
  200038. png_error(png_ptr, "Unknown custom filter method");
  200039. }
  200040. /* This allows us to influence the way in which libpng chooses the "best"
  200041. * filter for the current scanline. While the "minimum-sum-of-absolute-
  200042. * differences metric is relatively fast and effective, there is some
  200043. * question as to whether it can be improved upon by trying to keep the
  200044. * filtered data going to zlib more consistent, hopefully resulting in
  200045. * better compression.
  200046. */
  200047. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  200048. void PNGAPI
  200049. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  200050. int num_weights, png_doublep filter_weights,
  200051. png_doublep filter_costs)
  200052. {
  200053. int i;
  200054. png_debug(1, "in png_set_filter_heuristics\n");
  200055. if (png_ptr == NULL)
  200056. return;
  200057. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  200058. {
  200059. png_warning(png_ptr, "Unknown filter heuristic method");
  200060. return;
  200061. }
  200062. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  200063. {
  200064. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  200065. }
  200066. if (num_weights < 0 || filter_weights == NULL ||
  200067. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  200068. {
  200069. num_weights = 0;
  200070. }
  200071. png_ptr->num_prev_filters = (png_byte)num_weights;
  200072. png_ptr->heuristic_method = (png_byte)heuristic_method;
  200073. if (num_weights > 0)
  200074. {
  200075. if (png_ptr->prev_filters == NULL)
  200076. {
  200077. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  200078. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  200079. /* To make sure that the weighting starts out fairly */
  200080. for (i = 0; i < num_weights; i++)
  200081. {
  200082. png_ptr->prev_filters[i] = 255;
  200083. }
  200084. }
  200085. if (png_ptr->filter_weights == NULL)
  200086. {
  200087. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200088. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200089. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200090. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200091. for (i = 0; i < num_weights; i++)
  200092. {
  200093. png_ptr->inv_filter_weights[i] =
  200094. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200095. }
  200096. }
  200097. for (i = 0; i < num_weights; i++)
  200098. {
  200099. if (filter_weights[i] < 0.0)
  200100. {
  200101. png_ptr->inv_filter_weights[i] =
  200102. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200103. }
  200104. else
  200105. {
  200106. png_ptr->inv_filter_weights[i] =
  200107. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  200108. png_ptr->filter_weights[i] =
  200109. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  200110. }
  200111. }
  200112. }
  200113. /* If, in the future, there are other filter methods, this would
  200114. * need to be based on png_ptr->filter.
  200115. */
  200116. if (png_ptr->filter_costs == NULL)
  200117. {
  200118. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200119. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200120. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200121. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200122. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200123. {
  200124. png_ptr->inv_filter_costs[i] =
  200125. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200126. }
  200127. }
  200128. /* Here is where we set the relative costs of the different filters. We
  200129. * should take the desired compression level into account when setting
  200130. * the costs, so that Paeth, for instance, has a high relative cost at low
  200131. * compression levels, while it has a lower relative cost at higher
  200132. * compression settings. The filter types are in order of increasing
  200133. * relative cost, so it would be possible to do this with an algorithm.
  200134. */
  200135. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200136. {
  200137. if (filter_costs == NULL || filter_costs[i] < 0.0)
  200138. {
  200139. png_ptr->inv_filter_costs[i] =
  200140. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200141. }
  200142. else if (filter_costs[i] >= 1.0)
  200143. {
  200144. png_ptr->inv_filter_costs[i] =
  200145. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  200146. png_ptr->filter_costs[i] =
  200147. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  200148. }
  200149. }
  200150. }
  200151. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  200152. void PNGAPI
  200153. png_set_compression_level(png_structp png_ptr, int level)
  200154. {
  200155. png_debug(1, "in png_set_compression_level\n");
  200156. if (png_ptr == NULL)
  200157. return;
  200158. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  200159. png_ptr->zlib_level = level;
  200160. }
  200161. void PNGAPI
  200162. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  200163. {
  200164. png_debug(1, "in png_set_compression_mem_level\n");
  200165. if (png_ptr == NULL)
  200166. return;
  200167. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  200168. png_ptr->zlib_mem_level = mem_level;
  200169. }
  200170. void PNGAPI
  200171. png_set_compression_strategy(png_structp png_ptr, int strategy)
  200172. {
  200173. png_debug(1, "in png_set_compression_strategy\n");
  200174. if (png_ptr == NULL)
  200175. return;
  200176. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  200177. png_ptr->zlib_strategy = strategy;
  200178. }
  200179. void PNGAPI
  200180. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  200181. {
  200182. if (png_ptr == NULL)
  200183. return;
  200184. if (window_bits > 15)
  200185. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  200186. else if (window_bits < 8)
  200187. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  200188. #ifndef WBITS_8_OK
  200189. /* avoid libpng bug with 256-byte windows */
  200190. if (window_bits == 8)
  200191. {
  200192. png_warning(png_ptr, "Compression window is being reset to 512");
  200193. window_bits=9;
  200194. }
  200195. #endif
  200196. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200197. png_ptr->zlib_window_bits = window_bits;
  200198. }
  200199. void PNGAPI
  200200. png_set_compression_method(png_structp png_ptr, int method)
  200201. {
  200202. png_debug(1, "in png_set_compression_method\n");
  200203. if (png_ptr == NULL)
  200204. return;
  200205. if (method != 8)
  200206. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200207. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200208. png_ptr->zlib_method = method;
  200209. }
  200210. void PNGAPI
  200211. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200212. {
  200213. if (png_ptr == NULL)
  200214. return;
  200215. png_ptr->write_row_fn = write_row_fn;
  200216. }
  200217. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200218. void PNGAPI
  200219. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200220. write_user_transform_fn)
  200221. {
  200222. png_debug(1, "in png_set_write_user_transform_fn\n");
  200223. if (png_ptr == NULL)
  200224. return;
  200225. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200226. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200227. }
  200228. #endif
  200229. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200230. void PNGAPI
  200231. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200232. int transforms, voidp params)
  200233. {
  200234. if (png_ptr == NULL || info_ptr == NULL)
  200235. return;
  200236. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200237. /* invert the alpha channel from opacity to transparency */
  200238. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200239. png_set_invert_alpha(png_ptr);
  200240. #endif
  200241. /* Write the file header information. */
  200242. png_write_info(png_ptr, info_ptr);
  200243. /* ------ these transformations don't touch the info structure ------- */
  200244. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200245. /* invert monochrome pixels */
  200246. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200247. png_set_invert_mono(png_ptr);
  200248. #endif
  200249. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200250. /* Shift the pixels up to a legal bit depth and fill in
  200251. * as appropriate to correctly scale the image.
  200252. */
  200253. if ((transforms & PNG_TRANSFORM_SHIFT)
  200254. && (info_ptr->valid & PNG_INFO_sBIT))
  200255. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200256. #endif
  200257. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200258. /* pack pixels into bytes */
  200259. if (transforms & PNG_TRANSFORM_PACKING)
  200260. png_set_packing(png_ptr);
  200261. #endif
  200262. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200263. /* swap location of alpha bytes from ARGB to RGBA */
  200264. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200265. png_set_swap_alpha(png_ptr);
  200266. #endif
  200267. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200268. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200269. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200270. */
  200271. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200272. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200273. #endif
  200274. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200275. /* flip BGR pixels to RGB */
  200276. if (transforms & PNG_TRANSFORM_BGR)
  200277. png_set_bgr(png_ptr);
  200278. #endif
  200279. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200280. /* swap bytes of 16-bit files to most significant byte first */
  200281. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200282. png_set_swap(png_ptr);
  200283. #endif
  200284. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200285. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200286. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200287. png_set_packswap(png_ptr);
  200288. #endif
  200289. /* ----------------------- end of transformations ------------------- */
  200290. /* write the bits */
  200291. if (info_ptr->valid & PNG_INFO_IDAT)
  200292. png_write_image(png_ptr, info_ptr->row_pointers);
  200293. /* It is REQUIRED to call this to finish writing the rest of the file */
  200294. png_write_end(png_ptr, info_ptr);
  200295. transforms = transforms; /* quiet compiler warnings */
  200296. params = params;
  200297. }
  200298. #endif
  200299. #endif /* PNG_WRITE_SUPPORTED */
  200300. /*** End of inlined file: pngwrite.c ***/
  200301. /*** Start of inlined file: pngwtran.c ***/
  200302. /* pngwtran.c - transforms the data in a row for PNG writers
  200303. *
  200304. * Last changed in libpng 1.2.9 April 14, 2006
  200305. * For conditions of distribution and use, see copyright notice in png.h
  200306. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200307. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200308. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200309. */
  200310. #define PNG_INTERNAL
  200311. #ifdef PNG_WRITE_SUPPORTED
  200312. /* Transform the data according to the user's wishes. The order of
  200313. * transformations is significant.
  200314. */
  200315. void /* PRIVATE */
  200316. png_do_write_transformations(png_structp png_ptr)
  200317. {
  200318. png_debug(1, "in png_do_write_transformations\n");
  200319. if (png_ptr == NULL)
  200320. return;
  200321. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200322. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200323. if(png_ptr->write_user_transform_fn != NULL)
  200324. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200325. (png_ptr, /* png_ptr */
  200326. &(png_ptr->row_info), /* row_info: */
  200327. /* png_uint_32 width; width of row */
  200328. /* png_uint_32 rowbytes; number of bytes in row */
  200329. /* png_byte color_type; color type of pixels */
  200330. /* png_byte bit_depth; bit depth of samples */
  200331. /* png_byte channels; number of channels (1-4) */
  200332. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200333. png_ptr->row_buf + 1); /* start of pixel data for row */
  200334. #endif
  200335. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200336. if (png_ptr->transformations & PNG_FILLER)
  200337. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200338. png_ptr->flags);
  200339. #endif
  200340. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200341. if (png_ptr->transformations & PNG_PACKSWAP)
  200342. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200343. #endif
  200344. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200345. if (png_ptr->transformations & PNG_PACK)
  200346. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200347. (png_uint_32)png_ptr->bit_depth);
  200348. #endif
  200349. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200350. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200351. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200352. #endif
  200353. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200354. if (png_ptr->transformations & PNG_SHIFT)
  200355. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200356. &(png_ptr->shift));
  200357. #endif
  200358. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200359. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200360. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200361. #endif
  200362. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200363. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200364. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200365. #endif
  200366. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200367. if (png_ptr->transformations & PNG_BGR)
  200368. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200369. #endif
  200370. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200371. if (png_ptr->transformations & PNG_INVERT_MONO)
  200372. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200373. #endif
  200374. }
  200375. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200376. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200377. * row_info bit depth should be 8 (one pixel per byte). The channels
  200378. * should be 1 (this only happens on grayscale and paletted images).
  200379. */
  200380. void /* PRIVATE */
  200381. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200382. {
  200383. png_debug(1, "in png_do_pack\n");
  200384. if (row_info->bit_depth == 8 &&
  200385. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200386. row != NULL && row_info != NULL &&
  200387. #endif
  200388. row_info->channels == 1)
  200389. {
  200390. switch ((int)bit_depth)
  200391. {
  200392. case 1:
  200393. {
  200394. png_bytep sp, dp;
  200395. int mask, v;
  200396. png_uint_32 i;
  200397. png_uint_32 row_width = row_info->width;
  200398. sp = row;
  200399. dp = row;
  200400. mask = 0x80;
  200401. v = 0;
  200402. for (i = 0; i < row_width; i++)
  200403. {
  200404. if (*sp != 0)
  200405. v |= mask;
  200406. sp++;
  200407. if (mask > 1)
  200408. mask >>= 1;
  200409. else
  200410. {
  200411. mask = 0x80;
  200412. *dp = (png_byte)v;
  200413. dp++;
  200414. v = 0;
  200415. }
  200416. }
  200417. if (mask != 0x80)
  200418. *dp = (png_byte)v;
  200419. break;
  200420. }
  200421. case 2:
  200422. {
  200423. png_bytep sp, dp;
  200424. int shift, v;
  200425. png_uint_32 i;
  200426. png_uint_32 row_width = row_info->width;
  200427. sp = row;
  200428. dp = row;
  200429. shift = 6;
  200430. v = 0;
  200431. for (i = 0; i < row_width; i++)
  200432. {
  200433. png_byte value;
  200434. value = (png_byte)(*sp & 0x03);
  200435. v |= (value << shift);
  200436. if (shift == 0)
  200437. {
  200438. shift = 6;
  200439. *dp = (png_byte)v;
  200440. dp++;
  200441. v = 0;
  200442. }
  200443. else
  200444. shift -= 2;
  200445. sp++;
  200446. }
  200447. if (shift != 6)
  200448. *dp = (png_byte)v;
  200449. break;
  200450. }
  200451. case 4:
  200452. {
  200453. png_bytep sp, dp;
  200454. int shift, v;
  200455. png_uint_32 i;
  200456. png_uint_32 row_width = row_info->width;
  200457. sp = row;
  200458. dp = row;
  200459. shift = 4;
  200460. v = 0;
  200461. for (i = 0; i < row_width; i++)
  200462. {
  200463. png_byte value;
  200464. value = (png_byte)(*sp & 0x0f);
  200465. v |= (value << shift);
  200466. if (shift == 0)
  200467. {
  200468. shift = 4;
  200469. *dp = (png_byte)v;
  200470. dp++;
  200471. v = 0;
  200472. }
  200473. else
  200474. shift -= 4;
  200475. sp++;
  200476. }
  200477. if (shift != 4)
  200478. *dp = (png_byte)v;
  200479. break;
  200480. }
  200481. }
  200482. row_info->bit_depth = (png_byte)bit_depth;
  200483. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200484. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200485. row_info->width);
  200486. }
  200487. }
  200488. #endif
  200489. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200490. /* Shift pixel values to take advantage of whole range. Pass the
  200491. * true number of bits in bit_depth. The row should be packed
  200492. * according to row_info->bit_depth. Thus, if you had a row of
  200493. * bit depth 4, but the pixels only had values from 0 to 7, you
  200494. * would pass 3 as bit_depth, and this routine would translate the
  200495. * data to 0 to 15.
  200496. */
  200497. void /* PRIVATE */
  200498. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200499. {
  200500. png_debug(1, "in png_do_shift\n");
  200501. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200502. if (row != NULL && row_info != NULL &&
  200503. #else
  200504. if (
  200505. #endif
  200506. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200507. {
  200508. int shift_start[4], shift_dec[4];
  200509. int channels = 0;
  200510. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200511. {
  200512. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200513. shift_dec[channels] = bit_depth->red;
  200514. channels++;
  200515. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200516. shift_dec[channels] = bit_depth->green;
  200517. channels++;
  200518. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200519. shift_dec[channels] = bit_depth->blue;
  200520. channels++;
  200521. }
  200522. else
  200523. {
  200524. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200525. shift_dec[channels] = bit_depth->gray;
  200526. channels++;
  200527. }
  200528. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200529. {
  200530. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200531. shift_dec[channels] = bit_depth->alpha;
  200532. channels++;
  200533. }
  200534. /* with low row depths, could only be grayscale, so one channel */
  200535. if (row_info->bit_depth < 8)
  200536. {
  200537. png_bytep bp = row;
  200538. png_uint_32 i;
  200539. png_byte mask;
  200540. png_uint_32 row_bytes = row_info->rowbytes;
  200541. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200542. mask = 0x55;
  200543. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200544. mask = 0x11;
  200545. else
  200546. mask = 0xff;
  200547. for (i = 0; i < row_bytes; i++, bp++)
  200548. {
  200549. png_uint_16 v;
  200550. int j;
  200551. v = *bp;
  200552. *bp = 0;
  200553. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200554. {
  200555. if (j > 0)
  200556. *bp |= (png_byte)((v << j) & 0xff);
  200557. else
  200558. *bp |= (png_byte)((v >> (-j)) & mask);
  200559. }
  200560. }
  200561. }
  200562. else if (row_info->bit_depth == 8)
  200563. {
  200564. png_bytep bp = row;
  200565. png_uint_32 i;
  200566. png_uint_32 istop = channels * row_info->width;
  200567. for (i = 0; i < istop; i++, bp++)
  200568. {
  200569. png_uint_16 v;
  200570. int j;
  200571. int c = (int)(i%channels);
  200572. v = *bp;
  200573. *bp = 0;
  200574. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200575. {
  200576. if (j > 0)
  200577. *bp |= (png_byte)((v << j) & 0xff);
  200578. else
  200579. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200580. }
  200581. }
  200582. }
  200583. else
  200584. {
  200585. png_bytep bp;
  200586. png_uint_32 i;
  200587. png_uint_32 istop = channels * row_info->width;
  200588. for (bp = row, i = 0; i < istop; i++)
  200589. {
  200590. int c = (int)(i%channels);
  200591. png_uint_16 value, v;
  200592. int j;
  200593. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200594. value = 0;
  200595. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200596. {
  200597. if (j > 0)
  200598. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200599. else
  200600. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200601. }
  200602. *bp++ = (png_byte)(value >> 8);
  200603. *bp++ = (png_byte)(value & 0xff);
  200604. }
  200605. }
  200606. }
  200607. }
  200608. #endif
  200609. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200610. void /* PRIVATE */
  200611. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200612. {
  200613. png_debug(1, "in png_do_write_swap_alpha\n");
  200614. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200615. if (row != NULL && row_info != NULL)
  200616. #endif
  200617. {
  200618. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200619. {
  200620. /* This converts from ARGB to RGBA */
  200621. if (row_info->bit_depth == 8)
  200622. {
  200623. png_bytep sp, dp;
  200624. png_uint_32 i;
  200625. png_uint_32 row_width = row_info->width;
  200626. for (i = 0, sp = dp = row; i < row_width; i++)
  200627. {
  200628. png_byte save = *(sp++);
  200629. *(dp++) = *(sp++);
  200630. *(dp++) = *(sp++);
  200631. *(dp++) = *(sp++);
  200632. *(dp++) = save;
  200633. }
  200634. }
  200635. /* This converts from AARRGGBB to RRGGBBAA */
  200636. else
  200637. {
  200638. png_bytep sp, dp;
  200639. png_uint_32 i;
  200640. png_uint_32 row_width = row_info->width;
  200641. for (i = 0, sp = dp = row; i < row_width; i++)
  200642. {
  200643. png_byte save[2];
  200644. save[0] = *(sp++);
  200645. save[1] = *(sp++);
  200646. *(dp++) = *(sp++);
  200647. *(dp++) = *(sp++);
  200648. *(dp++) = *(sp++);
  200649. *(dp++) = *(sp++);
  200650. *(dp++) = *(sp++);
  200651. *(dp++) = *(sp++);
  200652. *(dp++) = save[0];
  200653. *(dp++) = save[1];
  200654. }
  200655. }
  200656. }
  200657. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200658. {
  200659. /* This converts from AG to GA */
  200660. if (row_info->bit_depth == 8)
  200661. {
  200662. png_bytep sp, dp;
  200663. png_uint_32 i;
  200664. png_uint_32 row_width = row_info->width;
  200665. for (i = 0, sp = dp = row; i < row_width; i++)
  200666. {
  200667. png_byte save = *(sp++);
  200668. *(dp++) = *(sp++);
  200669. *(dp++) = save;
  200670. }
  200671. }
  200672. /* This converts from AAGG to GGAA */
  200673. else
  200674. {
  200675. png_bytep sp, dp;
  200676. png_uint_32 i;
  200677. png_uint_32 row_width = row_info->width;
  200678. for (i = 0, sp = dp = row; i < row_width; i++)
  200679. {
  200680. png_byte save[2];
  200681. save[0] = *(sp++);
  200682. save[1] = *(sp++);
  200683. *(dp++) = *(sp++);
  200684. *(dp++) = *(sp++);
  200685. *(dp++) = save[0];
  200686. *(dp++) = save[1];
  200687. }
  200688. }
  200689. }
  200690. }
  200691. }
  200692. #endif
  200693. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200694. void /* PRIVATE */
  200695. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200696. {
  200697. png_debug(1, "in png_do_write_invert_alpha\n");
  200698. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200699. if (row != NULL && row_info != NULL)
  200700. #endif
  200701. {
  200702. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200703. {
  200704. /* This inverts the alpha channel in RGBA */
  200705. if (row_info->bit_depth == 8)
  200706. {
  200707. png_bytep sp, dp;
  200708. png_uint_32 i;
  200709. png_uint_32 row_width = row_info->width;
  200710. for (i = 0, sp = dp = row; i < row_width; i++)
  200711. {
  200712. /* does nothing
  200713. *(dp++) = *(sp++);
  200714. *(dp++) = *(sp++);
  200715. *(dp++) = *(sp++);
  200716. */
  200717. sp+=3; dp = sp;
  200718. *(dp++) = (png_byte)(255 - *(sp++));
  200719. }
  200720. }
  200721. /* This inverts the alpha channel in RRGGBBAA */
  200722. else
  200723. {
  200724. png_bytep sp, dp;
  200725. png_uint_32 i;
  200726. png_uint_32 row_width = row_info->width;
  200727. for (i = 0, sp = dp = row; i < row_width; i++)
  200728. {
  200729. /* does nothing
  200730. *(dp++) = *(sp++);
  200731. *(dp++) = *(sp++);
  200732. *(dp++) = *(sp++);
  200733. *(dp++) = *(sp++);
  200734. *(dp++) = *(sp++);
  200735. *(dp++) = *(sp++);
  200736. */
  200737. sp+=6; dp = sp;
  200738. *(dp++) = (png_byte)(255 - *(sp++));
  200739. *(dp++) = (png_byte)(255 - *(sp++));
  200740. }
  200741. }
  200742. }
  200743. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200744. {
  200745. /* This inverts the alpha channel in GA */
  200746. if (row_info->bit_depth == 8)
  200747. {
  200748. png_bytep sp, dp;
  200749. png_uint_32 i;
  200750. png_uint_32 row_width = row_info->width;
  200751. for (i = 0, sp = dp = row; i < row_width; i++)
  200752. {
  200753. *(dp++) = *(sp++);
  200754. *(dp++) = (png_byte)(255 - *(sp++));
  200755. }
  200756. }
  200757. /* This inverts the alpha channel in GGAA */
  200758. else
  200759. {
  200760. png_bytep sp, dp;
  200761. png_uint_32 i;
  200762. png_uint_32 row_width = row_info->width;
  200763. for (i = 0, sp = dp = row; i < row_width; i++)
  200764. {
  200765. /* does nothing
  200766. *(dp++) = *(sp++);
  200767. *(dp++) = *(sp++);
  200768. */
  200769. sp+=2; dp = sp;
  200770. *(dp++) = (png_byte)(255 - *(sp++));
  200771. *(dp++) = (png_byte)(255 - *(sp++));
  200772. }
  200773. }
  200774. }
  200775. }
  200776. }
  200777. #endif
  200778. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200779. /* undoes intrapixel differencing */
  200780. void /* PRIVATE */
  200781. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200782. {
  200783. png_debug(1, "in png_do_write_intrapixel\n");
  200784. if (
  200785. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200786. row != NULL && row_info != NULL &&
  200787. #endif
  200788. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200789. {
  200790. int bytes_per_pixel;
  200791. png_uint_32 row_width = row_info->width;
  200792. if (row_info->bit_depth == 8)
  200793. {
  200794. png_bytep rp;
  200795. png_uint_32 i;
  200796. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200797. bytes_per_pixel = 3;
  200798. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200799. bytes_per_pixel = 4;
  200800. else
  200801. return;
  200802. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200803. {
  200804. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200805. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200806. }
  200807. }
  200808. else if (row_info->bit_depth == 16)
  200809. {
  200810. png_bytep rp;
  200811. png_uint_32 i;
  200812. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200813. bytes_per_pixel = 6;
  200814. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200815. bytes_per_pixel = 8;
  200816. else
  200817. return;
  200818. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200819. {
  200820. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200821. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200822. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200823. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200824. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200825. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200826. *(rp+1) = (png_byte)(red & 0xff);
  200827. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200828. *(rp+5) = (png_byte)(blue & 0xff);
  200829. }
  200830. }
  200831. }
  200832. }
  200833. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200834. #endif /* PNG_WRITE_SUPPORTED */
  200835. /*** End of inlined file: pngwtran.c ***/
  200836. /*** Start of inlined file: pngwutil.c ***/
  200837. /* pngwutil.c - utilities to write a PNG file
  200838. *
  200839. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200840. * For conditions of distribution and use, see copyright notice in png.h
  200841. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200842. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200843. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200844. */
  200845. #define PNG_INTERNAL
  200846. #ifdef PNG_WRITE_SUPPORTED
  200847. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200848. * with unsigned numbers for convenience, although one supported
  200849. * ancillary chunk uses signed (two's complement) numbers.
  200850. */
  200851. void PNGAPI
  200852. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200853. {
  200854. buf[0] = (png_byte)((i >> 24) & 0xff);
  200855. buf[1] = (png_byte)((i >> 16) & 0xff);
  200856. buf[2] = (png_byte)((i >> 8) & 0xff);
  200857. buf[3] = (png_byte)(i & 0xff);
  200858. }
  200859. /* The png_save_int_32 function assumes integers are stored in two's
  200860. * complement format. If this isn't the case, then this routine needs to
  200861. * be modified to write data in two's complement format.
  200862. */
  200863. void PNGAPI
  200864. png_save_int_32(png_bytep buf, png_int_32 i)
  200865. {
  200866. buf[0] = (png_byte)((i >> 24) & 0xff);
  200867. buf[1] = (png_byte)((i >> 16) & 0xff);
  200868. buf[2] = (png_byte)((i >> 8) & 0xff);
  200869. buf[3] = (png_byte)(i & 0xff);
  200870. }
  200871. /* Place a 16-bit number into a buffer in PNG byte order.
  200872. * The parameter is declared unsigned int, not png_uint_16,
  200873. * just to avoid potential problems on pre-ANSI C compilers.
  200874. */
  200875. void PNGAPI
  200876. png_save_uint_16(png_bytep buf, unsigned int i)
  200877. {
  200878. buf[0] = (png_byte)((i >> 8) & 0xff);
  200879. buf[1] = (png_byte)(i & 0xff);
  200880. }
  200881. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200882. * representing the chunk name. The array must be at least 4 bytes in
  200883. * length, and does not need to be null terminated. To be safe, pass the
  200884. * pre-defined chunk names here, and if you need a new one, define it
  200885. * where the others are defined. The length is the length of the data.
  200886. * All the data must be present. If that is not possible, use the
  200887. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200888. * functions instead.
  200889. */
  200890. void PNGAPI
  200891. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200892. png_bytep data, png_size_t length)
  200893. {
  200894. if(png_ptr == NULL) return;
  200895. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200896. png_write_chunk_data(png_ptr, data, length);
  200897. png_write_chunk_end(png_ptr);
  200898. }
  200899. /* Write the start of a PNG chunk. The type is the chunk type.
  200900. * The total_length is the sum of the lengths of all the data you will be
  200901. * passing in png_write_chunk_data().
  200902. */
  200903. void PNGAPI
  200904. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200905. png_uint_32 length)
  200906. {
  200907. png_byte buf[4];
  200908. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200909. if(png_ptr == NULL) return;
  200910. /* write the length */
  200911. png_save_uint_32(buf, length);
  200912. png_write_data(png_ptr, buf, (png_size_t)4);
  200913. /* write the chunk name */
  200914. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200915. /* reset the crc and run it over the chunk name */
  200916. png_reset_crc(png_ptr);
  200917. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200918. }
  200919. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200920. * Note that multiple calls to this function are allowed, and that the
  200921. * sum of the lengths from these calls *must* add up to the total_length
  200922. * given to png_write_chunk_start().
  200923. */
  200924. void PNGAPI
  200925. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200926. {
  200927. /* write the data, and run the CRC over it */
  200928. if(png_ptr == NULL) return;
  200929. if (data != NULL && length > 0)
  200930. {
  200931. png_calculate_crc(png_ptr, data, length);
  200932. png_write_data(png_ptr, data, length);
  200933. }
  200934. }
  200935. /* Finish a chunk started with png_write_chunk_start(). */
  200936. void PNGAPI
  200937. png_write_chunk_end(png_structp png_ptr)
  200938. {
  200939. png_byte buf[4];
  200940. if(png_ptr == NULL) return;
  200941. /* write the crc */
  200942. png_save_uint_32(buf, png_ptr->crc);
  200943. png_write_data(png_ptr, buf, (png_size_t)4);
  200944. }
  200945. /* Simple function to write the signature. If we have already written
  200946. * the magic bytes of the signature, or more likely, the PNG stream is
  200947. * being embedded into another stream and doesn't need its own signature,
  200948. * we should call png_set_sig_bytes() to tell libpng how many of the
  200949. * bytes have already been written.
  200950. */
  200951. void /* PRIVATE */
  200952. png_write_sig(png_structp png_ptr)
  200953. {
  200954. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200955. /* write the rest of the 8 byte signature */
  200956. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200957. (png_size_t)8 - png_ptr->sig_bytes);
  200958. if(png_ptr->sig_bytes < 3)
  200959. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200960. }
  200961. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200962. /*
  200963. * This pair of functions encapsulates the operation of (a) compressing a
  200964. * text string, and (b) issuing it later as a series of chunk data writes.
  200965. * The compression_state structure is shared context for these functions
  200966. * set up by the caller in order to make the whole mess thread-safe.
  200967. */
  200968. typedef struct
  200969. {
  200970. char *input; /* the uncompressed input data */
  200971. int input_len; /* its length */
  200972. int num_output_ptr; /* number of output pointers used */
  200973. int max_output_ptr; /* size of output_ptr */
  200974. png_charpp output_ptr; /* array of pointers to output */
  200975. } compression_state;
  200976. /* compress given text into storage in the png_ptr structure */
  200977. static int /* PRIVATE */
  200978. png_text_compress(png_structp png_ptr,
  200979. png_charp text, png_size_t text_len, int compression,
  200980. compression_state *comp)
  200981. {
  200982. int ret;
  200983. comp->num_output_ptr = 0;
  200984. comp->max_output_ptr = 0;
  200985. comp->output_ptr = NULL;
  200986. comp->input = NULL;
  200987. comp->input_len = 0;
  200988. /* we may just want to pass the text right through */
  200989. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200990. {
  200991. comp->input = text;
  200992. comp->input_len = text_len;
  200993. return((int)text_len);
  200994. }
  200995. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200996. {
  200997. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200998. char msg[50];
  200999. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  201000. png_warning(png_ptr, msg);
  201001. #else
  201002. png_warning(png_ptr, "Unknown compression type");
  201003. #endif
  201004. }
  201005. /* We can't write the chunk until we find out how much data we have,
  201006. * which means we need to run the compressor first and save the
  201007. * output. This shouldn't be a problem, as the vast majority of
  201008. * comments should be reasonable, but we will set up an array of
  201009. * malloc'd pointers to be sure.
  201010. *
  201011. * If we knew the application was well behaved, we could simplify this
  201012. * greatly by assuming we can always malloc an output buffer large
  201013. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  201014. * and malloc this directly. The only time this would be a bad idea is
  201015. * if we can't malloc more than 64K and we have 64K of random input
  201016. * data, or if the input string is incredibly large (although this
  201017. * wouldn't cause a failure, just a slowdown due to swapping).
  201018. */
  201019. /* set up the compression buffers */
  201020. png_ptr->zstream.avail_in = (uInt)text_len;
  201021. png_ptr->zstream.next_in = (Bytef *)text;
  201022. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201023. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  201024. /* this is the same compression loop as in png_write_row() */
  201025. do
  201026. {
  201027. /* compress the data */
  201028. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  201029. if (ret != Z_OK)
  201030. {
  201031. /* error */
  201032. if (png_ptr->zstream.msg != NULL)
  201033. png_error(png_ptr, png_ptr->zstream.msg);
  201034. else
  201035. png_error(png_ptr, "zlib error");
  201036. }
  201037. /* check to see if we need more room */
  201038. if (!(png_ptr->zstream.avail_out))
  201039. {
  201040. /* make sure the output array has room */
  201041. if (comp->num_output_ptr >= comp->max_output_ptr)
  201042. {
  201043. int old_max;
  201044. old_max = comp->max_output_ptr;
  201045. comp->max_output_ptr = comp->num_output_ptr + 4;
  201046. if (comp->output_ptr != NULL)
  201047. {
  201048. png_charpp old_ptr;
  201049. old_ptr = comp->output_ptr;
  201050. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201051. (png_uint_32)(comp->max_output_ptr *
  201052. png_sizeof (png_charpp)));
  201053. png_memcpy(comp->output_ptr, old_ptr, old_max
  201054. * png_sizeof (png_charp));
  201055. png_free(png_ptr, old_ptr);
  201056. }
  201057. else
  201058. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201059. (png_uint_32)(comp->max_output_ptr *
  201060. png_sizeof (png_charp)));
  201061. }
  201062. /* save the data */
  201063. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  201064. (png_uint_32)png_ptr->zbuf_size);
  201065. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201066. png_ptr->zbuf_size);
  201067. comp->num_output_ptr++;
  201068. /* and reset the buffer */
  201069. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201070. png_ptr->zstream.next_out = png_ptr->zbuf;
  201071. }
  201072. /* continue until we don't have any more to compress */
  201073. } while (png_ptr->zstream.avail_in);
  201074. /* finish the compression */
  201075. do
  201076. {
  201077. /* tell zlib we are finished */
  201078. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201079. if (ret == Z_OK)
  201080. {
  201081. /* check to see if we need more room */
  201082. if (!(png_ptr->zstream.avail_out))
  201083. {
  201084. /* check to make sure our output array has room */
  201085. if (comp->num_output_ptr >= comp->max_output_ptr)
  201086. {
  201087. int old_max;
  201088. old_max = comp->max_output_ptr;
  201089. comp->max_output_ptr = comp->num_output_ptr + 4;
  201090. if (comp->output_ptr != NULL)
  201091. {
  201092. png_charpp old_ptr;
  201093. old_ptr = comp->output_ptr;
  201094. /* This could be optimized to realloc() */
  201095. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201096. (png_uint_32)(comp->max_output_ptr *
  201097. png_sizeof (png_charpp)));
  201098. png_memcpy(comp->output_ptr, old_ptr,
  201099. old_max * png_sizeof (png_charp));
  201100. png_free(png_ptr, old_ptr);
  201101. }
  201102. else
  201103. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201104. (png_uint_32)(comp->max_output_ptr *
  201105. png_sizeof (png_charp)));
  201106. }
  201107. /* save off the data */
  201108. comp->output_ptr[comp->num_output_ptr] =
  201109. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  201110. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201111. png_ptr->zbuf_size);
  201112. comp->num_output_ptr++;
  201113. /* and reset the buffer pointers */
  201114. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201115. png_ptr->zstream.next_out = png_ptr->zbuf;
  201116. }
  201117. }
  201118. else if (ret != Z_STREAM_END)
  201119. {
  201120. /* we got an error */
  201121. if (png_ptr->zstream.msg != NULL)
  201122. png_error(png_ptr, png_ptr->zstream.msg);
  201123. else
  201124. png_error(png_ptr, "zlib error");
  201125. }
  201126. } while (ret != Z_STREAM_END);
  201127. /* text length is number of buffers plus last buffer */
  201128. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  201129. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201130. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  201131. return((int)text_len);
  201132. }
  201133. /* ship the compressed text out via chunk writes */
  201134. static void /* PRIVATE */
  201135. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  201136. {
  201137. int i;
  201138. /* handle the no-compression case */
  201139. if (comp->input)
  201140. {
  201141. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  201142. (png_size_t)comp->input_len);
  201143. return;
  201144. }
  201145. /* write saved output buffers, if any */
  201146. for (i = 0; i < comp->num_output_ptr; i++)
  201147. {
  201148. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  201149. png_ptr->zbuf_size);
  201150. png_free(png_ptr, comp->output_ptr[i]);
  201151. comp->output_ptr[i]=NULL;
  201152. }
  201153. if (comp->max_output_ptr != 0)
  201154. png_free(png_ptr, comp->output_ptr);
  201155. comp->output_ptr=NULL;
  201156. /* write anything left in zbuf */
  201157. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  201158. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  201159. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  201160. /* reset zlib for another zTXt/iTXt or image data */
  201161. deflateReset(&png_ptr->zstream);
  201162. png_ptr->zstream.data_type = Z_BINARY;
  201163. }
  201164. #endif
  201165. /* Write the IHDR chunk, and update the png_struct with the necessary
  201166. * information. Note that the rest of this code depends upon this
  201167. * information being correct.
  201168. */
  201169. void /* PRIVATE */
  201170. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  201171. int bit_depth, int color_type, int compression_type, int filter_type,
  201172. int interlace_type)
  201173. {
  201174. #ifdef PNG_USE_LOCAL_ARRAYS
  201175. PNG_IHDR;
  201176. #endif
  201177. png_byte buf[13]; /* buffer to store the IHDR info */
  201178. png_debug(1, "in png_write_IHDR\n");
  201179. /* Check that we have valid input data from the application info */
  201180. switch (color_type)
  201181. {
  201182. case PNG_COLOR_TYPE_GRAY:
  201183. switch (bit_depth)
  201184. {
  201185. case 1:
  201186. case 2:
  201187. case 4:
  201188. case 8:
  201189. case 16: png_ptr->channels = 1; break;
  201190. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  201191. }
  201192. break;
  201193. case PNG_COLOR_TYPE_RGB:
  201194. if (bit_depth != 8 && bit_depth != 16)
  201195. png_error(png_ptr, "Invalid bit depth for RGB image");
  201196. png_ptr->channels = 3;
  201197. break;
  201198. case PNG_COLOR_TYPE_PALETTE:
  201199. switch (bit_depth)
  201200. {
  201201. case 1:
  201202. case 2:
  201203. case 4:
  201204. case 8: png_ptr->channels = 1; break;
  201205. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201206. }
  201207. break;
  201208. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201209. if (bit_depth != 8 && bit_depth != 16)
  201210. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201211. png_ptr->channels = 2;
  201212. break;
  201213. case PNG_COLOR_TYPE_RGB_ALPHA:
  201214. if (bit_depth != 8 && bit_depth != 16)
  201215. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201216. png_ptr->channels = 4;
  201217. break;
  201218. default:
  201219. png_error(png_ptr, "Invalid image color type specified");
  201220. }
  201221. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201222. {
  201223. png_warning(png_ptr, "Invalid compression type specified");
  201224. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201225. }
  201226. /* Write filter_method 64 (intrapixel differencing) only if
  201227. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201228. * 2. Libpng did not write a PNG signature (this filter_method is only
  201229. * used in PNG datastreams that are embedded in MNG datastreams) and
  201230. * 3. The application called png_permit_mng_features with a mask that
  201231. * included PNG_FLAG_MNG_FILTER_64 and
  201232. * 4. The filter_method is 64 and
  201233. * 5. The color_type is RGB or RGBA
  201234. */
  201235. if (
  201236. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201237. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201238. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201239. (color_type == PNG_COLOR_TYPE_RGB ||
  201240. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201241. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201242. #endif
  201243. filter_type != PNG_FILTER_TYPE_BASE)
  201244. {
  201245. png_warning(png_ptr, "Invalid filter type specified");
  201246. filter_type = PNG_FILTER_TYPE_BASE;
  201247. }
  201248. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201249. if (interlace_type != PNG_INTERLACE_NONE &&
  201250. interlace_type != PNG_INTERLACE_ADAM7)
  201251. {
  201252. png_warning(png_ptr, "Invalid interlace type specified");
  201253. interlace_type = PNG_INTERLACE_ADAM7;
  201254. }
  201255. #else
  201256. interlace_type=PNG_INTERLACE_NONE;
  201257. #endif
  201258. /* save off the relevent information */
  201259. png_ptr->bit_depth = (png_byte)bit_depth;
  201260. png_ptr->color_type = (png_byte)color_type;
  201261. png_ptr->interlaced = (png_byte)interlace_type;
  201262. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201263. png_ptr->filter_type = (png_byte)filter_type;
  201264. #endif
  201265. png_ptr->compression_type = (png_byte)compression_type;
  201266. png_ptr->width = width;
  201267. png_ptr->height = height;
  201268. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201269. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201270. /* set the usr info, so any transformations can modify it */
  201271. png_ptr->usr_width = png_ptr->width;
  201272. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201273. png_ptr->usr_channels = png_ptr->channels;
  201274. /* pack the header information into the buffer */
  201275. png_save_uint_32(buf, width);
  201276. png_save_uint_32(buf + 4, height);
  201277. buf[8] = (png_byte)bit_depth;
  201278. buf[9] = (png_byte)color_type;
  201279. buf[10] = (png_byte)compression_type;
  201280. buf[11] = (png_byte)filter_type;
  201281. buf[12] = (png_byte)interlace_type;
  201282. /* write the chunk */
  201283. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201284. /* initialize zlib with PNG info */
  201285. png_ptr->zstream.zalloc = png_zalloc;
  201286. png_ptr->zstream.zfree = png_zfree;
  201287. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201288. if (!(png_ptr->do_filter))
  201289. {
  201290. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201291. png_ptr->bit_depth < 8)
  201292. png_ptr->do_filter = PNG_FILTER_NONE;
  201293. else
  201294. png_ptr->do_filter = PNG_ALL_FILTERS;
  201295. }
  201296. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201297. {
  201298. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201299. png_ptr->zlib_strategy = Z_FILTERED;
  201300. else
  201301. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201302. }
  201303. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201304. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201305. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201306. png_ptr->zlib_mem_level = 8;
  201307. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201308. png_ptr->zlib_window_bits = 15;
  201309. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201310. png_ptr->zlib_method = 8;
  201311. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201312. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201313. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201314. png_error(png_ptr, "zlib failed to initialize compressor");
  201315. png_ptr->zstream.next_out = png_ptr->zbuf;
  201316. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201317. /* libpng is not interested in zstream.data_type */
  201318. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201319. png_ptr->zstream.data_type = Z_BINARY;
  201320. png_ptr->mode = PNG_HAVE_IHDR;
  201321. }
  201322. /* write the palette. We are careful not to trust png_color to be in the
  201323. * correct order for PNG, so people can redefine it to any convenient
  201324. * structure.
  201325. */
  201326. void /* PRIVATE */
  201327. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201328. {
  201329. #ifdef PNG_USE_LOCAL_ARRAYS
  201330. PNG_PLTE;
  201331. #endif
  201332. png_uint_32 i;
  201333. png_colorp pal_ptr;
  201334. png_byte buf[3];
  201335. png_debug(1, "in png_write_PLTE\n");
  201336. if ((
  201337. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201338. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201339. #endif
  201340. num_pal == 0) || num_pal > 256)
  201341. {
  201342. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201343. {
  201344. png_error(png_ptr, "Invalid number of colors in palette");
  201345. }
  201346. else
  201347. {
  201348. png_warning(png_ptr, "Invalid number of colors in palette");
  201349. return;
  201350. }
  201351. }
  201352. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201353. {
  201354. png_warning(png_ptr,
  201355. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201356. return;
  201357. }
  201358. png_ptr->num_palette = (png_uint_16)num_pal;
  201359. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201360. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201361. #ifndef PNG_NO_POINTER_INDEXING
  201362. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201363. {
  201364. buf[0] = pal_ptr->red;
  201365. buf[1] = pal_ptr->green;
  201366. buf[2] = pal_ptr->blue;
  201367. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201368. }
  201369. #else
  201370. /* This is a little slower but some buggy compilers need to do this instead */
  201371. pal_ptr=palette;
  201372. for (i = 0; i < num_pal; i++)
  201373. {
  201374. buf[0] = pal_ptr[i].red;
  201375. buf[1] = pal_ptr[i].green;
  201376. buf[2] = pal_ptr[i].blue;
  201377. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201378. }
  201379. #endif
  201380. png_write_chunk_end(png_ptr);
  201381. png_ptr->mode |= PNG_HAVE_PLTE;
  201382. }
  201383. /* write an IDAT chunk */
  201384. void /* PRIVATE */
  201385. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201386. {
  201387. #ifdef PNG_USE_LOCAL_ARRAYS
  201388. PNG_IDAT;
  201389. #endif
  201390. png_debug(1, "in png_write_IDAT\n");
  201391. /* Optimize the CMF field in the zlib stream. */
  201392. /* This hack of the zlib stream is compliant to the stream specification. */
  201393. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201394. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201395. {
  201396. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201397. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201398. {
  201399. /* Avoid memory underflows and multiplication overflows. */
  201400. /* The conditions below are practically always satisfied;
  201401. however, they still must be checked. */
  201402. if (length >= 2 &&
  201403. png_ptr->height < 16384 && png_ptr->width < 16384)
  201404. {
  201405. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201406. ((png_ptr->width *
  201407. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201408. unsigned int z_cinfo = z_cmf >> 4;
  201409. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201410. while (uncompressed_idat_size <= half_z_window_size &&
  201411. half_z_window_size >= 256)
  201412. {
  201413. z_cinfo--;
  201414. half_z_window_size >>= 1;
  201415. }
  201416. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201417. if (data[0] != (png_byte)z_cmf)
  201418. {
  201419. data[0] = (png_byte)z_cmf;
  201420. data[1] &= 0xe0;
  201421. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201422. }
  201423. }
  201424. }
  201425. else
  201426. png_error(png_ptr,
  201427. "Invalid zlib compression method or flags in IDAT");
  201428. }
  201429. png_write_chunk(png_ptr, png_IDAT, data, length);
  201430. png_ptr->mode |= PNG_HAVE_IDAT;
  201431. }
  201432. /* write an IEND chunk */
  201433. void /* PRIVATE */
  201434. png_write_IEND(png_structp png_ptr)
  201435. {
  201436. #ifdef PNG_USE_LOCAL_ARRAYS
  201437. PNG_IEND;
  201438. #endif
  201439. png_debug(1, "in png_write_IEND\n");
  201440. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201441. (png_size_t)0);
  201442. png_ptr->mode |= PNG_HAVE_IEND;
  201443. }
  201444. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201445. /* write a gAMA chunk */
  201446. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201447. void /* PRIVATE */
  201448. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201449. {
  201450. #ifdef PNG_USE_LOCAL_ARRAYS
  201451. PNG_gAMA;
  201452. #endif
  201453. png_uint_32 igamma;
  201454. png_byte buf[4];
  201455. png_debug(1, "in png_write_gAMA\n");
  201456. /* file_gamma is saved in 1/100,000ths */
  201457. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201458. png_save_uint_32(buf, igamma);
  201459. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201460. }
  201461. #endif
  201462. #ifdef PNG_FIXED_POINT_SUPPORTED
  201463. void /* PRIVATE */
  201464. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201465. {
  201466. #ifdef PNG_USE_LOCAL_ARRAYS
  201467. PNG_gAMA;
  201468. #endif
  201469. png_byte buf[4];
  201470. png_debug(1, "in png_write_gAMA\n");
  201471. /* file_gamma is saved in 1/100,000ths */
  201472. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201473. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201474. }
  201475. #endif
  201476. #endif
  201477. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201478. /* write a sRGB chunk */
  201479. void /* PRIVATE */
  201480. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201481. {
  201482. #ifdef PNG_USE_LOCAL_ARRAYS
  201483. PNG_sRGB;
  201484. #endif
  201485. png_byte buf[1];
  201486. png_debug(1, "in png_write_sRGB\n");
  201487. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201488. png_warning(png_ptr,
  201489. "Invalid sRGB rendering intent specified");
  201490. buf[0]=(png_byte)srgb_intent;
  201491. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201492. }
  201493. #endif
  201494. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201495. /* write an iCCP chunk */
  201496. void /* PRIVATE */
  201497. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201498. png_charp profile, int profile_len)
  201499. {
  201500. #ifdef PNG_USE_LOCAL_ARRAYS
  201501. PNG_iCCP;
  201502. #endif
  201503. png_size_t name_len;
  201504. png_charp new_name;
  201505. compression_state comp;
  201506. int embedded_profile_len = 0;
  201507. png_debug(1, "in png_write_iCCP\n");
  201508. comp.num_output_ptr = 0;
  201509. comp.max_output_ptr = 0;
  201510. comp.output_ptr = NULL;
  201511. comp.input = NULL;
  201512. comp.input_len = 0;
  201513. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201514. &new_name)) == 0)
  201515. {
  201516. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201517. return;
  201518. }
  201519. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201520. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201521. if (profile == NULL)
  201522. profile_len = 0;
  201523. if (profile_len > 3)
  201524. embedded_profile_len =
  201525. ((*( (png_bytep)profile ))<<24) |
  201526. ((*( (png_bytep)profile+1))<<16) |
  201527. ((*( (png_bytep)profile+2))<< 8) |
  201528. ((*( (png_bytep)profile+3)) );
  201529. if (profile_len < embedded_profile_len)
  201530. {
  201531. png_warning(png_ptr,
  201532. "Embedded profile length too large in iCCP chunk");
  201533. return;
  201534. }
  201535. if (profile_len > embedded_profile_len)
  201536. {
  201537. png_warning(png_ptr,
  201538. "Truncating profile to actual length in iCCP chunk");
  201539. profile_len = embedded_profile_len;
  201540. }
  201541. if (profile_len)
  201542. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201543. PNG_COMPRESSION_TYPE_BASE, &comp);
  201544. /* make sure we include the NULL after the name and the compression type */
  201545. png_write_chunk_start(png_ptr, png_iCCP,
  201546. (png_uint_32)name_len+profile_len+2);
  201547. new_name[name_len+1]=0x00;
  201548. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201549. if (profile_len)
  201550. png_write_compressed_data_out(png_ptr, &comp);
  201551. png_write_chunk_end(png_ptr);
  201552. png_free(png_ptr, new_name);
  201553. }
  201554. #endif
  201555. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201556. /* write a sPLT chunk */
  201557. void /* PRIVATE */
  201558. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201559. {
  201560. #ifdef PNG_USE_LOCAL_ARRAYS
  201561. PNG_sPLT;
  201562. #endif
  201563. png_size_t name_len;
  201564. png_charp new_name;
  201565. png_byte entrybuf[10];
  201566. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201567. int palette_size = entry_size * spalette->nentries;
  201568. png_sPLT_entryp ep;
  201569. #ifdef PNG_NO_POINTER_INDEXING
  201570. int i;
  201571. #endif
  201572. png_debug(1, "in png_write_sPLT\n");
  201573. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201574. spalette->name, &new_name))==0)
  201575. {
  201576. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201577. return;
  201578. }
  201579. /* make sure we include the NULL after the name */
  201580. png_write_chunk_start(png_ptr, png_sPLT,
  201581. (png_uint_32)(name_len + 2 + palette_size));
  201582. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201583. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201584. /* loop through each palette entry, writing appropriately */
  201585. #ifndef PNG_NO_POINTER_INDEXING
  201586. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201587. {
  201588. if (spalette->depth == 8)
  201589. {
  201590. entrybuf[0] = (png_byte)ep->red;
  201591. entrybuf[1] = (png_byte)ep->green;
  201592. entrybuf[2] = (png_byte)ep->blue;
  201593. entrybuf[3] = (png_byte)ep->alpha;
  201594. png_save_uint_16(entrybuf + 4, ep->frequency);
  201595. }
  201596. else
  201597. {
  201598. png_save_uint_16(entrybuf + 0, ep->red);
  201599. png_save_uint_16(entrybuf + 2, ep->green);
  201600. png_save_uint_16(entrybuf + 4, ep->blue);
  201601. png_save_uint_16(entrybuf + 6, ep->alpha);
  201602. png_save_uint_16(entrybuf + 8, ep->frequency);
  201603. }
  201604. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201605. }
  201606. #else
  201607. ep=spalette->entries;
  201608. for (i=0; i>spalette->nentries; i++)
  201609. {
  201610. if (spalette->depth == 8)
  201611. {
  201612. entrybuf[0] = (png_byte)ep[i].red;
  201613. entrybuf[1] = (png_byte)ep[i].green;
  201614. entrybuf[2] = (png_byte)ep[i].blue;
  201615. entrybuf[3] = (png_byte)ep[i].alpha;
  201616. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201617. }
  201618. else
  201619. {
  201620. png_save_uint_16(entrybuf + 0, ep[i].red);
  201621. png_save_uint_16(entrybuf + 2, ep[i].green);
  201622. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201623. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201624. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201625. }
  201626. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201627. }
  201628. #endif
  201629. png_write_chunk_end(png_ptr);
  201630. png_free(png_ptr, new_name);
  201631. }
  201632. #endif
  201633. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201634. /* write the sBIT chunk */
  201635. void /* PRIVATE */
  201636. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201637. {
  201638. #ifdef PNG_USE_LOCAL_ARRAYS
  201639. PNG_sBIT;
  201640. #endif
  201641. png_byte buf[4];
  201642. png_size_t size;
  201643. png_debug(1, "in png_write_sBIT\n");
  201644. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201645. if (color_type & PNG_COLOR_MASK_COLOR)
  201646. {
  201647. png_byte maxbits;
  201648. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201649. png_ptr->usr_bit_depth);
  201650. if (sbit->red == 0 || sbit->red > maxbits ||
  201651. sbit->green == 0 || sbit->green > maxbits ||
  201652. sbit->blue == 0 || sbit->blue > maxbits)
  201653. {
  201654. png_warning(png_ptr, "Invalid sBIT depth specified");
  201655. return;
  201656. }
  201657. buf[0] = sbit->red;
  201658. buf[1] = sbit->green;
  201659. buf[2] = sbit->blue;
  201660. size = 3;
  201661. }
  201662. else
  201663. {
  201664. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201665. {
  201666. png_warning(png_ptr, "Invalid sBIT depth specified");
  201667. return;
  201668. }
  201669. buf[0] = sbit->gray;
  201670. size = 1;
  201671. }
  201672. if (color_type & PNG_COLOR_MASK_ALPHA)
  201673. {
  201674. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201675. {
  201676. png_warning(png_ptr, "Invalid sBIT depth specified");
  201677. return;
  201678. }
  201679. buf[size++] = sbit->alpha;
  201680. }
  201681. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201682. }
  201683. #endif
  201684. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201685. /* write the cHRM chunk */
  201686. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201687. void /* PRIVATE */
  201688. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201689. double red_x, double red_y, double green_x, double green_y,
  201690. double blue_x, double blue_y)
  201691. {
  201692. #ifdef PNG_USE_LOCAL_ARRAYS
  201693. PNG_cHRM;
  201694. #endif
  201695. png_byte buf[32];
  201696. png_uint_32 itemp;
  201697. png_debug(1, "in png_write_cHRM\n");
  201698. /* each value is saved in 1/100,000ths */
  201699. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201700. white_x + white_y > 1.0)
  201701. {
  201702. png_warning(png_ptr, "Invalid cHRM white point specified");
  201703. #if !defined(PNG_NO_CONSOLE_IO)
  201704. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201705. #endif
  201706. return;
  201707. }
  201708. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201709. png_save_uint_32(buf, itemp);
  201710. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201711. png_save_uint_32(buf + 4, itemp);
  201712. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201713. {
  201714. png_warning(png_ptr, "Invalid cHRM red point specified");
  201715. return;
  201716. }
  201717. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201718. png_save_uint_32(buf + 8, itemp);
  201719. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201720. png_save_uint_32(buf + 12, itemp);
  201721. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201722. {
  201723. png_warning(png_ptr, "Invalid cHRM green point specified");
  201724. return;
  201725. }
  201726. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201727. png_save_uint_32(buf + 16, itemp);
  201728. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201729. png_save_uint_32(buf + 20, itemp);
  201730. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201731. {
  201732. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201733. return;
  201734. }
  201735. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201736. png_save_uint_32(buf + 24, itemp);
  201737. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201738. png_save_uint_32(buf + 28, itemp);
  201739. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201740. }
  201741. #endif
  201742. #ifdef PNG_FIXED_POINT_SUPPORTED
  201743. void /* PRIVATE */
  201744. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201745. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201746. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201747. png_fixed_point blue_y)
  201748. {
  201749. #ifdef PNG_USE_LOCAL_ARRAYS
  201750. PNG_cHRM;
  201751. #endif
  201752. png_byte buf[32];
  201753. png_debug(1, "in png_write_cHRM\n");
  201754. /* each value is saved in 1/100,000ths */
  201755. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201756. {
  201757. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201758. #if !defined(PNG_NO_CONSOLE_IO)
  201759. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201760. #endif
  201761. return;
  201762. }
  201763. png_save_uint_32(buf, (png_uint_32)white_x);
  201764. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201765. if (red_x + red_y > 100000L)
  201766. {
  201767. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201768. return;
  201769. }
  201770. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201771. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201772. if (green_x + green_y > 100000L)
  201773. {
  201774. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201775. return;
  201776. }
  201777. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201778. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201779. if (blue_x + blue_y > 100000L)
  201780. {
  201781. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201782. return;
  201783. }
  201784. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201785. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201786. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201787. }
  201788. #endif
  201789. #endif
  201790. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201791. /* write the tRNS chunk */
  201792. void /* PRIVATE */
  201793. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201794. int num_trans, int color_type)
  201795. {
  201796. #ifdef PNG_USE_LOCAL_ARRAYS
  201797. PNG_tRNS;
  201798. #endif
  201799. png_byte buf[6];
  201800. png_debug(1, "in png_write_tRNS\n");
  201801. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201802. {
  201803. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201804. {
  201805. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201806. return;
  201807. }
  201808. /* write the chunk out as it is */
  201809. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201810. }
  201811. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201812. {
  201813. /* one 16 bit value */
  201814. if(tran->gray >= (1 << png_ptr->bit_depth))
  201815. {
  201816. png_warning(png_ptr,
  201817. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201818. return;
  201819. }
  201820. png_save_uint_16(buf, tran->gray);
  201821. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201822. }
  201823. else if (color_type == PNG_COLOR_TYPE_RGB)
  201824. {
  201825. /* three 16 bit values */
  201826. png_save_uint_16(buf, tran->red);
  201827. png_save_uint_16(buf + 2, tran->green);
  201828. png_save_uint_16(buf + 4, tran->blue);
  201829. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201830. {
  201831. png_warning(png_ptr,
  201832. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201833. return;
  201834. }
  201835. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201836. }
  201837. else
  201838. {
  201839. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201840. }
  201841. }
  201842. #endif
  201843. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201844. /* write the background chunk */
  201845. void /* PRIVATE */
  201846. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201847. {
  201848. #ifdef PNG_USE_LOCAL_ARRAYS
  201849. PNG_bKGD;
  201850. #endif
  201851. png_byte buf[6];
  201852. png_debug(1, "in png_write_bKGD\n");
  201853. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201854. {
  201855. if (
  201856. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201857. (png_ptr->num_palette ||
  201858. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201859. #endif
  201860. back->index > png_ptr->num_palette)
  201861. {
  201862. png_warning(png_ptr, "Invalid background palette index");
  201863. return;
  201864. }
  201865. buf[0] = back->index;
  201866. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201867. }
  201868. else if (color_type & PNG_COLOR_MASK_COLOR)
  201869. {
  201870. png_save_uint_16(buf, back->red);
  201871. png_save_uint_16(buf + 2, back->green);
  201872. png_save_uint_16(buf + 4, back->blue);
  201873. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201874. {
  201875. png_warning(png_ptr,
  201876. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201877. return;
  201878. }
  201879. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201880. }
  201881. else
  201882. {
  201883. if(back->gray >= (1 << png_ptr->bit_depth))
  201884. {
  201885. png_warning(png_ptr,
  201886. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201887. return;
  201888. }
  201889. png_save_uint_16(buf, back->gray);
  201890. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201891. }
  201892. }
  201893. #endif
  201894. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201895. /* write the histogram */
  201896. void /* PRIVATE */
  201897. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201898. {
  201899. #ifdef PNG_USE_LOCAL_ARRAYS
  201900. PNG_hIST;
  201901. #endif
  201902. int i;
  201903. png_byte buf[3];
  201904. png_debug(1, "in png_write_hIST\n");
  201905. if (num_hist > (int)png_ptr->num_palette)
  201906. {
  201907. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201908. png_ptr->num_palette);
  201909. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201910. return;
  201911. }
  201912. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201913. for (i = 0; i < num_hist; i++)
  201914. {
  201915. png_save_uint_16(buf, hist[i]);
  201916. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201917. }
  201918. png_write_chunk_end(png_ptr);
  201919. }
  201920. #endif
  201921. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201922. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201923. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201924. * and if invalid, correct the keyword rather than discarding the entire
  201925. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201926. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201927. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201928. *
  201929. * The new_key is allocated to hold the corrected keyword and must be freed
  201930. * by the calling routine. This avoids problems with trying to write to
  201931. * static keywords without having to have duplicate copies of the strings.
  201932. */
  201933. png_size_t /* PRIVATE */
  201934. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201935. {
  201936. png_size_t key_len;
  201937. png_charp kp, dp;
  201938. int kflag;
  201939. int kwarn=0;
  201940. png_debug(1, "in png_check_keyword\n");
  201941. *new_key = NULL;
  201942. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201943. {
  201944. png_warning(png_ptr, "zero length keyword");
  201945. return ((png_size_t)0);
  201946. }
  201947. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201948. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201949. if (*new_key == NULL)
  201950. {
  201951. png_warning(png_ptr, "Out of memory while procesing keyword");
  201952. return ((png_size_t)0);
  201953. }
  201954. /* Replace non-printing characters with a blank and print a warning */
  201955. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201956. {
  201957. if ((png_byte)*kp < 0x20 ||
  201958. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201959. {
  201960. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201961. char msg[40];
  201962. png_snprintf(msg, 40,
  201963. "invalid keyword character 0x%02X", (png_byte)*kp);
  201964. png_warning(png_ptr, msg);
  201965. #else
  201966. png_warning(png_ptr, "invalid character in keyword");
  201967. #endif
  201968. *dp = ' ';
  201969. }
  201970. else
  201971. {
  201972. *dp = *kp;
  201973. }
  201974. }
  201975. *dp = '\0';
  201976. /* Remove any trailing white space. */
  201977. kp = *new_key + key_len - 1;
  201978. if (*kp == ' ')
  201979. {
  201980. png_warning(png_ptr, "trailing spaces removed from keyword");
  201981. while (*kp == ' ')
  201982. {
  201983. *(kp--) = '\0';
  201984. key_len--;
  201985. }
  201986. }
  201987. /* Remove any leading white space. */
  201988. kp = *new_key;
  201989. if (*kp == ' ')
  201990. {
  201991. png_warning(png_ptr, "leading spaces removed from keyword");
  201992. while (*kp == ' ')
  201993. {
  201994. kp++;
  201995. key_len--;
  201996. }
  201997. }
  201998. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201999. /* Remove multiple internal spaces. */
  202000. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  202001. {
  202002. if (*kp == ' ' && kflag == 0)
  202003. {
  202004. *(dp++) = *kp;
  202005. kflag = 1;
  202006. }
  202007. else if (*kp == ' ')
  202008. {
  202009. key_len--;
  202010. kwarn=1;
  202011. }
  202012. else
  202013. {
  202014. *(dp++) = *kp;
  202015. kflag = 0;
  202016. }
  202017. }
  202018. *dp = '\0';
  202019. if(kwarn)
  202020. png_warning(png_ptr, "extra interior spaces removed from keyword");
  202021. if (key_len == 0)
  202022. {
  202023. png_free(png_ptr, *new_key);
  202024. *new_key=NULL;
  202025. png_warning(png_ptr, "Zero length keyword");
  202026. }
  202027. if (key_len > 79)
  202028. {
  202029. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  202030. new_key[79] = '\0';
  202031. key_len = 79;
  202032. }
  202033. return (key_len);
  202034. }
  202035. #endif
  202036. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  202037. /* write a tEXt chunk */
  202038. void /* PRIVATE */
  202039. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  202040. png_size_t text_len)
  202041. {
  202042. #ifdef PNG_USE_LOCAL_ARRAYS
  202043. PNG_tEXt;
  202044. #endif
  202045. png_size_t key_len;
  202046. png_charp new_key;
  202047. png_debug(1, "in png_write_tEXt\n");
  202048. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202049. {
  202050. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  202051. return;
  202052. }
  202053. if (text == NULL || *text == '\0')
  202054. text_len = 0;
  202055. else
  202056. text_len = png_strlen(text);
  202057. /* make sure we include the 0 after the key */
  202058. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  202059. /*
  202060. * We leave it to the application to meet PNG-1.0 requirements on the
  202061. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202062. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202063. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202064. */
  202065. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202066. if (text_len)
  202067. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  202068. png_write_chunk_end(png_ptr);
  202069. png_free(png_ptr, new_key);
  202070. }
  202071. #endif
  202072. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  202073. /* write a compressed text chunk */
  202074. void /* PRIVATE */
  202075. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  202076. png_size_t text_len, int compression)
  202077. {
  202078. #ifdef PNG_USE_LOCAL_ARRAYS
  202079. PNG_zTXt;
  202080. #endif
  202081. png_size_t key_len;
  202082. char buf[1];
  202083. png_charp new_key;
  202084. compression_state comp;
  202085. png_debug(1, "in png_write_zTXt\n");
  202086. comp.num_output_ptr = 0;
  202087. comp.max_output_ptr = 0;
  202088. comp.output_ptr = NULL;
  202089. comp.input = NULL;
  202090. comp.input_len = 0;
  202091. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202092. {
  202093. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  202094. return;
  202095. }
  202096. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  202097. {
  202098. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  202099. png_free(png_ptr, new_key);
  202100. return;
  202101. }
  202102. text_len = png_strlen(text);
  202103. /* compute the compressed data; do it now for the length */
  202104. text_len = png_text_compress(png_ptr, text, text_len, compression,
  202105. &comp);
  202106. /* write start of chunk */
  202107. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  202108. (key_len+text_len+2));
  202109. /* write key */
  202110. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202111. png_free(png_ptr, new_key);
  202112. buf[0] = (png_byte)compression;
  202113. /* write compression */
  202114. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  202115. /* write the compressed data */
  202116. png_write_compressed_data_out(png_ptr, &comp);
  202117. /* close the chunk */
  202118. png_write_chunk_end(png_ptr);
  202119. }
  202120. #endif
  202121. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  202122. /* write an iTXt chunk */
  202123. void /* PRIVATE */
  202124. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  202125. png_charp lang, png_charp lang_key, png_charp text)
  202126. {
  202127. #ifdef PNG_USE_LOCAL_ARRAYS
  202128. PNG_iTXt;
  202129. #endif
  202130. png_size_t lang_len, key_len, lang_key_len, text_len;
  202131. png_charp new_lang, new_key;
  202132. png_byte cbuf[2];
  202133. compression_state comp;
  202134. png_debug(1, "in png_write_iTXt\n");
  202135. comp.num_output_ptr = 0;
  202136. comp.max_output_ptr = 0;
  202137. comp.output_ptr = NULL;
  202138. comp.input = NULL;
  202139. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202140. {
  202141. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  202142. return;
  202143. }
  202144. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  202145. {
  202146. png_warning(png_ptr, "Empty language field in iTXt chunk");
  202147. new_lang = NULL;
  202148. lang_len = 0;
  202149. }
  202150. if (lang_key == NULL)
  202151. lang_key_len = 0;
  202152. else
  202153. lang_key_len = png_strlen(lang_key);
  202154. if (text == NULL)
  202155. text_len = 0;
  202156. else
  202157. text_len = png_strlen(text);
  202158. /* compute the compressed data; do it now for the length */
  202159. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  202160. &comp);
  202161. /* make sure we include the compression flag, the compression byte,
  202162. * and the NULs after the key, lang, and lang_key parts */
  202163. png_write_chunk_start(png_ptr, png_iTXt,
  202164. (png_uint_32)(
  202165. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  202166. + key_len
  202167. + lang_len
  202168. + lang_key_len
  202169. + text_len));
  202170. /*
  202171. * We leave it to the application to meet PNG-1.0 requirements on the
  202172. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202173. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202174. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202175. */
  202176. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202177. /* set the compression flag */
  202178. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  202179. compression == PNG_TEXT_COMPRESSION_NONE)
  202180. cbuf[0] = 0;
  202181. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  202182. cbuf[0] = 1;
  202183. /* set the compression method */
  202184. cbuf[1] = 0;
  202185. png_write_chunk_data(png_ptr, cbuf, 2);
  202186. cbuf[0] = 0;
  202187. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  202188. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  202189. png_write_compressed_data_out(png_ptr, &comp);
  202190. png_write_chunk_end(png_ptr);
  202191. png_free(png_ptr, new_key);
  202192. if (new_lang)
  202193. png_free(png_ptr, new_lang);
  202194. }
  202195. #endif
  202196. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202197. /* write the oFFs chunk */
  202198. void /* PRIVATE */
  202199. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202200. int unit_type)
  202201. {
  202202. #ifdef PNG_USE_LOCAL_ARRAYS
  202203. PNG_oFFs;
  202204. #endif
  202205. png_byte buf[9];
  202206. png_debug(1, "in png_write_oFFs\n");
  202207. if (unit_type >= PNG_OFFSET_LAST)
  202208. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202209. png_save_int_32(buf, x_offset);
  202210. png_save_int_32(buf + 4, y_offset);
  202211. buf[8] = (png_byte)unit_type;
  202212. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202213. }
  202214. #endif
  202215. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202216. /* write the pCAL chunk (described in the PNG extensions document) */
  202217. void /* PRIVATE */
  202218. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202219. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202220. {
  202221. #ifdef PNG_USE_LOCAL_ARRAYS
  202222. PNG_pCAL;
  202223. #endif
  202224. png_size_t purpose_len, units_len, total_len;
  202225. png_uint_32p params_len;
  202226. png_byte buf[10];
  202227. png_charp new_purpose;
  202228. int i;
  202229. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202230. if (type >= PNG_EQUATION_LAST)
  202231. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202232. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202233. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202234. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202235. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202236. total_len = purpose_len + units_len + 10;
  202237. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202238. *png_sizeof(png_uint_32)));
  202239. /* Find the length of each parameter, making sure we don't count the
  202240. null terminator for the last parameter. */
  202241. for (i = 0; i < nparams; i++)
  202242. {
  202243. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202244. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202245. total_len += (png_size_t)params_len[i];
  202246. }
  202247. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202248. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202249. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202250. png_save_int_32(buf, X0);
  202251. png_save_int_32(buf + 4, X1);
  202252. buf[8] = (png_byte)type;
  202253. buf[9] = (png_byte)nparams;
  202254. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202255. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202256. png_free(png_ptr, new_purpose);
  202257. for (i = 0; i < nparams; i++)
  202258. {
  202259. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202260. (png_size_t)params_len[i]);
  202261. }
  202262. png_free(png_ptr, params_len);
  202263. png_write_chunk_end(png_ptr);
  202264. }
  202265. #endif
  202266. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202267. /* write the sCAL chunk */
  202268. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202269. void /* PRIVATE */
  202270. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202271. {
  202272. #ifdef PNG_USE_LOCAL_ARRAYS
  202273. PNG_sCAL;
  202274. #endif
  202275. char buf[64];
  202276. png_size_t total_len;
  202277. png_debug(1, "in png_write_sCAL\n");
  202278. buf[0] = (char)unit;
  202279. #if defined(_WIN32_WCE)
  202280. /* sprintf() function is not supported on WindowsCE */
  202281. {
  202282. wchar_t wc_buf[32];
  202283. size_t wc_len;
  202284. swprintf(wc_buf, TEXT("%12.12e"), width);
  202285. wc_len = wcslen(wc_buf);
  202286. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202287. total_len = wc_len + 2;
  202288. swprintf(wc_buf, TEXT("%12.12e"), height);
  202289. wc_len = wcslen(wc_buf);
  202290. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202291. NULL, NULL);
  202292. total_len += wc_len;
  202293. }
  202294. #else
  202295. png_snprintf(buf + 1, 63, "%12.12e", width);
  202296. total_len = 1 + png_strlen(buf + 1) + 1;
  202297. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202298. total_len += png_strlen(buf + total_len);
  202299. #endif
  202300. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202301. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202302. }
  202303. #else
  202304. #ifdef PNG_FIXED_POINT_SUPPORTED
  202305. void /* PRIVATE */
  202306. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202307. png_charp height)
  202308. {
  202309. #ifdef PNG_USE_LOCAL_ARRAYS
  202310. PNG_sCAL;
  202311. #endif
  202312. png_byte buf[64];
  202313. png_size_t wlen, hlen, total_len;
  202314. png_debug(1, "in png_write_sCAL_s\n");
  202315. wlen = png_strlen(width);
  202316. hlen = png_strlen(height);
  202317. total_len = wlen + hlen + 2;
  202318. if (total_len > 64)
  202319. {
  202320. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202321. return;
  202322. }
  202323. buf[0] = (png_byte)unit;
  202324. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202325. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202326. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202327. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202328. }
  202329. #endif
  202330. #endif
  202331. #endif
  202332. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202333. /* write the pHYs chunk */
  202334. void /* PRIVATE */
  202335. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202336. png_uint_32 y_pixels_per_unit,
  202337. int unit_type)
  202338. {
  202339. #ifdef PNG_USE_LOCAL_ARRAYS
  202340. PNG_pHYs;
  202341. #endif
  202342. png_byte buf[9];
  202343. png_debug(1, "in png_write_pHYs\n");
  202344. if (unit_type >= PNG_RESOLUTION_LAST)
  202345. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202346. png_save_uint_32(buf, x_pixels_per_unit);
  202347. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202348. buf[8] = (png_byte)unit_type;
  202349. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202350. }
  202351. #endif
  202352. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202353. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202354. * or png_convert_from_time_t(), or fill in the structure yourself.
  202355. */
  202356. void /* PRIVATE */
  202357. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202358. {
  202359. #ifdef PNG_USE_LOCAL_ARRAYS
  202360. PNG_tIME;
  202361. #endif
  202362. png_byte buf[7];
  202363. png_debug(1, "in png_write_tIME\n");
  202364. if (mod_time->month > 12 || mod_time->month < 1 ||
  202365. mod_time->day > 31 || mod_time->day < 1 ||
  202366. mod_time->hour > 23 || mod_time->second > 60)
  202367. {
  202368. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202369. return;
  202370. }
  202371. png_save_uint_16(buf, mod_time->year);
  202372. buf[2] = mod_time->month;
  202373. buf[3] = mod_time->day;
  202374. buf[4] = mod_time->hour;
  202375. buf[5] = mod_time->minute;
  202376. buf[6] = mod_time->second;
  202377. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202378. }
  202379. #endif
  202380. /* initializes the row writing capability of libpng */
  202381. void /* PRIVATE */
  202382. png_write_start_row(png_structp png_ptr)
  202383. {
  202384. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202385. #ifdef PNG_USE_LOCAL_ARRAYS
  202386. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202387. /* start of interlace block */
  202388. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202389. /* offset to next interlace block */
  202390. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202391. /* start of interlace block in the y direction */
  202392. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202393. /* offset to next interlace block in the y direction */
  202394. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202395. #endif
  202396. #endif
  202397. png_size_t buf_size;
  202398. png_debug(1, "in png_write_start_row\n");
  202399. buf_size = (png_size_t)(PNG_ROWBYTES(
  202400. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202401. /* set up row buffer */
  202402. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202403. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202404. #ifndef PNG_NO_WRITE_FILTERING
  202405. /* set up filtering buffer, if using this filter */
  202406. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202407. {
  202408. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202409. (png_ptr->rowbytes + 1));
  202410. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202411. }
  202412. /* We only need to keep the previous row if we are using one of these. */
  202413. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202414. {
  202415. /* set up previous row buffer */
  202416. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202417. png_memset(png_ptr->prev_row, 0, buf_size);
  202418. if (png_ptr->do_filter & PNG_FILTER_UP)
  202419. {
  202420. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202421. (png_ptr->rowbytes + 1));
  202422. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202423. }
  202424. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202425. {
  202426. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202427. (png_ptr->rowbytes + 1));
  202428. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202429. }
  202430. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202431. {
  202432. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202433. (png_ptr->rowbytes + 1));
  202434. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202435. }
  202436. #endif /* PNG_NO_WRITE_FILTERING */
  202437. }
  202438. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202439. /* if interlaced, we need to set up width and height of pass */
  202440. if (png_ptr->interlaced)
  202441. {
  202442. if (!(png_ptr->transformations & PNG_INTERLACE))
  202443. {
  202444. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202445. png_pass_ystart[0]) / png_pass_yinc[0];
  202446. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202447. png_pass_start[0]) / png_pass_inc[0];
  202448. }
  202449. else
  202450. {
  202451. png_ptr->num_rows = png_ptr->height;
  202452. png_ptr->usr_width = png_ptr->width;
  202453. }
  202454. }
  202455. else
  202456. #endif
  202457. {
  202458. png_ptr->num_rows = png_ptr->height;
  202459. png_ptr->usr_width = png_ptr->width;
  202460. }
  202461. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202462. png_ptr->zstream.next_out = png_ptr->zbuf;
  202463. }
  202464. /* Internal use only. Called when finished processing a row of data. */
  202465. void /* PRIVATE */
  202466. png_write_finish_row(png_structp png_ptr)
  202467. {
  202468. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202469. #ifdef PNG_USE_LOCAL_ARRAYS
  202470. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202471. /* start of interlace block */
  202472. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202473. /* offset to next interlace block */
  202474. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202475. /* start of interlace block in the y direction */
  202476. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202477. /* offset to next interlace block in the y direction */
  202478. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202479. #endif
  202480. #endif
  202481. int ret;
  202482. png_debug(1, "in png_write_finish_row\n");
  202483. /* next row */
  202484. png_ptr->row_number++;
  202485. /* see if we are done */
  202486. if (png_ptr->row_number < png_ptr->num_rows)
  202487. return;
  202488. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202489. /* if interlaced, go to next pass */
  202490. if (png_ptr->interlaced)
  202491. {
  202492. png_ptr->row_number = 0;
  202493. if (png_ptr->transformations & PNG_INTERLACE)
  202494. {
  202495. png_ptr->pass++;
  202496. }
  202497. else
  202498. {
  202499. /* loop until we find a non-zero width or height pass */
  202500. do
  202501. {
  202502. png_ptr->pass++;
  202503. if (png_ptr->pass >= 7)
  202504. break;
  202505. png_ptr->usr_width = (png_ptr->width +
  202506. png_pass_inc[png_ptr->pass] - 1 -
  202507. png_pass_start[png_ptr->pass]) /
  202508. png_pass_inc[png_ptr->pass];
  202509. png_ptr->num_rows = (png_ptr->height +
  202510. png_pass_yinc[png_ptr->pass] - 1 -
  202511. png_pass_ystart[png_ptr->pass]) /
  202512. png_pass_yinc[png_ptr->pass];
  202513. if (png_ptr->transformations & PNG_INTERLACE)
  202514. break;
  202515. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202516. }
  202517. /* reset the row above the image for the next pass */
  202518. if (png_ptr->pass < 7)
  202519. {
  202520. if (png_ptr->prev_row != NULL)
  202521. png_memset(png_ptr->prev_row, 0,
  202522. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202523. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202524. return;
  202525. }
  202526. }
  202527. #endif
  202528. /* if we get here, we've just written the last row, so we need
  202529. to flush the compressor */
  202530. do
  202531. {
  202532. /* tell the compressor we are done */
  202533. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202534. /* check for an error */
  202535. if (ret == Z_OK)
  202536. {
  202537. /* check to see if we need more room */
  202538. if (!(png_ptr->zstream.avail_out))
  202539. {
  202540. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202541. png_ptr->zstream.next_out = png_ptr->zbuf;
  202542. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202543. }
  202544. }
  202545. else if (ret != Z_STREAM_END)
  202546. {
  202547. if (png_ptr->zstream.msg != NULL)
  202548. png_error(png_ptr, png_ptr->zstream.msg);
  202549. else
  202550. png_error(png_ptr, "zlib error");
  202551. }
  202552. } while (ret != Z_STREAM_END);
  202553. /* write any extra space */
  202554. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202555. {
  202556. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202557. png_ptr->zstream.avail_out);
  202558. }
  202559. deflateReset(&png_ptr->zstream);
  202560. png_ptr->zstream.data_type = Z_BINARY;
  202561. }
  202562. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202563. /* Pick out the correct pixels for the interlace pass.
  202564. * The basic idea here is to go through the row with a source
  202565. * pointer and a destination pointer (sp and dp), and copy the
  202566. * correct pixels for the pass. As the row gets compacted,
  202567. * sp will always be >= dp, so we should never overwrite anything.
  202568. * See the default: case for the easiest code to understand.
  202569. */
  202570. void /* PRIVATE */
  202571. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202572. {
  202573. #ifdef PNG_USE_LOCAL_ARRAYS
  202574. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202575. /* start of interlace block */
  202576. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202577. /* offset to next interlace block */
  202578. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202579. #endif
  202580. png_debug(1, "in png_do_write_interlace\n");
  202581. /* we don't have to do anything on the last pass (6) */
  202582. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202583. if (row != NULL && row_info != NULL && pass < 6)
  202584. #else
  202585. if (pass < 6)
  202586. #endif
  202587. {
  202588. /* each pixel depth is handled separately */
  202589. switch (row_info->pixel_depth)
  202590. {
  202591. case 1:
  202592. {
  202593. png_bytep sp;
  202594. png_bytep dp;
  202595. int shift;
  202596. int d;
  202597. int value;
  202598. png_uint_32 i;
  202599. png_uint_32 row_width = row_info->width;
  202600. dp = row;
  202601. d = 0;
  202602. shift = 7;
  202603. for (i = png_pass_start[pass]; i < row_width;
  202604. i += png_pass_inc[pass])
  202605. {
  202606. sp = row + (png_size_t)(i >> 3);
  202607. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202608. d |= (value << shift);
  202609. if (shift == 0)
  202610. {
  202611. shift = 7;
  202612. *dp++ = (png_byte)d;
  202613. d = 0;
  202614. }
  202615. else
  202616. shift--;
  202617. }
  202618. if (shift != 7)
  202619. *dp = (png_byte)d;
  202620. break;
  202621. }
  202622. case 2:
  202623. {
  202624. png_bytep sp;
  202625. png_bytep dp;
  202626. int shift;
  202627. int d;
  202628. int value;
  202629. png_uint_32 i;
  202630. png_uint_32 row_width = row_info->width;
  202631. dp = row;
  202632. shift = 6;
  202633. d = 0;
  202634. for (i = png_pass_start[pass]; i < row_width;
  202635. i += png_pass_inc[pass])
  202636. {
  202637. sp = row + (png_size_t)(i >> 2);
  202638. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202639. d |= (value << shift);
  202640. if (shift == 0)
  202641. {
  202642. shift = 6;
  202643. *dp++ = (png_byte)d;
  202644. d = 0;
  202645. }
  202646. else
  202647. shift -= 2;
  202648. }
  202649. if (shift != 6)
  202650. *dp = (png_byte)d;
  202651. break;
  202652. }
  202653. case 4:
  202654. {
  202655. png_bytep sp;
  202656. png_bytep dp;
  202657. int shift;
  202658. int d;
  202659. int value;
  202660. png_uint_32 i;
  202661. png_uint_32 row_width = row_info->width;
  202662. dp = row;
  202663. shift = 4;
  202664. d = 0;
  202665. for (i = png_pass_start[pass]; i < row_width;
  202666. i += png_pass_inc[pass])
  202667. {
  202668. sp = row + (png_size_t)(i >> 1);
  202669. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202670. d |= (value << shift);
  202671. if (shift == 0)
  202672. {
  202673. shift = 4;
  202674. *dp++ = (png_byte)d;
  202675. d = 0;
  202676. }
  202677. else
  202678. shift -= 4;
  202679. }
  202680. if (shift != 4)
  202681. *dp = (png_byte)d;
  202682. break;
  202683. }
  202684. default:
  202685. {
  202686. png_bytep sp;
  202687. png_bytep dp;
  202688. png_uint_32 i;
  202689. png_uint_32 row_width = row_info->width;
  202690. png_size_t pixel_bytes;
  202691. /* start at the beginning */
  202692. dp = row;
  202693. /* find out how many bytes each pixel takes up */
  202694. pixel_bytes = (row_info->pixel_depth >> 3);
  202695. /* loop through the row, only looking at the pixels that
  202696. matter */
  202697. for (i = png_pass_start[pass]; i < row_width;
  202698. i += png_pass_inc[pass])
  202699. {
  202700. /* find out where the original pixel is */
  202701. sp = row + (png_size_t)i * pixel_bytes;
  202702. /* move the pixel */
  202703. if (dp != sp)
  202704. png_memcpy(dp, sp, pixel_bytes);
  202705. /* next pixel */
  202706. dp += pixel_bytes;
  202707. }
  202708. break;
  202709. }
  202710. }
  202711. /* set new row width */
  202712. row_info->width = (row_info->width +
  202713. png_pass_inc[pass] - 1 -
  202714. png_pass_start[pass]) /
  202715. png_pass_inc[pass];
  202716. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202717. row_info->width);
  202718. }
  202719. }
  202720. #endif
  202721. /* This filters the row, chooses which filter to use, if it has not already
  202722. * been specified by the application, and then writes the row out with the
  202723. * chosen filter.
  202724. */
  202725. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202726. #define PNG_HISHIFT 10
  202727. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202728. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202729. void /* PRIVATE */
  202730. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202731. {
  202732. png_bytep best_row;
  202733. #ifndef PNG_NO_WRITE_FILTER
  202734. png_bytep prev_row, row_buf;
  202735. png_uint_32 mins, bpp;
  202736. png_byte filter_to_do = png_ptr->do_filter;
  202737. png_uint_32 row_bytes = row_info->rowbytes;
  202738. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202739. int num_p_filters = (int)png_ptr->num_prev_filters;
  202740. #endif
  202741. png_debug(1, "in png_write_find_filter\n");
  202742. /* find out how many bytes offset each pixel is */
  202743. bpp = (row_info->pixel_depth + 7) >> 3;
  202744. prev_row = png_ptr->prev_row;
  202745. #endif
  202746. best_row = png_ptr->row_buf;
  202747. #ifndef PNG_NO_WRITE_FILTER
  202748. row_buf = best_row;
  202749. mins = PNG_MAXSUM;
  202750. /* The prediction method we use is to find which method provides the
  202751. * smallest value when summing the absolute values of the distances
  202752. * from zero, using anything >= 128 as negative numbers. This is known
  202753. * as the "minimum sum of absolute differences" heuristic. Other
  202754. * heuristics are the "weighted minimum sum of absolute differences"
  202755. * (experimental and can in theory improve compression), and the "zlib
  202756. * predictive" method (not implemented yet), which does test compressions
  202757. * of lines using different filter methods, and then chooses the
  202758. * (series of) filter(s) that give minimum compressed data size (VERY
  202759. * computationally expensive).
  202760. *
  202761. * GRR 980525: consider also
  202762. * (1) minimum sum of absolute differences from running average (i.e.,
  202763. * keep running sum of non-absolute differences & count of bytes)
  202764. * [track dispersion, too? restart average if dispersion too large?]
  202765. * (1b) minimum sum of absolute differences from sliding average, probably
  202766. * with window size <= deflate window (usually 32K)
  202767. * (2) minimum sum of squared differences from zero or running average
  202768. * (i.e., ~ root-mean-square approach)
  202769. */
  202770. /* We don't need to test the 'no filter' case if this is the only filter
  202771. * that has been chosen, as it doesn't actually do anything to the data.
  202772. */
  202773. if ((filter_to_do & PNG_FILTER_NONE) &&
  202774. filter_to_do != PNG_FILTER_NONE)
  202775. {
  202776. png_bytep rp;
  202777. png_uint_32 sum = 0;
  202778. png_uint_32 i;
  202779. int v;
  202780. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202781. {
  202782. v = *rp;
  202783. sum += (v < 128) ? v : 256 - v;
  202784. }
  202785. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202786. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202787. {
  202788. png_uint_32 sumhi, sumlo;
  202789. int j;
  202790. sumlo = sum & PNG_LOMASK;
  202791. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202792. /* Reduce the sum if we match any of the previous rows */
  202793. for (j = 0; j < num_p_filters; j++)
  202794. {
  202795. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202796. {
  202797. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202798. PNG_WEIGHT_SHIFT;
  202799. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202800. PNG_WEIGHT_SHIFT;
  202801. }
  202802. }
  202803. /* Factor in the cost of this filter (this is here for completeness,
  202804. * but it makes no sense to have a "cost" for the NONE filter, as
  202805. * it has the minimum possible computational cost - none).
  202806. */
  202807. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202808. PNG_COST_SHIFT;
  202809. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202810. PNG_COST_SHIFT;
  202811. if (sumhi > PNG_HIMASK)
  202812. sum = PNG_MAXSUM;
  202813. else
  202814. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202815. }
  202816. #endif
  202817. mins = sum;
  202818. }
  202819. /* sub filter */
  202820. if (filter_to_do == PNG_FILTER_SUB)
  202821. /* it's the only filter so no testing is needed */
  202822. {
  202823. png_bytep rp, lp, dp;
  202824. png_uint_32 i;
  202825. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202826. i++, rp++, dp++)
  202827. {
  202828. *dp = *rp;
  202829. }
  202830. for (lp = row_buf + 1; i < row_bytes;
  202831. i++, rp++, lp++, dp++)
  202832. {
  202833. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202834. }
  202835. best_row = png_ptr->sub_row;
  202836. }
  202837. else if (filter_to_do & PNG_FILTER_SUB)
  202838. {
  202839. png_bytep rp, dp, lp;
  202840. png_uint_32 sum = 0, lmins = mins;
  202841. png_uint_32 i;
  202842. int v;
  202843. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202844. /* We temporarily increase the "minimum sum" by the factor we
  202845. * would reduce the sum of this filter, so that we can do the
  202846. * early exit comparison without scaling the sum each time.
  202847. */
  202848. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202849. {
  202850. int j;
  202851. png_uint_32 lmhi, lmlo;
  202852. lmlo = lmins & PNG_LOMASK;
  202853. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202854. for (j = 0; j < num_p_filters; j++)
  202855. {
  202856. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202857. {
  202858. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202859. PNG_WEIGHT_SHIFT;
  202860. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202861. PNG_WEIGHT_SHIFT;
  202862. }
  202863. }
  202864. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202865. PNG_COST_SHIFT;
  202866. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202867. PNG_COST_SHIFT;
  202868. if (lmhi > PNG_HIMASK)
  202869. lmins = PNG_MAXSUM;
  202870. else
  202871. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202872. }
  202873. #endif
  202874. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202875. i++, rp++, dp++)
  202876. {
  202877. v = *dp = *rp;
  202878. sum += (v < 128) ? v : 256 - v;
  202879. }
  202880. for (lp = row_buf + 1; i < row_bytes;
  202881. i++, rp++, lp++, dp++)
  202882. {
  202883. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202884. sum += (v < 128) ? v : 256 - v;
  202885. if (sum > lmins) /* We are already worse, don't continue. */
  202886. break;
  202887. }
  202888. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202889. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202890. {
  202891. int j;
  202892. png_uint_32 sumhi, sumlo;
  202893. sumlo = sum & PNG_LOMASK;
  202894. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202895. for (j = 0; j < num_p_filters; j++)
  202896. {
  202897. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202898. {
  202899. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202900. PNG_WEIGHT_SHIFT;
  202901. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202902. PNG_WEIGHT_SHIFT;
  202903. }
  202904. }
  202905. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202906. PNG_COST_SHIFT;
  202907. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202908. PNG_COST_SHIFT;
  202909. if (sumhi > PNG_HIMASK)
  202910. sum = PNG_MAXSUM;
  202911. else
  202912. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202913. }
  202914. #endif
  202915. if (sum < mins)
  202916. {
  202917. mins = sum;
  202918. best_row = png_ptr->sub_row;
  202919. }
  202920. }
  202921. /* up filter */
  202922. if (filter_to_do == PNG_FILTER_UP)
  202923. {
  202924. png_bytep rp, dp, pp;
  202925. png_uint_32 i;
  202926. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202927. pp = prev_row + 1; i < row_bytes;
  202928. i++, rp++, pp++, dp++)
  202929. {
  202930. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202931. }
  202932. best_row = png_ptr->up_row;
  202933. }
  202934. else if (filter_to_do & PNG_FILTER_UP)
  202935. {
  202936. png_bytep rp, dp, pp;
  202937. png_uint_32 sum = 0, lmins = mins;
  202938. png_uint_32 i;
  202939. int v;
  202940. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202941. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202942. {
  202943. int j;
  202944. png_uint_32 lmhi, lmlo;
  202945. lmlo = lmins & PNG_LOMASK;
  202946. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202947. for (j = 0; j < num_p_filters; j++)
  202948. {
  202949. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202950. {
  202951. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202952. PNG_WEIGHT_SHIFT;
  202953. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202954. PNG_WEIGHT_SHIFT;
  202955. }
  202956. }
  202957. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202958. PNG_COST_SHIFT;
  202959. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202960. PNG_COST_SHIFT;
  202961. if (lmhi > PNG_HIMASK)
  202962. lmins = PNG_MAXSUM;
  202963. else
  202964. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202965. }
  202966. #endif
  202967. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202968. pp = prev_row + 1; i < row_bytes; i++)
  202969. {
  202970. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202971. sum += (v < 128) ? v : 256 - v;
  202972. if (sum > lmins) /* We are already worse, don't continue. */
  202973. break;
  202974. }
  202975. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202976. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202977. {
  202978. int j;
  202979. png_uint_32 sumhi, sumlo;
  202980. sumlo = sum & PNG_LOMASK;
  202981. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202982. for (j = 0; j < num_p_filters; j++)
  202983. {
  202984. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202985. {
  202986. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202987. PNG_WEIGHT_SHIFT;
  202988. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202989. PNG_WEIGHT_SHIFT;
  202990. }
  202991. }
  202992. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202993. PNG_COST_SHIFT;
  202994. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202995. PNG_COST_SHIFT;
  202996. if (sumhi > PNG_HIMASK)
  202997. sum = PNG_MAXSUM;
  202998. else
  202999. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203000. }
  203001. #endif
  203002. if (sum < mins)
  203003. {
  203004. mins = sum;
  203005. best_row = png_ptr->up_row;
  203006. }
  203007. }
  203008. /* avg filter */
  203009. if (filter_to_do == PNG_FILTER_AVG)
  203010. {
  203011. png_bytep rp, dp, pp, lp;
  203012. png_uint_32 i;
  203013. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203014. pp = prev_row + 1; i < bpp; i++)
  203015. {
  203016. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203017. }
  203018. for (lp = row_buf + 1; i < row_bytes; i++)
  203019. {
  203020. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  203021. & 0xff);
  203022. }
  203023. best_row = png_ptr->avg_row;
  203024. }
  203025. else if (filter_to_do & PNG_FILTER_AVG)
  203026. {
  203027. png_bytep rp, dp, pp, lp;
  203028. png_uint_32 sum = 0, lmins = mins;
  203029. png_uint_32 i;
  203030. int v;
  203031. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203032. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203033. {
  203034. int j;
  203035. png_uint_32 lmhi, lmlo;
  203036. lmlo = lmins & PNG_LOMASK;
  203037. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203038. for (j = 0; j < num_p_filters; j++)
  203039. {
  203040. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  203041. {
  203042. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203043. PNG_WEIGHT_SHIFT;
  203044. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203045. PNG_WEIGHT_SHIFT;
  203046. }
  203047. }
  203048. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203049. PNG_COST_SHIFT;
  203050. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203051. PNG_COST_SHIFT;
  203052. if (lmhi > PNG_HIMASK)
  203053. lmins = PNG_MAXSUM;
  203054. else
  203055. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203056. }
  203057. #endif
  203058. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203059. pp = prev_row + 1; i < bpp; i++)
  203060. {
  203061. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203062. sum += (v < 128) ? v : 256 - v;
  203063. }
  203064. for (lp = row_buf + 1; i < row_bytes; i++)
  203065. {
  203066. v = *dp++ =
  203067. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  203068. sum += (v < 128) ? v : 256 - v;
  203069. if (sum > lmins) /* We are already worse, don't continue. */
  203070. break;
  203071. }
  203072. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203073. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203074. {
  203075. int j;
  203076. png_uint_32 sumhi, sumlo;
  203077. sumlo = sum & PNG_LOMASK;
  203078. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203079. for (j = 0; j < num_p_filters; j++)
  203080. {
  203081. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  203082. {
  203083. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203084. PNG_WEIGHT_SHIFT;
  203085. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203086. PNG_WEIGHT_SHIFT;
  203087. }
  203088. }
  203089. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203090. PNG_COST_SHIFT;
  203091. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203092. PNG_COST_SHIFT;
  203093. if (sumhi > PNG_HIMASK)
  203094. sum = PNG_MAXSUM;
  203095. else
  203096. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203097. }
  203098. #endif
  203099. if (sum < mins)
  203100. {
  203101. mins = sum;
  203102. best_row = png_ptr->avg_row;
  203103. }
  203104. }
  203105. /* Paeth filter */
  203106. if (filter_to_do == PNG_FILTER_PAETH)
  203107. {
  203108. png_bytep rp, dp, pp, cp, lp;
  203109. png_uint_32 i;
  203110. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203111. pp = prev_row + 1; i < bpp; i++)
  203112. {
  203113. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203114. }
  203115. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203116. {
  203117. int a, b, c, pa, pb, pc, p;
  203118. b = *pp++;
  203119. c = *cp++;
  203120. a = *lp++;
  203121. p = b - c;
  203122. pc = a - c;
  203123. #ifdef PNG_USE_ABS
  203124. pa = abs(p);
  203125. pb = abs(pc);
  203126. pc = abs(p + pc);
  203127. #else
  203128. pa = p < 0 ? -p : p;
  203129. pb = pc < 0 ? -pc : pc;
  203130. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203131. #endif
  203132. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203133. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203134. }
  203135. best_row = png_ptr->paeth_row;
  203136. }
  203137. else if (filter_to_do & PNG_FILTER_PAETH)
  203138. {
  203139. png_bytep rp, dp, pp, cp, lp;
  203140. png_uint_32 sum = 0, lmins = mins;
  203141. png_uint_32 i;
  203142. int v;
  203143. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203144. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203145. {
  203146. int j;
  203147. png_uint_32 lmhi, lmlo;
  203148. lmlo = lmins & PNG_LOMASK;
  203149. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203150. for (j = 0; j < num_p_filters; j++)
  203151. {
  203152. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203153. {
  203154. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203155. PNG_WEIGHT_SHIFT;
  203156. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203157. PNG_WEIGHT_SHIFT;
  203158. }
  203159. }
  203160. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203161. PNG_COST_SHIFT;
  203162. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203163. PNG_COST_SHIFT;
  203164. if (lmhi > PNG_HIMASK)
  203165. lmins = PNG_MAXSUM;
  203166. else
  203167. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203168. }
  203169. #endif
  203170. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203171. pp = prev_row + 1; i < bpp; i++)
  203172. {
  203173. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203174. sum += (v < 128) ? v : 256 - v;
  203175. }
  203176. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203177. {
  203178. int a, b, c, pa, pb, pc, p;
  203179. b = *pp++;
  203180. c = *cp++;
  203181. a = *lp++;
  203182. #ifndef PNG_SLOW_PAETH
  203183. p = b - c;
  203184. pc = a - c;
  203185. #ifdef PNG_USE_ABS
  203186. pa = abs(p);
  203187. pb = abs(pc);
  203188. pc = abs(p + pc);
  203189. #else
  203190. pa = p < 0 ? -p : p;
  203191. pb = pc < 0 ? -pc : pc;
  203192. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203193. #endif
  203194. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203195. #else /* PNG_SLOW_PAETH */
  203196. p = a + b - c;
  203197. pa = abs(p - a);
  203198. pb = abs(p - b);
  203199. pc = abs(p - c);
  203200. if (pa <= pb && pa <= pc)
  203201. p = a;
  203202. else if (pb <= pc)
  203203. p = b;
  203204. else
  203205. p = c;
  203206. #endif /* PNG_SLOW_PAETH */
  203207. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203208. sum += (v < 128) ? v : 256 - v;
  203209. if (sum > lmins) /* We are already worse, don't continue. */
  203210. break;
  203211. }
  203212. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203213. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203214. {
  203215. int j;
  203216. png_uint_32 sumhi, sumlo;
  203217. sumlo = sum & PNG_LOMASK;
  203218. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203219. for (j = 0; j < num_p_filters; j++)
  203220. {
  203221. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203222. {
  203223. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203224. PNG_WEIGHT_SHIFT;
  203225. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203226. PNG_WEIGHT_SHIFT;
  203227. }
  203228. }
  203229. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203230. PNG_COST_SHIFT;
  203231. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203232. PNG_COST_SHIFT;
  203233. if (sumhi > PNG_HIMASK)
  203234. sum = PNG_MAXSUM;
  203235. else
  203236. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203237. }
  203238. #endif
  203239. if (sum < mins)
  203240. {
  203241. best_row = png_ptr->paeth_row;
  203242. }
  203243. }
  203244. #endif /* PNG_NO_WRITE_FILTER */
  203245. /* Do the actual writing of the filtered row data from the chosen filter. */
  203246. png_write_filtered_row(png_ptr, best_row);
  203247. #ifndef PNG_NO_WRITE_FILTER
  203248. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203249. /* Save the type of filter we picked this time for future calculations */
  203250. if (png_ptr->num_prev_filters > 0)
  203251. {
  203252. int j;
  203253. for (j = 1; j < num_p_filters; j++)
  203254. {
  203255. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203256. }
  203257. png_ptr->prev_filters[j] = best_row[0];
  203258. }
  203259. #endif
  203260. #endif /* PNG_NO_WRITE_FILTER */
  203261. }
  203262. /* Do the actual writing of a previously filtered row. */
  203263. void /* PRIVATE */
  203264. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203265. {
  203266. png_debug(1, "in png_write_filtered_row\n");
  203267. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203268. /* set up the zlib input buffer */
  203269. png_ptr->zstream.next_in = filtered_row;
  203270. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203271. /* repeat until we have compressed all the data */
  203272. do
  203273. {
  203274. int ret; /* return of zlib */
  203275. /* compress the data */
  203276. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203277. /* check for compression errors */
  203278. if (ret != Z_OK)
  203279. {
  203280. if (png_ptr->zstream.msg != NULL)
  203281. png_error(png_ptr, png_ptr->zstream.msg);
  203282. else
  203283. png_error(png_ptr, "zlib error");
  203284. }
  203285. /* see if it is time to write another IDAT */
  203286. if (!(png_ptr->zstream.avail_out))
  203287. {
  203288. /* write the IDAT and reset the zlib output buffer */
  203289. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203290. png_ptr->zstream.next_out = png_ptr->zbuf;
  203291. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203292. }
  203293. /* repeat until all data has been compressed */
  203294. } while (png_ptr->zstream.avail_in);
  203295. /* swap the current and previous rows */
  203296. if (png_ptr->prev_row != NULL)
  203297. {
  203298. png_bytep tptr;
  203299. tptr = png_ptr->prev_row;
  203300. png_ptr->prev_row = png_ptr->row_buf;
  203301. png_ptr->row_buf = tptr;
  203302. }
  203303. /* finish row - updates counters and flushes zlib if last row */
  203304. png_write_finish_row(png_ptr);
  203305. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203306. png_ptr->flush_rows++;
  203307. if (png_ptr->flush_dist > 0 &&
  203308. png_ptr->flush_rows >= png_ptr->flush_dist)
  203309. {
  203310. png_write_flush(png_ptr);
  203311. }
  203312. #endif
  203313. }
  203314. #endif /* PNG_WRITE_SUPPORTED */
  203315. /*** End of inlined file: pngwutil.c ***/
  203316. #else
  203317. extern "C"
  203318. {
  203319. #include <png.h>
  203320. #include <pngconf.h>
  203321. }
  203322. #endif
  203323. }
  203324. #undef max
  203325. #undef min
  203326. #if JUCE_MSVC
  203327. #pragma warning (pop)
  203328. #endif
  203329. BEGIN_JUCE_NAMESPACE
  203330. using ::calloc;
  203331. using ::malloc;
  203332. using ::free;
  203333. namespace PNGHelpers
  203334. {
  203335. using namespace pnglibNamespace;
  203336. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  203337. {
  203338. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203339. }
  203340. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203341. {
  203342. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203343. }
  203344. struct PNGErrorStruct {};
  203345. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  203346. {
  203347. throw PNGErrorStruct();
  203348. }
  203349. }
  203350. PNGImageFormat::PNGImageFormat() {}
  203351. PNGImageFormat::~PNGImageFormat() {}
  203352. const String PNGImageFormat::getFormatName()
  203353. {
  203354. return "PNG";
  203355. }
  203356. bool PNGImageFormat::canUnderstand (InputStream& in)
  203357. {
  203358. const int bytesNeeded = 4;
  203359. char header [bytesNeeded];
  203360. return in.read (header, bytesNeeded) == bytesNeeded
  203361. && header[1] == 'P'
  203362. && header[2] == 'N'
  203363. && header[3] == 'G';
  203364. }
  203365. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203366. const Image juce_loadWithCoreImage (InputStream& input);
  203367. #endif
  203368. const Image PNGImageFormat::decodeImage (InputStream& in)
  203369. {
  203370. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203371. return juce_loadWithCoreImage (in);
  203372. #else
  203373. using namespace pnglibNamespace;
  203374. Image image;
  203375. png_structp pngReadStruct;
  203376. png_infop pngInfoStruct;
  203377. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203378. if (pngReadStruct != 0)
  203379. {
  203380. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203381. if (pngInfoStruct == 0)
  203382. {
  203383. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203384. return Image::null;
  203385. }
  203386. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203387. // read the header..
  203388. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203389. png_uint_32 width, height;
  203390. int bitDepth, colorType, interlaceType;
  203391. png_read_info (pngReadStruct, pngInfoStruct);
  203392. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203393. &width, &height,
  203394. &bitDepth, &colorType,
  203395. &interlaceType, 0, 0);
  203396. if (bitDepth == 16)
  203397. png_set_strip_16 (pngReadStruct);
  203398. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203399. png_set_expand (pngReadStruct);
  203400. if (bitDepth < 8)
  203401. png_set_expand (pngReadStruct);
  203402. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203403. png_set_expand (pngReadStruct);
  203404. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203405. png_set_gray_to_rgb (pngReadStruct);
  203406. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203407. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203408. || pngInfoStruct->num_trans > 0;
  203409. // Load the image into a temp buffer in the pnglib format..
  203410. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203411. {
  203412. HeapBlock <png_bytep> rows (height);
  203413. for (int y = (int) height; --y >= 0;)
  203414. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203415. png_read_image (pngReadStruct, rows);
  203416. png_read_end (pngReadStruct, pngInfoStruct);
  203417. }
  203418. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203419. // now convert the data to a juce image format..
  203420. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203421. (int) width, (int) height, hasAlphaChan);
  203422. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  203423. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203424. const Image::BitmapData destData (image, true);
  203425. uint8* srcRow = tempBuffer;
  203426. uint8* destRow = destData.data;
  203427. for (int y = 0; y < (int) height; ++y)
  203428. {
  203429. const uint8* src = srcRow;
  203430. srcRow += (width << 2);
  203431. uint8* dest = destRow;
  203432. destRow += destData.lineStride;
  203433. if (hasAlphaChan)
  203434. {
  203435. for (int i = (int) width; --i >= 0;)
  203436. {
  203437. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203438. ((PixelARGB*) dest)->premultiply();
  203439. dest += destData.pixelStride;
  203440. src += 4;
  203441. }
  203442. }
  203443. else
  203444. {
  203445. for (int i = (int) width; --i >= 0;)
  203446. {
  203447. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203448. dest += destData.pixelStride;
  203449. src += 4;
  203450. }
  203451. }
  203452. }
  203453. }
  203454. return image;
  203455. #endif
  203456. }
  203457. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203458. {
  203459. using namespace pnglibNamespace;
  203460. const int width = image.getWidth();
  203461. const int height = image.getHeight();
  203462. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203463. if (pngWriteStruct == 0)
  203464. return false;
  203465. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203466. if (pngInfoStruct == 0)
  203467. {
  203468. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203469. return false;
  203470. }
  203471. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203472. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203473. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203474. : PNG_COLOR_TYPE_RGB,
  203475. PNG_INTERLACE_NONE,
  203476. PNG_COMPRESSION_TYPE_BASE,
  203477. PNG_FILTER_TYPE_BASE);
  203478. HeapBlock <uint8> rowData (width * 4);
  203479. png_color_8 sig_bit;
  203480. sig_bit.red = 8;
  203481. sig_bit.green = 8;
  203482. sig_bit.blue = 8;
  203483. sig_bit.alpha = 8;
  203484. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203485. png_write_info (pngWriteStruct, pngInfoStruct);
  203486. png_set_shift (pngWriteStruct, &sig_bit);
  203487. png_set_packing (pngWriteStruct);
  203488. const Image::BitmapData srcData (image, false);
  203489. for (int y = 0; y < height; ++y)
  203490. {
  203491. uint8* dst = rowData;
  203492. const uint8* src = srcData.getLinePointer (y);
  203493. if (image.hasAlphaChannel())
  203494. {
  203495. for (int i = width; --i >= 0;)
  203496. {
  203497. PixelARGB p (*(const PixelARGB*) src);
  203498. p.unpremultiply();
  203499. *dst++ = p.getRed();
  203500. *dst++ = p.getGreen();
  203501. *dst++ = p.getBlue();
  203502. *dst++ = p.getAlpha();
  203503. src += srcData.pixelStride;
  203504. }
  203505. }
  203506. else
  203507. {
  203508. for (int i = width; --i >= 0;)
  203509. {
  203510. *dst++ = ((const PixelRGB*) src)->getRed();
  203511. *dst++ = ((const PixelRGB*) src)->getGreen();
  203512. *dst++ = ((const PixelRGB*) src)->getBlue();
  203513. src += srcData.pixelStride;
  203514. }
  203515. }
  203516. png_bytep rowPtr = rowData;
  203517. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203518. }
  203519. png_write_end (pngWriteStruct, pngInfoStruct);
  203520. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203521. out.flush();
  203522. return true;
  203523. }
  203524. END_JUCE_NAMESPACE
  203525. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203526. #endif
  203527. //==============================================================================
  203528. #if JUCE_BUILD_NATIVE
  203529. // Non-public headers that are needed by more than one platform must be included
  203530. // before the platform-specific sections..
  203531. BEGIN_JUCE_NAMESPACE
  203532. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203533. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203534. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203535. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203536. /**
  203537. Helper class that takes chunks of incoming midi bytes, packages them into
  203538. messages, and dispatches them to a midi callback.
  203539. */
  203540. class MidiDataConcatenator
  203541. {
  203542. public:
  203543. MidiDataConcatenator (const int initialBufferSize)
  203544. : pendingData (initialBufferSize),
  203545. pendingBytes (0), pendingDataTime (0)
  203546. {
  203547. }
  203548. void reset()
  203549. {
  203550. pendingBytes = 0;
  203551. pendingDataTime = 0;
  203552. }
  203553. void pushMidiData (const void* data, int numBytes, double time,
  203554. MidiInput* input, MidiInputCallback& callback)
  203555. {
  203556. const uint8* d = static_cast <const uint8*> (data);
  203557. while (numBytes > 0)
  203558. {
  203559. if (pendingBytes > 0 || d[0] == 0xf0)
  203560. {
  203561. processSysex (d, numBytes, time, input, callback);
  203562. }
  203563. else
  203564. {
  203565. int used = 0;
  203566. const MidiMessage m (d, numBytes, used, 0, time);
  203567. if (used <= 0)
  203568. break; // malformed message..
  203569. callback.handleIncomingMidiMessage (input, m);
  203570. numBytes -= used;
  203571. d += used;
  203572. }
  203573. }
  203574. }
  203575. private:
  203576. void processSysex (const uint8*& d, int& numBytes, double time,
  203577. MidiInput* input, MidiInputCallback& callback)
  203578. {
  203579. if (*d == 0xf0)
  203580. {
  203581. pendingBytes = 0;
  203582. pendingDataTime = time;
  203583. }
  203584. pendingData.ensureSize (pendingBytes + numBytes, false);
  203585. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203586. uint8* dest = totalMessage + pendingBytes;
  203587. do
  203588. {
  203589. if (pendingBytes > 0 && *d >= 0x80)
  203590. {
  203591. if (*d >= 0xfa || *d == 0xf8)
  203592. {
  203593. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203594. ++d;
  203595. --numBytes;
  203596. }
  203597. else
  203598. {
  203599. if (*d == 0xf7)
  203600. {
  203601. *dest++ = *d++;
  203602. pendingBytes++;
  203603. --numBytes;
  203604. }
  203605. break;
  203606. }
  203607. }
  203608. else
  203609. {
  203610. *dest++ = *d++;
  203611. pendingBytes++;
  203612. --numBytes;
  203613. }
  203614. }
  203615. while (numBytes > 0);
  203616. if (pendingBytes > 0)
  203617. {
  203618. if (totalMessage [pendingBytes - 1] == 0xf7)
  203619. {
  203620. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203621. pendingBytes = 0;
  203622. }
  203623. else
  203624. {
  203625. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203626. }
  203627. }
  203628. }
  203629. MemoryBlock pendingData;
  203630. int pendingBytes;
  203631. double pendingDataTime;
  203632. JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator);
  203633. };
  203634. #endif
  203635. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203636. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203637. END_JUCE_NAMESPACE
  203638. #if JUCE_WINDOWS
  203639. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203640. /*
  203641. This file wraps together all the win32-specific code, so that
  203642. we can include all the native headers just once, and compile all our
  203643. platform-specific stuff in one big lump, keeping it out of the way of
  203644. the rest of the codebase.
  203645. */
  203646. #if JUCE_WINDOWS
  203647. #undef JUCE_BUILD_NATIVE
  203648. #define JUCE_BUILD_NATIVE 1
  203649. BEGIN_JUCE_NAMESPACE
  203650. #define JUCE_INCLUDED_FILE 1
  203651. // Now include the actual code files..
  203652. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203653. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203654. // compiled on its own).
  203655. #if JUCE_INCLUDED_FILE
  203656. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203657. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203658. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203659. #ifndef DOXYGEN
  203660. // use with DynamicLibraryLoader to simplify importing functions
  203661. //
  203662. // functionName: function to import
  203663. // localFunctionName: name you want to use to actually call it (must be different)
  203664. // returnType: the return type
  203665. // object: the DynamicLibraryLoader to use
  203666. // params: list of params (bracketed)
  203667. //
  203668. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203669. typedef returnType (WINAPI *type##localFunctionName) params; \
  203670. type##localFunctionName localFunctionName \
  203671. = (type##localFunctionName)object.findProcAddress (#functionName);
  203672. // loads and unloads a DLL automatically
  203673. class JUCE_API DynamicLibraryLoader
  203674. {
  203675. public:
  203676. DynamicLibraryLoader (const String& name = String::empty);
  203677. ~DynamicLibraryLoader();
  203678. bool load (const String& libraryName);
  203679. void* findProcAddress (const String& functionName);
  203680. private:
  203681. void* libHandle;
  203682. };
  203683. #endif
  203684. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203685. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203686. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203687. : libHandle (0)
  203688. {
  203689. load (name);
  203690. }
  203691. DynamicLibraryLoader::~DynamicLibraryLoader()
  203692. {
  203693. load (String::empty);
  203694. }
  203695. bool DynamicLibraryLoader::load (const String& name)
  203696. {
  203697. FreeLibrary ((HMODULE) libHandle);
  203698. libHandle = name.isNotEmpty() ? LoadLibrary (name) : 0;
  203699. return libHandle != 0;
  203700. }
  203701. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203702. {
  203703. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203704. }
  203705. #endif
  203706. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203707. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203708. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203709. // compiled on its own).
  203710. #if JUCE_INCLUDED_FILE
  203711. void Logger::outputDebugString (const String& text)
  203712. {
  203713. OutputDebugString (text + "\n");
  203714. }
  203715. static int64 hiResTicksPerSecond;
  203716. static double hiResTicksScaleFactor;
  203717. #if JUCE_USE_INTRINSICS
  203718. // CPU info functions using intrinsics...
  203719. #pragma intrinsic (__cpuid)
  203720. #pragma intrinsic (__rdtsc)
  203721. const String SystemStats::getCpuVendor()
  203722. {
  203723. int info [4];
  203724. __cpuid (info, 0);
  203725. char v [12];
  203726. memcpy (v, info + 1, 4);
  203727. memcpy (v + 4, info + 3, 4);
  203728. memcpy (v + 8, info + 2, 4);
  203729. return String (v, 12);
  203730. }
  203731. #else
  203732. // CPU info functions using old fashioned inline asm...
  203733. static void juce_getCpuVendor (char* const v)
  203734. {
  203735. int vendor[4];
  203736. zeromem (vendor, 16);
  203737. #ifdef JUCE_64BIT
  203738. #else
  203739. #ifndef __MINGW32__
  203740. __try
  203741. #endif
  203742. {
  203743. #if JUCE_GCC
  203744. unsigned int dummy = 0;
  203745. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203746. #else
  203747. __asm
  203748. {
  203749. mov eax, 0
  203750. cpuid
  203751. mov [vendor], ebx
  203752. mov [vendor + 4], edx
  203753. mov [vendor + 8], ecx
  203754. }
  203755. #endif
  203756. }
  203757. #ifndef __MINGW32__
  203758. __except (EXCEPTION_EXECUTE_HANDLER)
  203759. {
  203760. *v = 0;
  203761. }
  203762. #endif
  203763. #endif
  203764. memcpy (v, vendor, 16);
  203765. }
  203766. const String SystemStats::getCpuVendor()
  203767. {
  203768. char v [16];
  203769. juce_getCpuVendor (v);
  203770. return String (v, 16);
  203771. }
  203772. #endif
  203773. void SystemStats::initialiseStats()
  203774. {
  203775. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203776. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203777. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203778. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203779. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203780. #else
  203781. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203782. #endif
  203783. {
  203784. SYSTEM_INFO systemInfo;
  203785. GetSystemInfo (&systemInfo);
  203786. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203787. }
  203788. LARGE_INTEGER f;
  203789. QueryPerformanceFrequency (&f);
  203790. hiResTicksPerSecond = f.QuadPart;
  203791. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203792. String s (SystemStats::getJUCEVersion());
  203793. const MMRESULT res = timeBeginPeriod (1);
  203794. (void) res;
  203795. jassert (res == TIMERR_NOERROR);
  203796. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203797. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203798. #endif
  203799. }
  203800. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203801. {
  203802. OSVERSIONINFO info;
  203803. info.dwOSVersionInfoSize = sizeof (info);
  203804. GetVersionEx (&info);
  203805. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203806. {
  203807. switch (info.dwMajorVersion)
  203808. {
  203809. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203810. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203811. default: jassertfalse; break; // !! not a supported OS!
  203812. }
  203813. }
  203814. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203815. {
  203816. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203817. return Win98;
  203818. }
  203819. return UnknownOS;
  203820. }
  203821. const String SystemStats::getOperatingSystemName()
  203822. {
  203823. const char* name = "Unknown OS";
  203824. switch (getOperatingSystemType())
  203825. {
  203826. case Windows7: name = "Windows 7"; break;
  203827. case WinVista: name = "Windows Vista"; break;
  203828. case WinXP: name = "Windows XP"; break;
  203829. case Win2000: name = "Windows 2000"; break;
  203830. case Win98: name = "Windows 98"; break;
  203831. default: jassertfalse; break; // !! new type of OS?
  203832. }
  203833. return name;
  203834. }
  203835. bool SystemStats::isOperatingSystem64Bit()
  203836. {
  203837. #ifdef _WIN64
  203838. return true;
  203839. #else
  203840. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203841. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203842. BOOL isWow64 = FALSE;
  203843. return (fnIsWow64Process != 0)
  203844. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203845. && (isWow64 != FALSE);
  203846. #endif
  203847. }
  203848. int SystemStats::getMemorySizeInMegabytes()
  203849. {
  203850. MEMORYSTATUSEX mem;
  203851. mem.dwLength = sizeof (mem);
  203852. GlobalMemoryStatusEx (&mem);
  203853. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203854. }
  203855. uint32 juce_millisecondsSinceStartup() throw()
  203856. {
  203857. return (uint32) timeGetTime();
  203858. }
  203859. int64 Time::getHighResolutionTicks() throw()
  203860. {
  203861. LARGE_INTEGER ticks;
  203862. QueryPerformanceCounter (&ticks);
  203863. const int64 mainCounterAsHiResTicks = (juce_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000;
  203864. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203865. // fix for a very obscure PCI hardware bug that can make the counter
  203866. // sometimes jump forwards by a few seconds..
  203867. static int64 hiResTicksOffset = 0;
  203868. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203869. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203870. hiResTicksOffset = newOffset;
  203871. return ticks.QuadPart + hiResTicksOffset;
  203872. }
  203873. double Time::getMillisecondCounterHiRes() throw()
  203874. {
  203875. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203876. }
  203877. int64 Time::getHighResolutionTicksPerSecond() throw()
  203878. {
  203879. return hiResTicksPerSecond;
  203880. }
  203881. static int64 juce_getClockCycleCounter() throw()
  203882. {
  203883. #if JUCE_USE_INTRINSICS
  203884. // MS intrinsics version...
  203885. return __rdtsc();
  203886. #elif JUCE_GCC
  203887. // GNU inline asm version...
  203888. unsigned int hi = 0, lo = 0;
  203889. __asm__ __volatile__ (
  203890. "xor %%eax, %%eax \n\
  203891. xor %%edx, %%edx \n\
  203892. rdtsc \n\
  203893. movl %%eax, %[lo] \n\
  203894. movl %%edx, %[hi]"
  203895. :
  203896. : [hi] "m" (hi),
  203897. [lo] "m" (lo)
  203898. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203899. return (int64) ((((uint64) hi) << 32) | lo);
  203900. #else
  203901. // MSVC inline asm version...
  203902. unsigned int hi = 0, lo = 0;
  203903. __asm
  203904. {
  203905. xor eax, eax
  203906. xor edx, edx
  203907. rdtsc
  203908. mov lo, eax
  203909. mov hi, edx
  203910. }
  203911. return (int64) ((((uint64) hi) << 32) | lo);
  203912. #endif
  203913. }
  203914. int SystemStats::getCpuSpeedInMegaherz()
  203915. {
  203916. const int64 cycles = juce_getClockCycleCounter();
  203917. const uint32 millis = Time::getMillisecondCounter();
  203918. int lastResult = 0;
  203919. for (;;)
  203920. {
  203921. int n = 1000000;
  203922. while (--n > 0) {}
  203923. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203924. const int64 cyclesNow = juce_getClockCycleCounter();
  203925. if (millisElapsed > 80)
  203926. {
  203927. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203928. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203929. return newResult;
  203930. lastResult = newResult;
  203931. }
  203932. }
  203933. }
  203934. bool Time::setSystemTimeToThisTime() const
  203935. {
  203936. SYSTEMTIME st;
  203937. st.wDayOfWeek = 0;
  203938. st.wYear = (WORD) getYear();
  203939. st.wMonth = (WORD) (getMonth() + 1);
  203940. st.wDay = (WORD) getDayOfMonth();
  203941. st.wHour = (WORD) getHours();
  203942. st.wMinute = (WORD) getMinutes();
  203943. st.wSecond = (WORD) getSeconds();
  203944. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203945. // do this twice because of daylight saving conversion problems - the
  203946. // first one sets it up, the second one kicks it in.
  203947. return SetLocalTime (&st) != 0
  203948. && SetLocalTime (&st) != 0;
  203949. }
  203950. int SystemStats::getPageSize()
  203951. {
  203952. SYSTEM_INFO systemInfo;
  203953. GetSystemInfo (&systemInfo);
  203954. return systemInfo.dwPageSize;
  203955. }
  203956. const String SystemStats::getLogonName()
  203957. {
  203958. TCHAR text [256];
  203959. DWORD len = numElementsInArray (text) - 2;
  203960. zerostruct (text);
  203961. GetUserName (text, &len);
  203962. return String (text, len);
  203963. }
  203964. const String SystemStats::getFullUserName()
  203965. {
  203966. return getLogonName();
  203967. }
  203968. #endif
  203969. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203970. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203971. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203972. // compiled on its own).
  203973. #if JUCE_INCLUDED_FILE
  203974. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203975. extern HWND juce_messageWindowHandle;
  203976. #endif
  203977. #if ! JUCE_USE_INTRINSICS
  203978. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203979. // older ones we have to actually call the ops as win32 functions..
  203980. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203981. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203982. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203983. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203984. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203985. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203986. {
  203987. jassertfalse; // This operation isn't available in old MS compiler versions!
  203988. __int64 oldValue = *value;
  203989. if (oldValue == valueToCompare)
  203990. *value = newValue;
  203991. return oldValue;
  203992. }
  203993. #endif
  203994. CriticalSection::CriticalSection() throw()
  203995. {
  203996. // (just to check the MS haven't changed this structure and broken things...)
  203997. #if JUCE_VC7_OR_EARLIER
  203998. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203999. #else
  204000. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  204001. #endif
  204002. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  204003. }
  204004. CriticalSection::~CriticalSection() throw()
  204005. {
  204006. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  204007. }
  204008. void CriticalSection::enter() const throw()
  204009. {
  204010. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  204011. }
  204012. bool CriticalSection::tryEnter() const throw()
  204013. {
  204014. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  204015. }
  204016. void CriticalSection::exit() const throw()
  204017. {
  204018. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  204019. }
  204020. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  204021. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  204022. {
  204023. }
  204024. WaitableEvent::~WaitableEvent() throw()
  204025. {
  204026. CloseHandle (internal);
  204027. }
  204028. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  204029. {
  204030. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  204031. }
  204032. void WaitableEvent::signal() const throw()
  204033. {
  204034. SetEvent (internal);
  204035. }
  204036. void WaitableEvent::reset() const throw()
  204037. {
  204038. ResetEvent (internal);
  204039. }
  204040. void JUCE_API juce_threadEntryPoint (void*);
  204041. static unsigned int __stdcall threadEntryProc (void* userData)
  204042. {
  204043. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204044. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  204045. GetCurrentThreadId(), TRUE);
  204046. #endif
  204047. juce_threadEntryPoint (userData);
  204048. _endthreadex (0);
  204049. return 0;
  204050. }
  204051. void Thread::launchThread()
  204052. {
  204053. unsigned int newThreadId;
  204054. threadHandle_ = (void*) _beginthreadex (0, 0, &threadEntryProc, this, 0, &newThreadId);
  204055. threadId_ = (ThreadID) newThreadId;
  204056. }
  204057. void Thread::closeThreadHandle()
  204058. {
  204059. CloseHandle ((HANDLE) threadHandle_);
  204060. threadId_ = 0;
  204061. threadHandle_ = 0;
  204062. }
  204063. void Thread::killThread()
  204064. {
  204065. if (threadHandle_ != 0)
  204066. {
  204067. #if JUCE_DEBUG
  204068. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  204069. #endif
  204070. TerminateThread (threadHandle_, 0);
  204071. }
  204072. }
  204073. void Thread::setCurrentThreadName (const String& name)
  204074. {
  204075. #if JUCE_DEBUG && JUCE_MSVC
  204076. struct
  204077. {
  204078. DWORD dwType;
  204079. LPCSTR szName;
  204080. DWORD dwThreadID;
  204081. DWORD dwFlags;
  204082. } info;
  204083. info.dwType = 0x1000;
  204084. info.szName = name.toCString();
  204085. info.dwThreadID = GetCurrentThreadId();
  204086. info.dwFlags = 0;
  204087. __try
  204088. {
  204089. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  204090. }
  204091. __except (EXCEPTION_CONTINUE_EXECUTION)
  204092. {}
  204093. #else
  204094. (void) name;
  204095. #endif
  204096. }
  204097. Thread::ThreadID Thread::getCurrentThreadId()
  204098. {
  204099. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  204100. }
  204101. bool Thread::setThreadPriority (void* handle, int priority)
  204102. {
  204103. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  204104. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  204105. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  204106. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  204107. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  204108. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  204109. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  204110. if (handle == 0)
  204111. handle = GetCurrentThread();
  204112. return SetThreadPriority (handle, pri) != FALSE;
  204113. }
  204114. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  204115. {
  204116. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  204117. }
  204118. struct SleepEvent
  204119. {
  204120. SleepEvent()
  204121. : handle (CreateEvent (0, 0, 0,
  204122. #if JUCE_DEBUG
  204123. _T("Juce Sleep Event")))
  204124. #else
  204125. 0))
  204126. #endif
  204127. {
  204128. }
  204129. HANDLE handle;
  204130. };
  204131. static SleepEvent sleepEvent;
  204132. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  204133. {
  204134. if (millisecs >= 10)
  204135. {
  204136. Sleep (millisecs);
  204137. }
  204138. else
  204139. {
  204140. // unlike Sleep() this is guaranteed to return to the current thread after
  204141. // the time expires, so we'll use this for short waits, which are more likely
  204142. // to need to be accurate
  204143. WaitForSingleObject (sleepEvent.handle, millisecs);
  204144. }
  204145. }
  204146. void Thread::yield()
  204147. {
  204148. Sleep (0);
  204149. }
  204150. static int lastProcessPriority = -1;
  204151. // called by WindowDriver because Windows does wierd things to process priority
  204152. // when you swap apps, and this forces an update when the app is brought to the front.
  204153. void juce_repeatLastProcessPriority()
  204154. {
  204155. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  204156. {
  204157. DWORD p;
  204158. switch (lastProcessPriority)
  204159. {
  204160. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  204161. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  204162. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  204163. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  204164. default: jassertfalse; return; // bad priority value
  204165. }
  204166. SetPriorityClass (GetCurrentProcess(), p);
  204167. }
  204168. }
  204169. void Process::setPriority (ProcessPriority prior)
  204170. {
  204171. if (lastProcessPriority != (int) prior)
  204172. {
  204173. lastProcessPriority = (int) prior;
  204174. juce_repeatLastProcessPriority();
  204175. }
  204176. }
  204177. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  204178. {
  204179. return IsDebuggerPresent() != FALSE;
  204180. }
  204181. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  204182. {
  204183. return juce_isRunningUnderDebugger();
  204184. }
  204185. void Process::raisePrivilege()
  204186. {
  204187. jassertfalse; // xxx not implemented
  204188. }
  204189. void Process::lowerPrivilege()
  204190. {
  204191. jassertfalse; // xxx not implemented
  204192. }
  204193. void Process::terminate()
  204194. {
  204195. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204196. _CrtDumpMemoryLeaks();
  204197. #endif
  204198. // bullet in the head in case there's a problem shutting down..
  204199. ExitProcess (0);
  204200. }
  204201. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  204202. {
  204203. void* result = 0;
  204204. JUCE_TRY
  204205. {
  204206. result = LoadLibrary (name);
  204207. }
  204208. JUCE_CATCH_ALL
  204209. return result;
  204210. }
  204211. void PlatformUtilities::freeDynamicLibrary (void* h)
  204212. {
  204213. JUCE_TRY
  204214. {
  204215. if (h != 0)
  204216. FreeLibrary ((HMODULE) h);
  204217. }
  204218. JUCE_CATCH_ALL
  204219. }
  204220. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204221. {
  204222. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  204223. }
  204224. class InterProcessLock::Pimpl
  204225. {
  204226. public:
  204227. Pimpl (const String& name, const int timeOutMillisecs)
  204228. : handle (0), refCount (1)
  204229. {
  204230. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  204231. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204232. {
  204233. if (timeOutMillisecs == 0)
  204234. {
  204235. close();
  204236. return;
  204237. }
  204238. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204239. {
  204240. case WAIT_OBJECT_0:
  204241. case WAIT_ABANDONED:
  204242. break;
  204243. case WAIT_TIMEOUT:
  204244. default:
  204245. close();
  204246. break;
  204247. }
  204248. }
  204249. }
  204250. ~Pimpl()
  204251. {
  204252. close();
  204253. }
  204254. void close()
  204255. {
  204256. if (handle != 0)
  204257. {
  204258. ReleaseMutex (handle);
  204259. CloseHandle (handle);
  204260. handle = 0;
  204261. }
  204262. }
  204263. HANDLE handle;
  204264. int refCount;
  204265. };
  204266. InterProcessLock::InterProcessLock (const String& name_)
  204267. : name (name_)
  204268. {
  204269. }
  204270. InterProcessLock::~InterProcessLock()
  204271. {
  204272. }
  204273. bool InterProcessLock::enter (const int timeOutMillisecs)
  204274. {
  204275. const ScopedLock sl (lock);
  204276. if (pimpl == 0)
  204277. {
  204278. pimpl = new Pimpl (name, timeOutMillisecs);
  204279. if (pimpl->handle == 0)
  204280. pimpl = 0;
  204281. }
  204282. else
  204283. {
  204284. pimpl->refCount++;
  204285. }
  204286. return pimpl != 0;
  204287. }
  204288. void InterProcessLock::exit()
  204289. {
  204290. const ScopedLock sl (lock);
  204291. // Trying to release the lock too many times!
  204292. jassert (pimpl != 0);
  204293. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204294. pimpl = 0;
  204295. }
  204296. #endif
  204297. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204298. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204299. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204300. // compiled on its own).
  204301. #if JUCE_INCLUDED_FILE
  204302. #ifndef CSIDL_MYMUSIC
  204303. #define CSIDL_MYMUSIC 0x000d
  204304. #endif
  204305. #ifndef CSIDL_MYVIDEO
  204306. #define CSIDL_MYVIDEO 0x000e
  204307. #endif
  204308. #ifndef INVALID_FILE_ATTRIBUTES
  204309. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204310. #endif
  204311. namespace WindowsFileHelpers
  204312. {
  204313. int64 fileTimeToTime (const FILETIME* const ft)
  204314. {
  204315. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204316. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204317. }
  204318. void timeToFileTime (const int64 time, FILETIME* const ft)
  204319. {
  204320. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204321. }
  204322. const String getDriveFromPath (const String& path)
  204323. {
  204324. if (path.isNotEmpty() && path[1] == ':')
  204325. return path.substring (0, 2) + '\\';
  204326. return path;
  204327. }
  204328. int64 getDiskSpaceInfo (const String& path, const bool total)
  204329. {
  204330. ULARGE_INTEGER spc, tot, totFree;
  204331. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204332. return total ? (int64) tot.QuadPart
  204333. : (int64) spc.QuadPart;
  204334. return 0;
  204335. }
  204336. unsigned int getWindowsDriveType (const String& path)
  204337. {
  204338. return GetDriveType (getDriveFromPath (path));
  204339. }
  204340. const File getSpecialFolderPath (int type)
  204341. {
  204342. WCHAR path [MAX_PATH + 256];
  204343. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204344. return File (String (path));
  204345. return File::nonexistent;
  204346. }
  204347. }
  204348. const juce_wchar File::separator = '\\';
  204349. const String File::separatorString ("\\");
  204350. bool File::exists() const
  204351. {
  204352. return fullPath.isNotEmpty()
  204353. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204354. }
  204355. bool File::existsAsFile() const
  204356. {
  204357. return fullPath.isNotEmpty()
  204358. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204359. }
  204360. bool File::isDirectory() const
  204361. {
  204362. const DWORD attr = GetFileAttributes (fullPath);
  204363. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204364. }
  204365. bool File::hasWriteAccess() const
  204366. {
  204367. if (exists())
  204368. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204369. // on windows, it seems that even read-only directories can still be written into,
  204370. // so checking the parent directory's permissions would return the wrong result..
  204371. return true;
  204372. }
  204373. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204374. {
  204375. DWORD attr = GetFileAttributes (fullPath);
  204376. if (attr == INVALID_FILE_ATTRIBUTES)
  204377. return false;
  204378. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204379. return true;
  204380. if (shouldBeReadOnly)
  204381. attr |= FILE_ATTRIBUTE_READONLY;
  204382. else
  204383. attr &= ~FILE_ATTRIBUTE_READONLY;
  204384. return SetFileAttributes (fullPath, attr) != FALSE;
  204385. }
  204386. bool File::isHidden() const
  204387. {
  204388. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204389. }
  204390. bool File::deleteFile() const
  204391. {
  204392. if (! exists())
  204393. return true;
  204394. else if (isDirectory())
  204395. return RemoveDirectory (fullPath) != 0;
  204396. else
  204397. return DeleteFile (fullPath) != 0;
  204398. }
  204399. bool File::moveToTrash() const
  204400. {
  204401. if (! exists())
  204402. return true;
  204403. SHFILEOPSTRUCT fos;
  204404. zerostruct (fos);
  204405. // The string we pass in must be double null terminated..
  204406. String doubleNullTermPath (getFullPathName() + " ");
  204407. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204408. p [getFullPathName().length()] = 0;
  204409. fos.wFunc = FO_DELETE;
  204410. fos.pFrom = p;
  204411. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204412. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204413. return SHFileOperation (&fos) == 0;
  204414. }
  204415. bool File::copyInternal (const File& dest) const
  204416. {
  204417. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204418. }
  204419. bool File::moveInternal (const File& dest) const
  204420. {
  204421. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204422. }
  204423. void File::createDirectoryInternal (const String& fileName) const
  204424. {
  204425. CreateDirectory (fileName, 0);
  204426. }
  204427. int64 juce_fileSetPosition (void* handle, int64 pos)
  204428. {
  204429. LARGE_INTEGER li;
  204430. li.QuadPart = pos;
  204431. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204432. return li.QuadPart;
  204433. }
  204434. void FileInputStream::openHandle()
  204435. {
  204436. totalSize = file.getSize();
  204437. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204438. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204439. if (h != INVALID_HANDLE_VALUE)
  204440. fileHandle = (void*) h;
  204441. }
  204442. void FileInputStream::closeHandle()
  204443. {
  204444. CloseHandle ((HANDLE) fileHandle);
  204445. }
  204446. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204447. {
  204448. if (fileHandle != 0)
  204449. {
  204450. DWORD actualNum = 0;
  204451. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204452. return (size_t) actualNum;
  204453. }
  204454. return 0;
  204455. }
  204456. void FileOutputStream::openHandle()
  204457. {
  204458. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204459. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204460. if (h != INVALID_HANDLE_VALUE)
  204461. {
  204462. LARGE_INTEGER li;
  204463. li.QuadPart = 0;
  204464. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204465. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204466. {
  204467. fileHandle = (void*) h;
  204468. currentPosition = li.QuadPart;
  204469. }
  204470. }
  204471. }
  204472. void FileOutputStream::closeHandle()
  204473. {
  204474. CloseHandle ((HANDLE) fileHandle);
  204475. }
  204476. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204477. {
  204478. if (fileHandle != 0)
  204479. {
  204480. DWORD actualNum = 0;
  204481. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204482. return (int) actualNum;
  204483. }
  204484. return 0;
  204485. }
  204486. void FileOutputStream::flushInternal()
  204487. {
  204488. if (fileHandle != 0)
  204489. FlushFileBuffers ((HANDLE) fileHandle);
  204490. }
  204491. int64 File::getSize() const
  204492. {
  204493. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204494. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204495. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204496. return 0;
  204497. }
  204498. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204499. {
  204500. using namespace WindowsFileHelpers;
  204501. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204502. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204503. {
  204504. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204505. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204506. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204507. }
  204508. else
  204509. {
  204510. creationTime = accessTime = modificationTime = 0;
  204511. }
  204512. }
  204513. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204514. {
  204515. using namespace WindowsFileHelpers;
  204516. bool ok = false;
  204517. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204518. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204519. if (h != INVALID_HANDLE_VALUE)
  204520. {
  204521. FILETIME m, a, c;
  204522. timeToFileTime (modificationTime, &m);
  204523. timeToFileTime (accessTime, &a);
  204524. timeToFileTime (creationTime, &c);
  204525. ok = SetFileTime (h,
  204526. creationTime > 0 ? &c : 0,
  204527. accessTime > 0 ? &a : 0,
  204528. modificationTime > 0 ? &m : 0) != 0;
  204529. CloseHandle (h);
  204530. }
  204531. return ok;
  204532. }
  204533. void File::findFileSystemRoots (Array<File>& destArray)
  204534. {
  204535. TCHAR buffer [2048];
  204536. buffer[0] = 0;
  204537. buffer[1] = 0;
  204538. GetLogicalDriveStrings (2048, buffer);
  204539. const TCHAR* n = buffer;
  204540. StringArray roots;
  204541. while (*n != 0)
  204542. {
  204543. roots.add (String (n));
  204544. while (*n++ != 0)
  204545. {}
  204546. }
  204547. roots.sort (true);
  204548. for (int i = 0; i < roots.size(); ++i)
  204549. destArray.add (roots [i]);
  204550. }
  204551. const String File::getVolumeLabel() const
  204552. {
  204553. TCHAR dest[64];
  204554. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204555. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204556. dest[0] = 0;
  204557. return dest;
  204558. }
  204559. int File::getVolumeSerialNumber() const
  204560. {
  204561. TCHAR dest[64];
  204562. DWORD serialNum;
  204563. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204564. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204565. return 0;
  204566. return (int) serialNum;
  204567. }
  204568. int64 File::getBytesFreeOnVolume() const
  204569. {
  204570. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204571. }
  204572. int64 File::getVolumeTotalSize() const
  204573. {
  204574. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204575. }
  204576. bool File::isOnCDRomDrive() const
  204577. {
  204578. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204579. }
  204580. bool File::isOnHardDisk() const
  204581. {
  204582. if (fullPath.isEmpty())
  204583. return false;
  204584. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204585. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204586. return n != DRIVE_REMOVABLE;
  204587. else
  204588. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204589. }
  204590. bool File::isOnRemovableDrive() const
  204591. {
  204592. if (fullPath.isEmpty())
  204593. return false;
  204594. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204595. return n == DRIVE_CDROM
  204596. || n == DRIVE_REMOTE
  204597. || n == DRIVE_REMOVABLE
  204598. || n == DRIVE_RAMDISK;
  204599. }
  204600. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204601. {
  204602. int csidlType = 0;
  204603. switch (type)
  204604. {
  204605. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204606. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204607. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204608. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204609. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204610. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204611. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204612. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204613. case tempDirectory:
  204614. {
  204615. WCHAR dest [2048];
  204616. dest[0] = 0;
  204617. GetTempPath (numElementsInArray (dest), dest);
  204618. return File (String (dest));
  204619. }
  204620. case invokedExecutableFile:
  204621. case currentExecutableFile:
  204622. case currentApplicationFile:
  204623. {
  204624. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204625. WCHAR dest [MAX_PATH + 256];
  204626. dest[0] = 0;
  204627. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204628. return File (String (dest));
  204629. }
  204630. case hostApplicationPath:
  204631. {
  204632. WCHAR dest [MAX_PATH + 256];
  204633. dest[0] = 0;
  204634. GetModuleFileName (0, dest, numElementsInArray (dest));
  204635. return File (String (dest));
  204636. }
  204637. default:
  204638. jassertfalse; // unknown type?
  204639. return File::nonexistent;
  204640. }
  204641. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204642. }
  204643. const File File::getCurrentWorkingDirectory()
  204644. {
  204645. WCHAR dest [MAX_PATH + 256];
  204646. dest[0] = 0;
  204647. GetCurrentDirectory (numElementsInArray (dest), dest);
  204648. return File (String (dest));
  204649. }
  204650. bool File::setAsCurrentWorkingDirectory() const
  204651. {
  204652. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204653. }
  204654. const String File::getVersion() const
  204655. {
  204656. String result;
  204657. DWORD handle = 0;
  204658. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204659. HeapBlock<char> buffer;
  204660. buffer.calloc (bufferSize);
  204661. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204662. {
  204663. VS_FIXEDFILEINFO* vffi;
  204664. UINT len = 0;
  204665. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204666. {
  204667. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204668. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204669. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204670. << (int) LOWORD (vffi->dwFileVersionLS);
  204671. }
  204672. }
  204673. return result;
  204674. }
  204675. const File File::getLinkedTarget() const
  204676. {
  204677. File result (*this);
  204678. String p (getFullPathName());
  204679. if (! exists())
  204680. p += ".lnk";
  204681. else if (getFileExtension() != ".lnk")
  204682. return result;
  204683. ComSmartPtr <IShellLink> shellLink;
  204684. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204685. {
  204686. ComSmartPtr <IPersistFile> persistFile;
  204687. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204688. {
  204689. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204690. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204691. {
  204692. WIN32_FIND_DATA winFindData;
  204693. WCHAR resolvedPath [MAX_PATH];
  204694. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204695. result = File (resolvedPath);
  204696. }
  204697. }
  204698. }
  204699. return result;
  204700. }
  204701. class DirectoryIterator::NativeIterator::Pimpl
  204702. {
  204703. public:
  204704. Pimpl (const File& directory, const String& wildCard)
  204705. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204706. handle (INVALID_HANDLE_VALUE)
  204707. {
  204708. }
  204709. ~Pimpl()
  204710. {
  204711. if (handle != INVALID_HANDLE_VALUE)
  204712. FindClose (handle);
  204713. }
  204714. bool next (String& filenameFound,
  204715. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204716. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204717. {
  204718. using namespace WindowsFileHelpers;
  204719. WIN32_FIND_DATA findData;
  204720. if (handle == INVALID_HANDLE_VALUE)
  204721. {
  204722. handle = FindFirstFile (directoryWithWildCard, &findData);
  204723. if (handle == INVALID_HANDLE_VALUE)
  204724. return false;
  204725. }
  204726. else
  204727. {
  204728. if (FindNextFile (handle, &findData) == 0)
  204729. return false;
  204730. }
  204731. filenameFound = findData.cFileName;
  204732. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204733. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204734. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204735. if (modTime != 0) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime));
  204736. if (creationTime != 0) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime));
  204737. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204738. return true;
  204739. }
  204740. private:
  204741. const String directoryWithWildCard;
  204742. HANDLE handle;
  204743. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl);
  204744. };
  204745. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204746. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204747. {
  204748. }
  204749. DirectoryIterator::NativeIterator::~NativeIterator()
  204750. {
  204751. }
  204752. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204753. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204754. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204755. {
  204756. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204757. }
  204758. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204759. {
  204760. HINSTANCE hInstance = 0;
  204761. JUCE_TRY
  204762. {
  204763. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204764. }
  204765. JUCE_CATCH_ALL
  204766. return hInstance > (HINSTANCE) 32;
  204767. }
  204768. void File::revealToUser() const
  204769. {
  204770. if (isDirectory())
  204771. startAsProcess();
  204772. else if (getParentDirectory().exists())
  204773. getParentDirectory().startAsProcess();
  204774. }
  204775. class NamedPipeInternal
  204776. {
  204777. public:
  204778. NamedPipeInternal (const String& file, const bool isPipe_)
  204779. : pipeH (0),
  204780. cancelEvent (0),
  204781. connected (false),
  204782. isPipe (isPipe_)
  204783. {
  204784. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204785. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204786. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204787. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204788. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204789. }
  204790. ~NamedPipeInternal()
  204791. {
  204792. disconnectPipe();
  204793. if (pipeH != 0)
  204794. CloseHandle (pipeH);
  204795. CloseHandle (cancelEvent);
  204796. }
  204797. bool connect (const int timeOutMs)
  204798. {
  204799. if (! isPipe)
  204800. return true;
  204801. if (! connected)
  204802. {
  204803. OVERLAPPED over;
  204804. zerostruct (over);
  204805. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204806. if (ConnectNamedPipe (pipeH, &over))
  204807. {
  204808. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204809. }
  204810. else
  204811. {
  204812. const int err = GetLastError();
  204813. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204814. {
  204815. HANDLE handles[] = { over.hEvent, cancelEvent };
  204816. if (WaitForMultipleObjects (2, handles, FALSE,
  204817. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204818. connected = true;
  204819. }
  204820. else if (err == ERROR_PIPE_CONNECTED)
  204821. {
  204822. connected = true;
  204823. }
  204824. }
  204825. CloseHandle (over.hEvent);
  204826. }
  204827. return connected;
  204828. }
  204829. void disconnectPipe()
  204830. {
  204831. if (connected)
  204832. {
  204833. DisconnectNamedPipe (pipeH);
  204834. connected = false;
  204835. }
  204836. }
  204837. HANDLE pipeH;
  204838. HANDLE cancelEvent;
  204839. bool connected, isPipe;
  204840. };
  204841. void NamedPipe::close()
  204842. {
  204843. cancelPendingReads();
  204844. const ScopedLock sl (lock);
  204845. delete static_cast<NamedPipeInternal*> (internal);
  204846. internal = 0;
  204847. }
  204848. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204849. {
  204850. close();
  204851. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204852. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204853. {
  204854. internal = intern.release();
  204855. return true;
  204856. }
  204857. return false;
  204858. }
  204859. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204860. {
  204861. const ScopedLock sl (lock);
  204862. int bytesRead = -1;
  204863. bool waitAgain = true;
  204864. while (waitAgain && internal != 0)
  204865. {
  204866. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204867. waitAgain = false;
  204868. if (! intern->connect (timeOutMilliseconds))
  204869. break;
  204870. if (maxBytesToRead <= 0)
  204871. return 0;
  204872. OVERLAPPED over;
  204873. zerostruct (over);
  204874. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204875. unsigned long numRead;
  204876. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204877. {
  204878. bytesRead = (int) numRead;
  204879. }
  204880. else if (GetLastError() == ERROR_IO_PENDING)
  204881. {
  204882. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204883. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204884. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204885. : INFINITE);
  204886. if (waitResult != WAIT_OBJECT_0)
  204887. {
  204888. // if the operation timed out, let's cancel it...
  204889. CancelIo (intern->pipeH);
  204890. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204891. }
  204892. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204893. {
  204894. bytesRead = (int) numRead;
  204895. }
  204896. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204897. {
  204898. intern->disconnectPipe();
  204899. waitAgain = true;
  204900. }
  204901. }
  204902. else
  204903. {
  204904. waitAgain = internal != 0;
  204905. Sleep (5);
  204906. }
  204907. CloseHandle (over.hEvent);
  204908. }
  204909. return bytesRead;
  204910. }
  204911. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204912. {
  204913. int bytesWritten = -1;
  204914. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204915. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204916. {
  204917. if (numBytesToWrite <= 0)
  204918. return 0;
  204919. OVERLAPPED over;
  204920. zerostruct (over);
  204921. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204922. unsigned long numWritten;
  204923. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204924. {
  204925. bytesWritten = (int) numWritten;
  204926. }
  204927. else if (GetLastError() == ERROR_IO_PENDING)
  204928. {
  204929. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204930. DWORD waitResult;
  204931. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204932. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204933. : INFINITE);
  204934. if (waitResult != WAIT_OBJECT_0)
  204935. {
  204936. CancelIo (intern->pipeH);
  204937. WaitForSingleObject (over.hEvent, INFINITE);
  204938. }
  204939. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204940. {
  204941. bytesWritten = (int) numWritten;
  204942. }
  204943. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204944. {
  204945. intern->disconnectPipe();
  204946. }
  204947. }
  204948. CloseHandle (over.hEvent);
  204949. }
  204950. return bytesWritten;
  204951. }
  204952. void NamedPipe::cancelPendingReads()
  204953. {
  204954. if (internal != 0)
  204955. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204956. }
  204957. #endif
  204958. /*** End of inlined file: juce_win32_Files.cpp ***/
  204959. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204960. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204961. // compiled on its own).
  204962. #if JUCE_INCLUDED_FILE
  204963. #ifndef INTERNET_FLAG_NEED_FILE
  204964. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204965. #endif
  204966. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204967. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204968. #endif
  204969. static HINTERNET sessionHandle = 0;
  204970. #ifndef WORKAROUND_TIMEOUT_BUG
  204971. //#define WORKAROUND_TIMEOUT_BUG 1
  204972. #endif
  204973. #if WORKAROUND_TIMEOUT_BUG
  204974. // Required because of a Microsoft bug in setting a timeout
  204975. class InternetConnectThread : public Thread
  204976. {
  204977. public:
  204978. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204979. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204980. {
  204981. startThread();
  204982. }
  204983. ~InternetConnectThread()
  204984. {
  204985. stopThread (60000);
  204986. }
  204987. void run()
  204988. {
  204989. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204990. uc.nPort, _T(""), _T(""),
  204991. isFtp ? INTERNET_SERVICE_FTP
  204992. : INTERNET_SERVICE_HTTP,
  204993. 0, 0);
  204994. notify();
  204995. }
  204996. private:
  204997. URL_COMPONENTS& uc;
  204998. HINTERNET& connection;
  204999. const bool isFtp;
  205000. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternetConnectThread);
  205001. };
  205002. #endif
  205003. class WebInputStream : public InputStream
  205004. {
  205005. public:
  205006. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  205007. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  205008. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  205009. : connection (0), request (0),
  205010. address (address_), headers (headers_), postData (postData_), position (0),
  205011. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  205012. {
  205013. createConnection (progressCallback, progressCallbackContext);
  205014. if (responseHeaders != 0 && ! isError())
  205015. {
  205016. DWORD bufferSizeBytes = 4096;
  205017. for (;;)
  205018. {
  205019. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  205020. if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  205021. {
  205022. StringArray headersArray;
  205023. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  205024. for (int i = 0; i < headersArray.size(); ++i)
  205025. {
  205026. const String& header = headersArray[i];
  205027. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  205028. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  205029. const String previousValue ((*responseHeaders) [key]);
  205030. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  205031. }
  205032. break;
  205033. }
  205034. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  205035. break;
  205036. }
  205037. }
  205038. }
  205039. ~WebInputStream()
  205040. {
  205041. close();
  205042. }
  205043. bool isError() const { return request == 0; }
  205044. bool isExhausted() { return finished; }
  205045. int64 getPosition() { return position; }
  205046. int64 getTotalLength()
  205047. {
  205048. if (! isError())
  205049. {
  205050. DWORD index = 0, result = 0, size = sizeof (result);
  205051. if (HttpQueryInfo (request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  205052. return (int64) result;
  205053. }
  205054. return -1;
  205055. }
  205056. int read (void* buffer, int bytesToRead)
  205057. {
  205058. DWORD bytesRead = 0;
  205059. if (! (finished || isError()))
  205060. {
  205061. InternetReadFile (request, buffer, bytesToRead, &bytesRead);
  205062. position += bytesRead;
  205063. if (bytesRead == 0)
  205064. finished = true;
  205065. }
  205066. return (int) bytesRead;
  205067. }
  205068. bool setPosition (int64 wantedPos)
  205069. {
  205070. if (isError())
  205071. return false;
  205072. if (wantedPos != position)
  205073. {
  205074. finished = false;
  205075. position = (int64) InternetSetFilePointer (request, (LONG) wantedPos, 0, FILE_BEGIN, 0);
  205076. if (position == wantedPos)
  205077. return true;
  205078. if (wantedPos < position)
  205079. {
  205080. close();
  205081. position = 0;
  205082. createConnection (0, 0);
  205083. }
  205084. skipNextBytes (wantedPos - position);
  205085. }
  205086. return true;
  205087. }
  205088. private:
  205089. HINTERNET connection, request;
  205090. String address, headers;
  205091. MemoryBlock postData;
  205092. int64 position;
  205093. bool finished;
  205094. const bool isPost;
  205095. int timeOutMs;
  205096. void close()
  205097. {
  205098. if (request != 0)
  205099. {
  205100. InternetCloseHandle (request);
  205101. request = 0;
  205102. }
  205103. if (connection != 0)
  205104. {
  205105. InternetCloseHandle (connection);
  205106. connection = 0;
  205107. }
  205108. }
  205109. void createConnection (URL::OpenStreamProgressCallback* progressCallback,
  205110. void* progressCallbackContext)
  205111. {
  205112. static HINTERNET sessionHandle = InternetOpen (_T("juce"), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
  205113. close();
  205114. if (sessionHandle != 0)
  205115. {
  205116. // break up the url..
  205117. TCHAR file[1024], server[1024];
  205118. URL_COMPONENTS uc;
  205119. zerostruct (uc);
  205120. uc.dwStructSize = sizeof (uc);
  205121. uc.dwUrlPathLength = sizeof (file);
  205122. uc.dwHostNameLength = sizeof (server);
  205123. uc.lpszUrlPath = file;
  205124. uc.lpszHostName = server;
  205125. if (InternetCrackUrl (address, 0, 0, &uc))
  205126. {
  205127. int disable = 1;
  205128. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  205129. if (timeOutMs == 0)
  205130. timeOutMs = 30000;
  205131. else if (timeOutMs < 0)
  205132. timeOutMs = -1;
  205133. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  205134. const bool isFtp = address.startsWithIgnoreCase ("ftp:");
  205135. #if WORKAROUND_TIMEOUT_BUG
  205136. connection = 0;
  205137. {
  205138. InternetConnectThread connectThread (uc, connection, isFtp);
  205139. connectThread.wait (timeOutMs);
  205140. if (connection == 0)
  205141. {
  205142. InternetCloseHandle (sessionHandle);
  205143. sessionHandle = 0;
  205144. }
  205145. }
  205146. #else
  205147. connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort,
  205148. _T(""), _T(""),
  205149. isFtp ? INTERNET_SERVICE_FTP
  205150. : INTERNET_SERVICE_HTTP,
  205151. 0, 0);
  205152. #endif
  205153. if (connection != 0)
  205154. {
  205155. if (isFtp)
  205156. {
  205157. request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ,
  205158. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0);
  205159. }
  205160. else
  205161. {
  205162. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  205163. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  205164. if (address.startsWithIgnoreCase ("https:"))
  205165. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  205166. // IE7 seems to automatically work out when it's https)
  205167. request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
  205168. uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);
  205169. if (request != 0)
  205170. {
  205171. INTERNET_BUFFERS buffers;
  205172. zerostruct (buffers);
  205173. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  205174. buffers.lpcszHeader = static_cast <LPCTSTR> (headers);
  205175. buffers.dwHeadersLength = headers.length();
  205176. buffers.dwBufferTotal = (DWORD) postData.getSize();
  205177. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  205178. {
  205179. int bytesSent = 0;
  205180. for (;;)
  205181. {
  205182. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  205183. DWORD bytesDone = 0;
  205184. if (bytesToDo > 0
  205185. && ! InternetWriteFile (request,
  205186. static_cast <const char*> (postData.getData()) + bytesSent,
  205187. bytesToDo, &bytesDone))
  205188. {
  205189. break;
  205190. }
  205191. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  205192. {
  205193. if (HttpEndRequest (request, 0, 0, 0))
  205194. return;
  205195. break;
  205196. }
  205197. bytesSent += bytesDone;
  205198. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, bytesSent, postData.getSize()))
  205199. break;
  205200. }
  205201. }
  205202. }
  205203. close();
  205204. }
  205205. }
  205206. }
  205207. }
  205208. }
  205209. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  205210. };
  205211. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  205212. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  205213. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  205214. {
  205215. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  205216. progressCallback, progressCallbackContext,
  205217. headers, timeOutMs, responseHeaders));
  205218. return wi->isError() ? 0 : wi.release();
  205219. }
  205220. namespace MACAddressHelpers
  205221. {
  205222. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  205223. {
  205224. DynamicLibraryLoader dll ("iphlpapi.dll");
  205225. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  205226. if (getAdaptersInfo != 0)
  205227. {
  205228. ULONG len = sizeof (IP_ADAPTER_INFO);
  205229. MemoryBlock mb;
  205230. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205231. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  205232. {
  205233. mb.setSize (len);
  205234. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205235. }
  205236. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  205237. {
  205238. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  205239. {
  205240. if (adapter->AddressLength >= 6)
  205241. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  205242. }
  205243. }
  205244. }
  205245. }
  205246. void getViaNetBios (Array<MACAddress>& result)
  205247. {
  205248. DynamicLibraryLoader dll ("netapi32.dll");
  205249. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205250. if (NetbiosCall != 0)
  205251. {
  205252. NCB ncb;
  205253. zerostruct (ncb);
  205254. struct ASTAT
  205255. {
  205256. ADAPTER_STATUS adapt;
  205257. NAME_BUFFER NameBuff [30];
  205258. };
  205259. ASTAT astat;
  205260. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205261. LANA_ENUM enums;
  205262. zerostruct (enums);
  205263. ncb.ncb_command = NCBENUM;
  205264. ncb.ncb_buffer = (unsigned char*) &enums;
  205265. ncb.ncb_length = sizeof (LANA_ENUM);
  205266. NetbiosCall (&ncb);
  205267. for (int i = 0; i < enums.length; ++i)
  205268. {
  205269. zerostruct (ncb);
  205270. ncb.ncb_command = NCBRESET;
  205271. ncb.ncb_lana_num = enums.lana[i];
  205272. if (NetbiosCall (&ncb) == 0)
  205273. {
  205274. zerostruct (ncb);
  205275. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205276. ncb.ncb_command = NCBASTAT;
  205277. ncb.ncb_lana_num = enums.lana[i];
  205278. ncb.ncb_buffer = (unsigned char*) &astat;
  205279. ncb.ncb_length = sizeof (ASTAT);
  205280. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  205281. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  205282. }
  205283. }
  205284. }
  205285. }
  205286. }
  205287. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  205288. {
  205289. MACAddressHelpers::getViaGetAdaptersInfo (result);
  205290. MACAddressHelpers::getViaNetBios (result);
  205291. }
  205292. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205293. const String& emailSubject,
  205294. const String& bodyText,
  205295. const StringArray& filesToAttach)
  205296. {
  205297. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205298. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205299. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205300. bool ok = false;
  205301. if (mapiSendMail != 0)
  205302. {
  205303. MapiMessage message;
  205304. zerostruct (message);
  205305. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205306. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205307. MapiRecipDesc recip;
  205308. zerostruct (recip);
  205309. recip.ulRecipClass = MAPI_TO;
  205310. String targetEmailAddress_ (targetEmailAddress);
  205311. if (targetEmailAddress_.isEmpty())
  205312. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205313. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205314. message.nRecipCount = 1;
  205315. message.lpRecips = &recip;
  205316. HeapBlock <MapiFileDesc> files;
  205317. files.calloc (filesToAttach.size());
  205318. message.nFileCount = filesToAttach.size();
  205319. message.lpFiles = files;
  205320. for (int i = 0; i < filesToAttach.size(); ++i)
  205321. {
  205322. files[i].nPosition = (ULONG) -1;
  205323. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205324. }
  205325. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205326. }
  205327. FreeLibrary (h);
  205328. return ok;
  205329. }
  205330. #endif
  205331. /*** End of inlined file: juce_win32_Network.cpp ***/
  205332. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205333. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205334. // compiled on its own).
  205335. #if JUCE_INCLUDED_FILE
  205336. namespace
  205337. {
  205338. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  205339. {
  205340. HKEY rootKey = 0;
  205341. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205342. rootKey = HKEY_CURRENT_USER;
  205343. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205344. rootKey = HKEY_LOCAL_MACHINE;
  205345. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205346. rootKey = HKEY_CLASSES_ROOT;
  205347. if (rootKey != 0)
  205348. {
  205349. name = name.substring (name.indexOfChar ('\\') + 1);
  205350. const int lastSlash = name.lastIndexOfChar ('\\');
  205351. valueName = name.substring (lastSlash + 1);
  205352. name = name.substring (0, lastSlash);
  205353. HKEY key;
  205354. DWORD result;
  205355. if (createForWriting)
  205356. {
  205357. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205358. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205359. return key;
  205360. }
  205361. else
  205362. {
  205363. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205364. return key;
  205365. }
  205366. }
  205367. return 0;
  205368. }
  205369. }
  205370. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205371. const String& defaultValue)
  205372. {
  205373. String valueName, result (defaultValue);
  205374. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205375. if (k != 0)
  205376. {
  205377. WCHAR buffer [2048];
  205378. unsigned long bufferSize = sizeof (buffer);
  205379. DWORD type = REG_SZ;
  205380. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205381. {
  205382. if (type == REG_SZ)
  205383. result = buffer;
  205384. else if (type == REG_DWORD)
  205385. result = String ((int) *(DWORD*) buffer);
  205386. }
  205387. RegCloseKey (k);
  205388. }
  205389. return result;
  205390. }
  205391. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205392. const String& value)
  205393. {
  205394. String valueName;
  205395. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205396. if (k != 0)
  205397. {
  205398. RegSetValueEx (k, valueName, 0, REG_SZ,
  205399. (const BYTE*) (const WCHAR*) value,
  205400. sizeof (WCHAR) * (value.length() + 1));
  205401. RegCloseKey (k);
  205402. }
  205403. }
  205404. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205405. {
  205406. bool exists = false;
  205407. String valueName;
  205408. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205409. if (k != 0)
  205410. {
  205411. unsigned char buffer [2048];
  205412. unsigned long bufferSize = sizeof (buffer);
  205413. DWORD type = 0;
  205414. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205415. exists = true;
  205416. RegCloseKey (k);
  205417. }
  205418. return exists;
  205419. }
  205420. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205421. {
  205422. String valueName;
  205423. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205424. if (k != 0)
  205425. {
  205426. RegDeleteValue (k, valueName);
  205427. RegCloseKey (k);
  205428. }
  205429. }
  205430. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205431. {
  205432. String valueName;
  205433. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205434. if (k != 0)
  205435. {
  205436. RegDeleteKey (k, valueName);
  205437. RegCloseKey (k);
  205438. }
  205439. }
  205440. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205441. const String& symbolicDescription,
  205442. const String& fullDescription,
  205443. const File& targetExecutable,
  205444. int iconResourceNumber)
  205445. {
  205446. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205447. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205448. if (iconResourceNumber != 0)
  205449. setRegistryValue (key + "\\DefaultIcon\\",
  205450. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205451. setRegistryValue (key + "\\", fullDescription);
  205452. setRegistryValue (key + "\\shell\\open\\command\\",
  205453. targetExecutable.getFullPathName() + " %1");
  205454. }
  205455. bool juce_IsRunningInWine()
  205456. {
  205457. HKEY key;
  205458. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205459. {
  205460. RegCloseKey (key);
  205461. return true;
  205462. }
  205463. return false;
  205464. }
  205465. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205466. {
  205467. String s (::GetCommandLineW());
  205468. StringArray tokens;
  205469. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205470. return tokens.joinIntoString (" ", 1);
  205471. }
  205472. static void* currentModuleHandle = 0;
  205473. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205474. {
  205475. if (currentModuleHandle == 0)
  205476. currentModuleHandle = GetModuleHandle (0);
  205477. return currentModuleHandle;
  205478. }
  205479. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205480. {
  205481. currentModuleHandle = newHandle;
  205482. }
  205483. void PlatformUtilities::fpuReset()
  205484. {
  205485. #if JUCE_MSVC
  205486. _clearfp();
  205487. #endif
  205488. }
  205489. void PlatformUtilities::beep()
  205490. {
  205491. MessageBeep (MB_OK);
  205492. }
  205493. #endif
  205494. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205495. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205496. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205497. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205498. // compiled on its own).
  205499. #if JUCE_INCLUDED_FILE
  205500. static const unsigned int specialId = WM_APP + 0x4400;
  205501. static const unsigned int broadcastId = WM_APP + 0x4403;
  205502. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205503. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205504. HWND juce_messageWindowHandle = 0;
  205505. extern long improbableWindowNumber; // defined in windowing.cpp
  205506. #ifndef WM_APPCOMMAND
  205507. #define WM_APPCOMMAND 0x0319
  205508. #endif
  205509. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205510. const UINT message,
  205511. const WPARAM wParam,
  205512. const LPARAM lParam) throw()
  205513. {
  205514. JUCE_TRY
  205515. {
  205516. if (h == juce_messageWindowHandle)
  205517. {
  205518. if (message == specialCallbackId)
  205519. {
  205520. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205521. return (LRESULT) (*func) ((void*) lParam);
  205522. }
  205523. else if (message == specialId)
  205524. {
  205525. // these are trapped early in the dispatch call, but must also be checked
  205526. // here in case there are windows modal dialog boxes doing their own
  205527. // dispatch loop and not calling our version
  205528. Message* const message = reinterpret_cast <Message*> (lParam);
  205529. MessageManager::getInstance()->deliverMessage (message);
  205530. message->decReferenceCount();
  205531. return 0;
  205532. }
  205533. else if (message == broadcastId)
  205534. {
  205535. const ScopedPointer <String> messageString ((String*) lParam);
  205536. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205537. return 0;
  205538. }
  205539. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205540. {
  205541. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205542. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205543. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205544. return 0;
  205545. }
  205546. }
  205547. }
  205548. JUCE_CATCH_EXCEPTION
  205549. return DefWindowProc (h, message, wParam, lParam);
  205550. }
  205551. static bool isEventBlockedByModalComps (MSG& m)
  205552. {
  205553. if (Component::getNumCurrentlyModalComponents() == 0
  205554. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205555. return false;
  205556. switch (m.message)
  205557. {
  205558. case WM_MOUSEMOVE:
  205559. case WM_NCMOUSEMOVE:
  205560. case 0x020A: /* WM_MOUSEWHEEL */
  205561. case 0x020E: /* WM_MOUSEHWHEEL */
  205562. case WM_KEYUP:
  205563. case WM_SYSKEYUP:
  205564. case WM_CHAR:
  205565. case WM_APPCOMMAND:
  205566. case WM_LBUTTONUP:
  205567. case WM_MBUTTONUP:
  205568. case WM_RBUTTONUP:
  205569. case WM_MOUSEACTIVATE:
  205570. case WM_NCMOUSEHOVER:
  205571. case WM_MOUSEHOVER:
  205572. return true;
  205573. case WM_NCLBUTTONDOWN:
  205574. case WM_NCLBUTTONDBLCLK:
  205575. case WM_NCRBUTTONDOWN:
  205576. case WM_NCRBUTTONDBLCLK:
  205577. case WM_NCMBUTTONDOWN:
  205578. case WM_NCMBUTTONDBLCLK:
  205579. case WM_LBUTTONDOWN:
  205580. case WM_LBUTTONDBLCLK:
  205581. case WM_MBUTTONDOWN:
  205582. case WM_MBUTTONDBLCLK:
  205583. case WM_RBUTTONDOWN:
  205584. case WM_RBUTTONDBLCLK:
  205585. case WM_KEYDOWN:
  205586. case WM_SYSKEYDOWN:
  205587. {
  205588. Component* const modal = Component::getCurrentlyModalComponent (0);
  205589. if (modal != 0)
  205590. modal->inputAttemptWhenModal();
  205591. return true;
  205592. }
  205593. default:
  205594. break;
  205595. }
  205596. return false;
  205597. }
  205598. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205599. {
  205600. MSG m;
  205601. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205602. return false;
  205603. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205604. {
  205605. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205606. {
  205607. Message* const message = reinterpret_cast <Message*> (m.lParam);
  205608. MessageManager::getInstance()->deliverMessage (message);
  205609. message->decReferenceCount();
  205610. }
  205611. else if (m.message == WM_QUIT)
  205612. {
  205613. if (JUCEApplication::getInstance() != 0)
  205614. JUCEApplication::getInstance()->systemRequestedQuit();
  205615. }
  205616. else if (! isEventBlockedByModalComps (m))
  205617. {
  205618. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205619. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205620. {
  205621. // if it's someone else's window being clicked on, and the focus is
  205622. // currently on a juce window, pass the kb focus over..
  205623. HWND currentFocus = GetFocus();
  205624. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205625. SetFocus (m.hwnd);
  205626. }
  205627. TranslateMessage (&m);
  205628. DispatchMessage (&m);
  205629. }
  205630. }
  205631. return true;
  205632. }
  205633. bool juce_postMessageToSystemQueue (Message* message)
  205634. {
  205635. message->incReferenceCount();
  205636. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205637. }
  205638. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205639. void* userData)
  205640. {
  205641. if (MessageManager::getInstance()->isThisTheMessageThread())
  205642. {
  205643. return (*callback) (userData);
  205644. }
  205645. else
  205646. {
  205647. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205648. // deadlock because the message manager is blocked from running, and can't
  205649. // call your function..
  205650. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205651. return (void*) SendMessage (juce_messageWindowHandle,
  205652. specialCallbackId,
  205653. (WPARAM) callback,
  205654. (LPARAM) userData);
  205655. }
  205656. }
  205657. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205658. {
  205659. if (hwnd != juce_messageWindowHandle)
  205660. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205661. return TRUE;
  205662. }
  205663. void MessageManager::broadcastMessage (const String& value)
  205664. {
  205665. Array<void*> windows;
  205666. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205667. const String localCopy (value);
  205668. COPYDATASTRUCT data;
  205669. data.dwData = broadcastId;
  205670. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205671. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205672. for (int i = windows.size(); --i >= 0;)
  205673. {
  205674. HWND hwnd = (HWND) windows.getUnchecked(i);
  205675. TCHAR windowName [64]; // no need to read longer strings than this
  205676. GetWindowText (hwnd, windowName, 64);
  205677. windowName [63] = 0;
  205678. if (String (windowName) == messageWindowName)
  205679. {
  205680. DWORD_PTR result;
  205681. SendMessageTimeout (hwnd, WM_COPYDATA,
  205682. (WPARAM) juce_messageWindowHandle,
  205683. (LPARAM) &data,
  205684. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205685. 8000,
  205686. &result);
  205687. }
  205688. }
  205689. }
  205690. static const String getMessageWindowClassName()
  205691. {
  205692. // this name has to be different for each app/dll instance because otherwise
  205693. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205694. // window class).
  205695. static int number = 0;
  205696. if (number == 0)
  205697. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205698. return "JUCEcs_" + String (number);
  205699. }
  205700. void MessageManager::doPlatformSpecificInitialisation()
  205701. {
  205702. OleInitialize (0);
  205703. const String className (getMessageWindowClassName());
  205704. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205705. WNDCLASSEX wc;
  205706. zerostruct (wc);
  205707. wc.cbSize = sizeof (wc);
  205708. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205709. wc.cbWndExtra = 4;
  205710. wc.hInstance = hmod;
  205711. wc.lpszClassName = className;
  205712. RegisterClassEx (&wc);
  205713. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205714. messageWindowName,
  205715. 0, 0, 0, 0, 0, 0, 0,
  205716. hmod, 0);
  205717. }
  205718. void MessageManager::doPlatformSpecificShutdown()
  205719. {
  205720. DestroyWindow (juce_messageWindowHandle);
  205721. UnregisterClass (getMessageWindowClassName(), 0);
  205722. OleUninitialize();
  205723. }
  205724. #endif
  205725. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205726. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205727. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205728. // compiled on its own).
  205729. #if JUCE_INCLUDED_FILE
  205730. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205731. NEWTEXTMETRICEXW*,
  205732. int type,
  205733. LPARAM lParam)
  205734. {
  205735. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205736. {
  205737. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205738. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205739. }
  205740. return 1;
  205741. }
  205742. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205743. NEWTEXTMETRICEXW*,
  205744. int type,
  205745. LPARAM lParam)
  205746. {
  205747. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205748. {
  205749. LOGFONTW lf;
  205750. zerostruct (lf);
  205751. lf.lfWeight = FW_DONTCARE;
  205752. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205753. lf.lfQuality = DEFAULT_QUALITY;
  205754. lf.lfCharSet = DEFAULT_CHARSET;
  205755. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205756. lf.lfPitchAndFamily = FF_DONTCARE;
  205757. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205758. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205759. HDC dc = CreateCompatibleDC (0);
  205760. EnumFontFamiliesEx (dc, &lf,
  205761. (FONTENUMPROCW) &wfontEnum2,
  205762. lParam, 0);
  205763. DeleteDC (dc);
  205764. }
  205765. return 1;
  205766. }
  205767. const StringArray Font::findAllTypefaceNames()
  205768. {
  205769. StringArray results;
  205770. HDC dc = CreateCompatibleDC (0);
  205771. {
  205772. LOGFONTW lf;
  205773. zerostruct (lf);
  205774. lf.lfWeight = FW_DONTCARE;
  205775. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205776. lf.lfQuality = DEFAULT_QUALITY;
  205777. lf.lfCharSet = DEFAULT_CHARSET;
  205778. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205779. lf.lfPitchAndFamily = FF_DONTCARE;
  205780. lf.lfFaceName[0] = 0;
  205781. EnumFontFamiliesEx (dc, &lf,
  205782. (FONTENUMPROCW) &wfontEnum1,
  205783. (LPARAM) &results, 0);
  205784. }
  205785. DeleteDC (dc);
  205786. results.sort (true);
  205787. return results;
  205788. }
  205789. extern bool juce_IsRunningInWine();
  205790. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205791. {
  205792. if (juce_IsRunningInWine())
  205793. {
  205794. // If we're running in Wine, then use fonts that might be available on Linux..
  205795. defaultSans = "Bitstream Vera Sans";
  205796. defaultSerif = "Bitstream Vera Serif";
  205797. defaultFixed = "Bitstream Vera Sans Mono";
  205798. }
  205799. else
  205800. {
  205801. defaultSans = "Verdana";
  205802. defaultSerif = "Times";
  205803. defaultFixed = "Lucida Console";
  205804. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205805. }
  205806. }
  205807. class FontDCHolder : private DeletedAtShutdown
  205808. {
  205809. public:
  205810. FontDCHolder()
  205811. : dc (0), numKPs (0), size (0),
  205812. bold (false), italic (false)
  205813. {
  205814. }
  205815. ~FontDCHolder()
  205816. {
  205817. if (dc != 0)
  205818. {
  205819. DeleteDC (dc);
  205820. DeleteObject (fontH);
  205821. }
  205822. clearSingletonInstance();
  205823. }
  205824. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205825. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205826. {
  205827. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205828. {
  205829. fontName = fontName_;
  205830. bold = bold_;
  205831. italic = italic_;
  205832. size = size_;
  205833. if (dc != 0)
  205834. {
  205835. DeleteDC (dc);
  205836. DeleteObject (fontH);
  205837. kps.free();
  205838. }
  205839. fontH = 0;
  205840. dc = CreateCompatibleDC (0);
  205841. SetMapperFlags (dc, 0);
  205842. SetMapMode (dc, MM_TEXT);
  205843. LOGFONTW lfw;
  205844. zerostruct (lfw);
  205845. lfw.lfCharSet = DEFAULT_CHARSET;
  205846. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205847. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205848. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205849. lfw.lfQuality = PROOF_QUALITY;
  205850. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205851. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205852. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205853. lfw.lfHeight = size > 0 ? size : -256;
  205854. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205855. if (standardSizedFont != 0)
  205856. {
  205857. if (SelectObject (dc, standardSizedFont) != 0)
  205858. {
  205859. fontH = standardSizedFont;
  205860. if (size == 0)
  205861. {
  205862. OUTLINETEXTMETRIC otm;
  205863. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205864. {
  205865. lfw.lfHeight = -(int) otm.otmEMSquare;
  205866. fontH = CreateFontIndirect (&lfw);
  205867. SelectObject (dc, fontH);
  205868. DeleteObject (standardSizedFont);
  205869. }
  205870. }
  205871. }
  205872. else
  205873. {
  205874. jassertfalse;
  205875. }
  205876. }
  205877. else
  205878. {
  205879. jassertfalse;
  205880. }
  205881. }
  205882. return dc;
  205883. }
  205884. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205885. {
  205886. if (kps == 0)
  205887. {
  205888. numKPs = GetKerningPairs (dc, 0, 0);
  205889. kps.calloc (numKPs);
  205890. GetKerningPairs (dc, numKPs, kps);
  205891. }
  205892. numKPs_ = numKPs;
  205893. return kps;
  205894. }
  205895. private:
  205896. HFONT fontH;
  205897. HDC dc;
  205898. String fontName;
  205899. HeapBlock <KERNINGPAIR> kps;
  205900. int numKPs, size;
  205901. bool bold, italic;
  205902. JUCE_DECLARE_NON_COPYABLE (FontDCHolder);
  205903. };
  205904. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205905. class WindowsTypeface : public CustomTypeface
  205906. {
  205907. public:
  205908. WindowsTypeface (const Font& font)
  205909. {
  205910. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205911. font.isBold(), font.isItalic(), 0);
  205912. TEXTMETRIC tm;
  205913. tm.tmAscent = tm.tmHeight = 1;
  205914. tm.tmDefaultChar = 0;
  205915. GetTextMetrics (dc, &tm);
  205916. setCharacteristics (font.getTypefaceName(),
  205917. tm.tmAscent / (float) tm.tmHeight,
  205918. font.isBold(), font.isItalic(),
  205919. tm.tmDefaultChar);
  205920. }
  205921. bool loadGlyphIfPossible (juce_wchar character)
  205922. {
  205923. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205924. GLYPHMETRICS gm;
  205925. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205926. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205927. // gets correctly created later on.
  205928. if (! isFallbackFont)
  205929. {
  205930. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205931. WORD index = 0;
  205932. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205933. && index == 0xffff)
  205934. {
  205935. return false;
  205936. }
  205937. }
  205938. Path glyphPath;
  205939. TEXTMETRIC tm;
  205940. if (! GetTextMetrics (dc, &tm))
  205941. {
  205942. addGlyph (character, glyphPath, 0);
  205943. return true;
  205944. }
  205945. const float height = (float) tm.tmHeight;
  205946. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205947. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205948. &gm, 0, 0, &identityMatrix);
  205949. if (bufSize > 0)
  205950. {
  205951. HeapBlock<char> data (bufSize);
  205952. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205953. bufSize, data, &identityMatrix);
  205954. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205955. const float scaleX = 1.0f / height;
  205956. const float scaleY = -1.0f / height;
  205957. while ((char*) pheader < data + bufSize)
  205958. {
  205959. float x = scaleX * pheader->pfxStart.x.value;
  205960. float y = scaleY * pheader->pfxStart.y.value;
  205961. glyphPath.startNewSubPath (x, y);
  205962. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205963. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205964. while ((const char*) curve < curveEnd)
  205965. {
  205966. if (curve->wType == TT_PRIM_LINE)
  205967. {
  205968. for (int i = 0; i < curve->cpfx; ++i)
  205969. {
  205970. x = scaleX * curve->apfx[i].x.value;
  205971. y = scaleY * curve->apfx[i].y.value;
  205972. glyphPath.lineTo (x, y);
  205973. }
  205974. }
  205975. else if (curve->wType == TT_PRIM_QSPLINE)
  205976. {
  205977. for (int i = 0; i < curve->cpfx - 1; ++i)
  205978. {
  205979. const float x2 = scaleX * curve->apfx[i].x.value;
  205980. const float y2 = scaleY * curve->apfx[i].y.value;
  205981. float x3, y3;
  205982. if (i < curve->cpfx - 2)
  205983. {
  205984. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205985. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205986. }
  205987. else
  205988. {
  205989. x3 = scaleX * curve->apfx[i + 1].x.value;
  205990. y3 = scaleY * curve->apfx[i + 1].y.value;
  205991. }
  205992. glyphPath.quadraticTo (x2, y2, x3, y3);
  205993. x = x3;
  205994. y = y3;
  205995. }
  205996. }
  205997. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205998. }
  205999. pheader = (const TTPOLYGONHEADER*) curve;
  206000. glyphPath.closeSubPath();
  206001. }
  206002. }
  206003. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  206004. int numKPs;
  206005. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  206006. for (int i = 0; i < numKPs; ++i)
  206007. {
  206008. if (kps[i].wFirst == character)
  206009. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  206010. kps[i].iKernAmount / height);
  206011. }
  206012. return true;
  206013. }
  206014. private:
  206015. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
  206016. };
  206017. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  206018. {
  206019. return new WindowsTypeface (font);
  206020. }
  206021. #endif
  206022. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  206023. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206024. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206025. // compiled on its own).
  206026. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  206027. class SharedD2DFactory : public DeletedAtShutdown
  206028. {
  206029. public:
  206030. SharedD2DFactory()
  206031. {
  206032. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  206033. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  206034. if (directWriteFactory != 0)
  206035. directWriteFactory->GetSystemFontCollection (&systemFonts);
  206036. }
  206037. ~SharedD2DFactory()
  206038. {
  206039. clearSingletonInstance();
  206040. }
  206041. juce_DeclareSingleton (SharedD2DFactory, false);
  206042. ComSmartPtr <ID2D1Factory> d2dFactory;
  206043. ComSmartPtr <IDWriteFactory> directWriteFactory;
  206044. ComSmartPtr <IDWriteFontCollection> systemFonts;
  206045. };
  206046. juce_ImplementSingleton (SharedD2DFactory)
  206047. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  206048. {
  206049. public:
  206050. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  206051. : hwnd (hwnd_),
  206052. currentState (0)
  206053. {
  206054. RECT windowRect;
  206055. GetClientRect (hwnd, &windowRect);
  206056. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206057. bounds.setSize (size.width, size.height);
  206058. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  206059. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  206060. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  206061. // xxx check for error
  206062. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  206063. }
  206064. ~Direct2DLowLevelGraphicsContext()
  206065. {
  206066. states.clear();
  206067. }
  206068. void resized()
  206069. {
  206070. RECT windowRect;
  206071. GetClientRect (hwnd, &windowRect);
  206072. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206073. renderingTarget->Resize (size);
  206074. bounds.setSize (size.width, size.height);
  206075. }
  206076. void clear()
  206077. {
  206078. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  206079. }
  206080. void start()
  206081. {
  206082. renderingTarget->BeginDraw();
  206083. saveState();
  206084. }
  206085. void end()
  206086. {
  206087. states.clear();
  206088. currentState = 0;
  206089. renderingTarget->EndDraw();
  206090. renderingTarget->CheckWindowState();
  206091. }
  206092. bool isVectorDevice() const { return false; }
  206093. void setOrigin (int x, int y)
  206094. {
  206095. currentState->origin.addXY (x, y);
  206096. }
  206097. void addTransform (const AffineTransform& transform)
  206098. {
  206099. //xxx todo
  206100. jassertfalse;
  206101. }
  206102. float getScaleFactor()
  206103. {
  206104. jassertfalse; //xxx
  206105. return 1.0f;
  206106. }
  206107. bool clipToRectangle (const Rectangle<int>& r)
  206108. {
  206109. currentState->clipToRectangle (r);
  206110. return ! isClipEmpty();
  206111. }
  206112. bool clipToRectangleList (const RectangleList& clipRegion)
  206113. {
  206114. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  206115. return ! isClipEmpty();
  206116. }
  206117. void excludeClipRectangle (const Rectangle<int>&)
  206118. {
  206119. //xxx
  206120. }
  206121. void clipToPath (const Path& path, const AffineTransform& transform)
  206122. {
  206123. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  206124. }
  206125. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  206126. {
  206127. currentState->clipToImage (sourceImage,transform);
  206128. }
  206129. bool clipRegionIntersects (const Rectangle<int>& r)
  206130. {
  206131. const Rectangle<int> r2 (r + currentState->origin);
  206132. return currentState->clipRect.intersects (r2);
  206133. }
  206134. const Rectangle<int> getClipBounds() const
  206135. {
  206136. // xxx could this take into account complex clip regions?
  206137. return currentState->clipRect - currentState->origin;
  206138. }
  206139. bool isClipEmpty() const
  206140. {
  206141. return currentState->clipRect.isEmpty();
  206142. }
  206143. void saveState()
  206144. {
  206145. states.add (new SavedState (*this));
  206146. currentState = states.getLast();
  206147. }
  206148. void restoreState()
  206149. {
  206150. jassert (states.size() > 1) //you should never pop the last state!
  206151. states.removeLast (1);
  206152. currentState = states.getLast();
  206153. }
  206154. void beginTransparencyLayer (float opacity)
  206155. {
  206156. jassertfalse; //xxx todo
  206157. }
  206158. void endTransparencyLayer()
  206159. {
  206160. jassertfalse; //xxx todo
  206161. }
  206162. void setFill (const FillType& fillType)
  206163. {
  206164. currentState->setFill (fillType);
  206165. }
  206166. void setOpacity (float newOpacity)
  206167. {
  206168. currentState->setOpacity (newOpacity);
  206169. }
  206170. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  206171. {
  206172. }
  206173. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  206174. {
  206175. currentState->createBrush();
  206176. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  206177. }
  206178. void fillPath (const Path& p, const AffineTransform& transform)
  206179. {
  206180. currentState->createBrush();
  206181. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  206182. if (renderingTarget != 0)
  206183. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  206184. }
  206185. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  206186. {
  206187. const int x = currentState->origin.getX();
  206188. const int y = currentState->origin.getY();
  206189. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206190. D2D1_SIZE_U size;
  206191. size.width = image.getWidth();
  206192. size.height = image.getHeight();
  206193. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206194. Image img (image.convertedToFormat (Image::ARGB));
  206195. Image::BitmapData bd (img, false);
  206196. bp.pixelFormat = renderingTarget->GetPixelFormat();
  206197. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206198. {
  206199. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  206200. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  206201. if (tempBitmap != 0)
  206202. renderingTarget->DrawBitmap (tempBitmap);
  206203. }
  206204. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206205. }
  206206. void drawLine (const Line <float>& line)
  206207. {
  206208. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206209. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  206210. line.getEnd() + currentState->origin.toFloat());
  206211. currentState->createBrush();
  206212. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  206213. D2D1::Point2F (l.getEndX(), l.getEndY()),
  206214. currentState->currentBrush);
  206215. }
  206216. void drawVerticalLine (int x, float top, float bottom)
  206217. {
  206218. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206219. currentState->createBrush();
  206220. x += currentState->origin.getX();
  206221. const int y = currentState->origin.getY();
  206222. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  206223. D2D1::Point2F (x, y + bottom),
  206224. currentState->currentBrush);
  206225. }
  206226. void drawHorizontalLine (int y, float left, float right)
  206227. {
  206228. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206229. currentState->createBrush();
  206230. y += currentState->origin.getY();
  206231. const int x = currentState->origin.getX();
  206232. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  206233. D2D1::Point2F (x + right, y),
  206234. currentState->currentBrush);
  206235. }
  206236. void setFont (const Font& newFont)
  206237. {
  206238. currentState->setFont (newFont);
  206239. }
  206240. const Font getFont()
  206241. {
  206242. return currentState->font;
  206243. }
  206244. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  206245. {
  206246. const float x = currentState->origin.getX();
  206247. const float y = currentState->origin.getY();
  206248. currentState->createBrush();
  206249. currentState->createFont();
  206250. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206251. float hScale = currentState->font.getHorizontalScale();
  206252. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206253. float dpiX = 0, dpiY = 0;
  206254. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206255. UINT32 glyphNum = glyphNumber;
  206256. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206257. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206258. DWRITE_GLYPH_OFFSET offset;
  206259. offset.advanceOffset = 0;
  206260. offset.ascenderOffset = 0;
  206261. float glyphAdvances = 0;
  206262. DWRITE_GLYPH_RUN glyph;
  206263. glyph.fontFace = currentState->currentFontFace;
  206264. glyph.glyphCount = 1;
  206265. glyph.glyphIndices = &glyphNum1;
  206266. glyph.isSideways = FALSE;
  206267. glyph.glyphAdvances = &glyphAdvances;
  206268. glyph.glyphOffsets = &offset;
  206269. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206270. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206271. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206272. }
  206273. class SavedState
  206274. {
  206275. public:
  206276. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206277. : owner (owner_), currentBrush (0),
  206278. fontScaling (1.0f), currentFontFace (0),
  206279. clipsRect (false), shouldClipRect (false),
  206280. clipsRectList (false), shouldClipRectList (false),
  206281. clipsComplex (false), shouldClipComplex (false),
  206282. clipsBitmap (false), shouldClipBitmap (false)
  206283. {
  206284. if (owner.currentState != 0)
  206285. {
  206286. // xxx seems like a very slow way to create one of these, and this is a performance
  206287. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206288. setFill (owner.currentState->fillType);
  206289. currentBrush = owner.currentState->currentBrush;
  206290. origin = owner.currentState->origin;
  206291. clipRect = owner.currentState->clipRect;
  206292. font = owner.currentState->font;
  206293. currentFontFace = owner.currentState->currentFontFace;
  206294. }
  206295. else
  206296. {
  206297. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206298. clipRect.setSize (size.width, size.height);
  206299. setFill (FillType (Colours::black));
  206300. }
  206301. }
  206302. ~SavedState()
  206303. {
  206304. clearClip();
  206305. clearFont();
  206306. clearFill();
  206307. clearPathClip();
  206308. clearImageClip();
  206309. complexClipLayer = 0;
  206310. bitmapMaskLayer = 0;
  206311. }
  206312. void clearClip()
  206313. {
  206314. popClips();
  206315. shouldClipRect = false;
  206316. }
  206317. void clipToRectangle (const Rectangle<int>& r)
  206318. {
  206319. clearClip();
  206320. clipRect = r + origin;
  206321. shouldClipRect = true;
  206322. pushClips();
  206323. }
  206324. void clearPathClip()
  206325. {
  206326. popClips();
  206327. if (shouldClipComplex)
  206328. {
  206329. complexClipGeometry = 0;
  206330. shouldClipComplex = false;
  206331. }
  206332. }
  206333. void clipToPath (ID2D1Geometry* geometry)
  206334. {
  206335. clearPathClip();
  206336. if (complexClipLayer == 0)
  206337. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206338. complexClipGeometry = geometry;
  206339. shouldClipComplex = true;
  206340. pushClips();
  206341. }
  206342. void clearRectListClip()
  206343. {
  206344. popClips();
  206345. if (shouldClipRectList)
  206346. {
  206347. rectListGeometry = 0;
  206348. shouldClipRectList = false;
  206349. }
  206350. }
  206351. void clipToRectList (ID2D1Geometry* geometry)
  206352. {
  206353. clearRectListClip();
  206354. if (rectListLayer == 0)
  206355. owner.renderingTarget->CreateLayer (&rectListLayer);
  206356. rectListGeometry = geometry;
  206357. shouldClipRectList = true;
  206358. pushClips();
  206359. }
  206360. void clearImageClip()
  206361. {
  206362. popClips();
  206363. if (shouldClipBitmap)
  206364. {
  206365. maskBitmap = 0;
  206366. bitmapMaskBrush = 0;
  206367. shouldClipBitmap = false;
  206368. }
  206369. }
  206370. void clipToImage (const Image& image, const AffineTransform& transform)
  206371. {
  206372. clearImageClip();
  206373. if (bitmapMaskLayer == 0)
  206374. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206375. D2D1_BRUSH_PROPERTIES brushProps;
  206376. brushProps.opacity = 1;
  206377. brushProps.transform = transfromToMatrix (transform);
  206378. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206379. D2D1_SIZE_U size;
  206380. size.width = image.getWidth();
  206381. size.height = image.getHeight();
  206382. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206383. maskImage = image.convertedToFormat (Image::ARGB);
  206384. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206385. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206386. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206387. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206388. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206389. imageMaskLayerParams = D2D1::LayerParameters();
  206390. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206391. shouldClipBitmap = true;
  206392. pushClips();
  206393. }
  206394. void popClips()
  206395. {
  206396. if (clipsBitmap)
  206397. {
  206398. owner.renderingTarget->PopLayer();
  206399. clipsBitmap = false;
  206400. }
  206401. if (clipsComplex)
  206402. {
  206403. owner.renderingTarget->PopLayer();
  206404. clipsComplex = false;
  206405. }
  206406. if (clipsRectList)
  206407. {
  206408. owner.renderingTarget->PopLayer();
  206409. clipsRectList = false;
  206410. }
  206411. if (clipsRect)
  206412. {
  206413. owner.renderingTarget->PopAxisAlignedClip();
  206414. clipsRect = false;
  206415. }
  206416. }
  206417. void pushClips()
  206418. {
  206419. if (shouldClipRect && ! clipsRect)
  206420. {
  206421. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206422. clipsRect = true;
  206423. }
  206424. if (shouldClipRectList && ! clipsRectList)
  206425. {
  206426. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206427. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206428. layerParams.geometricMask = rectListGeometry;
  206429. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206430. clipsRectList = true;
  206431. }
  206432. if (shouldClipComplex && ! clipsComplex)
  206433. {
  206434. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206435. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206436. layerParams.geometricMask = complexClipGeometry;
  206437. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206438. clipsComplex = true;
  206439. }
  206440. if (shouldClipBitmap && ! clipsBitmap)
  206441. {
  206442. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206443. clipsBitmap = true;
  206444. }
  206445. }
  206446. void setFill (const FillType& newFillType)
  206447. {
  206448. if (fillType != newFillType)
  206449. {
  206450. fillType = newFillType;
  206451. clearFill();
  206452. }
  206453. }
  206454. void clearFont()
  206455. {
  206456. currentFontFace = localFontFace = 0;
  206457. }
  206458. void setFont (const Font& newFont)
  206459. {
  206460. if (font != newFont)
  206461. {
  206462. font = newFont;
  206463. clearFont();
  206464. }
  206465. }
  206466. void createFont()
  206467. {
  206468. // xxx The font shouldn't be managed by the graphics context.
  206469. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206470. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206471. // WindowsTypeface class.
  206472. if (currentFontFace == 0)
  206473. {
  206474. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206475. fontScaling = systemType->getAscent();
  206476. BOOL fontFound;
  206477. uint32 fontIndex;
  206478. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206479. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206480. if (! fontFound)
  206481. fontIndex = 0;
  206482. ComSmartPtr <IDWriteFontFamily> fontFam;
  206483. fonts->GetFontFamily (fontIndex, &fontFam);
  206484. ComSmartPtr <IDWriteFont> font;
  206485. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206486. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206487. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206488. font->CreateFontFace (&localFontFace);
  206489. currentFontFace = localFontFace;
  206490. }
  206491. }
  206492. void setOpacity (float newOpacity)
  206493. {
  206494. fillType.setOpacity (newOpacity);
  206495. if (currentBrush != 0)
  206496. currentBrush->SetOpacity (newOpacity);
  206497. }
  206498. void clearFill()
  206499. {
  206500. gradientStops = 0;
  206501. linearGradient = 0;
  206502. radialGradient = 0;
  206503. bitmap = 0;
  206504. bitmapBrush = 0;
  206505. currentBrush = 0;
  206506. }
  206507. void createBrush()
  206508. {
  206509. if (currentBrush == 0)
  206510. {
  206511. const int x = origin.getX();
  206512. const int y = origin.getY();
  206513. if (fillType.isColour())
  206514. {
  206515. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206516. owner.colourBrush->SetColor (colour);
  206517. currentBrush = owner.colourBrush;
  206518. }
  206519. else if (fillType.isTiledImage())
  206520. {
  206521. D2D1_BRUSH_PROPERTIES brushProps;
  206522. brushProps.opacity = fillType.getOpacity();
  206523. brushProps.transform = transfromToMatrix (fillType.transform);
  206524. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206525. image = fillType.image;
  206526. D2D1_SIZE_U size;
  206527. size.width = image.getWidth();
  206528. size.height = image.getHeight();
  206529. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206530. this->image = image.convertedToFormat (Image::ARGB);
  206531. Image::BitmapData bd (this->image, false);
  206532. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206533. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206534. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206535. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206536. currentBrush = bitmapBrush;
  206537. }
  206538. else if (fillType.isGradient())
  206539. {
  206540. gradientStops = 0;
  206541. D2D1_BRUSH_PROPERTIES brushProps;
  206542. brushProps.opacity = fillType.getOpacity();
  206543. brushProps.transform = transfromToMatrix (fillType.transform);
  206544. const int numColors = fillType.gradient->getNumColours();
  206545. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206546. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206547. {
  206548. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206549. stops[i].position = fillType.gradient->getColourPosition(i);
  206550. }
  206551. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206552. if (fillType.gradient->isRadial)
  206553. {
  206554. radialGradient = 0;
  206555. const Point<float>& p1 = fillType.gradient->point1;
  206556. const Point<float>& p2 = fillType.gradient->point2;
  206557. float r = p1.getDistanceFrom (p2);
  206558. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206559. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206560. D2D1::Point2F (0, 0),
  206561. r, r);
  206562. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206563. currentBrush = radialGradient;
  206564. }
  206565. else
  206566. {
  206567. linearGradient = 0;
  206568. const Point<float>& p1 = fillType.gradient->point1;
  206569. const Point<float>& p2 = fillType.gradient->point2;
  206570. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206571. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206572. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206573. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206574. currentBrush = linearGradient;
  206575. }
  206576. }
  206577. }
  206578. }
  206579. //xxx most of these members should probably be private...
  206580. Direct2DLowLevelGraphicsContext& owner;
  206581. Point<int> origin;
  206582. Font font;
  206583. float fontScaling;
  206584. IDWriteFontFace* currentFontFace;
  206585. ComSmartPtr <IDWriteFontFace> localFontFace;
  206586. FillType fillType;
  206587. Image image;
  206588. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206589. Rectangle<int> clipRect;
  206590. bool clipsRect, shouldClipRect;
  206591. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206592. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206593. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206594. bool clipsComplex, shouldClipComplex;
  206595. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206596. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206597. ComSmartPtr <ID2D1Layer> rectListLayer;
  206598. bool clipsRectList, shouldClipRectList;
  206599. Image maskImage;
  206600. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206601. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206602. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206603. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206604. bool clipsBitmap, shouldClipBitmap;
  206605. ID2D1Brush* currentBrush;
  206606. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206607. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206608. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206609. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206610. private:
  206611. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState);
  206612. };
  206613. private:
  206614. HWND hwnd;
  206615. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206616. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206617. Rectangle<int> bounds;
  206618. SavedState* currentState;
  206619. OwnedArray<SavedState> states;
  206620. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206621. {
  206622. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206623. }
  206624. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206625. {
  206626. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206627. }
  206628. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206629. {
  206630. transform.transformPoint (x, y);
  206631. return D2D1::Point2F (x, y);
  206632. }
  206633. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206634. {
  206635. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206636. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206637. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206638. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206639. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206640. }
  206641. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206642. {
  206643. ID2D1PathGeometry* p = 0;
  206644. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206645. ComSmartPtr <ID2D1GeometrySink> sink;
  206646. HRESULT hr = p->Open (&sink); // xxx handle error
  206647. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206648. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206649. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206650. hr = sink->Close();
  206651. return p;
  206652. }
  206653. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206654. {
  206655. Path::Iterator it (path);
  206656. while (it.next())
  206657. {
  206658. switch (it.elementType)
  206659. {
  206660. case Path::Iterator::cubicTo:
  206661. {
  206662. D2D1_BEZIER_SEGMENT seg;
  206663. transform.transformPoint (it.x1, it.y1);
  206664. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206665. transform.transformPoint (it.x2, it.y2);
  206666. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206667. transform.transformPoint(it.x3, it.y3);
  206668. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206669. sink->AddBezier (seg);
  206670. break;
  206671. }
  206672. case Path::Iterator::lineTo:
  206673. {
  206674. transform.transformPoint (it.x1, it.y1);
  206675. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206676. break;
  206677. }
  206678. case Path::Iterator::quadraticTo:
  206679. {
  206680. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206681. transform.transformPoint (it.x1, it.y1);
  206682. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206683. transform.transformPoint (it.x2, it.y2);
  206684. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206685. sink->AddQuadraticBezier (seg);
  206686. break;
  206687. }
  206688. case Path::Iterator::closePath:
  206689. {
  206690. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206691. break;
  206692. }
  206693. case Path::Iterator::startNewSubPath:
  206694. {
  206695. transform.transformPoint (it.x1, it.y1);
  206696. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206697. break;
  206698. }
  206699. }
  206700. }
  206701. }
  206702. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206703. {
  206704. ID2D1PathGeometry* p = 0;
  206705. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206706. ComSmartPtr <ID2D1GeometrySink> sink;
  206707. HRESULT hr = p->Open (&sink);
  206708. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206709. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206710. hr = sink->Close();
  206711. return p;
  206712. }
  206713. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206714. {
  206715. D2D1::Matrix3x2F matrix;
  206716. matrix._11 = transform.mat00;
  206717. matrix._12 = transform.mat10;
  206718. matrix._21 = transform.mat01;
  206719. matrix._22 = transform.mat11;
  206720. matrix._31 = transform.mat02;
  206721. matrix._32 = transform.mat12;
  206722. return matrix;
  206723. }
  206724. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DLowLevelGraphicsContext);
  206725. };
  206726. #endif
  206727. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206728. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206729. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206730. // compiled on its own).
  206731. #if JUCE_INCLUDED_FILE
  206732. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206733. // these are in the windows SDK, but need to be repeated here for GCC..
  206734. #ifndef GET_APPCOMMAND_LPARAM
  206735. #define FAPPCOMMAND_MASK 0xF000
  206736. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206737. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206738. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206739. #define APPCOMMAND_MEDIA_STOP 13
  206740. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206741. #define WM_APPCOMMAND 0x0319
  206742. #endif
  206743. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206744. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206745. extern bool juce_IsRunningInWine();
  206746. #ifndef ULW_ALPHA
  206747. #define ULW_ALPHA 0x00000002
  206748. #endif
  206749. #ifndef AC_SRC_ALPHA
  206750. #define AC_SRC_ALPHA 0x01
  206751. #endif
  206752. static bool shouldDeactivateTitleBar = true;
  206753. #define WM_TRAYNOTIFY WM_USER + 100
  206754. using ::abs;
  206755. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206756. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206757. bool Desktop::canUseSemiTransparentWindows() throw()
  206758. {
  206759. if (updateLayeredWindow == 0)
  206760. {
  206761. if (! juce_IsRunningInWine())
  206762. {
  206763. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206764. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206765. }
  206766. }
  206767. return updateLayeredWindow != 0;
  206768. }
  206769. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206770. {
  206771. return upright;
  206772. }
  206773. const int extendedKeyModifier = 0x10000;
  206774. const int KeyPress::spaceKey = VK_SPACE;
  206775. const int KeyPress::returnKey = VK_RETURN;
  206776. const int KeyPress::escapeKey = VK_ESCAPE;
  206777. const int KeyPress::backspaceKey = VK_BACK;
  206778. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206779. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206780. const int KeyPress::tabKey = VK_TAB;
  206781. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206782. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206783. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206784. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206785. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206786. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206787. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206788. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206789. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206790. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206791. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206792. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206793. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206794. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206795. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206796. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206797. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206798. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206799. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206800. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206801. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206802. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206803. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206804. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206805. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206806. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206807. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206808. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206809. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206810. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206811. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206812. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206813. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206814. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206815. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206816. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206817. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206818. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206819. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206820. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206821. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206822. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206823. const int KeyPress::playKey = 0x30000;
  206824. const int KeyPress::stopKey = 0x30001;
  206825. const int KeyPress::fastForwardKey = 0x30002;
  206826. const int KeyPress::rewindKey = 0x30003;
  206827. class WindowsBitmapImage : public Image::SharedImage
  206828. {
  206829. public:
  206830. HBITMAP hBitmap;
  206831. BITMAPV4HEADER bitmapInfo;
  206832. HDC hdc;
  206833. unsigned char* bitmapData;
  206834. WindowsBitmapImage (const Image::PixelFormat format_,
  206835. const int w, const int h, const bool clearImage)
  206836. : Image::SharedImage (format_, w, h)
  206837. {
  206838. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206839. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206840. zerostruct (bitmapInfo);
  206841. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206842. bitmapInfo.bV4Width = w;
  206843. bitmapInfo.bV4Height = h;
  206844. bitmapInfo.bV4Planes = 1;
  206845. bitmapInfo.bV4CSType = 1;
  206846. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206847. if (format_ == Image::ARGB)
  206848. {
  206849. bitmapInfo.bV4AlphaMask = 0xff000000;
  206850. bitmapInfo.bV4RedMask = 0xff0000;
  206851. bitmapInfo.bV4GreenMask = 0xff00;
  206852. bitmapInfo.bV4BlueMask = 0xff;
  206853. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206854. }
  206855. else
  206856. {
  206857. bitmapInfo.bV4V4Compression = BI_RGB;
  206858. }
  206859. lineStride = -((w * pixelStride + 3) & ~3);
  206860. HDC dc = GetDC (0);
  206861. hdc = CreateCompatibleDC (dc);
  206862. ReleaseDC (0, dc);
  206863. SetMapMode (hdc, MM_TEXT);
  206864. hBitmap = CreateDIBSection (hdc,
  206865. (BITMAPINFO*) &(bitmapInfo),
  206866. DIB_RGB_COLORS,
  206867. (void**) &bitmapData,
  206868. 0, 0);
  206869. SelectObject (hdc, hBitmap);
  206870. if (format_ == Image::ARGB && clearImage)
  206871. zeromem (bitmapData, abs (h * lineStride));
  206872. imageData = bitmapData - (lineStride * (h - 1));
  206873. }
  206874. ~WindowsBitmapImage()
  206875. {
  206876. DeleteDC (hdc);
  206877. DeleteObject (hBitmap);
  206878. }
  206879. Image::ImageType getType() const { return Image::NativeImage; }
  206880. LowLevelGraphicsContext* createLowLevelContext()
  206881. {
  206882. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206883. }
  206884. Image::SharedImage* clone()
  206885. {
  206886. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206887. for (int i = 0; i < height; ++i)
  206888. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206889. return im;
  206890. }
  206891. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206892. const int x, const int y,
  206893. const RectangleList& maskedRegion,
  206894. const uint8 updateLayeredWindowAlpha) throw()
  206895. {
  206896. static HDRAWDIB hdd = 0;
  206897. static bool needToCreateDrawDib = true;
  206898. if (needToCreateDrawDib)
  206899. {
  206900. needToCreateDrawDib = false;
  206901. HDC dc = GetDC (0);
  206902. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206903. ReleaseDC (0, dc);
  206904. // only open if we're not palettised
  206905. if (n > 8)
  206906. hdd = DrawDibOpen();
  206907. }
  206908. SetMapMode (dc, MM_TEXT);
  206909. if (transparent)
  206910. {
  206911. POINT p, pos;
  206912. SIZE size;
  206913. RECT windowBounds;
  206914. GetWindowRect (hwnd, &windowBounds);
  206915. p.x = -x;
  206916. p.y = -y;
  206917. pos.x = windowBounds.left;
  206918. pos.y = windowBounds.top;
  206919. size.cx = windowBounds.right - windowBounds.left;
  206920. size.cy = windowBounds.bottom - windowBounds.top;
  206921. BLENDFUNCTION bf;
  206922. bf.AlphaFormat = AC_SRC_ALPHA;
  206923. bf.BlendFlags = 0;
  206924. bf.BlendOp = AC_SRC_OVER;
  206925. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206926. if (! maskedRegion.isEmpty())
  206927. {
  206928. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206929. {
  206930. const Rectangle<int>& r = *i.getRectangle();
  206931. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206932. }
  206933. }
  206934. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206935. }
  206936. else
  206937. {
  206938. int savedDC = 0;
  206939. if (! maskedRegion.isEmpty())
  206940. {
  206941. savedDC = SaveDC (dc);
  206942. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206943. {
  206944. const Rectangle<int>& r = *i.getRectangle();
  206945. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206946. }
  206947. }
  206948. if (hdd == 0)
  206949. {
  206950. StretchDIBits (dc,
  206951. x, y, width, height,
  206952. 0, 0, width, height,
  206953. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206954. DIB_RGB_COLORS, SRCCOPY);
  206955. }
  206956. else
  206957. {
  206958. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206959. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206960. 0, 0, width, height, 0);
  206961. }
  206962. if (! maskedRegion.isEmpty())
  206963. RestoreDC (dc, savedDC);
  206964. }
  206965. }
  206966. private:
  206967. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage);
  206968. };
  206969. namespace IconConverters
  206970. {
  206971. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206972. {
  206973. Image im;
  206974. if (bitmap != 0)
  206975. {
  206976. BITMAP bm;
  206977. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206978. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206979. {
  206980. HDC tempDC = GetDC (0);
  206981. HDC dc = CreateCompatibleDC (tempDC);
  206982. ReleaseDC (0, tempDC);
  206983. SelectObject (dc, bitmap);
  206984. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206985. Image::BitmapData imageData (im, true);
  206986. for (int y = bm.bmHeight; --y >= 0;)
  206987. {
  206988. for (int x = bm.bmWidth; --x >= 0;)
  206989. {
  206990. COLORREF col = GetPixel (dc, x, y);
  206991. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206992. (uint8) GetGValue (col),
  206993. (uint8) GetBValue (col)));
  206994. }
  206995. }
  206996. DeleteDC (dc);
  206997. }
  206998. }
  206999. return im;
  207000. }
  207001. const Image createImageFromHICON (HICON icon)
  207002. {
  207003. ICONINFO info;
  207004. if (GetIconInfo (icon, &info))
  207005. {
  207006. Image mask (createImageFromHBITMAP (info.hbmMask));
  207007. Image image (createImageFromHBITMAP (info.hbmColor));
  207008. if (mask.isValid() && image.isValid())
  207009. {
  207010. for (int y = image.getHeight(); --y >= 0;)
  207011. {
  207012. for (int x = image.getWidth(); --x >= 0;)
  207013. {
  207014. const float brightness = mask.getPixelAt (x, y).getBrightness();
  207015. if (brightness > 0.0f)
  207016. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  207017. }
  207018. }
  207019. return image;
  207020. }
  207021. }
  207022. return Image::null;
  207023. }
  207024. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  207025. {
  207026. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  207027. Image bitmap (nativeBitmap);
  207028. {
  207029. Graphics g (bitmap);
  207030. g.drawImageAt (image, 0, 0);
  207031. }
  207032. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  207033. ICONINFO info;
  207034. info.fIcon = isIcon;
  207035. info.xHotspot = hotspotX;
  207036. info.yHotspot = hotspotY;
  207037. info.hbmMask = mask;
  207038. info.hbmColor = nativeBitmap->hBitmap;
  207039. HICON hi = CreateIconIndirect (&info);
  207040. DeleteObject (mask);
  207041. return hi;
  207042. }
  207043. }
  207044. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  207045. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  207046. {
  207047. SHORT k = (SHORT) keyCode;
  207048. if ((keyCode & extendedKeyModifier) == 0
  207049. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  207050. k += (SHORT) 'A' - (SHORT) 'a';
  207051. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  207052. (SHORT) '+', VK_OEM_PLUS,
  207053. (SHORT) '-', VK_OEM_MINUS,
  207054. (SHORT) '.', VK_OEM_PERIOD,
  207055. (SHORT) ';', VK_OEM_1,
  207056. (SHORT) ':', VK_OEM_1,
  207057. (SHORT) '/', VK_OEM_2,
  207058. (SHORT) '?', VK_OEM_2,
  207059. (SHORT) '[', VK_OEM_4,
  207060. (SHORT) ']', VK_OEM_6 };
  207061. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  207062. if (k == translatedValues [i])
  207063. k = translatedValues [i + 1];
  207064. return (GetKeyState (k) & 0x8000) != 0;
  207065. }
  207066. class Win32ComponentPeer : public ComponentPeer
  207067. {
  207068. public:
  207069. enum RenderingEngineType
  207070. {
  207071. softwareRenderingEngine = 0,
  207072. direct2DRenderingEngine
  207073. };
  207074. Win32ComponentPeer (Component* const component,
  207075. const int windowStyleFlags,
  207076. HWND parentToAddTo_)
  207077. : ComponentPeer (component, windowStyleFlags),
  207078. dontRepaint (false),
  207079. #if JUCE_DIRECT2D
  207080. currentRenderingEngine (direct2DRenderingEngine),
  207081. #else
  207082. currentRenderingEngine (softwareRenderingEngine),
  207083. #endif
  207084. fullScreen (false),
  207085. isDragging (false),
  207086. isMouseOver (false),
  207087. hasCreatedCaret (false),
  207088. constrainerIsResizing (false),
  207089. currentWindowIcon (0),
  207090. dropTarget (0),
  207091. updateLayeredWindowAlpha (255),
  207092. parentToAddTo (parentToAddTo_)
  207093. {
  207094. callFunctionIfNotLocked (&createWindowCallback, this);
  207095. setTitle (component->getName());
  207096. if ((windowStyleFlags & windowHasDropShadow) != 0
  207097. && Desktop::canUseSemiTransparentWindows())
  207098. {
  207099. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  207100. if (shadower != 0)
  207101. shadower->setOwner (component);
  207102. }
  207103. }
  207104. ~Win32ComponentPeer()
  207105. {
  207106. setTaskBarIcon (Image());
  207107. shadower = 0;
  207108. // do this before the next bit to avoid messages arriving for this window
  207109. // before it's destroyed
  207110. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  207111. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  207112. if (currentWindowIcon != 0)
  207113. DestroyIcon (currentWindowIcon);
  207114. if (dropTarget != 0)
  207115. {
  207116. dropTarget->Release();
  207117. dropTarget = 0;
  207118. }
  207119. #if JUCE_DIRECT2D
  207120. direct2DContext = 0;
  207121. #endif
  207122. }
  207123. void* getNativeHandle() const
  207124. {
  207125. return hwnd;
  207126. }
  207127. void setVisible (bool shouldBeVisible)
  207128. {
  207129. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207130. if (shouldBeVisible)
  207131. InvalidateRect (hwnd, 0, 0);
  207132. else
  207133. lastPaintTime = 0;
  207134. }
  207135. void setTitle (const String& title)
  207136. {
  207137. SetWindowText (hwnd, title);
  207138. }
  207139. void setPosition (int x, int y)
  207140. {
  207141. offsetWithinParent (x, y);
  207142. SetWindowPos (hwnd, 0,
  207143. x - windowBorder.getLeft(),
  207144. y - windowBorder.getTop(),
  207145. 0, 0,
  207146. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207147. }
  207148. void repaintNowIfTransparent()
  207149. {
  207150. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  207151. handlePaintMessage();
  207152. }
  207153. void updateBorderSize()
  207154. {
  207155. WINDOWINFO info;
  207156. info.cbSize = sizeof (info);
  207157. if (GetWindowInfo (hwnd, &info))
  207158. {
  207159. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  207160. info.rcClient.left - info.rcWindow.left,
  207161. info.rcWindow.bottom - info.rcClient.bottom,
  207162. info.rcWindow.right - info.rcClient.right);
  207163. }
  207164. #if JUCE_DIRECT2D
  207165. if (direct2DContext != 0)
  207166. direct2DContext->resized();
  207167. #endif
  207168. }
  207169. void setSize (int w, int h)
  207170. {
  207171. SetWindowPos (hwnd, 0, 0, 0,
  207172. w + windowBorder.getLeftAndRight(),
  207173. h + windowBorder.getTopAndBottom(),
  207174. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207175. updateBorderSize();
  207176. repaintNowIfTransparent();
  207177. }
  207178. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  207179. {
  207180. fullScreen = isNowFullScreen;
  207181. offsetWithinParent (x, y);
  207182. SetWindowPos (hwnd, 0,
  207183. x - windowBorder.getLeft(),
  207184. y - windowBorder.getTop(),
  207185. w + windowBorder.getLeftAndRight(),
  207186. h + windowBorder.getTopAndBottom(),
  207187. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207188. updateBorderSize();
  207189. repaintNowIfTransparent();
  207190. }
  207191. const Rectangle<int> getBounds() const
  207192. {
  207193. RECT r;
  207194. GetWindowRect (hwnd, &r);
  207195. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  207196. HWND parentH = GetParent (hwnd);
  207197. if (parentH != 0)
  207198. {
  207199. GetWindowRect (parentH, &r);
  207200. bounds.translate (-r.left, -r.top);
  207201. }
  207202. return windowBorder.subtractedFrom (bounds);
  207203. }
  207204. const Point<int> getScreenPosition() const
  207205. {
  207206. RECT r;
  207207. GetWindowRect (hwnd, &r);
  207208. return Point<int> (r.left + windowBorder.getLeft(),
  207209. r.top + windowBorder.getTop());
  207210. }
  207211. const Point<int> localToGlobal (const Point<int>& relativePosition)
  207212. {
  207213. return relativePosition + getScreenPosition();
  207214. }
  207215. const Point<int> globalToLocal (const Point<int>& screenPosition)
  207216. {
  207217. return screenPosition - getScreenPosition();
  207218. }
  207219. void setAlpha (float newAlpha)
  207220. {
  207221. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  207222. if (component->isOpaque())
  207223. {
  207224. if (newAlpha < 1.0f)
  207225. {
  207226. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  207227. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  207228. }
  207229. else
  207230. {
  207231. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  207232. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  207233. }
  207234. }
  207235. else
  207236. {
  207237. updateLayeredWindowAlpha = intAlpha;
  207238. component->repaint();
  207239. }
  207240. }
  207241. void setMinimised (bool shouldBeMinimised)
  207242. {
  207243. if (shouldBeMinimised != isMinimised())
  207244. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  207245. }
  207246. bool isMinimised() const
  207247. {
  207248. WINDOWPLACEMENT wp;
  207249. wp.length = sizeof (WINDOWPLACEMENT);
  207250. GetWindowPlacement (hwnd, &wp);
  207251. return wp.showCmd == SW_SHOWMINIMIZED;
  207252. }
  207253. void setFullScreen (bool shouldBeFullScreen)
  207254. {
  207255. setMinimised (false);
  207256. if (fullScreen != shouldBeFullScreen)
  207257. {
  207258. fullScreen = shouldBeFullScreen;
  207259. const WeakReference<Component> deletionChecker (component);
  207260. if (! fullScreen)
  207261. {
  207262. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  207263. if (hasTitleBar())
  207264. ShowWindow (hwnd, SW_SHOWNORMAL);
  207265. if (! boundsCopy.isEmpty())
  207266. {
  207267. setBounds (boundsCopy.getX(),
  207268. boundsCopy.getY(),
  207269. boundsCopy.getWidth(),
  207270. boundsCopy.getHeight(),
  207271. false);
  207272. }
  207273. }
  207274. else
  207275. {
  207276. if (hasTitleBar())
  207277. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207278. else
  207279. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207280. }
  207281. if (deletionChecker != 0)
  207282. handleMovedOrResized();
  207283. }
  207284. }
  207285. bool isFullScreen() const
  207286. {
  207287. if (! hasTitleBar())
  207288. return fullScreen;
  207289. WINDOWPLACEMENT wp;
  207290. wp.length = sizeof (wp);
  207291. GetWindowPlacement (hwnd, &wp);
  207292. return wp.showCmd == SW_SHOWMAXIMIZED;
  207293. }
  207294. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207295. {
  207296. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  207297. && isPositiveAndBelow (position.getY(), component->getHeight())))
  207298. return false;
  207299. RECT r;
  207300. GetWindowRect (hwnd, &r);
  207301. POINT p;
  207302. p.x = position.getX() + r.left + windowBorder.getLeft();
  207303. p.y = position.getY() + r.top + windowBorder.getTop();
  207304. HWND w = WindowFromPoint (p);
  207305. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207306. }
  207307. const BorderSize getFrameSize() const
  207308. {
  207309. return windowBorder;
  207310. }
  207311. bool setAlwaysOnTop (bool alwaysOnTop)
  207312. {
  207313. const bool oldDeactivate = shouldDeactivateTitleBar;
  207314. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207315. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207316. 0, 0, 0, 0,
  207317. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207318. shouldDeactivateTitleBar = oldDeactivate;
  207319. if (shadower != 0)
  207320. shadower->componentBroughtToFront (*component);
  207321. return true;
  207322. }
  207323. void toFront (bool makeActive)
  207324. {
  207325. setMinimised (false);
  207326. const bool oldDeactivate = shouldDeactivateTitleBar;
  207327. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207328. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207329. shouldDeactivateTitleBar = oldDeactivate;
  207330. if (! makeActive)
  207331. {
  207332. // in this case a broughttofront call won't have occured, so do it now..
  207333. handleBroughtToFront();
  207334. }
  207335. }
  207336. void toBehind (ComponentPeer* other)
  207337. {
  207338. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207339. jassert (otherPeer != 0); // wrong type of window?
  207340. if (otherPeer != 0)
  207341. {
  207342. setMinimised (false);
  207343. // must be careful not to try to put a topmost window behind a normal one, or win32
  207344. // promotes the normal one to be topmost!
  207345. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207346. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207347. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207348. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207349. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207350. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207351. }
  207352. }
  207353. bool isFocused() const
  207354. {
  207355. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207356. }
  207357. void grabFocus()
  207358. {
  207359. const bool oldDeactivate = shouldDeactivateTitleBar;
  207360. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207361. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207362. shouldDeactivateTitleBar = oldDeactivate;
  207363. }
  207364. void textInputRequired (const Point<int>&)
  207365. {
  207366. if (! hasCreatedCaret)
  207367. {
  207368. hasCreatedCaret = true;
  207369. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207370. }
  207371. ShowCaret (hwnd);
  207372. SetCaretPos (0, 0);
  207373. }
  207374. void repaint (const Rectangle<int>& area)
  207375. {
  207376. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207377. InvalidateRect (hwnd, &r, FALSE);
  207378. }
  207379. void performAnyPendingRepaintsNow()
  207380. {
  207381. MSG m;
  207382. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207383. DispatchMessage (&m);
  207384. }
  207385. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207386. {
  207387. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207388. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207389. return 0;
  207390. }
  207391. void setTaskBarIcon (const Image& image)
  207392. {
  207393. if (image.isValid())
  207394. {
  207395. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  207396. if (taskBarIcon == 0)
  207397. {
  207398. taskBarIcon = new NOTIFYICONDATA();
  207399. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  207400. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207401. taskBarIcon->hWnd = (HWND) hwnd;
  207402. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207403. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207404. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207405. taskBarIcon->hIcon = hicon;
  207406. taskBarIcon->szTip[0] = 0;
  207407. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207408. }
  207409. else
  207410. {
  207411. HICON oldIcon = taskBarIcon->hIcon;
  207412. taskBarIcon->hIcon = hicon;
  207413. taskBarIcon->uFlags = NIF_ICON;
  207414. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207415. DestroyIcon (oldIcon);
  207416. }
  207417. }
  207418. else if (taskBarIcon != 0)
  207419. {
  207420. taskBarIcon->uFlags = 0;
  207421. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207422. DestroyIcon (taskBarIcon->hIcon);
  207423. taskBarIcon = 0;
  207424. }
  207425. }
  207426. void setTaskBarIconToolTip (const String& toolTip) const
  207427. {
  207428. if (taskBarIcon != 0)
  207429. {
  207430. taskBarIcon->uFlags = NIF_TIP;
  207431. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207432. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207433. }
  207434. }
  207435. void handleTaskBarEvent (const LPARAM lParam)
  207436. {
  207437. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207438. {
  207439. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207440. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207441. {
  207442. Component* const current = Component::getCurrentlyModalComponent();
  207443. if (current != 0)
  207444. current->inputAttemptWhenModal();
  207445. }
  207446. }
  207447. else
  207448. {
  207449. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  207450. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207451. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  207452. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207453. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  207454. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207455. eventMods = eventMods.withoutMouseButtons();
  207456. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  207457. Point<int>(), eventMods, component, component, Time (getMouseEventTime()),
  207458. Point<int>(), Time (getMouseEventTime()), 1, false);
  207459. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207460. {
  207461. SetFocus (hwnd);
  207462. SetForegroundWindow (hwnd);
  207463. component->mouseDown (e);
  207464. }
  207465. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207466. {
  207467. component->mouseUp (e);
  207468. }
  207469. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207470. {
  207471. component->mouseDoubleClick (e);
  207472. }
  207473. else if (lParam == WM_MOUSEMOVE)
  207474. {
  207475. component->mouseMove (e);
  207476. }
  207477. }
  207478. }
  207479. bool isInside (HWND h) const
  207480. {
  207481. return GetAncestor (hwnd, GA_ROOT) == h;
  207482. }
  207483. static void updateKeyModifiers() throw()
  207484. {
  207485. int keyMods = 0;
  207486. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207487. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207488. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207489. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207490. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207491. }
  207492. static void updateModifiersFromWParam (const WPARAM wParam)
  207493. {
  207494. int mouseMods = 0;
  207495. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207496. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207497. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207498. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207499. updateKeyModifiers();
  207500. }
  207501. static int64 getMouseEventTime()
  207502. {
  207503. static int64 eventTimeOffset = 0;
  207504. static DWORD lastMessageTime = 0;
  207505. const DWORD thisMessageTime = GetMessageTime();
  207506. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207507. {
  207508. lastMessageTime = thisMessageTime;
  207509. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207510. }
  207511. return eventTimeOffset + thisMessageTime;
  207512. }
  207513. bool dontRepaint;
  207514. static ModifierKeys currentModifiers;
  207515. static ModifierKeys modifiersAtLastCallback;
  207516. private:
  207517. HWND hwnd, parentToAddTo;
  207518. ScopedPointer<DropShadower> shadower;
  207519. RenderingEngineType currentRenderingEngine;
  207520. #if JUCE_DIRECT2D
  207521. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207522. #endif
  207523. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret, constrainerIsResizing;
  207524. BorderSize windowBorder;
  207525. HICON currentWindowIcon;
  207526. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207527. IDropTarget* dropTarget;
  207528. uint8 updateLayeredWindowAlpha;
  207529. class TemporaryImage : public Timer
  207530. {
  207531. public:
  207532. TemporaryImage() {}
  207533. ~TemporaryImage() {}
  207534. const Image& getImage (const bool transparent, const int w, const int h)
  207535. {
  207536. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207537. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207538. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207539. startTimer (3000);
  207540. return image;
  207541. }
  207542. void timerCallback()
  207543. {
  207544. stopTimer();
  207545. image = Image::null;
  207546. }
  207547. private:
  207548. Image image;
  207549. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage);
  207550. };
  207551. TemporaryImage offscreenImageGenerator;
  207552. class WindowClassHolder : public DeletedAtShutdown
  207553. {
  207554. public:
  207555. WindowClassHolder()
  207556. : windowClassName ("JUCE_")
  207557. {
  207558. // this name has to be different for each app/dll instance because otherwise
  207559. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207560. // window class).
  207561. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207562. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207563. TCHAR moduleFile [1024];
  207564. moduleFile[0] = 0;
  207565. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207566. WORD iconNum = 0;
  207567. WNDCLASSEX wcex;
  207568. wcex.cbSize = sizeof (wcex);
  207569. wcex.style = CS_OWNDC;
  207570. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207571. wcex.lpszClassName = windowClassName;
  207572. wcex.cbClsExtra = 0;
  207573. wcex.cbWndExtra = 32;
  207574. wcex.hInstance = moduleHandle;
  207575. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207576. iconNum = 1;
  207577. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207578. wcex.hCursor = 0;
  207579. wcex.hbrBackground = 0;
  207580. wcex.lpszMenuName = 0;
  207581. RegisterClassEx (&wcex);
  207582. }
  207583. ~WindowClassHolder()
  207584. {
  207585. if (ComponentPeer::getNumPeers() == 0)
  207586. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207587. clearSingletonInstance();
  207588. }
  207589. String windowClassName;
  207590. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207591. };
  207592. static void* createWindowCallback (void* userData)
  207593. {
  207594. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207595. return 0;
  207596. }
  207597. void createWindow()
  207598. {
  207599. DWORD exstyle = WS_EX_ACCEPTFILES;
  207600. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207601. if (hasTitleBar())
  207602. {
  207603. type |= WS_OVERLAPPED;
  207604. if ((styleFlags & windowHasCloseButton) != 0)
  207605. {
  207606. type |= WS_SYSMENU;
  207607. }
  207608. else
  207609. {
  207610. // annoyingly, windows won't let you have a min/max button without a close button
  207611. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207612. }
  207613. if ((styleFlags & windowIsResizable) != 0)
  207614. type |= WS_THICKFRAME;
  207615. }
  207616. else if (parentToAddTo != 0)
  207617. {
  207618. type |= WS_CHILD;
  207619. }
  207620. else
  207621. {
  207622. type |= WS_POPUP | WS_SYSMENU;
  207623. }
  207624. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207625. exstyle |= WS_EX_TOOLWINDOW;
  207626. else
  207627. exstyle |= WS_EX_APPWINDOW;
  207628. if ((styleFlags & windowHasMinimiseButton) != 0)
  207629. type |= WS_MINIMIZEBOX;
  207630. if ((styleFlags & windowHasMaximiseButton) != 0)
  207631. type |= WS_MAXIMIZEBOX;
  207632. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207633. exstyle |= WS_EX_TRANSPARENT;
  207634. if ((styleFlags & windowIsSemiTransparent) != 0
  207635. && Desktop::canUseSemiTransparentWindows())
  207636. exstyle |= WS_EX_LAYERED;
  207637. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207638. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207639. #if JUCE_DIRECT2D
  207640. updateDirect2DContext();
  207641. #endif
  207642. if (hwnd != 0)
  207643. {
  207644. SetWindowLongPtr (hwnd, 0, 0);
  207645. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207646. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207647. if (dropTarget == 0)
  207648. dropTarget = new JuceDropTarget (this);
  207649. RegisterDragDrop (hwnd, dropTarget);
  207650. updateBorderSize();
  207651. // Calling this function here is (for some reason) necessary to make Windows
  207652. // correctly enable the menu items that we specify in the wm_initmenu message.
  207653. GetSystemMenu (hwnd, false);
  207654. const float alpha = component->getAlpha();
  207655. if (alpha < 1.0f)
  207656. setAlpha (alpha);
  207657. }
  207658. else
  207659. {
  207660. jassertfalse;
  207661. }
  207662. }
  207663. static void* destroyWindowCallback (void* handle)
  207664. {
  207665. RevokeDragDrop ((HWND) handle);
  207666. DestroyWindow ((HWND) handle);
  207667. return 0;
  207668. }
  207669. static void* toFrontCallback1 (void* h)
  207670. {
  207671. SetForegroundWindow ((HWND) h);
  207672. return 0;
  207673. }
  207674. static void* toFrontCallback2 (void* h)
  207675. {
  207676. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207677. return 0;
  207678. }
  207679. static void* setFocusCallback (void* h)
  207680. {
  207681. SetFocus ((HWND) h);
  207682. return 0;
  207683. }
  207684. static void* getFocusCallback (void*)
  207685. {
  207686. return GetFocus();
  207687. }
  207688. void offsetWithinParent (int& x, int& y) const
  207689. {
  207690. if (isUsingUpdateLayeredWindow())
  207691. {
  207692. HWND parentHwnd = GetParent (hwnd);
  207693. if (parentHwnd != 0)
  207694. {
  207695. RECT parentRect;
  207696. GetWindowRect (parentHwnd, &parentRect);
  207697. x += parentRect.left;
  207698. y += parentRect.top;
  207699. }
  207700. }
  207701. }
  207702. bool isUsingUpdateLayeredWindow() const
  207703. {
  207704. return ! component->isOpaque();
  207705. }
  207706. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207707. void setIcon (const Image& newIcon)
  207708. {
  207709. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207710. if (hicon != 0)
  207711. {
  207712. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207713. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207714. if (currentWindowIcon != 0)
  207715. DestroyIcon (currentWindowIcon);
  207716. currentWindowIcon = hicon;
  207717. }
  207718. }
  207719. void handlePaintMessage()
  207720. {
  207721. #if JUCE_DIRECT2D
  207722. if (direct2DContext != 0)
  207723. {
  207724. RECT r;
  207725. if (GetUpdateRect (hwnd, &r, false))
  207726. {
  207727. direct2DContext->start();
  207728. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207729. handlePaint (*direct2DContext);
  207730. direct2DContext->end();
  207731. }
  207732. }
  207733. else
  207734. #endif
  207735. {
  207736. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207737. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207738. PAINTSTRUCT paintStruct;
  207739. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207740. // message and become re-entrant, but that's OK
  207741. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207742. // corrupt the image it's using to paint into, so do a check here.
  207743. static bool reentrant = false;
  207744. if (reentrant)
  207745. {
  207746. DeleteObject (rgn);
  207747. EndPaint (hwnd, &paintStruct);
  207748. return;
  207749. }
  207750. reentrant = true;
  207751. // this is the rectangle to update..
  207752. int x = paintStruct.rcPaint.left;
  207753. int y = paintStruct.rcPaint.top;
  207754. int w = paintStruct.rcPaint.right - x;
  207755. int h = paintStruct.rcPaint.bottom - y;
  207756. const bool transparent = isUsingUpdateLayeredWindow();
  207757. if (transparent)
  207758. {
  207759. // it's not possible to have a transparent window with a title bar at the moment!
  207760. jassert (! hasTitleBar());
  207761. RECT r;
  207762. GetWindowRect (hwnd, &r);
  207763. x = y = 0;
  207764. w = r.right - r.left;
  207765. h = r.bottom - r.top;
  207766. }
  207767. if (w > 0 && h > 0)
  207768. {
  207769. clearMaskedRegion();
  207770. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207771. RectangleList contextClip;
  207772. const Rectangle<int> clipBounds (0, 0, w, h);
  207773. bool needToPaintAll = true;
  207774. if (regionType == COMPLEXREGION && ! transparent)
  207775. {
  207776. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207777. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207778. DeleteObject (clipRgn);
  207779. char rgnData [8192];
  207780. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207781. if (res > 0 && res <= sizeof (rgnData))
  207782. {
  207783. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207784. if (hdr->iType == RDH_RECTANGLES
  207785. && hdr->rcBound.right - hdr->rcBound.left >= w
  207786. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207787. {
  207788. needToPaintAll = false;
  207789. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207790. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207791. while (--num >= 0)
  207792. {
  207793. if (rects->right <= x + w && rects->bottom <= y + h)
  207794. {
  207795. const int cx = jmax (x, (int) rects->left);
  207796. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207797. .getIntersection (clipBounds));
  207798. }
  207799. else
  207800. {
  207801. needToPaintAll = true;
  207802. break;
  207803. }
  207804. ++rects;
  207805. }
  207806. }
  207807. }
  207808. }
  207809. if (needToPaintAll)
  207810. {
  207811. contextClip.clear();
  207812. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207813. }
  207814. if (transparent)
  207815. {
  207816. RectangleList::Iterator i (contextClip);
  207817. while (i.next())
  207818. offscreenImage.clear (*i.getRectangle());
  207819. }
  207820. // if the component's not opaque, this won't draw properly unless the platform can support this
  207821. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207822. updateCurrentModifiers();
  207823. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207824. handlePaint (context);
  207825. if (! dontRepaint)
  207826. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207827. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207828. }
  207829. DeleteObject (rgn);
  207830. EndPaint (hwnd, &paintStruct);
  207831. reentrant = false;
  207832. }
  207833. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207834. _fpreset(); // because some graphics cards can unmask FP exceptions
  207835. #endif
  207836. lastPaintTime = Time::getMillisecondCounter();
  207837. }
  207838. void doMouseEvent (const Point<int>& position)
  207839. {
  207840. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207841. }
  207842. const StringArray getAvailableRenderingEngines()
  207843. {
  207844. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207845. #if JUCE_DIRECT2D
  207846. // xxx is this correct? Seems to enable it on Vista too??
  207847. OSVERSIONINFO info;
  207848. zerostruct (info);
  207849. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207850. GetVersionEx (&info);
  207851. if (info.dwMajorVersion >= 6)
  207852. s.add ("Direct2D");
  207853. #endif
  207854. return s;
  207855. }
  207856. int getCurrentRenderingEngine() throw()
  207857. {
  207858. return currentRenderingEngine;
  207859. }
  207860. #if JUCE_DIRECT2D
  207861. void updateDirect2DContext()
  207862. {
  207863. if (currentRenderingEngine != direct2DRenderingEngine)
  207864. direct2DContext = 0;
  207865. else if (direct2DContext == 0)
  207866. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207867. }
  207868. #endif
  207869. void setCurrentRenderingEngine (int index)
  207870. {
  207871. (void) index;
  207872. #if JUCE_DIRECT2D
  207873. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207874. updateDirect2DContext();
  207875. repaint (component->getLocalBounds());
  207876. #endif
  207877. }
  207878. void doMouseMove (const Point<int>& position)
  207879. {
  207880. if (! isMouseOver)
  207881. {
  207882. isMouseOver = true;
  207883. updateKeyModifiers();
  207884. TRACKMOUSEEVENT tme;
  207885. tme.cbSize = sizeof (tme);
  207886. tme.dwFlags = TME_LEAVE;
  207887. tme.hwndTrack = hwnd;
  207888. tme.dwHoverTime = 0;
  207889. if (! TrackMouseEvent (&tme))
  207890. jassertfalse;
  207891. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207892. }
  207893. else if (! isDragging)
  207894. {
  207895. if (! contains (position, false))
  207896. return;
  207897. }
  207898. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207899. static uint32 lastMouseTime = 0;
  207900. const uint32 now = Time::getMillisecondCounter();
  207901. const int maxMouseMovesPerSecond = 60;
  207902. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207903. {
  207904. lastMouseTime = now;
  207905. doMouseEvent (position);
  207906. }
  207907. }
  207908. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207909. {
  207910. if (GetCapture() != hwnd)
  207911. SetCapture (hwnd);
  207912. doMouseMove (position);
  207913. updateModifiersFromWParam (wParam);
  207914. isDragging = true;
  207915. doMouseEvent (position);
  207916. }
  207917. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207918. {
  207919. updateModifiersFromWParam (wParam);
  207920. isDragging = false;
  207921. // release the mouse capture if the user has released all buttons
  207922. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207923. ReleaseCapture();
  207924. doMouseEvent (position);
  207925. }
  207926. void doCaptureChanged()
  207927. {
  207928. if (constrainerIsResizing)
  207929. {
  207930. if (constrainer != 0)
  207931. constrainer->resizeEnd();
  207932. constrainerIsResizing = false;
  207933. }
  207934. if (isDragging)
  207935. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207936. }
  207937. void doMouseExit()
  207938. {
  207939. isMouseOver = false;
  207940. doMouseEvent (getCurrentMousePos());
  207941. }
  207942. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207943. {
  207944. updateKeyModifiers();
  207945. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207946. handleMouseWheel (0, position, getMouseEventTime(),
  207947. isVertical ? 0.0f : amount,
  207948. isVertical ? amount : 0.0f);
  207949. }
  207950. void sendModifierKeyChangeIfNeeded()
  207951. {
  207952. if (modifiersAtLastCallback != currentModifiers)
  207953. {
  207954. modifiersAtLastCallback = currentModifiers;
  207955. handleModifierKeysChange();
  207956. }
  207957. }
  207958. bool doKeyUp (const WPARAM key)
  207959. {
  207960. updateKeyModifiers();
  207961. switch (key)
  207962. {
  207963. case VK_SHIFT:
  207964. case VK_CONTROL:
  207965. case VK_MENU:
  207966. case VK_CAPITAL:
  207967. case VK_LWIN:
  207968. case VK_RWIN:
  207969. case VK_APPS:
  207970. case VK_NUMLOCK:
  207971. case VK_SCROLL:
  207972. case VK_LSHIFT:
  207973. case VK_RSHIFT:
  207974. case VK_LCONTROL:
  207975. case VK_LMENU:
  207976. case VK_RCONTROL:
  207977. case VK_RMENU:
  207978. sendModifierKeyChangeIfNeeded();
  207979. }
  207980. return handleKeyUpOrDown (false)
  207981. || Component::getCurrentlyModalComponent() != 0;
  207982. }
  207983. bool doKeyDown (const WPARAM key)
  207984. {
  207985. updateKeyModifiers();
  207986. bool used = false;
  207987. switch (key)
  207988. {
  207989. case VK_SHIFT:
  207990. case VK_LSHIFT:
  207991. case VK_RSHIFT:
  207992. case VK_CONTROL:
  207993. case VK_LCONTROL:
  207994. case VK_RCONTROL:
  207995. case VK_MENU:
  207996. case VK_LMENU:
  207997. case VK_RMENU:
  207998. case VK_LWIN:
  207999. case VK_RWIN:
  208000. case VK_CAPITAL:
  208001. case VK_NUMLOCK:
  208002. case VK_SCROLL:
  208003. case VK_APPS:
  208004. sendModifierKeyChangeIfNeeded();
  208005. break;
  208006. case VK_LEFT:
  208007. case VK_RIGHT:
  208008. case VK_UP:
  208009. case VK_DOWN:
  208010. case VK_PRIOR:
  208011. case VK_NEXT:
  208012. case VK_HOME:
  208013. case VK_END:
  208014. case VK_DELETE:
  208015. case VK_INSERT:
  208016. case VK_F1:
  208017. case VK_F2:
  208018. case VK_F3:
  208019. case VK_F4:
  208020. case VK_F5:
  208021. case VK_F6:
  208022. case VK_F7:
  208023. case VK_F8:
  208024. case VK_F9:
  208025. case VK_F10:
  208026. case VK_F11:
  208027. case VK_F12:
  208028. case VK_F13:
  208029. case VK_F14:
  208030. case VK_F15:
  208031. case VK_F16:
  208032. used = handleKeyUpOrDown (true);
  208033. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  208034. break;
  208035. case VK_ADD:
  208036. case VK_SUBTRACT:
  208037. case VK_MULTIPLY:
  208038. case VK_DIVIDE:
  208039. case VK_SEPARATOR:
  208040. case VK_DECIMAL:
  208041. used = handleKeyUpOrDown (true);
  208042. break;
  208043. default:
  208044. used = handleKeyUpOrDown (true);
  208045. {
  208046. MSG msg;
  208047. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  208048. {
  208049. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  208050. // manually generate the key-press event that matches this key-down.
  208051. const UINT keyChar = MapVirtualKey (key, 2);
  208052. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  208053. }
  208054. }
  208055. break;
  208056. }
  208057. if (Component::getCurrentlyModalComponent() != 0)
  208058. used = true;
  208059. return used;
  208060. }
  208061. bool doKeyChar (int key, const LPARAM flags)
  208062. {
  208063. updateKeyModifiers();
  208064. juce_wchar textChar = (juce_wchar) key;
  208065. const int virtualScanCode = (flags >> 16) & 0xff;
  208066. if (key >= '0' && key <= '9')
  208067. {
  208068. switch (virtualScanCode) // check for a numeric keypad scan-code
  208069. {
  208070. case 0x52:
  208071. case 0x4f:
  208072. case 0x50:
  208073. case 0x51:
  208074. case 0x4b:
  208075. case 0x4c:
  208076. case 0x4d:
  208077. case 0x47:
  208078. case 0x48:
  208079. case 0x49:
  208080. key = (key - '0') + KeyPress::numberPad0;
  208081. break;
  208082. default:
  208083. break;
  208084. }
  208085. }
  208086. else
  208087. {
  208088. // convert the scan code to an unmodified character code..
  208089. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  208090. UINT keyChar = MapVirtualKey (virtualKey, 2);
  208091. keyChar = LOWORD (keyChar);
  208092. if (keyChar != 0)
  208093. key = (int) keyChar;
  208094. // avoid sending junk text characters for some control-key combinations
  208095. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  208096. textChar = 0;
  208097. }
  208098. return handleKeyPress (key, textChar);
  208099. }
  208100. bool doAppCommand (const LPARAM lParam)
  208101. {
  208102. int key = 0;
  208103. switch (GET_APPCOMMAND_LPARAM (lParam))
  208104. {
  208105. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  208106. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  208107. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  208108. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  208109. default: break;
  208110. }
  208111. if (key != 0)
  208112. {
  208113. updateKeyModifiers();
  208114. if (hwnd == GetActiveWindow())
  208115. {
  208116. handleKeyPress (key, 0);
  208117. return true;
  208118. }
  208119. }
  208120. return false;
  208121. }
  208122. bool isConstrainedNativeWindow() const
  208123. {
  208124. return constrainer != 0
  208125. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable);
  208126. }
  208127. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  208128. {
  208129. if (isConstrainedNativeWindow())
  208130. {
  208131. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  208132. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  208133. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208134. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  208135. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  208136. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  208137. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  208138. r->left = pos.getX();
  208139. r->top = pos.getY();
  208140. r->right = pos.getRight();
  208141. r->bottom = pos.getBottom();
  208142. }
  208143. return TRUE;
  208144. }
  208145. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  208146. {
  208147. if (isConstrainedNativeWindow())
  208148. {
  208149. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  208150. && ! Component::isMouseButtonDownAnywhere())
  208151. {
  208152. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  208153. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  208154. constrainer->checkBounds (pos, current,
  208155. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208156. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  208157. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  208158. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  208159. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  208160. wp->x = pos.getX();
  208161. wp->y = pos.getY();
  208162. wp->cx = pos.getWidth();
  208163. wp->cy = pos.getHeight();
  208164. }
  208165. }
  208166. return 0;
  208167. }
  208168. void handleAppActivation (const WPARAM wParam)
  208169. {
  208170. modifiersAtLastCallback = -1;
  208171. updateKeyModifiers();
  208172. if (isMinimised())
  208173. {
  208174. component->repaint();
  208175. handleMovedOrResized();
  208176. if (! ComponentPeer::isValidPeer (this))
  208177. return;
  208178. }
  208179. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  208180. {
  208181. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  208182. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  208183. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  208184. }
  208185. else
  208186. {
  208187. handleBroughtToFront();
  208188. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208189. Component::getCurrentlyModalComponent()->toFront (true);
  208190. }
  208191. }
  208192. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  208193. {
  208194. public:
  208195. JuceDropTarget (Win32ComponentPeer* const owner_)
  208196. : owner (owner_)
  208197. {
  208198. }
  208199. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208200. {
  208201. updateFileList (pDataObject);
  208202. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208203. *pdwEffect = DROPEFFECT_COPY;
  208204. return S_OK;
  208205. }
  208206. HRESULT __stdcall DragLeave()
  208207. {
  208208. owner->handleFileDragExit (files);
  208209. return S_OK;
  208210. }
  208211. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208212. {
  208213. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208214. *pdwEffect = DROPEFFECT_COPY;
  208215. return S_OK;
  208216. }
  208217. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208218. {
  208219. updateFileList (pDataObject);
  208220. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208221. *pdwEffect = DROPEFFECT_COPY;
  208222. return S_OK;
  208223. }
  208224. private:
  208225. Win32ComponentPeer* const owner;
  208226. StringArray files;
  208227. void updateFileList (IDataObject* const pDataObject)
  208228. {
  208229. files.clear();
  208230. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208231. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208232. if (pDataObject->GetData (&format, &medium) == S_OK)
  208233. {
  208234. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  208235. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  208236. unsigned int i = 0;
  208237. if (pDropFiles->fWide)
  208238. {
  208239. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  208240. for (;;)
  208241. {
  208242. unsigned int len = 0;
  208243. while (i + len < totalLen && fname [i + len] != 0)
  208244. ++len;
  208245. if (len == 0)
  208246. break;
  208247. files.add (String (fname + i, len));
  208248. i += len + 1;
  208249. }
  208250. }
  208251. else
  208252. {
  208253. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  208254. for (;;)
  208255. {
  208256. unsigned int len = 0;
  208257. while (i + len < totalLen && fname [i + len] != 0)
  208258. ++len;
  208259. if (len == 0)
  208260. break;
  208261. files.add (String (fname + i, len));
  208262. i += len + 1;
  208263. }
  208264. }
  208265. GlobalUnlock (medium.hGlobal);
  208266. }
  208267. }
  208268. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget);
  208269. };
  208270. void doSettingChange()
  208271. {
  208272. Desktop::getInstance().refreshMonitorSizes();
  208273. if (fullScreen && ! isMinimised())
  208274. {
  208275. const Rectangle<int> r (component->getParentMonitorArea());
  208276. SetWindowPos (hwnd, 0, r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  208277. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  208278. }
  208279. }
  208280. public:
  208281. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208282. {
  208283. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  208284. if (peer != 0)
  208285. {
  208286. jassert (isValidPeer (peer));
  208287. return peer->peerWindowProc (h, message, wParam, lParam);
  208288. }
  208289. return DefWindowProcW (h, message, wParam, lParam);
  208290. }
  208291. private:
  208292. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  208293. {
  208294. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  208295. return callback (userData);
  208296. else
  208297. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  208298. }
  208299. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  208300. {
  208301. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  208302. }
  208303. const Point<int> getCurrentMousePos() throw()
  208304. {
  208305. RECT wr;
  208306. GetWindowRect (hwnd, &wr);
  208307. const DWORD mp = GetMessagePos();
  208308. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  208309. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  208310. }
  208311. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208312. {
  208313. switch (message)
  208314. {
  208315. case WM_NCHITTEST:
  208316. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  208317. return HTTRANSPARENT;
  208318. else if (! hasTitleBar())
  208319. return HTCLIENT;
  208320. break;
  208321. case WM_PAINT:
  208322. handlePaintMessage();
  208323. return 0;
  208324. case WM_NCPAINT:
  208325. if (hasTitleBar())
  208326. break;
  208327. else if (wParam != 1)
  208328. handlePaintMessage();
  208329. return 0;
  208330. case WM_ERASEBKGND:
  208331. case WM_NCCALCSIZE:
  208332. if (hasTitleBar())
  208333. break;
  208334. return 1;
  208335. case WM_MOUSEMOVE:
  208336. doMouseMove (getPointFromLParam (lParam));
  208337. return 0;
  208338. case WM_MOUSELEAVE:
  208339. doMouseExit();
  208340. return 0;
  208341. case WM_LBUTTONDOWN:
  208342. case WM_MBUTTONDOWN:
  208343. case WM_RBUTTONDOWN:
  208344. doMouseDown (getPointFromLParam (lParam), wParam);
  208345. return 0;
  208346. case WM_LBUTTONUP:
  208347. case WM_MBUTTONUP:
  208348. case WM_RBUTTONUP:
  208349. doMouseUp (getPointFromLParam (lParam), wParam);
  208350. return 0;
  208351. case WM_CAPTURECHANGED:
  208352. doCaptureChanged();
  208353. return 0;
  208354. case WM_NCMOUSEMOVE:
  208355. if (hasTitleBar())
  208356. break;
  208357. return 0;
  208358. case 0x020A: /* WM_MOUSEWHEEL */
  208359. case 0x020E: /* WM_MOUSEHWHEEL */
  208360. doMouseWheel (getCurrentMousePos(), wParam, message == 0x020A);
  208361. return 0;
  208362. case WM_SIZING:
  208363. return handleSizeConstraining ((RECT*) lParam, wParam);
  208364. case WM_WINDOWPOSCHANGING:
  208365. return handlePositionChanging ((WINDOWPOS*) lParam);
  208366. case WM_WINDOWPOSCHANGED:
  208367. {
  208368. const Point<int> pos (getCurrentMousePos());
  208369. if (contains (pos, false))
  208370. doMouseEvent (pos);
  208371. }
  208372. handleMovedOrResized();
  208373. if (dontRepaint)
  208374. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208375. return 0;
  208376. case WM_KEYDOWN:
  208377. case WM_SYSKEYDOWN:
  208378. if (doKeyDown (wParam))
  208379. return 0;
  208380. break;
  208381. case WM_KEYUP:
  208382. case WM_SYSKEYUP:
  208383. if (doKeyUp (wParam))
  208384. return 0;
  208385. break;
  208386. case WM_CHAR:
  208387. if (doKeyChar ((int) wParam, lParam))
  208388. return 0;
  208389. break;
  208390. case WM_APPCOMMAND:
  208391. if (doAppCommand (lParam))
  208392. return TRUE;
  208393. break;
  208394. case WM_SETFOCUS:
  208395. updateKeyModifiers();
  208396. handleFocusGain();
  208397. break;
  208398. case WM_KILLFOCUS:
  208399. if (hasCreatedCaret)
  208400. {
  208401. hasCreatedCaret = false;
  208402. DestroyCaret();
  208403. }
  208404. handleFocusLoss();
  208405. break;
  208406. case WM_ACTIVATEAPP:
  208407. // Windows does weird things to process priority when you swap apps,
  208408. // so this forces an update when the app is brought to the front
  208409. if (wParam != FALSE)
  208410. juce_repeatLastProcessPriority();
  208411. else
  208412. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208413. juce_CheckCurrentlyFocusedTopLevelWindow();
  208414. modifiersAtLastCallback = -1;
  208415. return 0;
  208416. case WM_ACTIVATE:
  208417. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208418. {
  208419. handleAppActivation (wParam);
  208420. return 0;
  208421. }
  208422. break;
  208423. case WM_NCACTIVATE:
  208424. // while a temporary window is being shown, prevent Windows from deactivating the
  208425. // title bars of our main windows.
  208426. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208427. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208428. break;
  208429. case WM_MOUSEACTIVATE:
  208430. if (! component->getMouseClickGrabsKeyboardFocus())
  208431. return MA_NOACTIVATE;
  208432. break;
  208433. case WM_SHOWWINDOW:
  208434. if (wParam != 0)
  208435. handleBroughtToFront();
  208436. break;
  208437. case WM_CLOSE:
  208438. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208439. handleUserClosingWindow();
  208440. return 0;
  208441. case WM_QUERYENDSESSION:
  208442. if (JUCEApplication::getInstance() != 0)
  208443. {
  208444. JUCEApplication::getInstance()->systemRequestedQuit();
  208445. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208446. }
  208447. return TRUE;
  208448. case WM_TRAYNOTIFY:
  208449. handleTaskBarEvent (lParam);
  208450. break;
  208451. case WM_SYNCPAINT:
  208452. return 0;
  208453. case WM_DISPLAYCHANGE:
  208454. InvalidateRect (h, 0, 0);
  208455. // intentional fall-through...
  208456. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208457. doSettingChange();
  208458. break;
  208459. case WM_INITMENU:
  208460. if (! hasTitleBar())
  208461. {
  208462. if (isFullScreen())
  208463. {
  208464. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208465. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208466. }
  208467. else if (! isMinimised())
  208468. {
  208469. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208470. }
  208471. }
  208472. break;
  208473. case WM_SYSCOMMAND:
  208474. switch (wParam & 0xfff0)
  208475. {
  208476. case SC_CLOSE:
  208477. if (sendInputAttemptWhenModalMessage())
  208478. return 0;
  208479. if (hasTitleBar())
  208480. {
  208481. PostMessage (h, WM_CLOSE, 0, 0);
  208482. return 0;
  208483. }
  208484. break;
  208485. case SC_KEYMENU:
  208486. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  208487. // situations that can arise if a modal loop is started from an alt-key keypress).
  208488. if (hasTitleBar() && h == GetCapture())
  208489. ReleaseCapture();
  208490. break;
  208491. case SC_MAXIMIZE:
  208492. if (! sendInputAttemptWhenModalMessage())
  208493. setFullScreen (true);
  208494. return 0;
  208495. case SC_MINIMIZE:
  208496. if (sendInputAttemptWhenModalMessage())
  208497. return 0;
  208498. if (! hasTitleBar())
  208499. {
  208500. setMinimised (true);
  208501. return 0;
  208502. }
  208503. break;
  208504. case SC_RESTORE:
  208505. if (sendInputAttemptWhenModalMessage())
  208506. return 0;
  208507. if (hasTitleBar())
  208508. {
  208509. if (isFullScreen())
  208510. {
  208511. setFullScreen (false);
  208512. return 0;
  208513. }
  208514. }
  208515. else
  208516. {
  208517. if (isMinimised())
  208518. setMinimised (false);
  208519. else if (isFullScreen())
  208520. setFullScreen (false);
  208521. return 0;
  208522. }
  208523. break;
  208524. }
  208525. break;
  208526. case WM_NCLBUTTONDOWN:
  208527. if (! sendInputAttemptWhenModalMessage())
  208528. {
  208529. switch (wParam)
  208530. {
  208531. case HTBOTTOM:
  208532. case HTBOTTOMLEFT:
  208533. case HTBOTTOMRIGHT:
  208534. case HTGROWBOX:
  208535. case HTLEFT:
  208536. case HTRIGHT:
  208537. case HTTOP:
  208538. case HTTOPLEFT:
  208539. case HTTOPRIGHT:
  208540. if (isConstrainedNativeWindow())
  208541. {
  208542. constrainerIsResizing = true;
  208543. constrainer->resizeStart();
  208544. }
  208545. break;
  208546. default:
  208547. break;
  208548. };
  208549. }
  208550. break;
  208551. case WM_NCRBUTTONDOWN:
  208552. case WM_NCMBUTTONDOWN:
  208553. sendInputAttemptWhenModalMessage();
  208554. break;
  208555. //case WM_IME_STARTCOMPOSITION;
  208556. // return 0;
  208557. case WM_GETDLGCODE:
  208558. return DLGC_WANTALLKEYS;
  208559. default:
  208560. if (taskBarIcon != 0)
  208561. {
  208562. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  208563. if (message == taskbarCreatedMessage)
  208564. {
  208565. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  208566. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  208567. }
  208568. }
  208569. break;
  208570. }
  208571. return DefWindowProcW (h, message, wParam, lParam);
  208572. }
  208573. bool sendInputAttemptWhenModalMessage()
  208574. {
  208575. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208576. {
  208577. Component* const current = Component::getCurrentlyModalComponent();
  208578. if (current != 0)
  208579. current->inputAttemptWhenModal();
  208580. return true;
  208581. }
  208582. return false;
  208583. }
  208584. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32ComponentPeer);
  208585. };
  208586. ModifierKeys Win32ComponentPeer::currentModifiers;
  208587. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208588. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208589. {
  208590. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208591. }
  208592. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208593. void ModifierKeys::updateCurrentModifiers() throw()
  208594. {
  208595. currentModifiers = Win32ComponentPeer::currentModifiers;
  208596. }
  208597. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208598. {
  208599. Win32ComponentPeer::updateKeyModifiers();
  208600. int mouseMods = 0;
  208601. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208602. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208603. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208604. Win32ComponentPeer::currentModifiers
  208605. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208606. return Win32ComponentPeer::currentModifiers;
  208607. }
  208608. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208609. {
  208610. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208611. if (wp != 0)
  208612. wp->setTaskBarIcon (newImage);
  208613. }
  208614. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208615. {
  208616. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208617. if (wp != 0)
  208618. wp->setTaskBarIconToolTip (tooltip);
  208619. }
  208620. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208621. {
  208622. DWORD val = GetWindowLong (h, styleType);
  208623. if (bitIsSet)
  208624. val |= feature;
  208625. else
  208626. val &= ~feature;
  208627. SetWindowLongPtr (h, styleType, val);
  208628. SetWindowPos (h, 0, 0, 0, 0, 0,
  208629. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208630. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208631. }
  208632. bool Process::isForegroundProcess()
  208633. {
  208634. HWND fg = GetForegroundWindow();
  208635. if (fg == 0)
  208636. return true;
  208637. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208638. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208639. // have to see if any of our windows are children of the foreground window
  208640. fg = GetAncestor (fg, GA_ROOT);
  208641. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208642. {
  208643. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208644. if (wp != 0 && wp->isInside (fg))
  208645. return true;
  208646. }
  208647. return false;
  208648. }
  208649. bool AlertWindow::showNativeDialogBox (const String& title,
  208650. const String& bodyText,
  208651. bool isOkCancel)
  208652. {
  208653. return MessageBox (0, bodyText, title,
  208654. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208655. : MB_OK)) == IDOK;
  208656. }
  208657. void Desktop::createMouseInputSources()
  208658. {
  208659. mouseSources.add (new MouseInputSource (0, true));
  208660. }
  208661. const Point<int> MouseInputSource::getCurrentMousePosition()
  208662. {
  208663. POINT mousePos;
  208664. GetCursorPos (&mousePos);
  208665. return Point<int> (mousePos.x, mousePos.y);
  208666. }
  208667. void Desktop::setMousePosition (const Point<int>& newPosition)
  208668. {
  208669. SetCursorPos (newPosition.getX(), newPosition.getY());
  208670. }
  208671. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208672. {
  208673. return createSoftwareImage (format, width, height, clearImage);
  208674. }
  208675. class ScreenSaverDefeater : public Timer,
  208676. public DeletedAtShutdown
  208677. {
  208678. public:
  208679. ScreenSaverDefeater()
  208680. {
  208681. startTimer (10000);
  208682. timerCallback();
  208683. }
  208684. ~ScreenSaverDefeater() {}
  208685. void timerCallback()
  208686. {
  208687. if (Process::isForegroundProcess())
  208688. {
  208689. // simulate a shift key getting pressed..
  208690. INPUT input[2];
  208691. input[0].type = INPUT_KEYBOARD;
  208692. input[0].ki.wVk = VK_SHIFT;
  208693. input[0].ki.dwFlags = 0;
  208694. input[0].ki.dwExtraInfo = 0;
  208695. input[1].type = INPUT_KEYBOARD;
  208696. input[1].ki.wVk = VK_SHIFT;
  208697. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208698. input[1].ki.dwExtraInfo = 0;
  208699. SendInput (2, input, sizeof (INPUT));
  208700. }
  208701. }
  208702. };
  208703. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208704. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208705. {
  208706. if (isEnabled)
  208707. deleteAndZero (screenSaverDefeater);
  208708. else if (screenSaverDefeater == 0)
  208709. screenSaverDefeater = new ScreenSaverDefeater();
  208710. }
  208711. bool Desktop::isScreenSaverEnabled()
  208712. {
  208713. return screenSaverDefeater == 0;
  208714. }
  208715. /* (The code below is the "correct" way to disable the screen saver, but it
  208716. completely fails on winXP when the saver is password-protected...)
  208717. static bool juce_screenSaverEnabled = true;
  208718. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208719. {
  208720. juce_screenSaverEnabled = isEnabled;
  208721. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208722. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208723. }
  208724. bool Desktop::isScreenSaverEnabled() throw()
  208725. {
  208726. return juce_screenSaverEnabled;
  208727. }
  208728. */
  208729. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208730. {
  208731. if (enableOrDisable)
  208732. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208733. }
  208734. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208735. {
  208736. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208737. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208738. return TRUE;
  208739. }
  208740. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208741. {
  208742. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208743. // make sure the first in the list is the main monitor
  208744. for (int i = 1; i < monitorCoords.size(); ++i)
  208745. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208746. monitorCoords.swap (i, 0);
  208747. if (monitorCoords.size() == 0)
  208748. {
  208749. RECT r;
  208750. GetWindowRect (GetDesktopWindow(), &r);
  208751. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208752. }
  208753. if (clipToWorkArea)
  208754. {
  208755. // clip the main monitor to the active non-taskbar area
  208756. RECT r;
  208757. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208758. Rectangle<int>& screen = monitorCoords.getReference (0);
  208759. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208760. jmax (screen.getY(), (int) r.top));
  208761. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208762. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208763. }
  208764. }
  208765. const Image juce_createIconForFile (const File& file)
  208766. {
  208767. Image image;
  208768. WCHAR filename [1024];
  208769. file.getFullPathName().copyToUnicode (filename, 1023);
  208770. WORD iconNum = 0;
  208771. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208772. filename, &iconNum);
  208773. if (icon != 0)
  208774. {
  208775. image = IconConverters::createImageFromHICON (icon);
  208776. DestroyIcon (icon);
  208777. }
  208778. return image;
  208779. }
  208780. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208781. {
  208782. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208783. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208784. Image im (image);
  208785. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208786. {
  208787. im = im.rescaled (maxW, maxH);
  208788. hotspotX = (hotspotX * maxW) / image.getWidth();
  208789. hotspotY = (hotspotY * maxH) / image.getHeight();
  208790. }
  208791. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208792. }
  208793. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208794. {
  208795. if (cursorHandle != 0 && ! isStandard)
  208796. DestroyCursor ((HCURSOR) cursorHandle);
  208797. }
  208798. enum
  208799. {
  208800. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  208801. };
  208802. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208803. {
  208804. LPCTSTR cursorName = IDC_ARROW;
  208805. switch (type)
  208806. {
  208807. case NormalCursor: break;
  208808. case NoCursor: return (void*) hiddenMouseCursorHandle;
  208809. case WaitCursor: cursorName = IDC_WAIT; break;
  208810. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208811. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208812. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208813. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208814. case LeftRightResizeCursor:
  208815. case LeftEdgeResizeCursor:
  208816. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208817. case UpDownResizeCursor:
  208818. case TopEdgeResizeCursor:
  208819. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208820. case TopLeftCornerResizeCursor:
  208821. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208822. case TopRightCornerResizeCursor:
  208823. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208824. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208825. case DraggingHandCursor:
  208826. {
  208827. static void* dragHandCursor = 0;
  208828. if (dragHandCursor == 0)
  208829. {
  208830. static const unsigned char dragHandData[] =
  208831. { 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,
  208832. 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,
  208833. 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 };
  208834. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208835. }
  208836. return dragHandCursor;
  208837. }
  208838. default:
  208839. jassertfalse; break;
  208840. }
  208841. HCURSOR cursorH = LoadCursor (0, cursorName);
  208842. if (cursorH == 0)
  208843. cursorH = LoadCursor (0, IDC_ARROW);
  208844. return cursorH;
  208845. }
  208846. void MouseCursor::showInWindow (ComponentPeer*) const
  208847. {
  208848. HCURSOR c = (HCURSOR) getHandle();
  208849. if (c == 0)
  208850. c = LoadCursor (0, IDC_ARROW);
  208851. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  208852. c = 0;
  208853. SetCursor (c);
  208854. }
  208855. void MouseCursor::showInAllWindows() const
  208856. {
  208857. showInWindow (0);
  208858. }
  208859. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208860. {
  208861. public:
  208862. JuceDropSource() {}
  208863. ~JuceDropSource() {}
  208864. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208865. {
  208866. if (escapePressed)
  208867. return DRAGDROP_S_CANCEL;
  208868. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208869. return DRAGDROP_S_DROP;
  208870. return S_OK;
  208871. }
  208872. HRESULT __stdcall GiveFeedback (DWORD)
  208873. {
  208874. return DRAGDROP_S_USEDEFAULTCURSORS;
  208875. }
  208876. };
  208877. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208878. {
  208879. public:
  208880. JuceEnumFormatEtc (const FORMATETC* const format_)
  208881. : format (format_),
  208882. index (0)
  208883. {
  208884. }
  208885. ~JuceEnumFormatEtc() {}
  208886. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208887. {
  208888. if (result == 0)
  208889. return E_POINTER;
  208890. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208891. newOne->index = index;
  208892. *result = newOne;
  208893. return S_OK;
  208894. }
  208895. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208896. {
  208897. if (pceltFetched != 0)
  208898. *pceltFetched = 0;
  208899. else if (celt != 1)
  208900. return S_FALSE;
  208901. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208902. {
  208903. copyFormatEtc (lpFormatEtc [0], *format);
  208904. ++index;
  208905. if (pceltFetched != 0)
  208906. *pceltFetched = 1;
  208907. return S_OK;
  208908. }
  208909. return S_FALSE;
  208910. }
  208911. HRESULT __stdcall Skip (ULONG celt)
  208912. {
  208913. if (index + (int) celt >= 1)
  208914. return S_FALSE;
  208915. index += celt;
  208916. return S_OK;
  208917. }
  208918. HRESULT __stdcall Reset()
  208919. {
  208920. index = 0;
  208921. return S_OK;
  208922. }
  208923. private:
  208924. const FORMATETC* const format;
  208925. int index;
  208926. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208927. {
  208928. dest = source;
  208929. if (source.ptd != 0)
  208930. {
  208931. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208932. *(dest.ptd) = *(source.ptd);
  208933. }
  208934. }
  208935. JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc);
  208936. };
  208937. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208938. {
  208939. public:
  208940. JuceDataObject (JuceDropSource* const dropSource_,
  208941. const FORMATETC* const format_,
  208942. const STGMEDIUM* const medium_)
  208943. : dropSource (dropSource_),
  208944. format (format_),
  208945. medium (medium_)
  208946. {
  208947. }
  208948. ~JuceDataObject()
  208949. {
  208950. jassert (refCount == 0);
  208951. }
  208952. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208953. {
  208954. if ((pFormatEtc->tymed & format->tymed) != 0
  208955. && pFormatEtc->cfFormat == format->cfFormat
  208956. && pFormatEtc->dwAspect == format->dwAspect)
  208957. {
  208958. pMedium->tymed = format->tymed;
  208959. pMedium->pUnkForRelease = 0;
  208960. if (format->tymed == TYMED_HGLOBAL)
  208961. {
  208962. const SIZE_T len = GlobalSize (medium->hGlobal);
  208963. void* const src = GlobalLock (medium->hGlobal);
  208964. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208965. memcpy (dst, src, len);
  208966. GlobalUnlock (medium->hGlobal);
  208967. pMedium->hGlobal = dst;
  208968. return S_OK;
  208969. }
  208970. }
  208971. return DV_E_FORMATETC;
  208972. }
  208973. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208974. {
  208975. if (f == 0)
  208976. return E_INVALIDARG;
  208977. if (f->tymed == format->tymed
  208978. && f->cfFormat == format->cfFormat
  208979. && f->dwAspect == format->dwAspect)
  208980. return S_OK;
  208981. return DV_E_FORMATETC;
  208982. }
  208983. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208984. {
  208985. pFormatEtcOut->ptd = 0;
  208986. return E_NOTIMPL;
  208987. }
  208988. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208989. {
  208990. if (result == 0)
  208991. return E_POINTER;
  208992. if (direction == DATADIR_GET)
  208993. {
  208994. *result = new JuceEnumFormatEtc (format);
  208995. return S_OK;
  208996. }
  208997. *result = 0;
  208998. return E_NOTIMPL;
  208999. }
  209000. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  209001. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  209002. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  209003. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  209004. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  209005. private:
  209006. JuceDropSource* const dropSource;
  209007. const FORMATETC* const format;
  209008. const STGMEDIUM* const medium;
  209009. JUCE_DECLARE_NON_COPYABLE (JuceDataObject);
  209010. };
  209011. static HDROP createHDrop (const StringArray& fileNames)
  209012. {
  209013. int totalChars = 0;
  209014. for (int i = fileNames.size(); --i >= 0;)
  209015. totalChars += fileNames[i].length() + 1;
  209016. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  209017. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  209018. if (hDrop != 0)
  209019. {
  209020. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  209021. pDropFiles->pFiles = sizeof (DROPFILES);
  209022. pDropFiles->fWide = true;
  209023. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  209024. for (int i = 0; i < fileNames.size(); ++i)
  209025. {
  209026. fileNames[i].copyToUnicode (fname, 2048);
  209027. fname += fileNames[i].length() + 1;
  209028. }
  209029. *fname = 0;
  209030. GlobalUnlock (hDrop);
  209031. }
  209032. return hDrop;
  209033. }
  209034. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  209035. {
  209036. JuceDropSource* const source = new JuceDropSource();
  209037. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  209038. DWORD effect;
  209039. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  209040. data->Release();
  209041. source->Release();
  209042. return res == DRAGDROP_S_DROP;
  209043. }
  209044. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  209045. {
  209046. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  209047. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  209048. medium.hGlobal = createHDrop (files);
  209049. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  209050. : DROPEFFECT_COPY);
  209051. }
  209052. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  209053. {
  209054. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  209055. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  209056. const int numChars = text.length();
  209057. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  209058. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  209059. text.copyToUnicode (data, numChars + 1);
  209060. format.cfFormat = CF_UNICODETEXT;
  209061. GlobalUnlock (medium.hGlobal);
  209062. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  209063. }
  209064. #endif
  209065. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  209066. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  209067. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209068. // compiled on its own).
  209069. #if JUCE_INCLUDED_FILE
  209070. namespace FileChooserHelpers
  209071. {
  209072. static bool areThereAnyAlwaysOnTopWindows()
  209073. {
  209074. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  209075. {
  209076. Component* c = Desktop::getInstance().getComponent (i);
  209077. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  209078. return true;
  209079. }
  209080. return false;
  209081. }
  209082. struct FileChooserCallbackInfo
  209083. {
  209084. String initialPath;
  209085. String returnedString; // need this to get non-existent pathnames from the directory chooser
  209086. ScopedPointer<Component> customComponent;
  209087. };
  209088. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  209089. {
  209090. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  209091. if (msg == BFFM_INITIALIZED)
  209092. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  209093. else if (msg == BFFM_VALIDATEFAILEDW)
  209094. info->returnedString = (LPCWSTR) lParam;
  209095. else if (msg == BFFM_VALIDATEFAILEDA)
  209096. info->returnedString = (const char*) lParam;
  209097. return 0;
  209098. }
  209099. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  209100. {
  209101. if (uiMsg == WM_INITDIALOG)
  209102. {
  209103. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  209104. HWND dialogH = GetParent (hdlg);
  209105. jassert (dialogH != 0);
  209106. if (dialogH == 0)
  209107. dialogH = hdlg;
  209108. RECT r, cr;
  209109. GetWindowRect (dialogH, &r);
  209110. GetClientRect (dialogH, &cr);
  209111. SetWindowPos (dialogH, 0,
  209112. r.left, r.top,
  209113. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  209114. jmax (150, (int) (r.bottom - r.top)),
  209115. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  209116. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  209117. customComp->addToDesktop (0, dialogH);
  209118. }
  209119. else if (uiMsg == WM_NOTIFY)
  209120. {
  209121. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  209122. if (ofn->hdr.code == CDN_SELCHANGE)
  209123. {
  209124. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  209125. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  209126. if (comp != 0)
  209127. {
  209128. WCHAR path [MAX_PATH * 2];
  209129. zerostruct (path);
  209130. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  209131. comp->selectedFileChanged (File (path));
  209132. }
  209133. }
  209134. }
  209135. return 0;
  209136. }
  209137. class CustomComponentHolder : public Component
  209138. {
  209139. public:
  209140. CustomComponentHolder (Component* customComp)
  209141. {
  209142. setVisible (true);
  209143. setOpaque (true);
  209144. addAndMakeVisible (customComp);
  209145. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  209146. }
  209147. void paint (Graphics& g)
  209148. {
  209149. g.fillAll (Colours::lightgrey);
  209150. }
  209151. void resized()
  209152. {
  209153. if (getNumChildComponents() > 0)
  209154. getChildComponent(0)->setBounds (getLocalBounds());
  209155. }
  209156. private:
  209157. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder);
  209158. };
  209159. }
  209160. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  209161. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  209162. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  209163. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  209164. {
  209165. using namespace FileChooserHelpers;
  209166. HeapBlock<WCHAR> files;
  209167. const int charsAvailableForResult = 32768;
  209168. files.calloc (charsAvailableForResult + 1);
  209169. int filenameOffset = 0;
  209170. FileChooserCallbackInfo info;
  209171. // use a modal window as the parent for this dialog box
  209172. // to block input from other app windows
  209173. Component parentWindow (String::empty);
  209174. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  209175. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  209176. mainMon.getY() + mainMon.getHeight() / 4,
  209177. 0, 0);
  209178. parentWindow.setOpaque (true);
  209179. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  209180. parentWindow.addToDesktop (0);
  209181. if (extraInfoComponent == 0)
  209182. parentWindow.enterModalState();
  209183. if (currentFileOrDirectory.isDirectory())
  209184. {
  209185. info.initialPath = currentFileOrDirectory.getFullPathName();
  209186. }
  209187. else
  209188. {
  209189. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  209190. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  209191. }
  209192. if (selectsDirectory)
  209193. {
  209194. BROWSEINFO bi;
  209195. zerostruct (bi);
  209196. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209197. bi.pszDisplayName = files;
  209198. bi.lpszTitle = title;
  209199. bi.lParam = (LPARAM) &info;
  209200. bi.lpfn = browseCallbackProc;
  209201. #ifdef BIF_USENEWUI
  209202. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  209203. #else
  209204. bi.ulFlags = 0x50;
  209205. #endif
  209206. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  209207. if (! SHGetPathFromIDListW (list, files))
  209208. {
  209209. files[0] = 0;
  209210. info.returnedString = String::empty;
  209211. }
  209212. LPMALLOC al;
  209213. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  209214. al->Free (list);
  209215. if (info.returnedString.isNotEmpty())
  209216. {
  209217. results.add (File (String (files)).getSiblingFile (info.returnedString));
  209218. return;
  209219. }
  209220. }
  209221. else
  209222. {
  209223. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  209224. if (warnAboutOverwritingExistingFiles)
  209225. flags |= OFN_OVERWRITEPROMPT;
  209226. if (selectMultipleFiles)
  209227. flags |= OFN_ALLOWMULTISELECT;
  209228. if (extraInfoComponent != 0)
  209229. {
  209230. flags |= OFN_ENABLEHOOK;
  209231. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  209232. info.customComponent->enterModalState();
  209233. }
  209234. WCHAR filters [1024];
  209235. zerostruct (filters);
  209236. filter.copyToUnicode (filters, 1024);
  209237. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  209238. OPENFILENAMEW of;
  209239. zerostruct (of);
  209240. #ifdef OPENFILENAME_SIZE_VERSION_400W
  209241. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  209242. #else
  209243. of.lStructSize = sizeof (of);
  209244. #endif
  209245. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209246. of.lpstrFilter = filters;
  209247. of.nFilterIndex = 1;
  209248. of.lpstrFile = files;
  209249. of.nMaxFile = charsAvailableForResult;
  209250. of.lpstrInitialDir = info.initialPath;
  209251. of.lpstrTitle = title;
  209252. of.Flags = flags;
  209253. of.lCustData = (LPARAM) &info;
  209254. if (extraInfoComponent != 0)
  209255. of.lpfnHook = &openCallback;
  209256. if (! (isSaveDialogue ? GetSaveFileName (&of)
  209257. : GetOpenFileName (&of)))
  209258. return;
  209259. filenameOffset = of.nFileOffset;
  209260. }
  209261. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  209262. {
  209263. const WCHAR* filename = files + filenameOffset;
  209264. while (*filename != 0)
  209265. {
  209266. results.add (File (String (files) + "\\" + String (filename)));
  209267. filename += CharacterFunctions::length (filename) + 1;
  209268. }
  209269. }
  209270. else if (files[0] != 0)
  209271. {
  209272. results.add (File (String (files)));
  209273. }
  209274. }
  209275. #endif
  209276. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  209277. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  209278. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209279. // compiled on its own).
  209280. #if JUCE_INCLUDED_FILE
  209281. void SystemClipboard::copyTextToClipboard (const String& text)
  209282. {
  209283. if (OpenClipboard (0) != 0)
  209284. {
  209285. if (EmptyClipboard() != 0)
  209286. {
  209287. const int len = text.length();
  209288. if (len > 0)
  209289. {
  209290. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  209291. (len + 1) * sizeof (wchar_t));
  209292. if (bufH != 0)
  209293. {
  209294. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  209295. text.copyToUnicode (data, len);
  209296. GlobalUnlock (bufH);
  209297. SetClipboardData (CF_UNICODETEXT, bufH);
  209298. }
  209299. }
  209300. }
  209301. CloseClipboard();
  209302. }
  209303. }
  209304. const String SystemClipboard::getTextFromClipboard()
  209305. {
  209306. String result;
  209307. if (OpenClipboard (0) != 0)
  209308. {
  209309. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209310. if (bufH != 0)
  209311. {
  209312. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  209313. if (data != 0)
  209314. {
  209315. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  209316. GlobalUnlock (bufH);
  209317. }
  209318. }
  209319. CloseClipboard();
  209320. }
  209321. return result;
  209322. }
  209323. #endif
  209324. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209325. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209326. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209327. // compiled on its own).
  209328. #if JUCE_INCLUDED_FILE
  209329. namespace ActiveXHelpers
  209330. {
  209331. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209332. {
  209333. public:
  209334. JuceIStorage() {}
  209335. ~JuceIStorage() {}
  209336. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209337. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209338. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209339. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209340. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209341. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209342. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209343. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209344. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209345. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209346. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209347. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209348. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209349. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209350. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209351. };
  209352. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209353. {
  209354. HWND window;
  209355. public:
  209356. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209357. ~JuceOleInPlaceFrame() {}
  209358. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209359. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209360. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209361. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209362. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209363. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209364. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209365. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209366. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209367. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209368. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209369. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209370. };
  209371. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209372. {
  209373. HWND window;
  209374. JuceOleInPlaceFrame* frame;
  209375. public:
  209376. JuceIOleInPlaceSite (HWND window_)
  209377. : window (window_),
  209378. frame (new JuceOleInPlaceFrame (window))
  209379. {}
  209380. ~JuceIOleInPlaceSite()
  209381. {
  209382. frame->Release();
  209383. }
  209384. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209385. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209386. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209387. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209388. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209389. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209390. {
  209391. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209392. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209393. */
  209394. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209395. if (lplpDoc != 0) *lplpDoc = 0;
  209396. lpFrameInfo->fMDIApp = FALSE;
  209397. lpFrameInfo->hwndFrame = window;
  209398. lpFrameInfo->haccel = 0;
  209399. lpFrameInfo->cAccelEntries = 0;
  209400. return S_OK;
  209401. }
  209402. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209403. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209404. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209405. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209406. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209407. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209408. };
  209409. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209410. {
  209411. JuceIOleInPlaceSite* inplaceSite;
  209412. public:
  209413. JuceIOleClientSite (HWND window)
  209414. : inplaceSite (new JuceIOleInPlaceSite (window))
  209415. {}
  209416. ~JuceIOleClientSite()
  209417. {
  209418. inplaceSite->Release();
  209419. }
  209420. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  209421. {
  209422. if (type == IID_IOleInPlaceSite)
  209423. {
  209424. inplaceSite->AddRef();
  209425. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209426. return S_OK;
  209427. }
  209428. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209429. }
  209430. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209431. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209432. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209433. HRESULT __stdcall ShowObject() { return S_OK; }
  209434. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209435. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209436. };
  209437. static Array<ActiveXControlComponent*> activeXComps;
  209438. static HWND getHWND (const ActiveXControlComponent* const component)
  209439. {
  209440. HWND hwnd = 0;
  209441. const IID iid = IID_IOleWindow;
  209442. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209443. if (window != 0)
  209444. {
  209445. window->GetWindow (&hwnd);
  209446. window->Release();
  209447. }
  209448. return hwnd;
  209449. }
  209450. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209451. {
  209452. RECT activeXRect, peerRect;
  209453. GetWindowRect (hwnd, &activeXRect);
  209454. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209455. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209456. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209457. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209458. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209459. switch (message)
  209460. {
  209461. case WM_MOUSEMOVE:
  209462. case WM_LBUTTONDOWN:
  209463. case WM_MBUTTONDOWN:
  209464. case WM_RBUTTONDOWN:
  209465. case WM_LBUTTONUP:
  209466. case WM_MBUTTONUP:
  209467. case WM_RBUTTONUP:
  209468. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209469. break;
  209470. default:
  209471. break;
  209472. }
  209473. }
  209474. }
  209475. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209476. {
  209477. public:
  209478. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209479. : ComponentMovementWatcher (&owner_),
  209480. owner (owner_),
  209481. controlHWND (0),
  209482. storage (new ActiveXHelpers::JuceIStorage()),
  209483. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209484. control (0)
  209485. {
  209486. }
  209487. ~Pimpl()
  209488. {
  209489. if (control != 0)
  209490. {
  209491. control->Close (OLECLOSE_NOSAVE);
  209492. control->Release();
  209493. }
  209494. clientSite->Release();
  209495. storage->Release();
  209496. }
  209497. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209498. {
  209499. Component* const topComp = owner.getTopLevelComponent();
  209500. if (topComp->getPeer() != 0)
  209501. {
  209502. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  209503. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209504. }
  209505. }
  209506. void componentPeerChanged()
  209507. {
  209508. componentMovedOrResized (true, true);
  209509. }
  209510. void componentVisibilityChanged()
  209511. {
  209512. owner.setControlVisible (owner.isShowing());
  209513. componentPeerChanged();
  209514. }
  209515. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209516. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209517. {
  209518. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209519. {
  209520. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209521. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209522. {
  209523. switch (message)
  209524. {
  209525. case WM_MOUSEMOVE:
  209526. case WM_LBUTTONDOWN:
  209527. case WM_MBUTTONDOWN:
  209528. case WM_RBUTTONDOWN:
  209529. case WM_LBUTTONUP:
  209530. case WM_MBUTTONUP:
  209531. case WM_RBUTTONUP:
  209532. case WM_LBUTTONDBLCLK:
  209533. case WM_MBUTTONDBLCLK:
  209534. case WM_RBUTTONDBLCLK:
  209535. if (ax->isShowing())
  209536. {
  209537. ComponentPeer* const peer = ax->getPeer();
  209538. if (peer != 0)
  209539. {
  209540. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209541. if (! ax->areMouseEventsAllowed())
  209542. return 0;
  209543. }
  209544. }
  209545. break;
  209546. default:
  209547. break;
  209548. }
  209549. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209550. }
  209551. }
  209552. return DefWindowProc (hwnd, message, wParam, lParam);
  209553. }
  209554. private:
  209555. ActiveXControlComponent& owner;
  209556. public:
  209557. HWND controlHWND;
  209558. IStorage* storage;
  209559. IOleClientSite* clientSite;
  209560. IOleObject* control;
  209561. };
  209562. ActiveXControlComponent::ActiveXControlComponent()
  209563. : originalWndProc (0),
  209564. mouseEventsAllowed (true)
  209565. {
  209566. ActiveXHelpers::activeXComps.add (this);
  209567. }
  209568. ActiveXControlComponent::~ActiveXControlComponent()
  209569. {
  209570. deleteControl();
  209571. ActiveXHelpers::activeXComps.removeValue (this);
  209572. }
  209573. void ActiveXControlComponent::paint (Graphics& g)
  209574. {
  209575. if (control == 0)
  209576. g.fillAll (Colours::lightgrey);
  209577. }
  209578. bool ActiveXControlComponent::createControl (const void* controlIID)
  209579. {
  209580. deleteControl();
  209581. ComponentPeer* const peer = getPeer();
  209582. // the component must have already been added to a real window when you call this!
  209583. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209584. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209585. {
  209586. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  209587. HWND hwnd = (HWND) peer->getNativeHandle();
  209588. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209589. HRESULT hr;
  209590. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209591. newControl->clientSite, newControl->storage,
  209592. (void**) &(newControl->control))) == S_OK)
  209593. {
  209594. newControl->control->SetHostNames (L"Juce", 0);
  209595. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209596. {
  209597. RECT rect;
  209598. rect.left = pos.getX();
  209599. rect.top = pos.getY();
  209600. rect.right = pos.getX() + getWidth();
  209601. rect.bottom = pos.getY() + getHeight();
  209602. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209603. {
  209604. control = newControl;
  209605. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209606. control->controlHWND = ActiveXHelpers::getHWND (this);
  209607. if (control->controlHWND != 0)
  209608. {
  209609. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209610. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209611. }
  209612. return true;
  209613. }
  209614. }
  209615. }
  209616. }
  209617. return false;
  209618. }
  209619. void ActiveXControlComponent::deleteControl()
  209620. {
  209621. control = 0;
  209622. originalWndProc = 0;
  209623. }
  209624. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209625. {
  209626. void* result = 0;
  209627. if (control != 0 && control->control != 0
  209628. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209629. return result;
  209630. return 0;
  209631. }
  209632. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209633. {
  209634. if (control->controlHWND != 0)
  209635. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209636. }
  209637. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209638. {
  209639. if (control->controlHWND != 0)
  209640. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209641. }
  209642. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209643. {
  209644. mouseEventsAllowed = eventsCanReachControl;
  209645. }
  209646. #endif
  209647. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209648. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209649. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209650. // compiled on its own).
  209651. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209652. using namespace QTOLibrary;
  209653. using namespace QTOControlLib;
  209654. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209655. static bool isQTAvailable = false;
  209656. class QuickTimeMovieComponent::Pimpl
  209657. {
  209658. public:
  209659. Pimpl() : dataHandle (0)
  209660. {
  209661. }
  209662. ~Pimpl()
  209663. {
  209664. clearHandle();
  209665. }
  209666. void clearHandle()
  209667. {
  209668. if (dataHandle != 0)
  209669. {
  209670. DisposeHandle (dataHandle);
  209671. dataHandle = 0;
  209672. }
  209673. }
  209674. IQTControlPtr qtControl;
  209675. IQTMoviePtr qtMovie;
  209676. Handle dataHandle;
  209677. };
  209678. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209679. : movieLoaded (false),
  209680. controllerVisible (true)
  209681. {
  209682. pimpl = new Pimpl();
  209683. setMouseEventsAllowed (false);
  209684. }
  209685. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209686. {
  209687. closeMovie();
  209688. pimpl->qtControl = 0;
  209689. deleteControl();
  209690. pimpl = 0;
  209691. }
  209692. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209693. {
  209694. if (! isQTAvailable)
  209695. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209696. return isQTAvailable;
  209697. }
  209698. void QuickTimeMovieComponent::createControlIfNeeded()
  209699. {
  209700. if (isShowing() && ! isControlCreated())
  209701. {
  209702. const IID qtIID = __uuidof (QTControl);
  209703. if (createControl (&qtIID))
  209704. {
  209705. const IID qtInterfaceIID = __uuidof (IQTControl);
  209706. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209707. if (pimpl->qtControl != 0)
  209708. {
  209709. pimpl->qtControl->Release(); // it has one ref too many at this point
  209710. pimpl->qtControl->QuickTimeInitialize();
  209711. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209712. if (movieFile != File::nonexistent)
  209713. loadMovie (movieFile, controllerVisible);
  209714. }
  209715. }
  209716. }
  209717. }
  209718. bool QuickTimeMovieComponent::isControlCreated() const
  209719. {
  209720. return isControlOpen();
  209721. }
  209722. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209723. const bool isControllerVisible)
  209724. {
  209725. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209726. movieFile = File::nonexistent;
  209727. movieLoaded = false;
  209728. pimpl->qtMovie = 0;
  209729. controllerVisible = isControllerVisible;
  209730. createControlIfNeeded();
  209731. if (isControlCreated())
  209732. {
  209733. if (pimpl->qtControl != 0)
  209734. {
  209735. pimpl->qtControl->Put_MovieHandle (0);
  209736. pimpl->clearHandle();
  209737. Movie movie;
  209738. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209739. {
  209740. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209741. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209742. if (pimpl->qtMovie != 0)
  209743. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209744. : qtMovieControllerTypeNone);
  209745. }
  209746. if (movie == 0)
  209747. pimpl->clearHandle();
  209748. }
  209749. movieLoaded = (pimpl->qtMovie != 0);
  209750. }
  209751. else
  209752. {
  209753. // You're trying to open a movie when the control hasn't yet been created, probably because
  209754. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209755. jassertfalse;
  209756. }
  209757. return movieLoaded;
  209758. }
  209759. void QuickTimeMovieComponent::closeMovie()
  209760. {
  209761. stop();
  209762. movieFile = File::nonexistent;
  209763. movieLoaded = false;
  209764. pimpl->qtMovie = 0;
  209765. if (pimpl->qtControl != 0)
  209766. pimpl->qtControl->Put_MovieHandle (0);
  209767. pimpl->clearHandle();
  209768. }
  209769. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209770. {
  209771. return movieFile;
  209772. }
  209773. bool QuickTimeMovieComponent::isMovieOpen() const
  209774. {
  209775. return movieLoaded;
  209776. }
  209777. double QuickTimeMovieComponent::getMovieDuration() const
  209778. {
  209779. if (pimpl->qtMovie != 0)
  209780. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209781. return 0.0;
  209782. }
  209783. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209784. {
  209785. if (pimpl->qtMovie != 0)
  209786. {
  209787. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209788. width = r.right - r.left;
  209789. height = r.bottom - r.top;
  209790. }
  209791. else
  209792. {
  209793. width = height = 0;
  209794. }
  209795. }
  209796. void QuickTimeMovieComponent::play()
  209797. {
  209798. if (pimpl->qtMovie != 0)
  209799. pimpl->qtMovie->Play();
  209800. }
  209801. void QuickTimeMovieComponent::stop()
  209802. {
  209803. if (pimpl->qtMovie != 0)
  209804. pimpl->qtMovie->Stop();
  209805. }
  209806. bool QuickTimeMovieComponent::isPlaying() const
  209807. {
  209808. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209809. }
  209810. void QuickTimeMovieComponent::setPosition (const double seconds)
  209811. {
  209812. if (pimpl->qtMovie != 0)
  209813. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209814. }
  209815. double QuickTimeMovieComponent::getPosition() const
  209816. {
  209817. if (pimpl->qtMovie != 0)
  209818. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209819. return 0.0;
  209820. }
  209821. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209822. {
  209823. if (pimpl->qtMovie != 0)
  209824. pimpl->qtMovie->PutRate (newSpeed);
  209825. }
  209826. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209827. {
  209828. if (pimpl->qtMovie != 0)
  209829. {
  209830. pimpl->qtMovie->PutAudioVolume (newVolume);
  209831. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209832. }
  209833. }
  209834. float QuickTimeMovieComponent::getMovieVolume() const
  209835. {
  209836. if (pimpl->qtMovie != 0)
  209837. return pimpl->qtMovie->GetAudioVolume();
  209838. return 0.0f;
  209839. }
  209840. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209841. {
  209842. if (pimpl->qtMovie != 0)
  209843. pimpl->qtMovie->PutLoop (shouldLoop);
  209844. }
  209845. bool QuickTimeMovieComponent::isLooping() const
  209846. {
  209847. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209848. }
  209849. bool QuickTimeMovieComponent::isControllerVisible() const
  209850. {
  209851. return controllerVisible;
  209852. }
  209853. void QuickTimeMovieComponent::parentHierarchyChanged()
  209854. {
  209855. createControlIfNeeded();
  209856. QTCompBaseClass::parentHierarchyChanged();
  209857. }
  209858. void QuickTimeMovieComponent::visibilityChanged()
  209859. {
  209860. createControlIfNeeded();
  209861. QTCompBaseClass::visibilityChanged();
  209862. }
  209863. void QuickTimeMovieComponent::paint (Graphics& g)
  209864. {
  209865. if (! isControlCreated())
  209866. g.fillAll (Colours::black);
  209867. }
  209868. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209869. {
  209870. Handle dataRef = 0;
  209871. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209872. if (err == noErr)
  209873. {
  209874. Str255 suffix;
  209875. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209876. StringPtr name = suffix;
  209877. err = PtrAndHand (name, dataRef, name[0] + 1);
  209878. if (err == noErr)
  209879. {
  209880. long atoms[3];
  209881. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209882. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209883. atoms[2] = EndianU32_NtoB (MovieFileType);
  209884. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209885. if (err == noErr)
  209886. return dataRef;
  209887. }
  209888. DisposeHandle (dataRef);
  209889. }
  209890. return 0;
  209891. }
  209892. static CFStringRef juceStringToCFString (const String& s)
  209893. {
  209894. const int len = s.length();
  209895. const juce_wchar* const t = s;
  209896. HeapBlock <UniChar> temp (len + 2);
  209897. for (int i = 0; i <= len; ++i)
  209898. temp[i] = t[i];
  209899. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209900. }
  209901. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209902. {
  209903. Boolean trueBool = true;
  209904. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209905. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209906. props[prop].propValueSize = sizeof (trueBool);
  209907. props[prop].propValueAddress = &trueBool;
  209908. ++prop;
  209909. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209910. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209911. props[prop].propValueSize = sizeof (trueBool);
  209912. props[prop].propValueAddress = &trueBool;
  209913. ++prop;
  209914. Boolean isActive = true;
  209915. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209916. props[prop].propID = kQTNewMoviePropertyID_Active;
  209917. props[prop].propValueSize = sizeof (isActive);
  209918. props[prop].propValueAddress = &isActive;
  209919. ++prop;
  209920. MacSetPort (0);
  209921. jassert (prop <= 5);
  209922. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209923. return err == noErr;
  209924. }
  209925. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209926. {
  209927. if (input == 0)
  209928. return false;
  209929. dataHandle = 0;
  209930. bool ok = false;
  209931. QTNewMoviePropertyElement props[5];
  209932. zeromem (props, sizeof (props));
  209933. int prop = 0;
  209934. DataReferenceRecord dr;
  209935. props[prop].propClass = kQTPropertyClass_DataLocation;
  209936. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209937. props[prop].propValueSize = sizeof (dr);
  209938. props[prop].propValueAddress = &dr;
  209939. ++prop;
  209940. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209941. if (fin != 0)
  209942. {
  209943. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209944. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209945. &dr.dataRef, &dr.dataRefType);
  209946. ok = openMovie (props, prop, movie);
  209947. DisposeHandle (dr.dataRef);
  209948. CFRelease (filePath);
  209949. }
  209950. else
  209951. {
  209952. // sanity-check because this currently needs to load the whole stream into memory..
  209953. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209954. dataHandle = NewHandle ((Size) input->getTotalLength());
  209955. HLock (dataHandle);
  209956. // read the entire stream into memory - this is a pain, but can't get it to work
  209957. // properly using a custom callback to supply the data.
  209958. input->read (*dataHandle, (int) input->getTotalLength());
  209959. HUnlock (dataHandle);
  209960. // different types to get QT to try. (We should really be a bit smarter here by
  209961. // working out in advance which one the stream contains, rather than just trying
  209962. // each one)
  209963. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209964. "\04.avi", "\04.m4a" };
  209965. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209966. {
  209967. /* // this fails for some bizarre reason - it can be bodged to work with
  209968. // movies, but can't seem to do it for other file types..
  209969. QTNewMovieUserProcRecord procInfo;
  209970. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209971. procInfo.getMovieUserProcRefcon = this;
  209972. procInfo.defaultDataRef.dataRef = dataRef;
  209973. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209974. props[prop].propClass = kQTPropertyClass_DataLocation;
  209975. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209976. props[prop].propValueSize = sizeof (procInfo);
  209977. props[prop].propValueAddress = (void*) &procInfo;
  209978. ++prop; */
  209979. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209980. dr.dataRefType = HandleDataHandlerSubType;
  209981. ok = openMovie (props, prop, movie);
  209982. DisposeHandle (dr.dataRef);
  209983. }
  209984. }
  209985. return ok;
  209986. }
  209987. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209988. const bool isControllerVisible)
  209989. {
  209990. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209991. movieFile = movieFile_;
  209992. return ok;
  209993. }
  209994. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209995. const bool isControllerVisible)
  209996. {
  209997. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209998. }
  209999. void QuickTimeMovieComponent::goToStart()
  210000. {
  210001. setPosition (0.0);
  210002. }
  210003. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  210004. const RectanglePlacement& placement)
  210005. {
  210006. int normalWidth, normalHeight;
  210007. getMovieNormalSize (normalWidth, normalHeight);
  210008. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  210009. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  210010. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  210011. else
  210012. setBounds (spaceToFitWithin);
  210013. }
  210014. #endif
  210015. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  210016. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210017. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210018. // compiled on its own).
  210019. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  210020. class WebBrowserComponentInternal : public ActiveXControlComponent
  210021. {
  210022. public:
  210023. WebBrowserComponentInternal()
  210024. : browser (0),
  210025. connectionPoint (0),
  210026. adviseCookie (0)
  210027. {
  210028. }
  210029. ~WebBrowserComponentInternal()
  210030. {
  210031. if (connectionPoint != 0)
  210032. connectionPoint->Unadvise (adviseCookie);
  210033. if (browser != 0)
  210034. browser->Release();
  210035. }
  210036. void createBrowser()
  210037. {
  210038. createControl (&CLSID_WebBrowser);
  210039. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  210040. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  210041. if (connectionPointContainer != 0)
  210042. {
  210043. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  210044. &connectionPoint);
  210045. if (connectionPoint != 0)
  210046. {
  210047. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  210048. jassert (owner != 0);
  210049. EventHandler* handler = new EventHandler (*owner);
  210050. connectionPoint->Advise (handler, &adviseCookie);
  210051. handler->Release();
  210052. }
  210053. }
  210054. }
  210055. void goToURL (const String& url,
  210056. const StringArray* headers,
  210057. const MemoryBlock* postData)
  210058. {
  210059. if (browser != 0)
  210060. {
  210061. LPSAFEARRAY sa = 0;
  210062. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  210063. VariantInit (&flags);
  210064. VariantInit (&frame);
  210065. VariantInit (&postDataVar);
  210066. VariantInit (&headersVar);
  210067. if (headers != 0)
  210068. {
  210069. V_VT (&headersVar) = VT_BSTR;
  210070. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  210071. }
  210072. if (postData != 0 && postData->getSize() > 0)
  210073. {
  210074. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  210075. if (sa != 0)
  210076. {
  210077. void* data = 0;
  210078. SafeArrayAccessData (sa, &data);
  210079. jassert (data != 0);
  210080. if (data != 0)
  210081. {
  210082. postData->copyTo (data, 0, postData->getSize());
  210083. SafeArrayUnaccessData (sa);
  210084. VARIANT postDataVar2;
  210085. VariantInit (&postDataVar2);
  210086. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  210087. V_ARRAY (&postDataVar2) = sa;
  210088. postDataVar = postDataVar2;
  210089. }
  210090. }
  210091. }
  210092. browser->Navigate ((BSTR) (const OLECHAR*) url,
  210093. &flags, &frame,
  210094. &postDataVar, &headersVar);
  210095. if (sa != 0)
  210096. SafeArrayDestroy (sa);
  210097. VariantClear (&flags);
  210098. VariantClear (&frame);
  210099. VariantClear (&postDataVar);
  210100. VariantClear (&headersVar);
  210101. }
  210102. }
  210103. IWebBrowser2* browser;
  210104. private:
  210105. IConnectionPoint* connectionPoint;
  210106. DWORD adviseCookie;
  210107. class EventHandler : public ComBaseClassHelper <IDispatch>,
  210108. public ComponentMovementWatcher
  210109. {
  210110. public:
  210111. EventHandler (WebBrowserComponent& owner_)
  210112. : ComponentMovementWatcher (&owner_),
  210113. owner (owner_)
  210114. {
  210115. }
  210116. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  210117. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  210118. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  210119. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  210120. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  210121. {
  210122. if (dispIdMember == DISPID_BEFORENAVIGATE2)
  210123. {
  210124. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  210125. String url;
  210126. if ((vurl->vt & VT_BYREF) != 0)
  210127. url = *vurl->pbstrVal;
  210128. else
  210129. url = vurl->bstrVal;
  210130. *pDispParams->rgvarg->pboolVal
  210131. = owner.pageAboutToLoad (url) ? VARIANT_FALSE
  210132. : VARIANT_TRUE;
  210133. return S_OK;
  210134. }
  210135. return E_NOTIMPL;
  210136. }
  210137. void componentMovedOrResized (bool, bool ) {}
  210138. void componentPeerChanged() {}
  210139. void componentVisibilityChanged() { owner.visibilityChanged(); }
  210140. private:
  210141. WebBrowserComponent& owner;
  210142. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler);
  210143. };
  210144. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponentInternal);
  210145. };
  210146. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  210147. : browser (0),
  210148. blankPageShown (false),
  210149. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  210150. {
  210151. setOpaque (true);
  210152. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  210153. }
  210154. WebBrowserComponent::~WebBrowserComponent()
  210155. {
  210156. delete browser;
  210157. }
  210158. void WebBrowserComponent::goToURL (const String& url,
  210159. const StringArray* headers,
  210160. const MemoryBlock* postData)
  210161. {
  210162. lastURL = url;
  210163. lastHeaders.clear();
  210164. if (headers != 0)
  210165. lastHeaders = *headers;
  210166. lastPostData.setSize (0);
  210167. if (postData != 0)
  210168. lastPostData = *postData;
  210169. blankPageShown = false;
  210170. browser->goToURL (url, headers, postData);
  210171. }
  210172. void WebBrowserComponent::stop()
  210173. {
  210174. if (browser->browser != 0)
  210175. browser->browser->Stop();
  210176. }
  210177. void WebBrowserComponent::goBack()
  210178. {
  210179. lastURL = String::empty;
  210180. blankPageShown = false;
  210181. if (browser->browser != 0)
  210182. browser->browser->GoBack();
  210183. }
  210184. void WebBrowserComponent::goForward()
  210185. {
  210186. lastURL = String::empty;
  210187. if (browser->browser != 0)
  210188. browser->browser->GoForward();
  210189. }
  210190. void WebBrowserComponent::refresh()
  210191. {
  210192. if (browser->browser != 0)
  210193. browser->browser->Refresh();
  210194. }
  210195. void WebBrowserComponent::paint (Graphics& g)
  210196. {
  210197. if (browser->browser == 0)
  210198. g.fillAll (Colours::white);
  210199. }
  210200. void WebBrowserComponent::checkWindowAssociation()
  210201. {
  210202. if (isShowing())
  210203. {
  210204. if (browser->browser == 0 && getPeer() != 0)
  210205. {
  210206. browser->createBrowser();
  210207. reloadLastURL();
  210208. }
  210209. else
  210210. {
  210211. if (blankPageShown)
  210212. goBack();
  210213. }
  210214. }
  210215. else
  210216. {
  210217. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  210218. {
  210219. // when the component becomes invisible, some stuff like flash
  210220. // carries on playing audio, so we need to force it onto a blank
  210221. // page to avoid this..
  210222. blankPageShown = true;
  210223. browser->goToURL ("about:blank", 0, 0);
  210224. }
  210225. }
  210226. }
  210227. void WebBrowserComponent::reloadLastURL()
  210228. {
  210229. if (lastURL.isNotEmpty())
  210230. {
  210231. goToURL (lastURL, &lastHeaders, &lastPostData);
  210232. lastURL = String::empty;
  210233. }
  210234. }
  210235. void WebBrowserComponent::parentHierarchyChanged()
  210236. {
  210237. checkWindowAssociation();
  210238. }
  210239. void WebBrowserComponent::resized()
  210240. {
  210241. browser->setSize (getWidth(), getHeight());
  210242. }
  210243. void WebBrowserComponent::visibilityChanged()
  210244. {
  210245. checkWindowAssociation();
  210246. }
  210247. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210248. {
  210249. return true;
  210250. }
  210251. #endif
  210252. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210253. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210254. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210255. // compiled on its own).
  210256. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210257. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210258. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210259. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210260. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210261. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210262. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210263. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210264. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210265. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210266. #define WGL_ACCELERATION_ARB 0x2003
  210267. #define WGL_SWAP_METHOD_ARB 0x2007
  210268. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210269. #define WGL_PIXEL_TYPE_ARB 0x2013
  210270. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210271. #define WGL_COLOR_BITS_ARB 0x2014
  210272. #define WGL_RED_BITS_ARB 0x2015
  210273. #define WGL_GREEN_BITS_ARB 0x2017
  210274. #define WGL_BLUE_BITS_ARB 0x2019
  210275. #define WGL_ALPHA_BITS_ARB 0x201B
  210276. #define WGL_DEPTH_BITS_ARB 0x2022
  210277. #define WGL_STENCIL_BITS_ARB 0x2023
  210278. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210279. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210280. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210281. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210282. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210283. #define WGL_STEREO_ARB 0x2012
  210284. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210285. #define WGL_SAMPLES_ARB 0x2042
  210286. #define WGL_TYPE_RGBA_ARB 0x202B
  210287. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210288. {
  210289. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210290. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210291. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210292. else
  210293. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210294. }
  210295. class WindowedGLContext : public OpenGLContext
  210296. {
  210297. public:
  210298. WindowedGLContext (Component* const component_,
  210299. HGLRC contextToShareWith,
  210300. const OpenGLPixelFormat& pixelFormat)
  210301. : renderContext (0),
  210302. dc (0),
  210303. component (component_)
  210304. {
  210305. jassert (component != 0);
  210306. createNativeWindow();
  210307. // Use a default pixel format that should be supported everywhere
  210308. PIXELFORMATDESCRIPTOR pfd;
  210309. zerostruct (pfd);
  210310. pfd.nSize = sizeof (pfd);
  210311. pfd.nVersion = 1;
  210312. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210313. pfd.iPixelType = PFD_TYPE_RGBA;
  210314. pfd.cColorBits = 24;
  210315. pfd.cDepthBits = 16;
  210316. const int format = ChoosePixelFormat (dc, &pfd);
  210317. if (format != 0)
  210318. SetPixelFormat (dc, format, &pfd);
  210319. renderContext = wglCreateContext (dc);
  210320. makeActive();
  210321. setPixelFormat (pixelFormat);
  210322. if (contextToShareWith != 0 && renderContext != 0)
  210323. wglShareLists (contextToShareWith, renderContext);
  210324. }
  210325. ~WindowedGLContext()
  210326. {
  210327. deleteContext();
  210328. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210329. nativeWindow = 0;
  210330. }
  210331. void deleteContext()
  210332. {
  210333. makeInactive();
  210334. if (renderContext != 0)
  210335. {
  210336. wglDeleteContext (renderContext);
  210337. renderContext = 0;
  210338. }
  210339. }
  210340. bool makeActive() const throw()
  210341. {
  210342. jassert (renderContext != 0);
  210343. return wglMakeCurrent (dc, renderContext) != 0;
  210344. }
  210345. bool makeInactive() const throw()
  210346. {
  210347. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210348. }
  210349. bool isActive() const throw()
  210350. {
  210351. return wglGetCurrentContext() == renderContext;
  210352. }
  210353. const OpenGLPixelFormat getPixelFormat() const
  210354. {
  210355. OpenGLPixelFormat pf;
  210356. makeActive();
  210357. StringArray availableExtensions;
  210358. getWglExtensions (dc, availableExtensions);
  210359. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210360. return pf;
  210361. }
  210362. void* getRawContext() const throw()
  210363. {
  210364. return renderContext;
  210365. }
  210366. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210367. {
  210368. makeActive();
  210369. PIXELFORMATDESCRIPTOR pfd;
  210370. zerostruct (pfd);
  210371. pfd.nSize = sizeof (pfd);
  210372. pfd.nVersion = 1;
  210373. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210374. pfd.iPixelType = PFD_TYPE_RGBA;
  210375. pfd.iLayerType = PFD_MAIN_PLANE;
  210376. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210377. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210378. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210379. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210380. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210381. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210382. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210383. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210384. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210385. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210386. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210387. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210388. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210389. int format = 0;
  210390. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210391. StringArray availableExtensions;
  210392. getWglExtensions (dc, availableExtensions);
  210393. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210394. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210395. {
  210396. int attributes[64];
  210397. int n = 0;
  210398. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210399. attributes[n++] = GL_TRUE;
  210400. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210401. attributes[n++] = GL_TRUE;
  210402. attributes[n++] = WGL_ACCELERATION_ARB;
  210403. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210404. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210405. attributes[n++] = GL_TRUE;
  210406. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210407. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210408. attributes[n++] = WGL_COLOR_BITS_ARB;
  210409. attributes[n++] = pfd.cColorBits;
  210410. attributes[n++] = WGL_RED_BITS_ARB;
  210411. attributes[n++] = pixelFormat.redBits;
  210412. attributes[n++] = WGL_GREEN_BITS_ARB;
  210413. attributes[n++] = pixelFormat.greenBits;
  210414. attributes[n++] = WGL_BLUE_BITS_ARB;
  210415. attributes[n++] = pixelFormat.blueBits;
  210416. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210417. attributes[n++] = pixelFormat.alphaBits;
  210418. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210419. attributes[n++] = pixelFormat.depthBufferBits;
  210420. if (pixelFormat.stencilBufferBits > 0)
  210421. {
  210422. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210423. attributes[n++] = pixelFormat.stencilBufferBits;
  210424. }
  210425. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210426. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210427. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210428. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210429. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210430. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210431. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210432. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210433. if (availableExtensions.contains ("WGL_ARB_multisample")
  210434. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210435. {
  210436. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210437. attributes[n++] = 1;
  210438. attributes[n++] = WGL_SAMPLES_ARB;
  210439. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210440. }
  210441. attributes[n++] = 0;
  210442. UINT formatsCount;
  210443. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210444. (void) ok;
  210445. jassert (ok);
  210446. }
  210447. else
  210448. {
  210449. format = ChoosePixelFormat (dc, &pfd);
  210450. }
  210451. if (format != 0)
  210452. {
  210453. makeInactive();
  210454. // win32 can't change the pixel format of a window, so need to delete the
  210455. // old one and create a new one..
  210456. jassert (nativeWindow != 0);
  210457. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210458. nativeWindow = 0;
  210459. createNativeWindow();
  210460. if (SetPixelFormat (dc, format, &pfd))
  210461. {
  210462. wglDeleteContext (renderContext);
  210463. renderContext = wglCreateContext (dc);
  210464. jassert (renderContext != 0);
  210465. return renderContext != 0;
  210466. }
  210467. }
  210468. return false;
  210469. }
  210470. void updateWindowPosition (int x, int y, int w, int h, int)
  210471. {
  210472. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210473. x, y, w, h,
  210474. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210475. }
  210476. void repaint()
  210477. {
  210478. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210479. }
  210480. void swapBuffers()
  210481. {
  210482. SwapBuffers (dc);
  210483. }
  210484. bool setSwapInterval (int numFramesPerSwap)
  210485. {
  210486. makeActive();
  210487. StringArray availableExtensions;
  210488. getWglExtensions (dc, availableExtensions);
  210489. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210490. return availableExtensions.contains ("WGL_EXT_swap_control")
  210491. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210492. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210493. }
  210494. int getSwapInterval() const
  210495. {
  210496. makeActive();
  210497. StringArray availableExtensions;
  210498. getWglExtensions (dc, availableExtensions);
  210499. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210500. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210501. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210502. return wglGetSwapIntervalEXT();
  210503. return 0;
  210504. }
  210505. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210506. {
  210507. jassert (isActive());
  210508. StringArray availableExtensions;
  210509. getWglExtensions (dc, availableExtensions);
  210510. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210511. int numTypes = 0;
  210512. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210513. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210514. {
  210515. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210516. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210517. jassertfalse;
  210518. }
  210519. else
  210520. {
  210521. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210522. }
  210523. OpenGLPixelFormat pf;
  210524. for (int i = 0; i < numTypes; ++i)
  210525. {
  210526. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210527. {
  210528. bool alreadyListed = false;
  210529. for (int j = results.size(); --j >= 0;)
  210530. if (pf == *results.getUnchecked(j))
  210531. alreadyListed = true;
  210532. if (! alreadyListed)
  210533. results.add (new OpenGLPixelFormat (pf));
  210534. }
  210535. }
  210536. }
  210537. void* getNativeWindowHandle() const
  210538. {
  210539. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210540. }
  210541. HGLRC renderContext;
  210542. private:
  210543. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210544. Component* const component;
  210545. HDC dc;
  210546. void createNativeWindow()
  210547. {
  210548. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210549. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210550. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210551. nativeWindow->dontRepaint = true;
  210552. nativeWindow->setVisible (true);
  210553. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210554. }
  210555. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210556. OpenGLPixelFormat& result,
  210557. const StringArray& availableExtensions) const throw()
  210558. {
  210559. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210560. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210561. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210562. {
  210563. int attributes[32];
  210564. int numAttributes = 0;
  210565. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210566. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210567. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210568. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210569. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210570. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210571. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210572. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210573. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210574. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210575. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210576. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210577. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210578. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210579. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210580. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210581. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210582. int values[32];
  210583. zeromem (values, sizeof (values));
  210584. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210585. {
  210586. int n = 0;
  210587. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210588. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210589. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210590. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210591. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210592. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210593. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210594. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210595. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210596. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210597. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210598. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210599. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210600. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210601. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210602. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210603. return isValidFormat;
  210604. }
  210605. else
  210606. {
  210607. jassertfalse;
  210608. }
  210609. }
  210610. else
  210611. {
  210612. PIXELFORMATDESCRIPTOR pfd;
  210613. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210614. {
  210615. result.redBits = pfd.cRedBits;
  210616. result.greenBits = pfd.cGreenBits;
  210617. result.blueBits = pfd.cBlueBits;
  210618. result.alphaBits = pfd.cAlphaBits;
  210619. result.depthBufferBits = pfd.cDepthBits;
  210620. result.stencilBufferBits = pfd.cStencilBits;
  210621. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210622. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210623. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210624. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210625. result.fullSceneAntiAliasingNumSamples = 0;
  210626. return true;
  210627. }
  210628. else
  210629. {
  210630. jassertfalse;
  210631. }
  210632. }
  210633. return false;
  210634. }
  210635. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  210636. };
  210637. OpenGLContext* OpenGLComponent::createContext()
  210638. {
  210639. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210640. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210641. preferredPixelFormat));
  210642. return (c->renderContext != 0) ? c.release() : 0;
  210643. }
  210644. void* OpenGLComponent::getNativeWindowHandle() const
  210645. {
  210646. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210647. }
  210648. void juce_glViewport (const int w, const int h)
  210649. {
  210650. glViewport (0, 0, w, h);
  210651. }
  210652. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210653. OwnedArray <OpenGLPixelFormat>& results)
  210654. {
  210655. Component tempComp;
  210656. {
  210657. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210658. wc.makeActive();
  210659. wc.findAlternativeOpenGLPixelFormats (results);
  210660. }
  210661. }
  210662. #endif
  210663. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210664. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210665. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210666. // compiled on its own).
  210667. #if JUCE_INCLUDED_FILE
  210668. #if JUCE_USE_CDREADER
  210669. namespace CDReaderHelpers
  210670. {
  210671. #define FILE_ANY_ACCESS 0
  210672. #ifndef FILE_READ_ACCESS
  210673. #define FILE_READ_ACCESS 1
  210674. #endif
  210675. #ifndef FILE_WRITE_ACCESS
  210676. #define FILE_WRITE_ACCESS 2
  210677. #endif
  210678. #define METHOD_BUFFERED 0
  210679. #define IOCTL_SCSI_BASE 4
  210680. #define SCSI_IOCTL_DATA_OUT 0
  210681. #define SCSI_IOCTL_DATA_IN 1
  210682. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210683. #define CTL_CODE2(DevType, Function, Method, Access) (((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
  210684. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210685. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210686. #define SENSE_LEN 14
  210687. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210688. #define SRB_DIR_IN 0x08
  210689. #define SRB_DIR_OUT 0x10
  210690. #define SRB_EVENT_NOTIFY 0x40
  210691. #define SC_HA_INQUIRY 0x00
  210692. #define SC_GET_DEV_TYPE 0x01
  210693. #define SC_EXEC_SCSI_CMD 0x02
  210694. #define SS_PENDING 0x00
  210695. #define SS_COMP 0x01
  210696. #define SS_ERR 0x04
  210697. enum
  210698. {
  210699. READTYPE_ANY = 0,
  210700. READTYPE_ATAPI1 = 1,
  210701. READTYPE_ATAPI2 = 2,
  210702. READTYPE_READ6 = 3,
  210703. READTYPE_READ10 = 4,
  210704. READTYPE_READ_D8 = 5,
  210705. READTYPE_READ_D4 = 6,
  210706. READTYPE_READ_D4_1 = 7,
  210707. READTYPE_READ10_2 = 8
  210708. };
  210709. struct SCSI_PASS_THROUGH
  210710. {
  210711. USHORT Length;
  210712. UCHAR ScsiStatus;
  210713. UCHAR PathId;
  210714. UCHAR TargetId;
  210715. UCHAR Lun;
  210716. UCHAR CdbLength;
  210717. UCHAR SenseInfoLength;
  210718. UCHAR DataIn;
  210719. ULONG DataTransferLength;
  210720. ULONG TimeOutValue;
  210721. ULONG DataBufferOffset;
  210722. ULONG SenseInfoOffset;
  210723. UCHAR Cdb[16];
  210724. };
  210725. struct SCSI_PASS_THROUGH_DIRECT
  210726. {
  210727. USHORT Length;
  210728. UCHAR ScsiStatus;
  210729. UCHAR PathId;
  210730. UCHAR TargetId;
  210731. UCHAR Lun;
  210732. UCHAR CdbLength;
  210733. UCHAR SenseInfoLength;
  210734. UCHAR DataIn;
  210735. ULONG DataTransferLength;
  210736. ULONG TimeOutValue;
  210737. PVOID DataBuffer;
  210738. ULONG SenseInfoOffset;
  210739. UCHAR Cdb[16];
  210740. };
  210741. struct SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER
  210742. {
  210743. SCSI_PASS_THROUGH_DIRECT spt;
  210744. ULONG Filler;
  210745. UCHAR ucSenseBuf[32];
  210746. };
  210747. struct SCSI_ADDRESS
  210748. {
  210749. ULONG Length;
  210750. UCHAR PortNumber;
  210751. UCHAR PathId;
  210752. UCHAR TargetId;
  210753. UCHAR Lun;
  210754. };
  210755. #pragma pack(1)
  210756. struct SRB_GDEVBlock
  210757. {
  210758. BYTE SRB_Cmd;
  210759. BYTE SRB_Status;
  210760. BYTE SRB_HaID;
  210761. BYTE SRB_Flags;
  210762. DWORD SRB_Hdr_Rsvd;
  210763. BYTE SRB_Target;
  210764. BYTE SRB_Lun;
  210765. BYTE SRB_DeviceType;
  210766. BYTE SRB_Rsvd1;
  210767. BYTE pad[68];
  210768. };
  210769. struct SRB_ExecSCSICmd
  210770. {
  210771. BYTE SRB_Cmd;
  210772. BYTE SRB_Status;
  210773. BYTE SRB_HaID;
  210774. BYTE SRB_Flags;
  210775. DWORD SRB_Hdr_Rsvd;
  210776. BYTE SRB_Target;
  210777. BYTE SRB_Lun;
  210778. WORD SRB_Rsvd1;
  210779. DWORD SRB_BufLen;
  210780. BYTE *SRB_BufPointer;
  210781. BYTE SRB_SenseLen;
  210782. BYTE SRB_CDBLen;
  210783. BYTE SRB_HaStat;
  210784. BYTE SRB_TargStat;
  210785. VOID *SRB_PostProc;
  210786. BYTE SRB_Rsvd2[20];
  210787. BYTE CDBByte[16];
  210788. BYTE SenseArea[SENSE_LEN + 2];
  210789. };
  210790. struct SRB
  210791. {
  210792. BYTE SRB_Cmd;
  210793. BYTE SRB_Status;
  210794. BYTE SRB_HaId;
  210795. BYTE SRB_Flags;
  210796. DWORD SRB_Hdr_Rsvd;
  210797. };
  210798. struct TOCTRACK
  210799. {
  210800. BYTE rsvd;
  210801. BYTE ADR;
  210802. BYTE trackNumber;
  210803. BYTE rsvd2;
  210804. BYTE addr[4];
  210805. };
  210806. struct TOC
  210807. {
  210808. WORD tocLen;
  210809. BYTE firstTrack;
  210810. BYTE lastTrack;
  210811. TOCTRACK tracks[100];
  210812. };
  210813. #pragma pack()
  210814. struct CDDeviceDescription
  210815. {
  210816. CDDeviceDescription() : ha (0), tgt (0), lun (0), scsiDriveLetter (0)
  210817. {
  210818. }
  210819. void createDescription (const char* data)
  210820. {
  210821. description << String (data + 8, 8).trim() // vendor
  210822. << ' ' << String (data + 16, 16).trim() // product id
  210823. << ' ' << String (data + 32, 4).trim(); // rev
  210824. }
  210825. String description;
  210826. BYTE ha, tgt, lun;
  210827. char scsiDriveLetter; // will be 0 if not using scsi
  210828. };
  210829. class CDReadBuffer
  210830. {
  210831. public:
  210832. CDReadBuffer (const int numberOfFrames)
  210833. : startFrame (0), numFrames (0), dataStartOffset (0),
  210834. dataLength (0), bufferSize (2352 * numberOfFrames), index (0),
  210835. buffer (bufferSize), wantsIndex (false)
  210836. {
  210837. }
  210838. bool isZero() const throw()
  210839. {
  210840. for (int i = 0; i < dataLength; ++i)
  210841. if (buffer [dataStartOffset + i] != 0)
  210842. return false;
  210843. return true;
  210844. }
  210845. int startFrame, numFrames, dataStartOffset;
  210846. int dataLength, bufferSize, index;
  210847. HeapBlock<BYTE> buffer;
  210848. bool wantsIndex;
  210849. };
  210850. class CDDeviceHandle;
  210851. class CDController
  210852. {
  210853. public:
  210854. CDController() : initialised (false) {}
  210855. virtual ~CDController() {}
  210856. virtual bool read (CDReadBuffer&) = 0;
  210857. virtual void shutDown() {}
  210858. bool readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer = 0);
  210859. int getLastIndex();
  210860. public:
  210861. CDDeviceHandle* deviceInfo;
  210862. int framesToCheck, framesOverlap;
  210863. bool initialised;
  210864. void prepare (SRB_ExecSCSICmd& s);
  210865. void perform (SRB_ExecSCSICmd& s);
  210866. void setPaused (bool paused);
  210867. };
  210868. class CDDeviceHandle
  210869. {
  210870. public:
  210871. CDDeviceHandle (const CDDeviceDescription& device, HANDLE scsiHandle_)
  210872. : info (device), scsiHandle (scsiHandle_), readType (READTYPE_ANY)
  210873. {
  210874. }
  210875. ~CDDeviceHandle()
  210876. {
  210877. if (controller != 0)
  210878. {
  210879. controller->shutDown();
  210880. controller = 0;
  210881. }
  210882. if (scsiHandle != 0)
  210883. CloseHandle (scsiHandle);
  210884. }
  210885. bool readTOC (TOC* lpToc);
  210886. bool readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer = 0);
  210887. void openDrawer (bool shouldBeOpen);
  210888. void performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s);
  210889. CDDeviceDescription info;
  210890. HANDLE scsiHandle;
  210891. BYTE readType;
  210892. private:
  210893. ScopedPointer<CDController> controller;
  210894. bool testController (int readType, CDController* newController, CDReadBuffer& bufferToUse);
  210895. };
  210896. HANDLE createSCSIDeviceHandle (const char driveLetter)
  210897. {
  210898. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210899. DWORD flags = GENERIC_READ | GENERIC_WRITE;
  210900. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210901. if (h == INVALID_HANDLE_VALUE)
  210902. {
  210903. flags ^= GENERIC_WRITE;
  210904. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210905. }
  210906. return h;
  210907. }
  210908. void findCDDevices (Array<CDDeviceDescription>& list)
  210909. {
  210910. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210911. {
  210912. TCHAR drivePath[] = { driveLetter, ':', '\\', 0, 0 };
  210913. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210914. {
  210915. HANDLE h = createSCSIDeviceHandle (driveLetter);
  210916. if (h != INVALID_HANDLE_VALUE)
  210917. {
  210918. char buffer[100];
  210919. zeromem (buffer, sizeof (buffer));
  210920. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p;
  210921. zerostruct (p);
  210922. p.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210923. p.spt.CdbLength = 6;
  210924. p.spt.SenseInfoLength = 24;
  210925. p.spt.DataIn = SCSI_IOCTL_DATA_IN;
  210926. p.spt.DataTransferLength = sizeof (buffer);
  210927. p.spt.TimeOutValue = 2;
  210928. p.spt.DataBuffer = buffer;
  210929. p.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210930. p.spt.Cdb[0] = 0x12;
  210931. p.spt.Cdb[4] = 100;
  210932. DWORD bytesReturned = 0;
  210933. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210934. &p, sizeof (p), &p, sizeof (p),
  210935. &bytesReturned, 0) != 0)
  210936. {
  210937. CDDeviceDescription dev;
  210938. dev.scsiDriveLetter = driveLetter;
  210939. dev.createDescription (buffer);
  210940. SCSI_ADDRESS scsiAddr;
  210941. zerostruct (scsiAddr);
  210942. scsiAddr.Length = sizeof (scsiAddr);
  210943. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210944. 0, 0, &scsiAddr, sizeof (scsiAddr),
  210945. &bytesReturned, 0) != 0)
  210946. {
  210947. dev.ha = scsiAddr.PortNumber;
  210948. dev.tgt = scsiAddr.TargetId;
  210949. dev.lun = scsiAddr.Lun;
  210950. list.add (dev);
  210951. }
  210952. }
  210953. CloseHandle (h);
  210954. }
  210955. }
  210956. }
  210957. }
  210958. DWORD performScsiPassThroughCommand (SRB_ExecSCSICmd* const srb, const char driveLetter,
  210959. HANDLE& deviceHandle, const bool retryOnFailure)
  210960. {
  210961. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210962. zerostruct (s);
  210963. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210964. s.spt.CdbLength = srb->SRB_CDBLen;
  210965. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210966. ? SCSI_IOCTL_DATA_IN
  210967. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210968. ? SCSI_IOCTL_DATA_OUT
  210969. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210970. s.spt.DataTransferLength = srb->SRB_BufLen;
  210971. s.spt.TimeOutValue = 5;
  210972. s.spt.DataBuffer = srb->SRB_BufPointer;
  210973. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210974. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210975. srb->SRB_Status = SS_ERR;
  210976. srb->SRB_TargStat = 0x0004;
  210977. DWORD bytesReturned = 0;
  210978. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210979. &s, sizeof (s), &s, sizeof (s), &bytesReturned, 0) != 0)
  210980. {
  210981. srb->SRB_Status = SS_COMP;
  210982. }
  210983. else if (retryOnFailure)
  210984. {
  210985. const DWORD error = GetLastError();
  210986. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210987. {
  210988. if (error != ERROR_INVALID_HANDLE)
  210989. CloseHandle (deviceHandle);
  210990. deviceHandle = createSCSIDeviceHandle (driveLetter);
  210991. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210992. }
  210993. }
  210994. return srb->SRB_Status;
  210995. }
  210996. // Controller types..
  210997. class ControllerType1 : public CDController
  210998. {
  210999. public:
  211000. ControllerType1() {}
  211001. bool read (CDReadBuffer& rb)
  211002. {
  211003. if (rb.numFrames * 2352 > rb.bufferSize)
  211004. return false;
  211005. SRB_ExecSCSICmd s;
  211006. prepare (s);
  211007. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211008. s.SRB_BufLen = rb.bufferSize;
  211009. s.SRB_BufPointer = rb.buffer;
  211010. s.SRB_CDBLen = 12;
  211011. s.CDBByte[0] = 0xBE;
  211012. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211013. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211014. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211015. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  211016. s.CDBByte[9] = (BYTE) (deviceInfo->readType == READTYPE_ATAPI1 ? 0x10 : 0xF0);
  211017. perform (s);
  211018. if (s.SRB_Status != SS_COMP)
  211019. return false;
  211020. rb.dataLength = rb.numFrames * 2352;
  211021. rb.dataStartOffset = 0;
  211022. return true;
  211023. }
  211024. };
  211025. class ControllerType2 : public CDController
  211026. {
  211027. public:
  211028. ControllerType2() {}
  211029. void shutDown()
  211030. {
  211031. if (initialised)
  211032. {
  211033. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211034. SRB_ExecSCSICmd s;
  211035. prepare (s);
  211036. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211037. s.SRB_BufLen = 0x0C;
  211038. s.SRB_BufPointer = bufPointer;
  211039. s.SRB_CDBLen = 6;
  211040. s.CDBByte[0] = 0x15;
  211041. s.CDBByte[4] = 0x0C;
  211042. perform (s);
  211043. }
  211044. }
  211045. bool init()
  211046. {
  211047. SRB_ExecSCSICmd s;
  211048. s.SRB_Status = SS_ERR;
  211049. if (deviceInfo->readType == READTYPE_READ10_2)
  211050. {
  211051. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211052. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211053. for (int i = 0; i < 2; ++i)
  211054. {
  211055. prepare (s);
  211056. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211057. s.SRB_BufLen = 0x14;
  211058. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211059. s.SRB_CDBLen = 6;
  211060. s.CDBByte[0] = 0x15;
  211061. s.CDBByte[1] = 0x10;
  211062. s.CDBByte[4] = 0x14;
  211063. perform (s);
  211064. if (s.SRB_Status != SS_COMP)
  211065. return false;
  211066. }
  211067. }
  211068. else
  211069. {
  211070. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211071. prepare (s);
  211072. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211073. s.SRB_BufLen = 0x0C;
  211074. s.SRB_BufPointer = bufPointer;
  211075. s.SRB_CDBLen = 6;
  211076. s.CDBByte[0] = 0x15;
  211077. s.CDBByte[4] = 0x0C;
  211078. perform (s);
  211079. }
  211080. return s.SRB_Status == SS_COMP;
  211081. }
  211082. bool read (CDReadBuffer& rb)
  211083. {
  211084. if (rb.numFrames * 2352 > rb.bufferSize)
  211085. return false;
  211086. if (! initialised)
  211087. {
  211088. initialised = init();
  211089. if (! initialised)
  211090. return false;
  211091. }
  211092. SRB_ExecSCSICmd s;
  211093. prepare (s);
  211094. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211095. s.SRB_BufLen = rb.bufferSize;
  211096. s.SRB_BufPointer = rb.buffer;
  211097. s.SRB_CDBLen = 10;
  211098. s.CDBByte[0] = 0x28;
  211099. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  211100. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211101. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211102. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211103. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  211104. perform (s);
  211105. if (s.SRB_Status != SS_COMP)
  211106. return false;
  211107. rb.dataLength = rb.numFrames * 2352;
  211108. rb.dataStartOffset = 0;
  211109. return true;
  211110. }
  211111. };
  211112. class ControllerType3 : public CDController
  211113. {
  211114. public:
  211115. ControllerType3() {}
  211116. bool read (CDReadBuffer& rb)
  211117. {
  211118. if (rb.numFrames * 2352 > rb.bufferSize)
  211119. return false;
  211120. if (! initialised)
  211121. {
  211122. setPaused (false);
  211123. initialised = true;
  211124. }
  211125. SRB_ExecSCSICmd s;
  211126. prepare (s);
  211127. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211128. s.SRB_BufLen = rb.numFrames * 2352;
  211129. s.SRB_BufPointer = rb.buffer;
  211130. s.SRB_CDBLen = 12;
  211131. s.CDBByte[0] = 0xD8;
  211132. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211133. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211134. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211135. s.CDBByte[9] = (BYTE) (rb.numFrames & 0xFF);
  211136. perform (s);
  211137. if (s.SRB_Status != SS_COMP)
  211138. return false;
  211139. rb.dataLength = rb.numFrames * 2352;
  211140. rb.dataStartOffset = 0;
  211141. return true;
  211142. }
  211143. };
  211144. class ControllerType4 : public CDController
  211145. {
  211146. public:
  211147. ControllerType4() {}
  211148. bool selectD4Mode()
  211149. {
  211150. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211151. SRB_ExecSCSICmd s;
  211152. prepare (s);
  211153. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211154. s.SRB_CDBLen = 6;
  211155. s.SRB_BufLen = 12;
  211156. s.SRB_BufPointer = bufPointer;
  211157. s.CDBByte[0] = 0x15;
  211158. s.CDBByte[1] = 0x10;
  211159. s.CDBByte[4] = 0x08;
  211160. perform (s);
  211161. return s.SRB_Status == SS_COMP;
  211162. }
  211163. bool read (CDReadBuffer& rb)
  211164. {
  211165. if (rb.numFrames * 2352 > rb.bufferSize)
  211166. return false;
  211167. if (! initialised)
  211168. {
  211169. setPaused (true);
  211170. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211171. selectD4Mode();
  211172. initialised = true;
  211173. }
  211174. SRB_ExecSCSICmd s;
  211175. prepare (s);
  211176. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211177. s.SRB_BufLen = rb.bufferSize;
  211178. s.SRB_BufPointer = rb.buffer;
  211179. s.SRB_CDBLen = 10;
  211180. s.CDBByte[0] = 0xD4;
  211181. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211182. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211183. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211184. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  211185. perform (s);
  211186. if (s.SRB_Status != SS_COMP)
  211187. return false;
  211188. rb.dataLength = rb.numFrames * 2352;
  211189. rb.dataStartOffset = 0;
  211190. return true;
  211191. }
  211192. };
  211193. void CDController::prepare (SRB_ExecSCSICmd& s)
  211194. {
  211195. zerostruct (s);
  211196. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211197. s.SRB_HaID = deviceInfo->info.ha;
  211198. s.SRB_Target = deviceInfo->info.tgt;
  211199. s.SRB_Lun = deviceInfo->info.lun;
  211200. s.SRB_SenseLen = SENSE_LEN;
  211201. }
  211202. void CDController::perform (SRB_ExecSCSICmd& s)
  211203. {
  211204. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211205. deviceInfo->performScsiCommand (s.SRB_PostProc, s);
  211206. }
  211207. void CDController::setPaused (bool paused)
  211208. {
  211209. SRB_ExecSCSICmd s;
  211210. prepare (s);
  211211. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211212. s.SRB_CDBLen = 10;
  211213. s.CDBByte[0] = 0x4B;
  211214. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211215. perform (s);
  211216. }
  211217. bool CDController::readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer)
  211218. {
  211219. if (overlapBuffer != 0)
  211220. {
  211221. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211222. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211223. if (doJitter
  211224. && overlapBuffer->startFrame > 0
  211225. && overlapBuffer->numFrames > 0
  211226. && overlapBuffer->dataLength > 0)
  211227. {
  211228. const int numFrames = rb.numFrames;
  211229. if (overlapBuffer->startFrame == (rb.startFrame - framesToCheck))
  211230. {
  211231. rb.startFrame -= framesOverlap;
  211232. if (framesToCheck < framesOverlap
  211233. && numFrames + framesOverlap <= rb.bufferSize / 2352)
  211234. rb.numFrames += framesOverlap;
  211235. }
  211236. else
  211237. {
  211238. overlapBuffer->dataLength = 0;
  211239. overlapBuffer->startFrame = 0;
  211240. overlapBuffer->numFrames = 0;
  211241. }
  211242. }
  211243. if (! read (rb))
  211244. return false;
  211245. if (doJitter)
  211246. {
  211247. const int checkLen = framesToCheck * 2352;
  211248. const int maxToCheck = rb.dataLength - checkLen;
  211249. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211250. return true;
  211251. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211252. bool found = false;
  211253. for (int i = 0; i < maxToCheck; ++i)
  211254. {
  211255. if (memcmp (p, rb.buffer + i, checkLen) == 0)
  211256. {
  211257. i += checkLen;
  211258. rb.dataStartOffset = i;
  211259. rb.dataLength -= i;
  211260. rb.startFrame = overlapBuffer->startFrame + framesToCheck;
  211261. found = true;
  211262. break;
  211263. }
  211264. }
  211265. rb.numFrames = rb.dataLength / 2352;
  211266. rb.dataLength = 2352 * rb.numFrames;
  211267. if (! found)
  211268. return false;
  211269. }
  211270. if (canDoJitter)
  211271. {
  211272. memcpy (overlapBuffer->buffer,
  211273. rb.buffer + rb.dataStartOffset + 2352 * (rb.numFrames - framesToCheck),
  211274. 2352 * framesToCheck);
  211275. overlapBuffer->startFrame = rb.startFrame + rb.numFrames - framesToCheck;
  211276. overlapBuffer->numFrames = framesToCheck;
  211277. overlapBuffer->dataLength = 2352 * framesToCheck;
  211278. overlapBuffer->dataStartOffset = 0;
  211279. }
  211280. else
  211281. {
  211282. overlapBuffer->startFrame = 0;
  211283. overlapBuffer->numFrames = 0;
  211284. overlapBuffer->dataLength = 0;
  211285. }
  211286. return true;
  211287. }
  211288. return read (rb);
  211289. }
  211290. int CDController::getLastIndex()
  211291. {
  211292. char qdata[100];
  211293. SRB_ExecSCSICmd s;
  211294. prepare (s);
  211295. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211296. s.SRB_BufLen = sizeof (qdata);
  211297. s.SRB_BufPointer = (BYTE*) qdata;
  211298. s.SRB_CDBLen = 12;
  211299. s.CDBByte[0] = 0x42;
  211300. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  211301. s.CDBByte[2] = 64;
  211302. s.CDBByte[3] = 1; // get current position
  211303. s.CDBByte[7] = 0;
  211304. s.CDBByte[8] = (BYTE) sizeof (qdata);
  211305. perform (s);
  211306. return s.SRB_Status == SS_COMP ? qdata[7] : 0;
  211307. }
  211308. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211309. {
  211310. SRB_ExecSCSICmd s;
  211311. zerostruct (s);
  211312. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211313. s.SRB_HaID = info.ha;
  211314. s.SRB_Target = info.tgt;
  211315. s.SRB_Lun = info.lun;
  211316. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211317. s.SRB_BufLen = 0x324;
  211318. s.SRB_BufPointer = (BYTE*) lpToc;
  211319. s.SRB_SenseLen = 0x0E;
  211320. s.SRB_CDBLen = 0x0A;
  211321. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211322. s.CDBByte[0] = 0x43;
  211323. s.CDBByte[1] = 0x00;
  211324. s.CDBByte[7] = 0x03;
  211325. s.CDBByte[8] = 0x24;
  211326. performScsiCommand (s.SRB_PostProc, s);
  211327. return (s.SRB_Status == SS_COMP);
  211328. }
  211329. void CDDeviceHandle::performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s)
  211330. {
  211331. ResetEvent (event);
  211332. DWORD status = performScsiPassThroughCommand ((SRB_ExecSCSICmd*) &s, info.scsiDriveLetter, scsiHandle, true);
  211333. if (status == SS_PENDING)
  211334. WaitForSingleObject (event, 4000);
  211335. CloseHandle (event);
  211336. }
  211337. bool CDDeviceHandle::readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer)
  211338. {
  211339. if (controller == 0)
  211340. {
  211341. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211342. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211343. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211344. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211345. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211346. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211347. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211348. }
  211349. buffer.index = 0;
  211350. if (controller != 0 && controller->readAudio (buffer, overlapBuffer))
  211351. {
  211352. if (buffer.wantsIndex)
  211353. buffer.index = controller->getLastIndex();
  211354. return true;
  211355. }
  211356. return false;
  211357. }
  211358. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211359. {
  211360. if (shouldBeOpen)
  211361. {
  211362. if (controller != 0)
  211363. {
  211364. controller->shutDown();
  211365. controller = 0;
  211366. }
  211367. if (scsiHandle != 0)
  211368. {
  211369. CloseHandle (scsiHandle);
  211370. scsiHandle = 0;
  211371. }
  211372. }
  211373. SRB_ExecSCSICmd s;
  211374. zerostruct (s);
  211375. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211376. s.SRB_HaID = info.ha;
  211377. s.SRB_Target = info.tgt;
  211378. s.SRB_Lun = info.lun;
  211379. s.SRB_SenseLen = SENSE_LEN;
  211380. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211381. s.SRB_BufLen = 0;
  211382. s.SRB_BufPointer = 0;
  211383. s.SRB_CDBLen = 12;
  211384. s.CDBByte[0] = 0x1b;
  211385. s.CDBByte[1] = (BYTE) (info.lun << 5);
  211386. s.CDBByte[4] = (BYTE) (shouldBeOpen ? 2 : 3);
  211387. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211388. performScsiCommand (s.SRB_PostProc, s);
  211389. }
  211390. bool CDDeviceHandle::testController (const int type, CDController* const newController, CDReadBuffer& rb)
  211391. {
  211392. controller = newController;
  211393. readType = (BYTE) type;
  211394. controller->deviceInfo = this;
  211395. controller->framesToCheck = 1;
  211396. controller->framesOverlap = 3;
  211397. bool passed = false;
  211398. memset (rb.buffer, 0xcd, rb.bufferSize);
  211399. if (controller->read (rb))
  211400. {
  211401. passed = true;
  211402. int* p = (int*) (rb.buffer + rb.dataStartOffset);
  211403. int wrong = 0;
  211404. for (int i = rb.dataLength / 4; --i >= 0;)
  211405. {
  211406. if (*p++ == (int) 0xcdcdcdcd)
  211407. {
  211408. if (++wrong == 4)
  211409. {
  211410. passed = false;
  211411. break;
  211412. }
  211413. }
  211414. else
  211415. {
  211416. wrong = 0;
  211417. }
  211418. }
  211419. }
  211420. if (! passed)
  211421. {
  211422. controller->shutDown();
  211423. controller = 0;
  211424. }
  211425. return passed;
  211426. }
  211427. struct CDDeviceWrapper
  211428. {
  211429. CDDeviceWrapper (const CDDeviceDescription& device, HANDLE scsiHandle)
  211430. : deviceHandle (device, scsiHandle), overlapBuffer (3), jitter (false)
  211431. {
  211432. // xxx jitter never seemed to actually be enabled (??)
  211433. }
  211434. CDDeviceHandle deviceHandle;
  211435. CDReadBuffer overlapBuffer;
  211436. bool jitter;
  211437. };
  211438. int getAddressOfTrack (const TOCTRACK& t) throw()
  211439. {
  211440. return (((DWORD) t.addr[0]) << 24) + (((DWORD) t.addr[1]) << 16)
  211441. + (((DWORD) t.addr[2]) << 8) + ((DWORD) t.addr[3]);
  211442. }
  211443. const int samplesPerFrame = 44100 / 75;
  211444. const int bytesPerFrame = samplesPerFrame * 4;
  211445. const int framesPerIndexRead = 4;
  211446. }
  211447. const StringArray AudioCDReader::getAvailableCDNames()
  211448. {
  211449. using namespace CDReaderHelpers;
  211450. StringArray results;
  211451. Array<CDDeviceDescription> list;
  211452. findCDDevices (list);
  211453. for (int i = 0; i < list.size(); ++i)
  211454. {
  211455. String s;
  211456. if (list[i].scsiDriveLetter > 0)
  211457. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211458. s << list[i].description;
  211459. results.add (s);
  211460. }
  211461. return results;
  211462. }
  211463. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211464. {
  211465. using namespace CDReaderHelpers;
  211466. Array<CDDeviceDescription> list;
  211467. findCDDevices (list);
  211468. if (isPositiveAndBelow (deviceIndex, list.size()))
  211469. {
  211470. HANDLE h = createSCSIDeviceHandle (list [deviceIndex].scsiDriveLetter);
  211471. if (h != INVALID_HANDLE_VALUE)
  211472. return new AudioCDReader (new CDDeviceWrapper (list [deviceIndex], h));
  211473. }
  211474. return 0;
  211475. }
  211476. AudioCDReader::AudioCDReader (void* handle_)
  211477. : AudioFormatReader (0, "CD Audio"),
  211478. handle (handle_),
  211479. indexingEnabled (false),
  211480. lastIndex (0),
  211481. firstFrameInBuffer (0),
  211482. samplesInBuffer (0)
  211483. {
  211484. using namespace CDReaderHelpers;
  211485. jassert (handle_ != 0);
  211486. refreshTrackLengths();
  211487. sampleRate = 44100.0;
  211488. bitsPerSample = 16;
  211489. numChannels = 2;
  211490. usesFloatingPointData = false;
  211491. buffer.setSize (4 * bytesPerFrame, true);
  211492. }
  211493. AudioCDReader::~AudioCDReader()
  211494. {
  211495. using namespace CDReaderHelpers;
  211496. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211497. delete device;
  211498. }
  211499. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211500. int64 startSampleInFile, int numSamples)
  211501. {
  211502. using namespace CDReaderHelpers;
  211503. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211504. bool ok = true;
  211505. while (numSamples > 0)
  211506. {
  211507. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211508. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211509. if (startSampleInFile >= bufferStartSample
  211510. && startSampleInFile < bufferEndSample)
  211511. {
  211512. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211513. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211514. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211515. const short* src = (const short*) buffer.getData();
  211516. src += 2 * (startSampleInFile - bufferStartSample);
  211517. for (int i = 0; i < toDo; ++i)
  211518. {
  211519. l[i] = src [i << 1] << 16;
  211520. if (r != 0)
  211521. r[i] = src [(i << 1) + 1] << 16;
  211522. }
  211523. startOffsetInDestBuffer += toDo;
  211524. startSampleInFile += toDo;
  211525. numSamples -= toDo;
  211526. }
  211527. else
  211528. {
  211529. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211530. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211531. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211532. {
  211533. device->overlapBuffer.dataLength = 0;
  211534. device->overlapBuffer.startFrame = 0;
  211535. device->overlapBuffer.numFrames = 0;
  211536. device->jitter = false;
  211537. }
  211538. firstFrameInBuffer = frameNeeded;
  211539. lastIndex = 0;
  211540. CDReadBuffer readBuffer (framesInBuffer + 4);
  211541. readBuffer.wantsIndex = indexingEnabled;
  211542. int i;
  211543. for (i = 5; --i >= 0;)
  211544. {
  211545. readBuffer.startFrame = frameNeeded;
  211546. readBuffer.numFrames = framesInBuffer;
  211547. if (device->deviceHandle.readAudio (readBuffer, device->jitter ? &device->overlapBuffer : 0))
  211548. break;
  211549. else
  211550. device->overlapBuffer.dataLength = 0;
  211551. }
  211552. if (i >= 0)
  211553. {
  211554. buffer.copyFrom (readBuffer.buffer + readBuffer.dataStartOffset, 0, readBuffer.dataLength);
  211555. samplesInBuffer = readBuffer.dataLength >> 2;
  211556. lastIndex = readBuffer.index;
  211557. }
  211558. else
  211559. {
  211560. int* l = destSamples[0] + startOffsetInDestBuffer;
  211561. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211562. while (--numSamples >= 0)
  211563. {
  211564. *l++ = 0;
  211565. if (r != 0)
  211566. *r++ = 0;
  211567. }
  211568. // sometimes the read fails for just the very last couple of blocks, so
  211569. // we'll ignore and errors in the last half-second of the disk..
  211570. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211571. break;
  211572. }
  211573. }
  211574. }
  211575. return ok;
  211576. }
  211577. bool AudioCDReader::isCDStillPresent() const
  211578. {
  211579. using namespace CDReaderHelpers;
  211580. TOC toc;
  211581. zerostruct (toc);
  211582. return static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc);
  211583. }
  211584. void AudioCDReader::refreshTrackLengths()
  211585. {
  211586. using namespace CDReaderHelpers;
  211587. trackStartSamples.clear();
  211588. zeromem (audioTracks, sizeof (audioTracks));
  211589. TOC toc;
  211590. zerostruct (toc);
  211591. if (static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc))
  211592. {
  211593. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211594. for (int i = 0; i <= numTracks; ++i)
  211595. {
  211596. trackStartSamples.add (samplesPerFrame * getAddressOfTrack (toc.tracks [i]));
  211597. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211598. }
  211599. }
  211600. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211601. }
  211602. bool AudioCDReader::isTrackAudio (int trackNum) const
  211603. {
  211604. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211605. }
  211606. void AudioCDReader::enableIndexScanning (bool b)
  211607. {
  211608. indexingEnabled = b;
  211609. }
  211610. int AudioCDReader::getLastIndex() const
  211611. {
  211612. return lastIndex;
  211613. }
  211614. int AudioCDReader::getIndexAt (int samplePos)
  211615. {
  211616. using namespace CDReaderHelpers;
  211617. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211618. const int frameNeeded = samplePos / samplesPerFrame;
  211619. device->overlapBuffer.dataLength = 0;
  211620. device->overlapBuffer.startFrame = 0;
  211621. device->overlapBuffer.numFrames = 0;
  211622. device->jitter = false;
  211623. firstFrameInBuffer = 0;
  211624. lastIndex = 0;
  211625. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211626. readBuffer.wantsIndex = true;
  211627. int i;
  211628. for (i = 5; --i >= 0;)
  211629. {
  211630. readBuffer.startFrame = frameNeeded;
  211631. readBuffer.numFrames = framesPerIndexRead;
  211632. if (device->deviceHandle.readAudio (readBuffer))
  211633. break;
  211634. }
  211635. if (i >= 0)
  211636. return readBuffer.index;
  211637. return -1;
  211638. }
  211639. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211640. {
  211641. using namespace CDReaderHelpers;
  211642. Array <int> indexes;
  211643. const int trackStart = getPositionOfTrackStart (trackNumber);
  211644. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211645. bool needToScan = true;
  211646. if (trackEnd - trackStart > 20 * 44100)
  211647. {
  211648. // check the end of the track for indexes before scanning the whole thing
  211649. needToScan = false;
  211650. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211651. bool seenAnIndex = false;
  211652. while (pos <= trackEnd - samplesPerFrame)
  211653. {
  211654. const int index = getIndexAt (pos);
  211655. if (index == 0)
  211656. {
  211657. // lead-out, so skip back a bit if we've not found any indexes yet..
  211658. if (seenAnIndex)
  211659. break;
  211660. pos -= 44100 * 5;
  211661. if (pos < trackStart)
  211662. break;
  211663. }
  211664. else
  211665. {
  211666. if (index > 0)
  211667. seenAnIndex = true;
  211668. if (index > 1)
  211669. {
  211670. needToScan = true;
  211671. break;
  211672. }
  211673. pos += samplesPerFrame * framesPerIndexRead;
  211674. }
  211675. }
  211676. }
  211677. if (needToScan)
  211678. {
  211679. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211680. int pos = trackStart;
  211681. int last = -1;
  211682. while (pos < trackEnd - samplesPerFrame * 10)
  211683. {
  211684. const int frameNeeded = pos / samplesPerFrame;
  211685. device->overlapBuffer.dataLength = 0;
  211686. device->overlapBuffer.startFrame = 0;
  211687. device->overlapBuffer.numFrames = 0;
  211688. device->jitter = false;
  211689. firstFrameInBuffer = 0;
  211690. CDReadBuffer readBuffer (4);
  211691. readBuffer.wantsIndex = true;
  211692. int i;
  211693. for (i = 5; --i >= 0;)
  211694. {
  211695. readBuffer.startFrame = frameNeeded;
  211696. readBuffer.numFrames = framesPerIndexRead;
  211697. if (device->deviceHandle.readAudio (readBuffer))
  211698. break;
  211699. }
  211700. if (i < 0)
  211701. break;
  211702. if (readBuffer.index > last && readBuffer.index > 1)
  211703. {
  211704. last = readBuffer.index;
  211705. indexes.add (pos);
  211706. }
  211707. pos += samplesPerFrame * framesPerIndexRead;
  211708. }
  211709. indexes.removeValue (trackStart);
  211710. }
  211711. return indexes;
  211712. }
  211713. void AudioCDReader::ejectDisk()
  211714. {
  211715. using namespace CDReaderHelpers;
  211716. static_cast <CDDeviceWrapper*> (handle)->deviceHandle.openDrawer (true);
  211717. }
  211718. #endif
  211719. #if JUCE_USE_CDBURNER
  211720. namespace CDBurnerHelpers
  211721. {
  211722. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211723. {
  211724. CoInitialize (0);
  211725. IDiscMaster* dm;
  211726. IDiscRecorder* result = 0;
  211727. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211728. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211729. IID_IDiscMaster,
  211730. (void**) &dm)))
  211731. {
  211732. if (SUCCEEDED (dm->Open()))
  211733. {
  211734. IEnumDiscRecorders* drEnum = 0;
  211735. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211736. {
  211737. IDiscRecorder* dr = 0;
  211738. DWORD dummy;
  211739. int index = 0;
  211740. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211741. {
  211742. if (indexToOpen == index)
  211743. {
  211744. result = dr;
  211745. break;
  211746. }
  211747. else if (list != 0)
  211748. {
  211749. BSTR path;
  211750. if (SUCCEEDED (dr->GetPath (&path)))
  211751. list->add ((const WCHAR*) path);
  211752. }
  211753. ++index;
  211754. dr->Release();
  211755. }
  211756. drEnum->Release();
  211757. }
  211758. if (master == 0)
  211759. dm->Close();
  211760. }
  211761. if (master != 0)
  211762. *master = dm;
  211763. else
  211764. dm->Release();
  211765. }
  211766. return result;
  211767. }
  211768. }
  211769. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211770. public Timer
  211771. {
  211772. public:
  211773. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211774. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211775. listener (0), progress (0), shouldCancel (false)
  211776. {
  211777. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211778. jassert (SUCCEEDED (hr));
  211779. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211780. //jassert (SUCCEEDED (hr));
  211781. lastState = getDiskState();
  211782. startTimer (2000);
  211783. }
  211784. ~Pimpl() {}
  211785. void releaseObjects()
  211786. {
  211787. discRecorder->Close();
  211788. if (redbook != 0)
  211789. redbook->Release();
  211790. discRecorder->Release();
  211791. discMaster->Release();
  211792. Release();
  211793. }
  211794. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211795. {
  211796. if (listener != 0 && ! shouldCancel)
  211797. shouldCancel = listener->audioCDBurnProgress (progress);
  211798. *pbCancel = shouldCancel;
  211799. return S_OK;
  211800. }
  211801. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211802. {
  211803. progress = nCompleted / (float) nTotal;
  211804. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211805. return E_NOTIMPL;
  211806. }
  211807. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211808. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211809. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211810. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211811. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211812. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211813. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211814. class ScopedDiscOpener
  211815. {
  211816. public:
  211817. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211818. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211819. private:
  211820. Pimpl& pimpl;
  211821. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener);
  211822. };
  211823. DiskState getDiskState()
  211824. {
  211825. const ScopedDiscOpener opener (*this);
  211826. long type, flags;
  211827. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211828. if (FAILED (hr))
  211829. return unknown;
  211830. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211831. return writableDiskPresent;
  211832. if (type == 0)
  211833. return noDisc;
  211834. else
  211835. return readOnlyDiskPresent;
  211836. }
  211837. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211838. {
  211839. ComSmartPtr<IPropertyStorage> prop;
  211840. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211841. return defaultReturn;
  211842. PROPSPEC iPropSpec;
  211843. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211844. iPropSpec.lpwstr = name;
  211845. PROPVARIANT iPropVariant;
  211846. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211847. ? defaultReturn : (int) iPropVariant.lVal;
  211848. }
  211849. bool setIntProperty (const LPOLESTR name, const int value) const
  211850. {
  211851. ComSmartPtr<IPropertyStorage> prop;
  211852. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211853. return false;
  211854. PROPSPEC iPropSpec;
  211855. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211856. iPropSpec.lpwstr = name;
  211857. PROPVARIANT iPropVariant;
  211858. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211859. return false;
  211860. iPropVariant.lVal = (long) value;
  211861. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211862. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211863. }
  211864. void timerCallback()
  211865. {
  211866. const DiskState state = getDiskState();
  211867. if (state != lastState)
  211868. {
  211869. lastState = state;
  211870. owner.sendChangeMessage();
  211871. }
  211872. }
  211873. AudioCDBurner& owner;
  211874. DiskState lastState;
  211875. IDiscMaster* discMaster;
  211876. IDiscRecorder* discRecorder;
  211877. IRedbookDiscMaster* redbook;
  211878. AudioCDBurner::BurnProgressListener* listener;
  211879. float progress;
  211880. bool shouldCancel;
  211881. };
  211882. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  211883. {
  211884. IDiscMaster* discMaster = 0;
  211885. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  211886. if (discRecorder != 0)
  211887. pimpl = new Pimpl (*this, discMaster, discRecorder);
  211888. }
  211889. AudioCDBurner::~AudioCDBurner()
  211890. {
  211891. if (pimpl != 0)
  211892. pimpl.release()->releaseObjects();
  211893. }
  211894. const StringArray AudioCDBurner::findAvailableDevices()
  211895. {
  211896. StringArray devs;
  211897. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  211898. return devs;
  211899. }
  211900. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  211901. {
  211902. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  211903. if (b->pimpl == 0)
  211904. b = 0;
  211905. return b.release();
  211906. }
  211907. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  211908. {
  211909. return pimpl->getDiskState();
  211910. }
  211911. bool AudioCDBurner::isDiskPresent() const
  211912. {
  211913. return getDiskState() == writableDiskPresent;
  211914. }
  211915. bool AudioCDBurner::openTray()
  211916. {
  211917. const Pimpl::ScopedDiscOpener opener (*pimpl);
  211918. return SUCCEEDED (pimpl->discRecorder->Eject());
  211919. }
  211920. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  211921. {
  211922. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  211923. DiskState oldState = getDiskState();
  211924. DiskState newState = oldState;
  211925. while (newState == oldState && Time::currentTimeMillis() < timeout)
  211926. {
  211927. newState = getDiskState();
  211928. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  211929. }
  211930. return newState;
  211931. }
  211932. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  211933. {
  211934. Array<int> results;
  211935. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  211936. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  211937. for (int i = 0; i < numElementsInArray (speeds); ++i)
  211938. if (speeds[i] <= maxSpeed)
  211939. results.add (speeds[i]);
  211940. results.addIfNotAlreadyThere (maxSpeed);
  211941. return results;
  211942. }
  211943. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  211944. {
  211945. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  211946. return false;
  211947. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  211948. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  211949. }
  211950. int AudioCDBurner::getNumAvailableAudioBlocks() const
  211951. {
  211952. long blocksFree = 0;
  211953. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  211954. return blocksFree;
  211955. }
  211956. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  211957. bool performFakeBurnForTesting, int writeSpeed)
  211958. {
  211959. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  211960. pimpl->listener = listener;
  211961. pimpl->progress = 0;
  211962. pimpl->shouldCancel = false;
  211963. UINT_PTR cookie;
  211964. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  211965. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  211966. ejectDiscAfterwards);
  211967. String error;
  211968. if (hr != S_OK)
  211969. {
  211970. const char* e = "Couldn't open or write to the CD device";
  211971. if (hr == IMAPI_E_USERABORT)
  211972. e = "User cancelled the write operation";
  211973. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  211974. e = "No Disk present";
  211975. error = e;
  211976. }
  211977. pimpl->discMaster->ProgressUnadvise (cookie);
  211978. pimpl->listener = 0;
  211979. return error;
  211980. }
  211981. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  211982. {
  211983. if (audioSource == 0)
  211984. return false;
  211985. ScopedPointer<AudioSource> source (audioSource);
  211986. long bytesPerBlock;
  211987. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  211988. const int samplesPerBlock = bytesPerBlock / 4;
  211989. bool ok = true;
  211990. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  211991. HeapBlock <byte> buffer (bytesPerBlock);
  211992. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  211993. int samplesDone = 0;
  211994. source->prepareToPlay (samplesPerBlock, 44100.0);
  211995. while (ok)
  211996. {
  211997. {
  211998. AudioSourceChannelInfo info;
  211999. info.buffer = &sourceBuffer;
  212000. info.numSamples = samplesPerBlock;
  212001. info.startSample = 0;
  212002. sourceBuffer.clear();
  212003. source->getNextAudioBlock (info);
  212004. }
  212005. zeromem (buffer, bytesPerBlock);
  212006. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  212007. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  212008. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  212009. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  212010. CDSampleFormat left (buffer, 2);
  212011. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  212012. CDSampleFormat right (buffer + 2, 2);
  212013. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  212014. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212015. if (FAILED (hr))
  212016. ok = false;
  212017. samplesDone += samplesPerBlock;
  212018. if (samplesDone >= numSamples)
  212019. break;
  212020. }
  212021. hr = pimpl->redbook->CloseAudioTrack();
  212022. return ok && hr == S_OK;
  212023. }
  212024. #endif
  212025. #endif
  212026. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212027. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212028. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212029. // compiled on its own).
  212030. #if JUCE_INCLUDED_FILE
  212031. class MidiInCollector
  212032. {
  212033. public:
  212034. MidiInCollector (MidiInput* const input_,
  212035. MidiInputCallback& callback_)
  212036. : deviceHandle (0),
  212037. input (input_),
  212038. callback (callback_),
  212039. concatenator (4096),
  212040. isStarted (false),
  212041. startTime (0)
  212042. {
  212043. }
  212044. ~MidiInCollector()
  212045. {
  212046. stop();
  212047. if (deviceHandle != 0)
  212048. {
  212049. int count = 5;
  212050. while (--count >= 0)
  212051. {
  212052. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212053. break;
  212054. Sleep (20);
  212055. }
  212056. }
  212057. }
  212058. void handleMessage (const uint32 message, const uint32 timeStamp)
  212059. {
  212060. if ((message & 0xff) >= 0x80 && isStarted)
  212061. {
  212062. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212063. writeFinishedBlocks();
  212064. }
  212065. }
  212066. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212067. {
  212068. if (isStarted)
  212069. {
  212070. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212071. writeFinishedBlocks();
  212072. }
  212073. }
  212074. void start()
  212075. {
  212076. jassert (deviceHandle != 0);
  212077. if (deviceHandle != 0 && ! isStarted)
  212078. {
  212079. activeMidiCollectors.addIfNotAlreadyThere (this);
  212080. for (int i = 0; i < (int) numHeaders; ++i)
  212081. headers[i].write (deviceHandle);
  212082. startTime = Time::getMillisecondCounter();
  212083. MMRESULT res = midiInStart (deviceHandle);
  212084. if (res == MMSYSERR_NOERROR)
  212085. {
  212086. concatenator.reset();
  212087. isStarted = true;
  212088. }
  212089. else
  212090. {
  212091. unprepareAllHeaders();
  212092. }
  212093. }
  212094. }
  212095. void stop()
  212096. {
  212097. if (isStarted)
  212098. {
  212099. isStarted = false;
  212100. midiInReset (deviceHandle);
  212101. midiInStop (deviceHandle);
  212102. activeMidiCollectors.removeValue (this);
  212103. unprepareAllHeaders();
  212104. concatenator.reset();
  212105. }
  212106. }
  212107. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212108. {
  212109. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212110. if (activeMidiCollectors.contains (collector))
  212111. {
  212112. if (uMsg == MIM_DATA)
  212113. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212114. else if (uMsg == MIM_LONGDATA)
  212115. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212116. }
  212117. }
  212118. HMIDIIN deviceHandle;
  212119. private:
  212120. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212121. MidiInput* input;
  212122. MidiInputCallback& callback;
  212123. MidiDataConcatenator concatenator;
  212124. bool volatile isStarted;
  212125. uint32 startTime;
  212126. class MidiHeader
  212127. {
  212128. public:
  212129. MidiHeader()
  212130. {
  212131. zerostruct (hdr);
  212132. hdr.lpData = data;
  212133. hdr.dwBufferLength = numElementsInArray (data);
  212134. }
  212135. void write (HMIDIIN deviceHandle)
  212136. {
  212137. hdr.dwBytesRecorded = 0;
  212138. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212139. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212140. }
  212141. void writeIfFinished (HMIDIIN deviceHandle)
  212142. {
  212143. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212144. {
  212145. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212146. (void) res;
  212147. write (deviceHandle);
  212148. }
  212149. }
  212150. void unprepare (HMIDIIN deviceHandle)
  212151. {
  212152. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212153. {
  212154. int c = 10;
  212155. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212156. Thread::sleep (20);
  212157. jassert (c >= 0);
  212158. }
  212159. }
  212160. private:
  212161. MIDIHDR hdr;
  212162. char data [256];
  212163. JUCE_DECLARE_NON_COPYABLE (MidiHeader);
  212164. };
  212165. enum { numHeaders = 32 };
  212166. MidiHeader headers [numHeaders];
  212167. void writeFinishedBlocks()
  212168. {
  212169. for (int i = 0; i < (int) numHeaders; ++i)
  212170. headers[i].writeIfFinished (deviceHandle);
  212171. }
  212172. void unprepareAllHeaders()
  212173. {
  212174. for (int i = 0; i < (int) numHeaders; ++i)
  212175. headers[i].unprepare (deviceHandle);
  212176. }
  212177. double convertTimeStamp (uint32 timeStamp)
  212178. {
  212179. timeStamp += startTime;
  212180. const uint32 now = Time::getMillisecondCounter();
  212181. if (timeStamp > now)
  212182. {
  212183. if (timeStamp > now + 2)
  212184. --startTime;
  212185. timeStamp = now;
  212186. }
  212187. return timeStamp * 0.001;
  212188. }
  212189. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector);
  212190. };
  212191. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212192. const StringArray MidiInput::getDevices()
  212193. {
  212194. StringArray s;
  212195. const int num = midiInGetNumDevs();
  212196. for (int i = 0; i < num; ++i)
  212197. {
  212198. MIDIINCAPS mc;
  212199. zerostruct (mc);
  212200. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212201. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212202. }
  212203. return s;
  212204. }
  212205. int MidiInput::getDefaultDeviceIndex()
  212206. {
  212207. return 0;
  212208. }
  212209. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212210. {
  212211. if (callback == 0)
  212212. return 0;
  212213. UINT deviceId = MIDI_MAPPER;
  212214. int n = 0;
  212215. String name;
  212216. const int num = midiInGetNumDevs();
  212217. for (int i = 0; i < num; ++i)
  212218. {
  212219. MIDIINCAPS mc;
  212220. zerostruct (mc);
  212221. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212222. {
  212223. if (index == n)
  212224. {
  212225. deviceId = i;
  212226. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212227. break;
  212228. }
  212229. ++n;
  212230. }
  212231. }
  212232. ScopedPointer <MidiInput> in (new MidiInput (name));
  212233. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212234. HMIDIIN h;
  212235. HRESULT err = midiInOpen (&h, deviceId,
  212236. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212237. (DWORD_PTR) (MidiInCollector*) collector,
  212238. CALLBACK_FUNCTION);
  212239. if (err == MMSYSERR_NOERROR)
  212240. {
  212241. collector->deviceHandle = h;
  212242. in->internal = collector.release();
  212243. return in.release();
  212244. }
  212245. return 0;
  212246. }
  212247. MidiInput::MidiInput (const String& name_)
  212248. : name (name_),
  212249. internal (0)
  212250. {
  212251. }
  212252. MidiInput::~MidiInput()
  212253. {
  212254. delete static_cast <MidiInCollector*> (internal);
  212255. }
  212256. void MidiInput::start()
  212257. {
  212258. static_cast <MidiInCollector*> (internal)->start();
  212259. }
  212260. void MidiInput::stop()
  212261. {
  212262. static_cast <MidiInCollector*> (internal)->stop();
  212263. }
  212264. struct MidiOutHandle
  212265. {
  212266. int refCount;
  212267. UINT deviceId;
  212268. HMIDIOUT handle;
  212269. static Array<MidiOutHandle*> activeHandles;
  212270. private:
  212271. JUCE_LEAK_DETECTOR (MidiOutHandle);
  212272. };
  212273. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212274. const StringArray MidiOutput::getDevices()
  212275. {
  212276. StringArray s;
  212277. const int num = midiOutGetNumDevs();
  212278. for (int i = 0; i < num; ++i)
  212279. {
  212280. MIDIOUTCAPS mc;
  212281. zerostruct (mc);
  212282. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212283. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212284. }
  212285. return s;
  212286. }
  212287. int MidiOutput::getDefaultDeviceIndex()
  212288. {
  212289. const int num = midiOutGetNumDevs();
  212290. int n = 0;
  212291. for (int i = 0; i < num; ++i)
  212292. {
  212293. MIDIOUTCAPS mc;
  212294. zerostruct (mc);
  212295. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212296. {
  212297. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212298. return n;
  212299. ++n;
  212300. }
  212301. }
  212302. return 0;
  212303. }
  212304. MidiOutput* MidiOutput::openDevice (int index)
  212305. {
  212306. UINT deviceId = MIDI_MAPPER;
  212307. const int num = midiOutGetNumDevs();
  212308. int i, n = 0;
  212309. for (i = 0; i < num; ++i)
  212310. {
  212311. MIDIOUTCAPS mc;
  212312. zerostruct (mc);
  212313. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212314. {
  212315. // use the microsoft sw synth as a default - best not to allow deviceId
  212316. // to be MIDI_MAPPER, or else device sharing breaks
  212317. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212318. deviceId = i;
  212319. if (index == n)
  212320. {
  212321. deviceId = i;
  212322. break;
  212323. }
  212324. ++n;
  212325. }
  212326. }
  212327. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212328. {
  212329. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212330. if (han != 0 && han->deviceId == deviceId)
  212331. {
  212332. han->refCount++;
  212333. MidiOutput* const out = new MidiOutput();
  212334. out->internal = han;
  212335. return out;
  212336. }
  212337. }
  212338. for (i = 4; --i >= 0;)
  212339. {
  212340. HMIDIOUT h = 0;
  212341. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212342. if (res == MMSYSERR_NOERROR)
  212343. {
  212344. MidiOutHandle* const han = new MidiOutHandle();
  212345. han->deviceId = deviceId;
  212346. han->refCount = 1;
  212347. han->handle = h;
  212348. MidiOutHandle::activeHandles.add (han);
  212349. MidiOutput* const out = new MidiOutput();
  212350. out->internal = han;
  212351. return out;
  212352. }
  212353. else if (res == MMSYSERR_ALLOCATED)
  212354. {
  212355. Sleep (100);
  212356. }
  212357. else
  212358. {
  212359. break;
  212360. }
  212361. }
  212362. return 0;
  212363. }
  212364. MidiOutput::~MidiOutput()
  212365. {
  212366. stopBackgroundThread();
  212367. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212368. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212369. {
  212370. midiOutClose (h->handle);
  212371. MidiOutHandle::activeHandles.removeValue (h);
  212372. delete h;
  212373. }
  212374. }
  212375. void MidiOutput::reset()
  212376. {
  212377. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212378. midiOutReset (h->handle);
  212379. }
  212380. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212381. {
  212382. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212383. DWORD n;
  212384. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212385. {
  212386. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212387. rightVol = nn[0] / (float) 0xffff;
  212388. leftVol = nn[1] / (float) 0xffff;
  212389. return true;
  212390. }
  212391. else
  212392. {
  212393. rightVol = leftVol = 1.0f;
  212394. return false;
  212395. }
  212396. }
  212397. void MidiOutput::setVolume (float leftVol, float rightVol)
  212398. {
  212399. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212400. DWORD n;
  212401. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212402. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212403. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212404. midiOutSetVolume (handle->handle, n);
  212405. }
  212406. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212407. {
  212408. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212409. if (message.getRawDataSize() > 3
  212410. || message.isSysEx())
  212411. {
  212412. MIDIHDR h;
  212413. zerostruct (h);
  212414. h.lpData = (char*) message.getRawData();
  212415. h.dwBufferLength = message.getRawDataSize();
  212416. h.dwBytesRecorded = message.getRawDataSize();
  212417. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212418. {
  212419. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212420. if (res == MMSYSERR_NOERROR)
  212421. {
  212422. while ((h.dwFlags & MHDR_DONE) == 0)
  212423. Sleep (1);
  212424. int count = 500; // 1 sec timeout
  212425. while (--count >= 0)
  212426. {
  212427. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212428. if (res == MIDIERR_STILLPLAYING)
  212429. Sleep (2);
  212430. else
  212431. break;
  212432. }
  212433. }
  212434. }
  212435. }
  212436. else
  212437. {
  212438. midiOutShortMsg (handle->handle,
  212439. *(unsigned int*) message.getRawData());
  212440. }
  212441. }
  212442. #endif
  212443. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212444. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212445. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212446. // compiled on its own).
  212447. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212448. #undef WINDOWS
  212449. // #define ASIO_DEBUGGING 1
  212450. #undef log
  212451. #if ASIO_DEBUGGING
  212452. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212453. #else
  212454. #define log(a) {}
  212455. #endif
  212456. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  212457. to be pretty random about whether or not they do this. If you hit an error using these functions
  212458. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  212459. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  212460. */
  212461. #define JUCE_ASIOCALLBACK __cdecl
  212462. namespace ASIODebugging
  212463. {
  212464. #if ASIO_DEBUGGING
  212465. static void log (const String& context, long error)
  212466. {
  212467. String err ("unknown error");
  212468. if (error == ASE_NotPresent) err = "Not Present";
  212469. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212470. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212471. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212472. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212473. else if (error == ASE_NoClock) err = "No Clock";
  212474. else if (error == ASE_NoMemory) err = "Out of memory";
  212475. log ("!!error: " + context + " - " + err);
  212476. }
  212477. #define logError(a, b) ASIODebugging::log ((a), (b))
  212478. #else
  212479. #define logError(a, b) {}
  212480. #endif
  212481. }
  212482. class ASIOAudioIODevice;
  212483. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212484. static const int maxASIOChannels = 160;
  212485. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212486. private Timer
  212487. {
  212488. public:
  212489. Component ourWindow;
  212490. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212491. const String& optionalDllForDirectLoading_)
  212492. : AudioIODevice (name_, "ASIO"),
  212493. asioObject (0),
  212494. classId (classId_),
  212495. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212496. currentBitDepth (16),
  212497. currentSampleRate (0),
  212498. isOpen_ (false),
  212499. isStarted (false),
  212500. postOutput (true),
  212501. insideControlPanelModalLoop (false),
  212502. shouldUsePreferredSize (false)
  212503. {
  212504. name = name_;
  212505. ourWindow.addToDesktop (0);
  212506. windowHandle = ourWindow.getWindowHandle();
  212507. jassert (currentASIODev [slotNumber] == 0);
  212508. currentASIODev [slotNumber] = this;
  212509. openDevice();
  212510. }
  212511. ~ASIOAudioIODevice()
  212512. {
  212513. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212514. if (currentASIODev[i] == this)
  212515. currentASIODev[i] = 0;
  212516. close();
  212517. log ("ASIO - exiting");
  212518. removeCurrentDriver();
  212519. }
  212520. void updateSampleRates()
  212521. {
  212522. // find a list of sample rates..
  212523. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212524. sampleRates.clear();
  212525. if (asioObject != 0)
  212526. {
  212527. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212528. {
  212529. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212530. if (err == 0)
  212531. {
  212532. sampleRates.add ((int) possibleSampleRates[index]);
  212533. log ("rate: " + String ((int) possibleSampleRates[index]));
  212534. }
  212535. else if (err != ASE_NoClock)
  212536. {
  212537. logError ("CanSampleRate", err);
  212538. }
  212539. }
  212540. if (sampleRates.size() == 0)
  212541. {
  212542. double cr = 0;
  212543. const long err = asioObject->getSampleRate (&cr);
  212544. log ("No sample rates supported - current rate: " + String ((int) cr));
  212545. if (err == 0)
  212546. sampleRates.add ((int) cr);
  212547. }
  212548. }
  212549. }
  212550. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212551. const StringArray getInputChannelNames() { return inputChannelNames; }
  212552. int getNumSampleRates() { return sampleRates.size(); }
  212553. double getSampleRate (int index) { return sampleRates [index]; }
  212554. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212555. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212556. int getDefaultBufferSize() { return preferredSize; }
  212557. const String open (const BigInteger& inputChannels,
  212558. const BigInteger& outputChannels,
  212559. double sr,
  212560. int bufferSizeSamples)
  212561. {
  212562. close();
  212563. currentCallback = 0;
  212564. if (bufferSizeSamples <= 0)
  212565. shouldUsePreferredSize = true;
  212566. if (asioObject == 0 || ! isASIOOpen)
  212567. {
  212568. log ("Warning: device not open");
  212569. const String err (openDevice());
  212570. if (asioObject == 0 || ! isASIOOpen)
  212571. return err;
  212572. }
  212573. isStarted = false;
  212574. bufferIndex = -1;
  212575. long err = 0;
  212576. long newPreferredSize = 0;
  212577. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212578. minSize = 0;
  212579. maxSize = 0;
  212580. newPreferredSize = 0;
  212581. granularity = 0;
  212582. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212583. {
  212584. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212585. shouldUsePreferredSize = true;
  212586. preferredSize = newPreferredSize;
  212587. }
  212588. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212589. // dynamic changes to the buffer size...
  212590. shouldUsePreferredSize = shouldUsePreferredSize
  212591. || getName().containsIgnoreCase ("Digidesign");
  212592. if (shouldUsePreferredSize)
  212593. {
  212594. log ("Using preferred size for buffer..");
  212595. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212596. {
  212597. bufferSizeSamples = preferredSize;
  212598. }
  212599. else
  212600. {
  212601. bufferSizeSamples = 1024;
  212602. logError ("GetBufferSize1", err);
  212603. }
  212604. shouldUsePreferredSize = false;
  212605. }
  212606. int sampleRate = roundDoubleToInt (sr);
  212607. currentSampleRate = sampleRate;
  212608. currentBlockSizeSamples = bufferSizeSamples;
  212609. currentChansOut.clear();
  212610. currentChansIn.clear();
  212611. zeromem (inBuffers, sizeof (inBuffers));
  212612. zeromem (outBuffers, sizeof (outBuffers));
  212613. updateSampleRates();
  212614. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212615. sampleRate = sampleRates[0];
  212616. jassert (sampleRate != 0);
  212617. if (sampleRate == 0)
  212618. sampleRate = 44100;
  212619. long numSources = 32;
  212620. ASIOClockSource clocks[32];
  212621. zeromem (clocks, sizeof (clocks));
  212622. asioObject->getClockSources (clocks, &numSources);
  212623. bool isSourceSet = false;
  212624. // careful not to remove this loop because it does more than just logging!
  212625. int i;
  212626. for (i = 0; i < numSources; ++i)
  212627. {
  212628. String s ("clock: ");
  212629. s += clocks[i].name;
  212630. if (clocks[i].isCurrentSource)
  212631. {
  212632. isSourceSet = true;
  212633. s << " (cur)";
  212634. }
  212635. log (s);
  212636. }
  212637. if (numSources > 1 && ! isSourceSet)
  212638. {
  212639. log ("setting clock source");
  212640. asioObject->setClockSource (clocks[0].index);
  212641. Thread::sleep (20);
  212642. }
  212643. else
  212644. {
  212645. if (numSources == 0)
  212646. {
  212647. log ("ASIO - no clock sources!");
  212648. }
  212649. }
  212650. double cr = 0;
  212651. err = asioObject->getSampleRate (&cr);
  212652. if (err == 0)
  212653. {
  212654. currentSampleRate = cr;
  212655. }
  212656. else
  212657. {
  212658. logError ("GetSampleRate", err);
  212659. currentSampleRate = 0;
  212660. }
  212661. error = String::empty;
  212662. needToReset = false;
  212663. isReSync = false;
  212664. err = 0;
  212665. bool buffersCreated = false;
  212666. if (currentSampleRate != sampleRate)
  212667. {
  212668. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212669. err = asioObject->setSampleRate (sampleRate);
  212670. if (err == ASE_NoClock && numSources > 0)
  212671. {
  212672. log ("trying to set a clock source..");
  212673. Thread::sleep (10);
  212674. err = asioObject->setClockSource (clocks[0].index);
  212675. if (err != 0)
  212676. {
  212677. logError ("SetClock", err);
  212678. }
  212679. Thread::sleep (10);
  212680. err = asioObject->setSampleRate (sampleRate);
  212681. }
  212682. }
  212683. if (err == 0)
  212684. {
  212685. currentSampleRate = sampleRate;
  212686. if (needToReset)
  212687. {
  212688. if (isReSync)
  212689. {
  212690. log ("Resync request");
  212691. }
  212692. log ("! Resetting ASIO after sample rate change");
  212693. removeCurrentDriver();
  212694. loadDriver();
  212695. const String error (initDriver());
  212696. if (error.isNotEmpty())
  212697. {
  212698. log ("ASIOInit: " + error);
  212699. }
  212700. needToReset = false;
  212701. isReSync = false;
  212702. }
  212703. numActiveInputChans = 0;
  212704. numActiveOutputChans = 0;
  212705. ASIOBufferInfo* info = bufferInfos;
  212706. int i;
  212707. for (i = 0; i < totalNumInputChans; ++i)
  212708. {
  212709. if (inputChannels[i])
  212710. {
  212711. currentChansIn.setBit (i);
  212712. info->isInput = 1;
  212713. info->channelNum = i;
  212714. info->buffers[0] = info->buffers[1] = 0;
  212715. ++info;
  212716. ++numActiveInputChans;
  212717. }
  212718. }
  212719. for (i = 0; i < totalNumOutputChans; ++i)
  212720. {
  212721. if (outputChannels[i])
  212722. {
  212723. currentChansOut.setBit (i);
  212724. info->isInput = 0;
  212725. info->channelNum = i;
  212726. info->buffers[0] = info->buffers[1] = 0;
  212727. ++info;
  212728. ++numActiveOutputChans;
  212729. }
  212730. }
  212731. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212732. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212733. if (currentASIODev[0] == this)
  212734. {
  212735. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212736. callbacks.asioMessage = &asioMessagesCallback0;
  212737. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212738. }
  212739. else if (currentASIODev[1] == this)
  212740. {
  212741. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212742. callbacks.asioMessage = &asioMessagesCallback1;
  212743. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212744. }
  212745. else if (currentASIODev[2] == this)
  212746. {
  212747. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212748. callbacks.asioMessage = &asioMessagesCallback2;
  212749. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212750. }
  212751. else
  212752. {
  212753. jassertfalse;
  212754. }
  212755. log ("disposing buffers");
  212756. err = asioObject->disposeBuffers();
  212757. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212758. err = asioObject->createBuffers (bufferInfos,
  212759. totalBuffers,
  212760. currentBlockSizeSamples,
  212761. &callbacks);
  212762. if (err != 0)
  212763. {
  212764. currentBlockSizeSamples = preferredSize;
  212765. logError ("create buffers 2", err);
  212766. asioObject->disposeBuffers();
  212767. err = asioObject->createBuffers (bufferInfos,
  212768. totalBuffers,
  212769. currentBlockSizeSamples,
  212770. &callbacks);
  212771. }
  212772. if (err == 0)
  212773. {
  212774. buffersCreated = true;
  212775. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212776. int n = 0;
  212777. Array <int> types;
  212778. currentBitDepth = 16;
  212779. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212780. {
  212781. if (inputChannels[i])
  212782. {
  212783. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212784. ASIOChannelInfo channelInfo;
  212785. zerostruct (channelInfo);
  212786. channelInfo.channel = i;
  212787. channelInfo.isInput = 1;
  212788. asioObject->getChannelInfo (&channelInfo);
  212789. types.addIfNotAlreadyThere (channelInfo.type);
  212790. typeToFormatParameters (channelInfo.type,
  212791. inputChannelBitDepths[n],
  212792. inputChannelBytesPerSample[n],
  212793. inputChannelIsFloat[n],
  212794. inputChannelLittleEndian[n]);
  212795. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212796. ++n;
  212797. }
  212798. }
  212799. jassert (numActiveInputChans == n);
  212800. n = 0;
  212801. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  212802. {
  212803. if (outputChannels[i])
  212804. {
  212805. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  212806. ASIOChannelInfo channelInfo;
  212807. zerostruct (channelInfo);
  212808. channelInfo.channel = i;
  212809. channelInfo.isInput = 0;
  212810. asioObject->getChannelInfo (&channelInfo);
  212811. types.addIfNotAlreadyThere (channelInfo.type);
  212812. typeToFormatParameters (channelInfo.type,
  212813. outputChannelBitDepths[n],
  212814. outputChannelBytesPerSample[n],
  212815. outputChannelIsFloat[n],
  212816. outputChannelLittleEndian[n]);
  212817. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  212818. ++n;
  212819. }
  212820. }
  212821. jassert (numActiveOutputChans == n);
  212822. for (i = types.size(); --i >= 0;)
  212823. {
  212824. log ("channel format: " + String (types[i]));
  212825. }
  212826. jassert (n <= totalBuffers);
  212827. for (i = 0; i < numActiveOutputChans; ++i)
  212828. {
  212829. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  212830. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  212831. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  212832. {
  212833. log ("!! Null buffers");
  212834. }
  212835. else
  212836. {
  212837. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  212838. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  212839. }
  212840. }
  212841. inputLatency = outputLatency = 0;
  212842. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212843. {
  212844. log ("ASIO - no latencies");
  212845. }
  212846. else
  212847. {
  212848. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  212849. }
  212850. isOpen_ = true;
  212851. log ("starting ASIO");
  212852. calledback = false;
  212853. err = asioObject->start();
  212854. if (err != 0)
  212855. {
  212856. isOpen_ = false;
  212857. log ("ASIO - stop on failure");
  212858. Thread::sleep (10);
  212859. asioObject->stop();
  212860. error = "Can't start device";
  212861. Thread::sleep (10);
  212862. }
  212863. else
  212864. {
  212865. int count = 300;
  212866. while (--count > 0 && ! calledback)
  212867. Thread::sleep (10);
  212868. isStarted = true;
  212869. if (! calledback)
  212870. {
  212871. error = "Device didn't start correctly";
  212872. log ("ASIO didn't callback - stopping..");
  212873. asioObject->stop();
  212874. }
  212875. }
  212876. }
  212877. else
  212878. {
  212879. error = "Can't create i/o buffers";
  212880. }
  212881. }
  212882. else
  212883. {
  212884. error = "Can't set sample rate: ";
  212885. error << sampleRate;
  212886. }
  212887. if (error.isNotEmpty())
  212888. {
  212889. logError (error, err);
  212890. if (asioObject != 0 && buffersCreated)
  212891. asioObject->disposeBuffers();
  212892. Thread::sleep (20);
  212893. isStarted = false;
  212894. isOpen_ = false;
  212895. const String errorCopy (error);
  212896. close(); // (this resets the error string)
  212897. error = errorCopy;
  212898. }
  212899. needToReset = false;
  212900. isReSync = false;
  212901. return error;
  212902. }
  212903. void close()
  212904. {
  212905. error = String::empty;
  212906. stopTimer();
  212907. stop();
  212908. if (isASIOOpen && isOpen_)
  212909. {
  212910. const ScopedLock sl (callbackLock);
  212911. isOpen_ = false;
  212912. isStarted = false;
  212913. needToReset = false;
  212914. isReSync = false;
  212915. log ("ASIO - stopping");
  212916. if (asioObject != 0)
  212917. {
  212918. Thread::sleep (20);
  212919. asioObject->stop();
  212920. Thread::sleep (10);
  212921. asioObject->disposeBuffers();
  212922. }
  212923. Thread::sleep (10);
  212924. }
  212925. }
  212926. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  212927. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  212928. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  212929. double getCurrentSampleRate() { return currentSampleRate; }
  212930. int getCurrentBitDepth() { return currentBitDepth; }
  212931. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  212932. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  212933. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  212934. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  212935. void start (AudioIODeviceCallback* callback)
  212936. {
  212937. if (callback != 0)
  212938. {
  212939. callback->audioDeviceAboutToStart (this);
  212940. const ScopedLock sl (callbackLock);
  212941. currentCallback = callback;
  212942. }
  212943. }
  212944. void stop()
  212945. {
  212946. AudioIODeviceCallback* const lastCallback = currentCallback;
  212947. {
  212948. const ScopedLock sl (callbackLock);
  212949. currentCallback = 0;
  212950. }
  212951. if (lastCallback != 0)
  212952. lastCallback->audioDeviceStopped();
  212953. }
  212954. const String getLastError() { return error; }
  212955. bool hasControlPanel() const { return true; }
  212956. bool showControlPanel()
  212957. {
  212958. log ("ASIO - showing control panel");
  212959. Component modalWindow (String::empty);
  212960. modalWindow.setOpaque (true);
  212961. modalWindow.addToDesktop (0);
  212962. modalWindow.enterModalState();
  212963. bool done = false;
  212964. JUCE_TRY
  212965. {
  212966. // are there are devices that need to be closed before showing their control panel?
  212967. // close();
  212968. insideControlPanelModalLoop = true;
  212969. const uint32 started = Time::getMillisecondCounter();
  212970. if (asioObject != 0)
  212971. {
  212972. asioObject->controlPanel();
  212973. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  212974. log ("spent: " + String (spent));
  212975. if (spent > 300)
  212976. {
  212977. shouldUsePreferredSize = true;
  212978. done = true;
  212979. }
  212980. }
  212981. }
  212982. JUCE_CATCH_ALL
  212983. insideControlPanelModalLoop = false;
  212984. return done;
  212985. }
  212986. void resetRequest() throw()
  212987. {
  212988. needToReset = true;
  212989. }
  212990. void resyncRequest() throw()
  212991. {
  212992. needToReset = true;
  212993. isReSync = true;
  212994. }
  212995. void timerCallback()
  212996. {
  212997. if (! insideControlPanelModalLoop)
  212998. {
  212999. stopTimer();
  213000. // used to cause a reset
  213001. log ("! ASIO restart request!");
  213002. if (isOpen_)
  213003. {
  213004. AudioIODeviceCallback* const oldCallback = currentCallback;
  213005. close();
  213006. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213007. currentSampleRate, currentBlockSizeSamples);
  213008. if (oldCallback != 0)
  213009. start (oldCallback);
  213010. }
  213011. }
  213012. else
  213013. {
  213014. startTimer (100);
  213015. }
  213016. }
  213017. private:
  213018. IASIO* volatile asioObject;
  213019. ASIOCallbacks callbacks;
  213020. void* windowHandle;
  213021. CLSID classId;
  213022. const String optionalDllForDirectLoading;
  213023. String error;
  213024. long totalNumInputChans, totalNumOutputChans;
  213025. StringArray inputChannelNames, outputChannelNames;
  213026. Array<int> sampleRates, bufferSizes;
  213027. long inputLatency, outputLatency;
  213028. long minSize, maxSize, preferredSize, granularity;
  213029. int volatile currentBlockSizeSamples;
  213030. int volatile currentBitDepth;
  213031. double volatile currentSampleRate;
  213032. BigInteger currentChansOut, currentChansIn;
  213033. AudioIODeviceCallback* volatile currentCallback;
  213034. CriticalSection callbackLock;
  213035. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213036. float* inBuffers [maxASIOChannels];
  213037. float* outBuffers [maxASIOChannels];
  213038. int inputChannelBitDepths [maxASIOChannels];
  213039. int outputChannelBitDepths [maxASIOChannels];
  213040. int inputChannelBytesPerSample [maxASIOChannels];
  213041. int outputChannelBytesPerSample [maxASIOChannels];
  213042. bool inputChannelIsFloat [maxASIOChannels];
  213043. bool outputChannelIsFloat [maxASIOChannels];
  213044. bool inputChannelLittleEndian [maxASIOChannels];
  213045. bool outputChannelLittleEndian [maxASIOChannels];
  213046. WaitableEvent event1;
  213047. HeapBlock <float> tempBuffer;
  213048. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213049. bool isOpen_, isStarted;
  213050. bool volatile isASIOOpen;
  213051. bool volatile calledback;
  213052. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213053. bool volatile insideControlPanelModalLoop;
  213054. bool volatile shouldUsePreferredSize;
  213055. void removeCurrentDriver()
  213056. {
  213057. if (asioObject != 0)
  213058. {
  213059. asioObject->Release();
  213060. asioObject = 0;
  213061. }
  213062. }
  213063. bool loadDriver()
  213064. {
  213065. removeCurrentDriver();
  213066. JUCE_TRY
  213067. {
  213068. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213069. classId, (void**) &asioObject) == S_OK)
  213070. {
  213071. return true;
  213072. }
  213073. // If a class isn't registered but we have a path for it, we can fallback to
  213074. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213075. if (optionalDllForDirectLoading.isNotEmpty())
  213076. {
  213077. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213078. if (h != 0)
  213079. {
  213080. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213081. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213082. if (dllGetClassObject != 0)
  213083. {
  213084. IClassFactory* classFactory = 0;
  213085. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213086. if (classFactory != 0)
  213087. {
  213088. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213089. classFactory->Release();
  213090. }
  213091. return asioObject != 0;
  213092. }
  213093. }
  213094. }
  213095. }
  213096. JUCE_CATCH_ALL
  213097. asioObject = 0;
  213098. return false;
  213099. }
  213100. const String initDriver()
  213101. {
  213102. if (asioObject != 0)
  213103. {
  213104. char buffer [256];
  213105. zeromem (buffer, sizeof (buffer));
  213106. if (! asioObject->init (windowHandle))
  213107. {
  213108. asioObject->getErrorMessage (buffer);
  213109. return String (buffer, sizeof (buffer) - 1);
  213110. }
  213111. // just in case any daft drivers expect this to be called..
  213112. asioObject->getDriverName (buffer);
  213113. return String::empty;
  213114. }
  213115. return "No Driver";
  213116. }
  213117. const String openDevice()
  213118. {
  213119. // use this in case the driver starts opening dialog boxes..
  213120. Component modalWindow (String::empty);
  213121. modalWindow.setOpaque (true);
  213122. modalWindow.addToDesktop (0);
  213123. modalWindow.enterModalState();
  213124. // open the device and get its info..
  213125. log ("opening ASIO device: " + getName());
  213126. needToReset = false;
  213127. isReSync = false;
  213128. outputChannelNames.clear();
  213129. inputChannelNames.clear();
  213130. bufferSizes.clear();
  213131. sampleRates.clear();
  213132. isASIOOpen = false;
  213133. isOpen_ = false;
  213134. totalNumInputChans = 0;
  213135. totalNumOutputChans = 0;
  213136. numActiveInputChans = 0;
  213137. numActiveOutputChans = 0;
  213138. currentCallback = 0;
  213139. error = String::empty;
  213140. if (getName().isEmpty())
  213141. return error;
  213142. long err = 0;
  213143. if (loadDriver())
  213144. {
  213145. if ((error = initDriver()).isEmpty())
  213146. {
  213147. numActiveInputChans = 0;
  213148. numActiveOutputChans = 0;
  213149. totalNumInputChans = 0;
  213150. totalNumOutputChans = 0;
  213151. if (asioObject != 0
  213152. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213153. {
  213154. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213155. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213156. {
  213157. // find a list of buffer sizes..
  213158. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213159. if (granularity >= 0)
  213160. {
  213161. granularity = jmax (1, (int) granularity);
  213162. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213163. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213164. }
  213165. else if (granularity < 0)
  213166. {
  213167. for (int i = 0; i < 18; ++i)
  213168. {
  213169. const int s = (1 << i);
  213170. if (s >= minSize && s <= maxSize)
  213171. bufferSizes.add (s);
  213172. }
  213173. }
  213174. if (! bufferSizes.contains (preferredSize))
  213175. bufferSizes.insert (0, preferredSize);
  213176. double currentRate = 0;
  213177. asioObject->getSampleRate (&currentRate);
  213178. if (currentRate <= 0.0 || currentRate > 192001.0)
  213179. {
  213180. log ("setting sample rate");
  213181. err = asioObject->setSampleRate (44100.0);
  213182. if (err != 0)
  213183. {
  213184. logError ("setting sample rate", err);
  213185. }
  213186. asioObject->getSampleRate (&currentRate);
  213187. }
  213188. currentSampleRate = currentRate;
  213189. postOutput = (asioObject->outputReady() == 0);
  213190. if (postOutput)
  213191. {
  213192. log ("ASIO outputReady = ok");
  213193. }
  213194. updateSampleRates();
  213195. // ..because cubase does it at this point
  213196. inputLatency = outputLatency = 0;
  213197. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213198. {
  213199. log ("ASIO - no latencies");
  213200. }
  213201. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213202. // create some dummy buffers now.. because cubase does..
  213203. numActiveInputChans = 0;
  213204. numActiveOutputChans = 0;
  213205. ASIOBufferInfo* info = bufferInfos;
  213206. int i, numChans = 0;
  213207. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213208. {
  213209. info->isInput = 1;
  213210. info->channelNum = i;
  213211. info->buffers[0] = info->buffers[1] = 0;
  213212. ++info;
  213213. ++numChans;
  213214. }
  213215. const int outputBufferIndex = numChans;
  213216. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213217. {
  213218. info->isInput = 0;
  213219. info->channelNum = i;
  213220. info->buffers[0] = info->buffers[1] = 0;
  213221. ++info;
  213222. ++numChans;
  213223. }
  213224. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213225. if (currentASIODev[0] == this)
  213226. {
  213227. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213228. callbacks.asioMessage = &asioMessagesCallback0;
  213229. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213230. }
  213231. else if (currentASIODev[1] == this)
  213232. {
  213233. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213234. callbacks.asioMessage = &asioMessagesCallback1;
  213235. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213236. }
  213237. else if (currentASIODev[2] == this)
  213238. {
  213239. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213240. callbacks.asioMessage = &asioMessagesCallback2;
  213241. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213242. }
  213243. else
  213244. {
  213245. jassertfalse;
  213246. }
  213247. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213248. if (preferredSize > 0)
  213249. {
  213250. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213251. if (err != 0)
  213252. {
  213253. logError ("dummy buffers", err);
  213254. }
  213255. }
  213256. long newInps = 0, newOuts = 0;
  213257. asioObject->getChannels (&newInps, &newOuts);
  213258. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213259. {
  213260. totalNumInputChans = newInps;
  213261. totalNumOutputChans = newOuts;
  213262. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213263. }
  213264. updateSampleRates();
  213265. ASIOChannelInfo channelInfo;
  213266. channelInfo.type = 0;
  213267. for (i = 0; i < totalNumInputChans; ++i)
  213268. {
  213269. zerostruct (channelInfo);
  213270. channelInfo.channel = i;
  213271. channelInfo.isInput = 1;
  213272. asioObject->getChannelInfo (&channelInfo);
  213273. inputChannelNames.add (String (channelInfo.name));
  213274. }
  213275. for (i = 0; i < totalNumOutputChans; ++i)
  213276. {
  213277. zerostruct (channelInfo);
  213278. channelInfo.channel = i;
  213279. channelInfo.isInput = 0;
  213280. asioObject->getChannelInfo (&channelInfo);
  213281. outputChannelNames.add (String (channelInfo.name));
  213282. typeToFormatParameters (channelInfo.type,
  213283. outputChannelBitDepths[i],
  213284. outputChannelBytesPerSample[i],
  213285. outputChannelIsFloat[i],
  213286. outputChannelLittleEndian[i]);
  213287. if (i < 2)
  213288. {
  213289. // clear the channels that are used with the dummy stuff
  213290. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213291. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213292. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213293. }
  213294. }
  213295. outputChannelNames.trim();
  213296. inputChannelNames.trim();
  213297. outputChannelNames.appendNumbersToDuplicates (false, true);
  213298. inputChannelNames.appendNumbersToDuplicates (false, true);
  213299. // start and stop because cubase does it..
  213300. asioObject->getLatencies (&inputLatency, &outputLatency);
  213301. if ((err = asioObject->start()) != 0)
  213302. {
  213303. // ignore an error here, as it might start later after setting other stuff up
  213304. logError ("ASIO start", err);
  213305. }
  213306. Thread::sleep (100);
  213307. asioObject->stop();
  213308. }
  213309. else
  213310. {
  213311. error = "Can't detect buffer sizes";
  213312. }
  213313. }
  213314. else
  213315. {
  213316. error = "Can't detect asio channels";
  213317. }
  213318. }
  213319. }
  213320. else
  213321. {
  213322. error = "No such device";
  213323. }
  213324. if (error.isNotEmpty())
  213325. {
  213326. logError (error, err);
  213327. if (asioObject != 0)
  213328. asioObject->disposeBuffers();
  213329. removeCurrentDriver();
  213330. isASIOOpen = false;
  213331. }
  213332. else
  213333. {
  213334. isASIOOpen = true;
  213335. log ("ASIO device open");
  213336. }
  213337. isOpen_ = false;
  213338. needToReset = false;
  213339. isReSync = false;
  213340. return error;
  213341. }
  213342. void JUCE_ASIOCALLBACK callback (const long index)
  213343. {
  213344. if (isStarted)
  213345. {
  213346. bufferIndex = index;
  213347. processBuffer();
  213348. }
  213349. else
  213350. {
  213351. if (postOutput && (asioObject != 0))
  213352. asioObject->outputReady();
  213353. }
  213354. calledback = true;
  213355. }
  213356. void processBuffer()
  213357. {
  213358. const ASIOBufferInfo* const infos = bufferInfos;
  213359. const int bi = bufferIndex;
  213360. const ScopedLock sl (callbackLock);
  213361. if (needToReset)
  213362. {
  213363. needToReset = false;
  213364. if (isReSync)
  213365. {
  213366. log ("! ASIO resync");
  213367. isReSync = false;
  213368. }
  213369. else
  213370. {
  213371. startTimer (20);
  213372. }
  213373. }
  213374. if (bi >= 0)
  213375. {
  213376. const int samps = currentBlockSizeSamples;
  213377. if (currentCallback != 0)
  213378. {
  213379. int i;
  213380. for (i = 0; i < numActiveInputChans; ++i)
  213381. {
  213382. float* const dst = inBuffers[i];
  213383. jassert (dst != 0);
  213384. const char* const src = (const char*) (infos[i].buffers[bi]);
  213385. if (inputChannelIsFloat[i])
  213386. {
  213387. memcpy (dst, src, samps * sizeof (float));
  213388. }
  213389. else
  213390. {
  213391. jassert (dst == tempBuffer + (samps * i));
  213392. switch (inputChannelBitDepths[i])
  213393. {
  213394. case 16:
  213395. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213396. samps, inputChannelLittleEndian[i]);
  213397. break;
  213398. case 24:
  213399. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213400. samps, inputChannelLittleEndian[i]);
  213401. break;
  213402. case 32:
  213403. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213404. samps, inputChannelLittleEndian[i]);
  213405. break;
  213406. case 64:
  213407. jassertfalse;
  213408. break;
  213409. }
  213410. }
  213411. }
  213412. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213413. outBuffers, numActiveOutputChans, samps);
  213414. for (i = 0; i < numActiveOutputChans; ++i)
  213415. {
  213416. float* const src = outBuffers[i];
  213417. jassert (src != 0);
  213418. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213419. if (outputChannelIsFloat[i])
  213420. {
  213421. memcpy (dst, src, samps * sizeof (float));
  213422. }
  213423. else
  213424. {
  213425. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213426. switch (outputChannelBitDepths[i])
  213427. {
  213428. case 16:
  213429. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213430. samps, outputChannelLittleEndian[i]);
  213431. break;
  213432. case 24:
  213433. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213434. samps, outputChannelLittleEndian[i]);
  213435. break;
  213436. case 32:
  213437. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213438. samps, outputChannelLittleEndian[i]);
  213439. break;
  213440. case 64:
  213441. jassertfalse;
  213442. break;
  213443. }
  213444. }
  213445. }
  213446. }
  213447. else
  213448. {
  213449. for (int i = 0; i < numActiveOutputChans; ++i)
  213450. {
  213451. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213452. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213453. }
  213454. }
  213455. }
  213456. if (postOutput)
  213457. asioObject->outputReady();
  213458. }
  213459. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213460. {
  213461. if (currentASIODev[0] != 0)
  213462. currentASIODev[0]->callback (index);
  213463. return 0;
  213464. }
  213465. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213466. {
  213467. if (currentASIODev[1] != 0)
  213468. currentASIODev[1]->callback (index);
  213469. return 0;
  213470. }
  213471. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213472. {
  213473. if (currentASIODev[2] != 0)
  213474. currentASIODev[2]->callback (index);
  213475. return 0;
  213476. }
  213477. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  213478. {
  213479. if (currentASIODev[0] != 0)
  213480. currentASIODev[0]->callback (index);
  213481. }
  213482. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  213483. {
  213484. if (currentASIODev[1] != 0)
  213485. currentASIODev[1]->callback (index);
  213486. }
  213487. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  213488. {
  213489. if (currentASIODev[2] != 0)
  213490. currentASIODev[2]->callback (index);
  213491. }
  213492. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  213493. {
  213494. return asioMessagesCallback (selector, value, 0);
  213495. }
  213496. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  213497. {
  213498. return asioMessagesCallback (selector, value, 1);
  213499. }
  213500. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  213501. {
  213502. return asioMessagesCallback (selector, value, 2);
  213503. }
  213504. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  213505. {
  213506. switch (selector)
  213507. {
  213508. case kAsioSelectorSupported:
  213509. if (value == kAsioResetRequest
  213510. || value == kAsioEngineVersion
  213511. || value == kAsioResyncRequest
  213512. || value == kAsioLatenciesChanged
  213513. || value == kAsioSupportsInputMonitor)
  213514. return 1;
  213515. break;
  213516. case kAsioBufferSizeChange:
  213517. break;
  213518. case kAsioResetRequest:
  213519. if (currentASIODev[deviceIndex] != 0)
  213520. currentASIODev[deviceIndex]->resetRequest();
  213521. return 1;
  213522. case kAsioResyncRequest:
  213523. if (currentASIODev[deviceIndex] != 0)
  213524. currentASIODev[deviceIndex]->resyncRequest();
  213525. return 1;
  213526. case kAsioLatenciesChanged:
  213527. return 1;
  213528. case kAsioEngineVersion:
  213529. return 2;
  213530. case kAsioSupportsTimeInfo:
  213531. case kAsioSupportsTimeCode:
  213532. return 0;
  213533. }
  213534. return 0;
  213535. }
  213536. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213537. {
  213538. }
  213539. static void convertInt16ToFloat (const char* src,
  213540. float* dest,
  213541. const int srcStrideBytes,
  213542. int numSamples,
  213543. const bool littleEndian) throw()
  213544. {
  213545. const double g = 1.0 / 32768.0;
  213546. if (littleEndian)
  213547. {
  213548. while (--numSamples >= 0)
  213549. {
  213550. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213551. src += srcStrideBytes;
  213552. }
  213553. }
  213554. else
  213555. {
  213556. while (--numSamples >= 0)
  213557. {
  213558. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213559. src += srcStrideBytes;
  213560. }
  213561. }
  213562. }
  213563. static void convertFloatToInt16 (const float* src,
  213564. char* dest,
  213565. const int dstStrideBytes,
  213566. int numSamples,
  213567. const bool littleEndian) throw()
  213568. {
  213569. const double maxVal = (double) 0x7fff;
  213570. if (littleEndian)
  213571. {
  213572. while (--numSamples >= 0)
  213573. {
  213574. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213575. dest += dstStrideBytes;
  213576. }
  213577. }
  213578. else
  213579. {
  213580. while (--numSamples >= 0)
  213581. {
  213582. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213583. dest += dstStrideBytes;
  213584. }
  213585. }
  213586. }
  213587. static void convertInt24ToFloat (const char* src,
  213588. float* dest,
  213589. const int srcStrideBytes,
  213590. int numSamples,
  213591. const bool littleEndian) throw()
  213592. {
  213593. const double g = 1.0 / 0x7fffff;
  213594. if (littleEndian)
  213595. {
  213596. while (--numSamples >= 0)
  213597. {
  213598. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213599. src += srcStrideBytes;
  213600. }
  213601. }
  213602. else
  213603. {
  213604. while (--numSamples >= 0)
  213605. {
  213606. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213607. src += srcStrideBytes;
  213608. }
  213609. }
  213610. }
  213611. static void convertFloatToInt24 (const float* src,
  213612. char* dest,
  213613. const int dstStrideBytes,
  213614. int numSamples,
  213615. const bool littleEndian) throw()
  213616. {
  213617. const double maxVal = (double) 0x7fffff;
  213618. if (littleEndian)
  213619. {
  213620. while (--numSamples >= 0)
  213621. {
  213622. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213623. dest += dstStrideBytes;
  213624. }
  213625. }
  213626. else
  213627. {
  213628. while (--numSamples >= 0)
  213629. {
  213630. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213631. dest += dstStrideBytes;
  213632. }
  213633. }
  213634. }
  213635. static void convertInt32ToFloat (const char* src,
  213636. float* dest,
  213637. const int srcStrideBytes,
  213638. int numSamples,
  213639. const bool littleEndian) throw()
  213640. {
  213641. const double g = 1.0 / 0x7fffffff;
  213642. if (littleEndian)
  213643. {
  213644. while (--numSamples >= 0)
  213645. {
  213646. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213647. src += srcStrideBytes;
  213648. }
  213649. }
  213650. else
  213651. {
  213652. while (--numSamples >= 0)
  213653. {
  213654. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213655. src += srcStrideBytes;
  213656. }
  213657. }
  213658. }
  213659. static void convertFloatToInt32 (const float* src,
  213660. char* dest,
  213661. const int dstStrideBytes,
  213662. int numSamples,
  213663. const bool littleEndian) throw()
  213664. {
  213665. const double maxVal = (double) 0x7fffffff;
  213666. if (littleEndian)
  213667. {
  213668. while (--numSamples >= 0)
  213669. {
  213670. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213671. dest += dstStrideBytes;
  213672. }
  213673. }
  213674. else
  213675. {
  213676. while (--numSamples >= 0)
  213677. {
  213678. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213679. dest += dstStrideBytes;
  213680. }
  213681. }
  213682. }
  213683. static void typeToFormatParameters (const long type,
  213684. int& bitDepth,
  213685. int& byteStride,
  213686. bool& formatIsFloat,
  213687. bool& littleEndian) throw()
  213688. {
  213689. bitDepth = 0;
  213690. littleEndian = false;
  213691. formatIsFloat = false;
  213692. switch (type)
  213693. {
  213694. case ASIOSTInt16MSB:
  213695. case ASIOSTInt16LSB:
  213696. case ASIOSTInt32MSB16:
  213697. case ASIOSTInt32LSB16:
  213698. bitDepth = 16; break;
  213699. case ASIOSTFloat32MSB:
  213700. case ASIOSTFloat32LSB:
  213701. formatIsFloat = true;
  213702. bitDepth = 32; break;
  213703. case ASIOSTInt32MSB:
  213704. case ASIOSTInt32LSB:
  213705. bitDepth = 32; break;
  213706. case ASIOSTInt24MSB:
  213707. case ASIOSTInt24LSB:
  213708. case ASIOSTInt32MSB24:
  213709. case ASIOSTInt32LSB24:
  213710. case ASIOSTInt32MSB18:
  213711. case ASIOSTInt32MSB20:
  213712. case ASIOSTInt32LSB18:
  213713. case ASIOSTInt32LSB20:
  213714. bitDepth = 24; break;
  213715. case ASIOSTFloat64MSB:
  213716. case ASIOSTFloat64LSB:
  213717. default:
  213718. bitDepth = 64;
  213719. break;
  213720. }
  213721. switch (type)
  213722. {
  213723. case ASIOSTInt16MSB:
  213724. case ASIOSTInt32MSB16:
  213725. case ASIOSTFloat32MSB:
  213726. case ASIOSTFloat64MSB:
  213727. case ASIOSTInt32MSB:
  213728. case ASIOSTInt32MSB18:
  213729. case ASIOSTInt32MSB20:
  213730. case ASIOSTInt32MSB24:
  213731. case ASIOSTInt24MSB:
  213732. littleEndian = false; break;
  213733. case ASIOSTInt16LSB:
  213734. case ASIOSTInt32LSB16:
  213735. case ASIOSTFloat32LSB:
  213736. case ASIOSTFloat64LSB:
  213737. case ASIOSTInt32LSB:
  213738. case ASIOSTInt32LSB18:
  213739. case ASIOSTInt32LSB20:
  213740. case ASIOSTInt32LSB24:
  213741. case ASIOSTInt24LSB:
  213742. littleEndian = true; break;
  213743. default:
  213744. break;
  213745. }
  213746. switch (type)
  213747. {
  213748. case ASIOSTInt16LSB:
  213749. case ASIOSTInt16MSB:
  213750. byteStride = 2; break;
  213751. case ASIOSTInt24LSB:
  213752. case ASIOSTInt24MSB:
  213753. byteStride = 3; break;
  213754. case ASIOSTInt32MSB16:
  213755. case ASIOSTInt32LSB16:
  213756. case ASIOSTInt32MSB:
  213757. case ASIOSTInt32MSB18:
  213758. case ASIOSTInt32MSB20:
  213759. case ASIOSTInt32MSB24:
  213760. case ASIOSTInt32LSB:
  213761. case ASIOSTInt32LSB18:
  213762. case ASIOSTInt32LSB20:
  213763. case ASIOSTInt32LSB24:
  213764. case ASIOSTFloat32LSB:
  213765. case ASIOSTFloat32MSB:
  213766. byteStride = 4; break;
  213767. case ASIOSTFloat64MSB:
  213768. case ASIOSTFloat64LSB:
  213769. byteStride = 8; break;
  213770. default:
  213771. break;
  213772. }
  213773. }
  213774. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice);
  213775. };
  213776. class ASIOAudioIODeviceType : public AudioIODeviceType
  213777. {
  213778. public:
  213779. ASIOAudioIODeviceType()
  213780. : AudioIODeviceType ("ASIO"),
  213781. hasScanned (false)
  213782. {
  213783. CoInitialize (0);
  213784. }
  213785. ~ASIOAudioIODeviceType()
  213786. {
  213787. }
  213788. void scanForDevices()
  213789. {
  213790. hasScanned = true;
  213791. deviceNames.clear();
  213792. classIds.clear();
  213793. HKEY hk = 0;
  213794. int index = 0;
  213795. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  213796. {
  213797. for (;;)
  213798. {
  213799. char name [256];
  213800. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  213801. {
  213802. addDriverInfo (name, hk);
  213803. }
  213804. else
  213805. {
  213806. break;
  213807. }
  213808. }
  213809. RegCloseKey (hk);
  213810. }
  213811. }
  213812. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  213813. {
  213814. jassert (hasScanned); // need to call scanForDevices() before doing this
  213815. return deviceNames;
  213816. }
  213817. int getDefaultDeviceIndex (bool) const
  213818. {
  213819. jassert (hasScanned); // need to call scanForDevices() before doing this
  213820. for (int i = deviceNames.size(); --i >= 0;)
  213821. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  213822. return i; // asio4all is a safe choice for a default..
  213823. #if JUCE_DEBUG
  213824. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  213825. return 1; // (the digi m-box driver crashes the app when you run
  213826. // it in the debugger, which can be a bit annoying)
  213827. #endif
  213828. return 0;
  213829. }
  213830. static int findFreeSlot()
  213831. {
  213832. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213833. if (currentASIODev[i] == 0)
  213834. return i;
  213835. jassertfalse; // unfortunately you can only have a finite number
  213836. // of ASIO devices open at the same time..
  213837. return -1;
  213838. }
  213839. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  213840. {
  213841. jassert (hasScanned); // need to call scanForDevices() before doing this
  213842. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  213843. }
  213844. bool hasSeparateInputsAndOutputs() const { return false; }
  213845. AudioIODevice* createDevice (const String& outputDeviceName,
  213846. const String& inputDeviceName)
  213847. {
  213848. // ASIO can't open two different devices for input and output - they must be the same one.
  213849. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  213850. jassert (hasScanned); // need to call scanForDevices() before doing this
  213851. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  213852. : inputDeviceName);
  213853. if (index >= 0)
  213854. {
  213855. const int freeSlot = findFreeSlot();
  213856. if (freeSlot >= 0)
  213857. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  213858. }
  213859. return 0;
  213860. }
  213861. private:
  213862. StringArray deviceNames;
  213863. OwnedArray <CLSID> classIds;
  213864. bool hasScanned;
  213865. static bool checkClassIsOk (const String& classId)
  213866. {
  213867. HKEY hk = 0;
  213868. bool ok = false;
  213869. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  213870. {
  213871. int index = 0;
  213872. for (;;)
  213873. {
  213874. WCHAR buf [512];
  213875. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  213876. {
  213877. if (classId.equalsIgnoreCase (buf))
  213878. {
  213879. HKEY subKey, pathKey;
  213880. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213881. {
  213882. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  213883. {
  213884. WCHAR pathName [1024];
  213885. DWORD dtype = REG_SZ;
  213886. DWORD dsize = sizeof (pathName);
  213887. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  213888. ok = File (pathName).exists();
  213889. RegCloseKey (pathKey);
  213890. }
  213891. RegCloseKey (subKey);
  213892. }
  213893. break;
  213894. }
  213895. }
  213896. else
  213897. {
  213898. break;
  213899. }
  213900. }
  213901. RegCloseKey (hk);
  213902. }
  213903. return ok;
  213904. }
  213905. void addDriverInfo (const String& keyName, HKEY hk)
  213906. {
  213907. HKEY subKey;
  213908. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213909. {
  213910. WCHAR buf [256];
  213911. zerostruct (buf);
  213912. DWORD dtype = REG_SZ;
  213913. DWORD dsize = sizeof (buf);
  213914. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213915. {
  213916. if (dsize > 0 && checkClassIsOk (buf))
  213917. {
  213918. CLSID classId;
  213919. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  213920. {
  213921. dtype = REG_SZ;
  213922. dsize = sizeof (buf);
  213923. String deviceName;
  213924. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213925. deviceName = buf;
  213926. else
  213927. deviceName = keyName;
  213928. log ("found " + deviceName);
  213929. deviceNames.add (deviceName);
  213930. classIds.add (new CLSID (classId));
  213931. }
  213932. }
  213933. RegCloseKey (subKey);
  213934. }
  213935. }
  213936. }
  213937. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType);
  213938. };
  213939. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  213940. {
  213941. return new ASIOAudioIODeviceType();
  213942. }
  213943. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  213944. void* guid,
  213945. const String& optionalDllForDirectLoading)
  213946. {
  213947. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  213948. if (freeSlot < 0)
  213949. return 0;
  213950. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  213951. }
  213952. #undef logError
  213953. #undef log
  213954. #endif
  213955. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  213956. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  213957. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213958. // compiled on its own).
  213959. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  213960. END_JUCE_NAMESPACE
  213961. extern "C"
  213962. {
  213963. // Declare just the minimum number of interfaces for the DSound objects that we need..
  213964. typedef struct typeDSBUFFERDESC
  213965. {
  213966. DWORD dwSize;
  213967. DWORD dwFlags;
  213968. DWORD dwBufferBytes;
  213969. DWORD dwReserved;
  213970. LPWAVEFORMATEX lpwfxFormat;
  213971. GUID guid3DAlgorithm;
  213972. } DSBUFFERDESC;
  213973. struct IDirectSoundBuffer;
  213974. #undef INTERFACE
  213975. #define INTERFACE IDirectSound
  213976. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213977. {
  213978. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213979. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213980. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213981. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213982. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213983. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213984. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213985. STDMETHOD(Compact) (THIS) PURE;
  213986. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213987. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213988. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213989. };
  213990. #undef INTERFACE
  213991. #define INTERFACE IDirectSoundBuffer
  213992. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213993. {
  213994. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213995. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213996. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213997. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213998. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213999. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214000. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214001. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214002. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214003. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214004. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214005. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214006. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214007. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214008. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214009. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214010. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214011. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214012. STDMETHOD(Stop) (THIS) PURE;
  214013. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214014. STDMETHOD(Restore) (THIS) PURE;
  214015. };
  214016. typedef struct typeDSCBUFFERDESC
  214017. {
  214018. DWORD dwSize;
  214019. DWORD dwFlags;
  214020. DWORD dwBufferBytes;
  214021. DWORD dwReserved;
  214022. LPWAVEFORMATEX lpwfxFormat;
  214023. } DSCBUFFERDESC;
  214024. struct IDirectSoundCaptureBuffer;
  214025. #undef INTERFACE
  214026. #define INTERFACE IDirectSoundCapture
  214027. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214028. {
  214029. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214030. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214031. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214032. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214033. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214034. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214035. };
  214036. #undef INTERFACE
  214037. #define INTERFACE IDirectSoundCaptureBuffer
  214038. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214039. {
  214040. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214041. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214042. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214043. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214044. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214045. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214046. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214047. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214048. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214049. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214050. STDMETHOD(Stop) (THIS) PURE;
  214051. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214052. };
  214053. };
  214054. BEGIN_JUCE_NAMESPACE
  214055. namespace
  214056. {
  214057. const String getDSErrorMessage (HRESULT hr)
  214058. {
  214059. const char* result = 0;
  214060. switch (hr)
  214061. {
  214062. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214063. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214064. case E_INVALIDARG: result = "Invalid parameter"; break;
  214065. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214066. case E_FAIL: result = "Generic error"; break;
  214067. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214068. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214069. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214070. case E_NOTIMPL: result = "Unsupported function"; break;
  214071. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214072. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214073. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214074. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214075. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214076. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214077. case E_NOINTERFACE: result = "No interface"; break;
  214078. case S_OK: result = "No error"; break;
  214079. default: return "Unknown error: " + String ((int) hr);
  214080. }
  214081. return result;
  214082. }
  214083. #define DS_DEBUGGING 1
  214084. #ifdef DS_DEBUGGING
  214085. #define CATCH JUCE_CATCH_EXCEPTION
  214086. #undef log
  214087. #define log(a) Logger::writeToLog(a);
  214088. #undef logError
  214089. #define logError(a) logDSError(a, __LINE__);
  214090. static void logDSError (HRESULT hr, int lineNum)
  214091. {
  214092. if (hr != S_OK)
  214093. {
  214094. String error ("DS error at line ");
  214095. error << lineNum << " - " << getDSErrorMessage (hr);
  214096. log (error);
  214097. }
  214098. }
  214099. #else
  214100. #define CATCH JUCE_CATCH_ALL
  214101. #define log(a)
  214102. #define logError(a)
  214103. #endif
  214104. #define DSOUND_FUNCTION(functionName, params) \
  214105. typedef HRESULT (WINAPI *type##functionName) params; \
  214106. static type##functionName ds##functionName = 0;
  214107. #define DSOUND_FUNCTION_LOAD(functionName) \
  214108. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214109. jassert (ds##functionName != 0);
  214110. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214111. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214112. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214113. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214114. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214115. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214116. void initialiseDSoundFunctions()
  214117. {
  214118. if (dsDirectSoundCreate == 0)
  214119. {
  214120. HMODULE h = LoadLibraryA ("dsound.dll");
  214121. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214122. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214123. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214124. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214125. }
  214126. }
  214127. }
  214128. class DSoundInternalOutChannel
  214129. {
  214130. public:
  214131. DSoundInternalOutChannel (const String& name_, LPGUID guid_, int rate,
  214132. int bufferSize, float* left, float* right)
  214133. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  214134. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  214135. pDirectSound (0), pOutputBuffer (0)
  214136. {
  214137. }
  214138. ~DSoundInternalOutChannel()
  214139. {
  214140. close();
  214141. }
  214142. void close()
  214143. {
  214144. HRESULT hr;
  214145. if (pOutputBuffer != 0)
  214146. {
  214147. log ("closing dsound out: " + name);
  214148. hr = pOutputBuffer->Stop();
  214149. logError (hr);
  214150. hr = pOutputBuffer->Release();
  214151. pOutputBuffer = 0;
  214152. logError (hr);
  214153. }
  214154. if (pDirectSound != 0)
  214155. {
  214156. hr = pDirectSound->Release();
  214157. pDirectSound = 0;
  214158. logError (hr);
  214159. }
  214160. }
  214161. const String open()
  214162. {
  214163. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214164. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214165. pDirectSound = 0;
  214166. pOutputBuffer = 0;
  214167. writeOffset = 0;
  214168. String error;
  214169. HRESULT hr = E_NOINTERFACE;
  214170. if (dsDirectSoundCreate != 0)
  214171. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214172. if (hr == S_OK)
  214173. {
  214174. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214175. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214176. const int numChannels = 2;
  214177. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214178. logError (hr);
  214179. if (hr == S_OK)
  214180. {
  214181. IDirectSoundBuffer* pPrimaryBuffer;
  214182. DSBUFFERDESC primaryDesc;
  214183. zerostruct (primaryDesc);
  214184. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214185. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214186. primaryDesc.dwBufferBytes = 0;
  214187. primaryDesc.lpwfxFormat = 0;
  214188. log ("opening dsound out step 2");
  214189. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214190. logError (hr);
  214191. if (hr == S_OK)
  214192. {
  214193. WAVEFORMATEX wfFormat;
  214194. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214195. wfFormat.nChannels = (unsigned short) numChannels;
  214196. wfFormat.nSamplesPerSec = sampleRate;
  214197. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214198. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214199. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214200. wfFormat.cbSize = 0;
  214201. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214202. logError (hr);
  214203. if (hr == S_OK)
  214204. {
  214205. DSBUFFERDESC secondaryDesc;
  214206. zerostruct (secondaryDesc);
  214207. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214208. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214209. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214210. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214211. secondaryDesc.lpwfxFormat = &wfFormat;
  214212. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214213. logError (hr);
  214214. if (hr == S_OK)
  214215. {
  214216. log ("opening dsound out step 3");
  214217. DWORD dwDataLen;
  214218. unsigned char* pDSBuffData;
  214219. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214220. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214221. logError (hr);
  214222. if (hr == S_OK)
  214223. {
  214224. zeromem (pDSBuffData, dwDataLen);
  214225. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214226. if (hr == S_OK)
  214227. {
  214228. hr = pOutputBuffer->SetCurrentPosition (0);
  214229. if (hr == S_OK)
  214230. {
  214231. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214232. if (hr == S_OK)
  214233. return String::empty;
  214234. }
  214235. }
  214236. }
  214237. }
  214238. }
  214239. }
  214240. }
  214241. }
  214242. error = getDSErrorMessage (hr);
  214243. close();
  214244. return error;
  214245. }
  214246. void synchronisePosition()
  214247. {
  214248. if (pOutputBuffer != 0)
  214249. {
  214250. DWORD playCursor;
  214251. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214252. }
  214253. }
  214254. bool service()
  214255. {
  214256. if (pOutputBuffer == 0)
  214257. return true;
  214258. DWORD playCursor, writeCursor;
  214259. for (;;)
  214260. {
  214261. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214262. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214263. {
  214264. pOutputBuffer->Restore();
  214265. continue;
  214266. }
  214267. if (hr == S_OK)
  214268. break;
  214269. logError (hr);
  214270. jassertfalse;
  214271. return true;
  214272. }
  214273. int playWriteGap = writeCursor - playCursor;
  214274. if (playWriteGap < 0)
  214275. playWriteGap += totalBytesPerBuffer;
  214276. int bytesEmpty = playCursor - writeOffset;
  214277. if (bytesEmpty < 0)
  214278. bytesEmpty += totalBytesPerBuffer;
  214279. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214280. {
  214281. writeOffset = writeCursor;
  214282. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214283. }
  214284. if (bytesEmpty >= bytesPerBuffer)
  214285. {
  214286. void* lpbuf1 = 0;
  214287. void* lpbuf2 = 0;
  214288. DWORD dwSize1 = 0;
  214289. DWORD dwSize2 = 0;
  214290. HRESULT hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  214291. &lpbuf1, &dwSize1,
  214292. &lpbuf2, &dwSize2, 0);
  214293. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214294. {
  214295. pOutputBuffer->Restore();
  214296. hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  214297. &lpbuf1, &dwSize1,
  214298. &lpbuf2, &dwSize2, 0);
  214299. }
  214300. if (hr == S_OK)
  214301. {
  214302. if (bitDepth == 16)
  214303. {
  214304. int* dest = static_cast<int*> (lpbuf1);
  214305. const float* left = leftBuffer;
  214306. const float* right = rightBuffer;
  214307. int samples1 = dwSize1 >> 2;
  214308. int samples2 = dwSize2 >> 2;
  214309. if (left == 0)
  214310. {
  214311. while (--samples1 >= 0)
  214312. *dest++ = (convertInputValue (*right++) << 16);
  214313. dest = static_cast<int*> (lpbuf2);
  214314. while (--samples2 >= 0)
  214315. *dest++ = (convertInputValue (*right++) << 16);
  214316. }
  214317. else if (right == 0)
  214318. {
  214319. while (--samples1 >= 0)
  214320. *dest++ = (0xffff & convertInputValue (*left++));
  214321. dest = static_cast<int*> (lpbuf2);
  214322. while (--samples2 >= 0)
  214323. *dest++ = (0xffff & convertInputValue (*left++));
  214324. }
  214325. else
  214326. {
  214327. while (--samples1 >= 0)
  214328. {
  214329. const int l = convertInputValue (*left++);
  214330. const int r = convertInputValue (*right++);
  214331. *dest++ = (r << 16) | (0xffff & l);
  214332. }
  214333. dest = static_cast<int*> (lpbuf2);
  214334. while (--samples2 >= 0)
  214335. {
  214336. const int l = convertInputValue (*left++);
  214337. const int r = convertInputValue (*right++);
  214338. *dest++ = (r << 16) | (0xffff & l);
  214339. }
  214340. }
  214341. }
  214342. else
  214343. {
  214344. jassertfalse;
  214345. }
  214346. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214347. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214348. }
  214349. else
  214350. {
  214351. jassertfalse;
  214352. logError (hr);
  214353. }
  214354. bytesEmpty -= bytesPerBuffer;
  214355. return true;
  214356. }
  214357. else
  214358. {
  214359. return false;
  214360. }
  214361. }
  214362. int bitDepth;
  214363. bool doneFlag;
  214364. private:
  214365. String name;
  214366. LPGUID guid;
  214367. int sampleRate, bufferSizeSamples;
  214368. float* leftBuffer;
  214369. float* rightBuffer;
  214370. IDirectSound* pDirectSound;
  214371. IDirectSoundBuffer* pOutputBuffer;
  214372. DWORD writeOffset;
  214373. int totalBytesPerBuffer, bytesPerBuffer;
  214374. unsigned int lastPlayCursor;
  214375. static inline int convertInputValue (const float v) throw()
  214376. {
  214377. return jlimit (-32768, 32767, roundToInt (32767.0f * v));
  214378. }
  214379. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel);
  214380. };
  214381. struct DSoundInternalInChannel
  214382. {
  214383. public:
  214384. DSoundInternalInChannel (const String& name_, LPGUID guid_, int rate,
  214385. int bufferSize, float* left, float* right)
  214386. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  214387. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  214388. pDirectSound (0), pDirectSoundCapture (0), pInputBuffer (0)
  214389. {
  214390. }
  214391. ~DSoundInternalInChannel()
  214392. {
  214393. close();
  214394. }
  214395. void close()
  214396. {
  214397. HRESULT hr;
  214398. if (pInputBuffer != 0)
  214399. {
  214400. log ("closing dsound in: " + name);
  214401. hr = pInputBuffer->Stop();
  214402. logError (hr);
  214403. hr = pInputBuffer->Release();
  214404. pInputBuffer = 0;
  214405. logError (hr);
  214406. }
  214407. if (pDirectSoundCapture != 0)
  214408. {
  214409. hr = pDirectSoundCapture->Release();
  214410. pDirectSoundCapture = 0;
  214411. logError (hr);
  214412. }
  214413. if (pDirectSound != 0)
  214414. {
  214415. hr = pDirectSound->Release();
  214416. pDirectSound = 0;
  214417. logError (hr);
  214418. }
  214419. }
  214420. const String open()
  214421. {
  214422. log ("opening dsound in device: " + name
  214423. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214424. pDirectSound = 0;
  214425. pDirectSoundCapture = 0;
  214426. pInputBuffer = 0;
  214427. readOffset = 0;
  214428. totalBytesPerBuffer = 0;
  214429. String error;
  214430. HRESULT hr = E_NOINTERFACE;
  214431. if (dsDirectSoundCaptureCreate != 0)
  214432. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214433. logError (hr);
  214434. if (hr == S_OK)
  214435. {
  214436. const int numChannels = 2;
  214437. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214438. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214439. WAVEFORMATEX wfFormat;
  214440. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214441. wfFormat.nChannels = (unsigned short)numChannels;
  214442. wfFormat.nSamplesPerSec = sampleRate;
  214443. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214444. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214445. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214446. wfFormat.cbSize = 0;
  214447. DSCBUFFERDESC captureDesc;
  214448. zerostruct (captureDesc);
  214449. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214450. captureDesc.dwFlags = 0;
  214451. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214452. captureDesc.lpwfxFormat = &wfFormat;
  214453. log ("opening dsound in step 2");
  214454. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214455. logError (hr);
  214456. if (hr == S_OK)
  214457. {
  214458. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214459. logError (hr);
  214460. if (hr == S_OK)
  214461. return String::empty;
  214462. }
  214463. }
  214464. error = getDSErrorMessage (hr);
  214465. close();
  214466. return error;
  214467. }
  214468. void synchronisePosition()
  214469. {
  214470. if (pInputBuffer != 0)
  214471. {
  214472. DWORD capturePos;
  214473. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214474. }
  214475. }
  214476. bool service()
  214477. {
  214478. if (pInputBuffer == 0)
  214479. return true;
  214480. DWORD capturePos, readPos;
  214481. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214482. logError (hr);
  214483. if (hr != S_OK)
  214484. return true;
  214485. int bytesFilled = readPos - readOffset;
  214486. if (bytesFilled < 0)
  214487. bytesFilled += totalBytesPerBuffer;
  214488. if (bytesFilled >= bytesPerBuffer)
  214489. {
  214490. LPBYTE lpbuf1 = 0;
  214491. LPBYTE lpbuf2 = 0;
  214492. DWORD dwsize1 = 0;
  214493. DWORD dwsize2 = 0;
  214494. HRESULT hr = pInputBuffer->Lock (readOffset, bytesPerBuffer,
  214495. (void**) &lpbuf1, &dwsize1,
  214496. (void**) &lpbuf2, &dwsize2, 0);
  214497. if (hr == S_OK)
  214498. {
  214499. if (bitDepth == 16)
  214500. {
  214501. const float g = 1.0f / 32768.0f;
  214502. float* destL = leftBuffer;
  214503. float* destR = rightBuffer;
  214504. int samples1 = dwsize1 >> 2;
  214505. int samples2 = dwsize2 >> 2;
  214506. const short* src = (const short*)lpbuf1;
  214507. if (destL == 0)
  214508. {
  214509. while (--samples1 >= 0)
  214510. {
  214511. ++src;
  214512. *destR++ = *src++ * g;
  214513. }
  214514. src = (const short*)lpbuf2;
  214515. while (--samples2 >= 0)
  214516. {
  214517. ++src;
  214518. *destR++ = *src++ * g;
  214519. }
  214520. }
  214521. else if (destR == 0)
  214522. {
  214523. while (--samples1 >= 0)
  214524. {
  214525. *destL++ = *src++ * g;
  214526. ++src;
  214527. }
  214528. src = (const short*)lpbuf2;
  214529. while (--samples2 >= 0)
  214530. {
  214531. *destL++ = *src++ * g;
  214532. ++src;
  214533. }
  214534. }
  214535. else
  214536. {
  214537. while (--samples1 >= 0)
  214538. {
  214539. *destL++ = *src++ * g;
  214540. *destR++ = *src++ * g;
  214541. }
  214542. src = (const short*)lpbuf2;
  214543. while (--samples2 >= 0)
  214544. {
  214545. *destL++ = *src++ * g;
  214546. *destR++ = *src++ * g;
  214547. }
  214548. }
  214549. }
  214550. else
  214551. {
  214552. jassertfalse;
  214553. }
  214554. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214555. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214556. }
  214557. else
  214558. {
  214559. logError (hr);
  214560. jassertfalse;
  214561. }
  214562. bytesFilled -= bytesPerBuffer;
  214563. return true;
  214564. }
  214565. else
  214566. {
  214567. return false;
  214568. }
  214569. }
  214570. unsigned int readOffset;
  214571. int bytesPerBuffer, totalBytesPerBuffer;
  214572. int bitDepth;
  214573. bool doneFlag;
  214574. private:
  214575. String name;
  214576. LPGUID guid;
  214577. int sampleRate, bufferSizeSamples;
  214578. float* leftBuffer;
  214579. float* rightBuffer;
  214580. IDirectSound* pDirectSound;
  214581. IDirectSoundCapture* pDirectSoundCapture;
  214582. IDirectSoundCaptureBuffer* pInputBuffer;
  214583. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel);
  214584. };
  214585. class DSoundAudioIODevice : public AudioIODevice,
  214586. public Thread
  214587. {
  214588. public:
  214589. DSoundAudioIODevice (const String& deviceName,
  214590. const int outputDeviceIndex_,
  214591. const int inputDeviceIndex_)
  214592. : AudioIODevice (deviceName, "DirectSound"),
  214593. Thread ("Juce DSound"),
  214594. isOpen_ (false),
  214595. isStarted (false),
  214596. outputDeviceIndex (outputDeviceIndex_),
  214597. inputDeviceIndex (inputDeviceIndex_),
  214598. totalSamplesOut (0),
  214599. sampleRate (0.0),
  214600. inputBuffers (1, 1),
  214601. outputBuffers (1, 1),
  214602. callback (0),
  214603. bufferSizeSamples (0)
  214604. {
  214605. if (outputDeviceIndex_ >= 0)
  214606. {
  214607. outChannels.add (TRANS("Left"));
  214608. outChannels.add (TRANS("Right"));
  214609. }
  214610. if (inputDeviceIndex_ >= 0)
  214611. {
  214612. inChannels.add (TRANS("Left"));
  214613. inChannels.add (TRANS("Right"));
  214614. }
  214615. }
  214616. ~DSoundAudioIODevice()
  214617. {
  214618. close();
  214619. }
  214620. const String open (const BigInteger& inputChannels,
  214621. const BigInteger& outputChannels,
  214622. double sampleRate, int bufferSizeSamples)
  214623. {
  214624. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214625. isOpen_ = lastError.isEmpty();
  214626. return lastError;
  214627. }
  214628. void close()
  214629. {
  214630. stop();
  214631. if (isOpen_)
  214632. {
  214633. closeDevice();
  214634. isOpen_ = false;
  214635. }
  214636. }
  214637. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214638. int getCurrentBufferSizeSamples() { return bufferSizeSamples; }
  214639. double getCurrentSampleRate() { return sampleRate; }
  214640. const BigInteger getActiveOutputChannels() const { return enabledOutputs; }
  214641. const BigInteger getActiveInputChannels() const { return enabledInputs; }
  214642. int getOutputLatencyInSamples() { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  214643. int getInputLatencyInSamples() { return getOutputLatencyInSamples(); }
  214644. const StringArray getOutputChannelNames() { return outChannels; }
  214645. const StringArray getInputChannelNames() { return inChannels; }
  214646. int getNumSampleRates() { return 4; }
  214647. int getDefaultBufferSize() { return 2560; }
  214648. int getNumBufferSizesAvailable() { return 50; }
  214649. double getSampleRate (int index)
  214650. {
  214651. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214652. return samps [jlimit (0, 3, index)];
  214653. }
  214654. int getBufferSizeSamples (int index)
  214655. {
  214656. int n = 64;
  214657. for (int i = 0; i < index; ++i)
  214658. n += (n < 512) ? 32
  214659. : ((n < 1024) ? 64
  214660. : ((n < 2048) ? 128 : 256));
  214661. return n;
  214662. }
  214663. int getCurrentBitDepth()
  214664. {
  214665. int i, bits = 256;
  214666. for (i = inChans.size(); --i >= 0;)
  214667. bits = jmin (bits, inChans[i]->bitDepth);
  214668. for (i = outChans.size(); --i >= 0;)
  214669. bits = jmin (bits, outChans[i]->bitDepth);
  214670. if (bits > 32)
  214671. bits = 16;
  214672. return bits;
  214673. }
  214674. void start (AudioIODeviceCallback* call)
  214675. {
  214676. if (isOpen_ && call != 0 && ! isStarted)
  214677. {
  214678. if (! isThreadRunning())
  214679. {
  214680. // something gone wrong and the thread's stopped..
  214681. isOpen_ = false;
  214682. return;
  214683. }
  214684. call->audioDeviceAboutToStart (this);
  214685. const ScopedLock sl (startStopLock);
  214686. callback = call;
  214687. isStarted = true;
  214688. }
  214689. }
  214690. void stop()
  214691. {
  214692. if (isStarted)
  214693. {
  214694. AudioIODeviceCallback* const callbackLocal = callback;
  214695. {
  214696. const ScopedLock sl (startStopLock);
  214697. isStarted = false;
  214698. }
  214699. if (callbackLocal != 0)
  214700. callbackLocal->audioDeviceStopped();
  214701. }
  214702. }
  214703. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214704. const String getLastError() { return lastError; }
  214705. StringArray inChannels, outChannels;
  214706. int outputDeviceIndex, inputDeviceIndex;
  214707. private:
  214708. bool isOpen_;
  214709. bool isStarted;
  214710. String lastError;
  214711. OwnedArray <DSoundInternalInChannel> inChans;
  214712. OwnedArray <DSoundInternalOutChannel> outChans;
  214713. WaitableEvent startEvent;
  214714. int bufferSizeSamples;
  214715. int volatile totalSamplesOut;
  214716. int64 volatile lastBlockTime;
  214717. double sampleRate;
  214718. BigInteger enabledInputs, enabledOutputs;
  214719. AudioSampleBuffer inputBuffers, outputBuffers;
  214720. AudioIODeviceCallback* callback;
  214721. CriticalSection startStopLock;
  214722. const String openDevice (const BigInteger& inputChannels,
  214723. const BigInteger& outputChannels,
  214724. double sampleRate_, int bufferSizeSamples_);
  214725. void closeDevice()
  214726. {
  214727. isStarted = false;
  214728. stopThread (5000);
  214729. inChans.clear();
  214730. outChans.clear();
  214731. inputBuffers.setSize (1, 1);
  214732. outputBuffers.setSize (1, 1);
  214733. }
  214734. void resync()
  214735. {
  214736. if (! threadShouldExit())
  214737. {
  214738. sleep (5);
  214739. int i;
  214740. for (i = 0; i < outChans.size(); ++i)
  214741. outChans.getUnchecked(i)->synchronisePosition();
  214742. for (i = 0; i < inChans.size(); ++i)
  214743. inChans.getUnchecked(i)->synchronisePosition();
  214744. }
  214745. }
  214746. public:
  214747. void run()
  214748. {
  214749. while (! threadShouldExit())
  214750. {
  214751. if (wait (100))
  214752. break;
  214753. }
  214754. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  214755. const int maxTimeMS = jmax (5, 3 * latencyMs);
  214756. while (! threadShouldExit())
  214757. {
  214758. int numToDo = 0;
  214759. uint32 startTime = Time::getMillisecondCounter();
  214760. int i;
  214761. for (i = inChans.size(); --i >= 0;)
  214762. {
  214763. inChans.getUnchecked(i)->doneFlag = false;
  214764. ++numToDo;
  214765. }
  214766. for (i = outChans.size(); --i >= 0;)
  214767. {
  214768. outChans.getUnchecked(i)->doneFlag = false;
  214769. ++numToDo;
  214770. }
  214771. if (numToDo > 0)
  214772. {
  214773. const int maxCount = 3;
  214774. int count = maxCount;
  214775. for (;;)
  214776. {
  214777. for (i = inChans.size(); --i >= 0;)
  214778. {
  214779. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  214780. if ((! in->doneFlag) && in->service())
  214781. {
  214782. in->doneFlag = true;
  214783. --numToDo;
  214784. }
  214785. }
  214786. for (i = outChans.size(); --i >= 0;)
  214787. {
  214788. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  214789. if ((! out->doneFlag) && out->service())
  214790. {
  214791. out->doneFlag = true;
  214792. --numToDo;
  214793. }
  214794. }
  214795. if (numToDo <= 0)
  214796. break;
  214797. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  214798. {
  214799. resync();
  214800. break;
  214801. }
  214802. if (--count <= 0)
  214803. {
  214804. Sleep (1);
  214805. count = maxCount;
  214806. }
  214807. if (threadShouldExit())
  214808. return;
  214809. }
  214810. }
  214811. else
  214812. {
  214813. sleep (1);
  214814. }
  214815. const ScopedLock sl (startStopLock);
  214816. if (isStarted)
  214817. {
  214818. JUCE_TRY
  214819. {
  214820. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  214821. inputBuffers.getNumChannels(),
  214822. outputBuffers.getArrayOfChannels(),
  214823. outputBuffers.getNumChannels(),
  214824. bufferSizeSamples);
  214825. }
  214826. JUCE_CATCH_EXCEPTION
  214827. totalSamplesOut += bufferSizeSamples;
  214828. }
  214829. else
  214830. {
  214831. outputBuffers.clear();
  214832. totalSamplesOut = 0;
  214833. sleep (1);
  214834. }
  214835. }
  214836. }
  214837. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice);
  214838. };
  214839. class DSoundAudioIODeviceType : public AudioIODeviceType
  214840. {
  214841. public:
  214842. DSoundAudioIODeviceType()
  214843. : AudioIODeviceType ("DirectSound"),
  214844. hasScanned (false)
  214845. {
  214846. initialiseDSoundFunctions();
  214847. }
  214848. void scanForDevices()
  214849. {
  214850. hasScanned = true;
  214851. outputDeviceNames.clear();
  214852. outputGuids.clear();
  214853. inputDeviceNames.clear();
  214854. inputGuids.clear();
  214855. if (dsDirectSoundEnumerateW != 0)
  214856. {
  214857. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214858. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214859. }
  214860. }
  214861. const StringArray getDeviceNames (bool wantInputNames) const
  214862. {
  214863. jassert (hasScanned); // need to call scanForDevices() before doing this
  214864. return wantInputNames ? inputDeviceNames
  214865. : outputDeviceNames;
  214866. }
  214867. int getDefaultDeviceIndex (bool /*forInput*/) const
  214868. {
  214869. jassert (hasScanned); // need to call scanForDevices() before doing this
  214870. return 0;
  214871. }
  214872. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214873. {
  214874. jassert (hasScanned); // need to call scanForDevices() before doing this
  214875. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214876. if (d == 0)
  214877. return -1;
  214878. return asInput ? d->inputDeviceIndex
  214879. : d->outputDeviceIndex;
  214880. }
  214881. bool hasSeparateInputsAndOutputs() const { return true; }
  214882. AudioIODevice* createDevice (const String& outputDeviceName,
  214883. const String& inputDeviceName)
  214884. {
  214885. jassert (hasScanned); // need to call scanForDevices() before doing this
  214886. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214887. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214888. if (outputIndex >= 0 || inputIndex >= 0)
  214889. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214890. : inputDeviceName,
  214891. outputIndex, inputIndex);
  214892. return 0;
  214893. }
  214894. StringArray outputDeviceNames, inputDeviceNames;
  214895. OwnedArray <GUID> outputGuids, inputGuids;
  214896. private:
  214897. bool hasScanned;
  214898. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214899. {
  214900. desc = desc.trim();
  214901. if (desc.isNotEmpty())
  214902. {
  214903. const String origDesc (desc);
  214904. int n = 2;
  214905. while (outputDeviceNames.contains (desc))
  214906. desc = origDesc + " (" + String (n++) + ")";
  214907. outputDeviceNames.add (desc);
  214908. if (lpGUID != 0)
  214909. outputGuids.add (new GUID (*lpGUID));
  214910. else
  214911. outputGuids.add (0);
  214912. }
  214913. return TRUE;
  214914. }
  214915. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214916. {
  214917. return ((DSoundAudioIODeviceType*) object)
  214918. ->outputEnumProc (lpGUID, String (description));
  214919. }
  214920. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214921. {
  214922. return ((DSoundAudioIODeviceType*) object)
  214923. ->outputEnumProc (lpGUID, String (description));
  214924. }
  214925. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214926. {
  214927. desc = desc.trim();
  214928. if (desc.isNotEmpty())
  214929. {
  214930. const String origDesc (desc);
  214931. int n = 2;
  214932. while (inputDeviceNames.contains (desc))
  214933. desc = origDesc + " (" + String (n++) + ")";
  214934. inputDeviceNames.add (desc);
  214935. if (lpGUID != 0)
  214936. inputGuids.add (new GUID (*lpGUID));
  214937. else
  214938. inputGuids.add (0);
  214939. }
  214940. return TRUE;
  214941. }
  214942. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214943. {
  214944. return ((DSoundAudioIODeviceType*) object)
  214945. ->inputEnumProc (lpGUID, String (description));
  214946. }
  214947. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214948. {
  214949. return ((DSoundAudioIODeviceType*) object)
  214950. ->inputEnumProc (lpGUID, String (description));
  214951. }
  214952. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType);
  214953. };
  214954. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214955. const BigInteger& outputChannels,
  214956. double sampleRate_, int bufferSizeSamples_)
  214957. {
  214958. closeDevice();
  214959. totalSamplesOut = 0;
  214960. sampleRate = sampleRate_;
  214961. if (bufferSizeSamples_ <= 0)
  214962. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214963. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214964. DSoundAudioIODeviceType dlh;
  214965. dlh.scanForDevices();
  214966. enabledInputs = inputChannels;
  214967. enabledInputs.setRange (inChannels.size(),
  214968. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214969. false);
  214970. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214971. inputBuffers.clear();
  214972. int i, numIns = 0;
  214973. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214974. {
  214975. float* left = 0;
  214976. if (enabledInputs[i])
  214977. left = inputBuffers.getSampleData (numIns++);
  214978. float* right = 0;
  214979. if (enabledInputs[i + 1])
  214980. right = inputBuffers.getSampleData (numIns++);
  214981. if (left != 0 || right != 0)
  214982. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214983. dlh.inputGuids [inputDeviceIndex],
  214984. (int) sampleRate, bufferSizeSamples,
  214985. left, right));
  214986. }
  214987. enabledOutputs = outputChannels;
  214988. enabledOutputs.setRange (outChannels.size(),
  214989. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214990. false);
  214991. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214992. outputBuffers.clear();
  214993. int numOuts = 0;
  214994. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  214995. {
  214996. float* left = 0;
  214997. if (enabledOutputs[i])
  214998. left = outputBuffers.getSampleData (numOuts++);
  214999. float* right = 0;
  215000. if (enabledOutputs[i + 1])
  215001. right = outputBuffers.getSampleData (numOuts++);
  215002. if (left != 0 || right != 0)
  215003. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215004. dlh.outputGuids [outputDeviceIndex],
  215005. (int) sampleRate, bufferSizeSamples,
  215006. left, right));
  215007. }
  215008. String error;
  215009. // boost our priority while opening the devices to try to get better sync between them
  215010. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215011. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215012. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215013. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215014. for (i = 0; i < outChans.size(); ++i)
  215015. {
  215016. error = outChans[i]->open();
  215017. if (error.isNotEmpty())
  215018. {
  215019. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215020. break;
  215021. }
  215022. }
  215023. if (error.isEmpty())
  215024. {
  215025. for (i = 0; i < inChans.size(); ++i)
  215026. {
  215027. error = inChans[i]->open();
  215028. if (error.isNotEmpty())
  215029. {
  215030. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215031. break;
  215032. }
  215033. }
  215034. }
  215035. if (error.isEmpty())
  215036. {
  215037. totalSamplesOut = 0;
  215038. for (i = 0; i < outChans.size(); ++i)
  215039. outChans.getUnchecked(i)->synchronisePosition();
  215040. for (i = 0; i < inChans.size(); ++i)
  215041. inChans.getUnchecked(i)->synchronisePosition();
  215042. startThread (9);
  215043. sleep (10);
  215044. notify();
  215045. }
  215046. else
  215047. {
  215048. log (error);
  215049. }
  215050. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215051. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215052. return error;
  215053. }
  215054. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215055. {
  215056. return new DSoundAudioIODeviceType();
  215057. }
  215058. #undef log
  215059. #endif
  215060. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215061. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215062. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215063. // compiled on its own).
  215064. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215065. #ifndef WASAPI_ENABLE_LOGGING
  215066. #define WASAPI_ENABLE_LOGGING 0
  215067. #endif
  215068. namespace WasapiClasses
  215069. {
  215070. void logFailure (HRESULT hr)
  215071. {
  215072. (void) hr;
  215073. #if WASAPI_ENABLE_LOGGING
  215074. if (FAILED (hr))
  215075. {
  215076. String e;
  215077. e << Time::getCurrentTime().toString (true, true, true, true)
  215078. << " -- WASAPI error: ";
  215079. switch (hr)
  215080. {
  215081. case E_POINTER: e << "E_POINTER"; break;
  215082. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215083. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215084. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215085. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215086. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215087. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215088. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215089. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215090. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215091. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215092. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215093. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215094. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215095. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215096. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215097. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215098. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215099. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215100. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215101. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215102. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215103. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215104. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215105. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215106. default: e << String::toHexString ((int) hr); break;
  215107. }
  215108. DBG (e);
  215109. jassertfalse;
  215110. }
  215111. #endif
  215112. }
  215113. #undef check
  215114. bool check (HRESULT hr)
  215115. {
  215116. logFailure (hr);
  215117. return SUCCEEDED (hr);
  215118. }
  215119. const String getDeviceID (IMMDevice* const device)
  215120. {
  215121. String s;
  215122. WCHAR* deviceId = 0;
  215123. if (check (device->GetId (&deviceId)))
  215124. {
  215125. s = String (deviceId);
  215126. CoTaskMemFree (deviceId);
  215127. }
  215128. return s;
  215129. }
  215130. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  215131. {
  215132. EDataFlow flow = eRender;
  215133. ComSmartPtr <IMMEndpoint> endPoint;
  215134. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  215135. (void) check (endPoint->GetDataFlow (&flow));
  215136. return flow;
  215137. }
  215138. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215139. {
  215140. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215141. }
  215142. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215143. {
  215144. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215145. : sizeof (WAVEFORMATEX));
  215146. }
  215147. class WASAPIDeviceBase
  215148. {
  215149. public:
  215150. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215151. : device (device_),
  215152. sampleRate (0),
  215153. numChannels (0),
  215154. actualNumChannels (0),
  215155. defaultSampleRate (0),
  215156. minBufferSize (0),
  215157. defaultBufferSize (0),
  215158. latencySamples (0),
  215159. useExclusiveMode (useExclusiveMode_)
  215160. {
  215161. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215162. ComSmartPtr <IAudioClient> tempClient (createClient());
  215163. if (tempClient == 0)
  215164. return;
  215165. REFERENCE_TIME defaultPeriod, minPeriod;
  215166. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215167. return;
  215168. WAVEFORMATEX* mixFormat = 0;
  215169. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215170. return;
  215171. WAVEFORMATEXTENSIBLE format;
  215172. copyWavFormat (format, mixFormat);
  215173. CoTaskMemFree (mixFormat);
  215174. actualNumChannels = numChannels = format.Format.nChannels;
  215175. defaultSampleRate = format.Format.nSamplesPerSec;
  215176. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215177. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215178. rates.addUsingDefaultSort (defaultSampleRate);
  215179. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215180. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215181. {
  215182. if (ratesToTest[i] == defaultSampleRate)
  215183. continue;
  215184. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215185. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215186. (WAVEFORMATEX*) &format, 0)))
  215187. if (! rates.contains (ratesToTest[i]))
  215188. rates.addUsingDefaultSort (ratesToTest[i]);
  215189. }
  215190. }
  215191. ~WASAPIDeviceBase()
  215192. {
  215193. device = 0;
  215194. CloseHandle (clientEvent);
  215195. }
  215196. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215197. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215198. {
  215199. sampleRate = newSampleRate;
  215200. channels = newChannels;
  215201. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215202. numChannels = channels.getHighestBit() + 1;
  215203. if (numChannels == 0)
  215204. return true;
  215205. client = createClient();
  215206. if (client != 0
  215207. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215208. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215209. {
  215210. channelMaps.clear();
  215211. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215212. if (channels[i])
  215213. channelMaps.add (i);
  215214. REFERENCE_TIME latency;
  215215. if (check (client->GetStreamLatency (&latency)))
  215216. latencySamples = refTimeToSamples (latency, sampleRate);
  215217. (void) check (client->GetBufferSize (&actualBufferSize));
  215218. return check (client->SetEventHandle (clientEvent));
  215219. }
  215220. return false;
  215221. }
  215222. void closeClient()
  215223. {
  215224. if (client != 0)
  215225. client->Stop();
  215226. client = 0;
  215227. ResetEvent (clientEvent);
  215228. }
  215229. ComSmartPtr <IMMDevice> device;
  215230. ComSmartPtr <IAudioClient> client;
  215231. double sampleRate, defaultSampleRate;
  215232. int numChannels, actualNumChannels;
  215233. int minBufferSize, defaultBufferSize, latencySamples;
  215234. const bool useExclusiveMode;
  215235. Array <double> rates;
  215236. HANDLE clientEvent;
  215237. BigInteger channels;
  215238. Array <int> channelMaps;
  215239. UINT32 actualBufferSize;
  215240. int bytesPerSample;
  215241. virtual void updateFormat (bool isFloat) = 0;
  215242. private:
  215243. const ComSmartPtr <IAudioClient> createClient()
  215244. {
  215245. ComSmartPtr <IAudioClient> client;
  215246. if (device != 0)
  215247. {
  215248. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215249. logFailure (hr);
  215250. }
  215251. return client;
  215252. }
  215253. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215254. {
  215255. WAVEFORMATEXTENSIBLE format;
  215256. zerostruct (format);
  215257. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215258. {
  215259. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215260. }
  215261. else
  215262. {
  215263. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215264. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215265. }
  215266. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215267. format.Format.nChannels = (WORD) numChannels;
  215268. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215269. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215270. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215271. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215272. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215273. switch (numChannels)
  215274. {
  215275. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215276. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215277. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215278. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215279. 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;
  215280. default: break;
  215281. }
  215282. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215283. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215284. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215285. logFailure (hr);
  215286. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215287. {
  215288. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215289. hr = S_OK;
  215290. }
  215291. CoTaskMemFree (nearestFormat);
  215292. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215293. if (useExclusiveMode)
  215294. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215295. GUID session;
  215296. if (hr == S_OK
  215297. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215298. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215299. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215300. {
  215301. actualNumChannels = format.Format.nChannels;
  215302. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215303. bytesPerSample = format.Format.wBitsPerSample / 8;
  215304. updateFormat (isFloat);
  215305. return true;
  215306. }
  215307. return false;
  215308. }
  215309. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase);
  215310. };
  215311. class WASAPIInputDevice : public WASAPIDeviceBase
  215312. {
  215313. public:
  215314. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215315. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215316. reservoir (1, 1)
  215317. {
  215318. }
  215319. ~WASAPIInputDevice()
  215320. {
  215321. close();
  215322. }
  215323. bool open (const double newSampleRate, const BigInteger& newChannels)
  215324. {
  215325. reservoirSize = 0;
  215326. reservoirCapacity = 16384;
  215327. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215328. return openClient (newSampleRate, newChannels)
  215329. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  215330. (void**) captureClient.resetAndGetPointerAddress())));
  215331. }
  215332. void close()
  215333. {
  215334. closeClient();
  215335. captureClient = 0;
  215336. reservoir.setSize (0);
  215337. }
  215338. template <class SourceType>
  215339. void updateFormatWithType (SourceType*)
  215340. {
  215341. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215342. converter = new AudioData::ConverterInstance <AudioData::Pointer <SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215343. }
  215344. void updateFormat (bool isFloat)
  215345. {
  215346. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215347. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215348. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215349. else updateFormatWithType ((AudioData::Int16*) 0);
  215350. }
  215351. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215352. {
  215353. if (numChannels <= 0)
  215354. return;
  215355. int offset = 0;
  215356. while (bufferSize > 0)
  215357. {
  215358. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215359. {
  215360. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215361. for (int i = 0; i < numDestBuffers; ++i)
  215362. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215363. bufferSize -= samplesToDo;
  215364. offset += samplesToDo;
  215365. reservoirSize = 0;
  215366. }
  215367. else
  215368. {
  215369. UINT32 packetLength = 0;
  215370. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215371. break;
  215372. if (packetLength == 0)
  215373. {
  215374. if (thread.threadShouldExit()
  215375. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215376. break;
  215377. continue;
  215378. }
  215379. uint8* inputData;
  215380. UINT32 numSamplesAvailable;
  215381. DWORD flags;
  215382. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215383. {
  215384. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215385. for (int i = 0; i < numDestBuffers; ++i)
  215386. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215387. bufferSize -= samplesToDo;
  215388. offset += samplesToDo;
  215389. if (samplesToDo < (int) numSamplesAvailable)
  215390. {
  215391. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215392. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215393. bytesPerSample * actualNumChannels * reservoirSize);
  215394. }
  215395. captureClient->ReleaseBuffer (numSamplesAvailable);
  215396. }
  215397. }
  215398. }
  215399. }
  215400. ComSmartPtr <IAudioCaptureClient> captureClient;
  215401. MemoryBlock reservoir;
  215402. int reservoirSize, reservoirCapacity;
  215403. ScopedPointer <AudioData::Converter> converter;
  215404. private:
  215405. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice);
  215406. };
  215407. class WASAPIOutputDevice : public WASAPIDeviceBase
  215408. {
  215409. public:
  215410. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215411. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215412. {
  215413. }
  215414. ~WASAPIOutputDevice()
  215415. {
  215416. close();
  215417. }
  215418. bool open (const double newSampleRate, const BigInteger& newChannels)
  215419. {
  215420. return openClient (newSampleRate, newChannels)
  215421. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215422. }
  215423. void close()
  215424. {
  215425. closeClient();
  215426. renderClient = 0;
  215427. }
  215428. template <class DestType>
  215429. void updateFormatWithType (DestType*)
  215430. {
  215431. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215432. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215433. }
  215434. void updateFormat (bool isFloat)
  215435. {
  215436. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215437. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215438. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215439. else updateFormatWithType ((AudioData::Int16*) 0);
  215440. }
  215441. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215442. {
  215443. if (numChannels <= 0)
  215444. return;
  215445. int offset = 0;
  215446. while (bufferSize > 0)
  215447. {
  215448. UINT32 padding = 0;
  215449. if (! check (client->GetCurrentPadding (&padding)))
  215450. return;
  215451. int samplesToDo = useExclusiveMode ? bufferSize
  215452. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215453. if (samplesToDo <= 0)
  215454. {
  215455. if (thread.threadShouldExit()
  215456. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215457. break;
  215458. continue;
  215459. }
  215460. uint8* outputData = 0;
  215461. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215462. {
  215463. for (int i = 0; i < numSrcBuffers; ++i)
  215464. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  215465. renderClient->ReleaseBuffer (samplesToDo, 0);
  215466. offset += samplesToDo;
  215467. bufferSize -= samplesToDo;
  215468. }
  215469. }
  215470. }
  215471. ComSmartPtr <IAudioRenderClient> renderClient;
  215472. ScopedPointer <AudioData::Converter> converter;
  215473. private:
  215474. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice);
  215475. };
  215476. class WASAPIAudioIODevice : public AudioIODevice,
  215477. public Thread
  215478. {
  215479. public:
  215480. WASAPIAudioIODevice (const String& deviceName,
  215481. const String& outputDeviceId_,
  215482. const String& inputDeviceId_,
  215483. const bool useExclusiveMode_)
  215484. : AudioIODevice (deviceName, "Windows Audio"),
  215485. Thread ("Juce WASAPI"),
  215486. isOpen_ (false),
  215487. isStarted (false),
  215488. outputDeviceId (outputDeviceId_),
  215489. inputDeviceId (inputDeviceId_),
  215490. useExclusiveMode (useExclusiveMode_),
  215491. currentBufferSizeSamples (0),
  215492. currentSampleRate (0),
  215493. callback (0)
  215494. {
  215495. }
  215496. ~WASAPIAudioIODevice()
  215497. {
  215498. close();
  215499. }
  215500. bool initialise()
  215501. {
  215502. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215503. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215504. latencyIn = latencyOut = 0;
  215505. Array <double> ratesIn, ratesOut;
  215506. if (createDevices())
  215507. {
  215508. jassert (inputDevice != 0 || outputDevice != 0);
  215509. if (inputDevice != 0 && outputDevice != 0)
  215510. {
  215511. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215512. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215513. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215514. sampleRates = inputDevice->rates;
  215515. sampleRates.removeValuesNotIn (outputDevice->rates);
  215516. }
  215517. else
  215518. {
  215519. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215520. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215521. defaultSampleRate = d->defaultSampleRate;
  215522. minBufferSize = d->minBufferSize;
  215523. defaultBufferSize = d->defaultBufferSize;
  215524. sampleRates = d->rates;
  215525. }
  215526. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215527. if (minBufferSize != defaultBufferSize)
  215528. bufferSizes.addUsingDefaultSort (minBufferSize);
  215529. int n = 64;
  215530. for (int i = 0; i < 40; ++i)
  215531. {
  215532. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215533. bufferSizes.addUsingDefaultSort (n);
  215534. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215535. }
  215536. return true;
  215537. }
  215538. return false;
  215539. }
  215540. const StringArray getOutputChannelNames()
  215541. {
  215542. StringArray outChannels;
  215543. if (outputDevice != 0)
  215544. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215545. outChannels.add ("Output channel " + String (i));
  215546. return outChannels;
  215547. }
  215548. const StringArray getInputChannelNames()
  215549. {
  215550. StringArray inChannels;
  215551. if (inputDevice != 0)
  215552. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215553. inChannels.add ("Input channel " + String (i));
  215554. return inChannels;
  215555. }
  215556. int getNumSampleRates() { return sampleRates.size(); }
  215557. double getSampleRate (int index) { return sampleRates [index]; }
  215558. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215559. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215560. int getDefaultBufferSize() { return defaultBufferSize; }
  215561. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215562. double getCurrentSampleRate() { return currentSampleRate; }
  215563. int getCurrentBitDepth() { return 32; }
  215564. int getOutputLatencyInSamples() { return latencyOut; }
  215565. int getInputLatencyInSamples() { return latencyIn; }
  215566. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215567. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215568. const String getLastError() { return lastError; }
  215569. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215570. double sampleRate, int bufferSizeSamples)
  215571. {
  215572. close();
  215573. lastError = String::empty;
  215574. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215575. {
  215576. lastError = "The input and output devices don't share a common sample rate!";
  215577. return lastError;
  215578. }
  215579. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  215580. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  215581. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  215582. {
  215583. lastError = "Couldn't open the input device!";
  215584. return lastError;
  215585. }
  215586. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  215587. {
  215588. close();
  215589. lastError = "Couldn't open the output device!";
  215590. return lastError;
  215591. }
  215592. if (inputDevice != 0) ResetEvent (inputDevice->clientEvent);
  215593. if (outputDevice != 0) ResetEvent (outputDevice->clientEvent);
  215594. startThread (8);
  215595. Thread::sleep (5);
  215596. if (inputDevice != 0 && inputDevice->client != 0)
  215597. {
  215598. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  215599. HRESULT hr = inputDevice->client->Start();
  215600. logFailure (hr); //xxx handle this
  215601. }
  215602. if (outputDevice != 0 && outputDevice->client != 0)
  215603. {
  215604. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  215605. HRESULT hr = outputDevice->client->Start();
  215606. logFailure (hr); //xxx handle this
  215607. }
  215608. isOpen_ = true;
  215609. return lastError;
  215610. }
  215611. void close()
  215612. {
  215613. stop();
  215614. signalThreadShouldExit();
  215615. if (inputDevice != 0) SetEvent (inputDevice->clientEvent);
  215616. if (outputDevice != 0) SetEvent (outputDevice->clientEvent);
  215617. stopThread (5000);
  215618. if (inputDevice != 0) inputDevice->close();
  215619. if (outputDevice != 0) outputDevice->close();
  215620. isOpen_ = false;
  215621. }
  215622. bool isOpen() { return isOpen_ && isThreadRunning(); }
  215623. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  215624. void start (AudioIODeviceCallback* call)
  215625. {
  215626. if (isOpen_ && call != 0 && ! isStarted)
  215627. {
  215628. if (! isThreadRunning())
  215629. {
  215630. // something's gone wrong and the thread's stopped..
  215631. isOpen_ = false;
  215632. return;
  215633. }
  215634. call->audioDeviceAboutToStart (this);
  215635. const ScopedLock sl (startStopLock);
  215636. callback = call;
  215637. isStarted = true;
  215638. }
  215639. }
  215640. void stop()
  215641. {
  215642. if (isStarted)
  215643. {
  215644. AudioIODeviceCallback* const callbackLocal = callback;
  215645. {
  215646. const ScopedLock sl (startStopLock);
  215647. isStarted = false;
  215648. }
  215649. if (callbackLocal != 0)
  215650. callbackLocal->audioDeviceStopped();
  215651. }
  215652. }
  215653. void setMMThreadPriority()
  215654. {
  215655. DynamicLibraryLoader dll ("avrt.dll");
  215656. DynamicLibraryImport (AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, dll, (LPCWSTR, LPDWORD))
  215657. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  215658. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  215659. {
  215660. DWORD dummy = 0;
  215661. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  215662. if (h != 0)
  215663. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  215664. }
  215665. }
  215666. void run()
  215667. {
  215668. setMMThreadPriority();
  215669. const int bufferSize = currentBufferSizeSamples;
  215670. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  215671. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  215672. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  215673. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  215674. float** const inputBuffers = ins.getArrayOfChannels();
  215675. float** const outputBuffers = outs.getArrayOfChannels();
  215676. ins.clear();
  215677. while (! threadShouldExit())
  215678. {
  215679. if (inputDevice != 0)
  215680. {
  215681. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  215682. if (threadShouldExit())
  215683. break;
  215684. }
  215685. JUCE_TRY
  215686. {
  215687. const ScopedLock sl (startStopLock);
  215688. if (isStarted)
  215689. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  215690. outputBuffers, numOutputBuffers, bufferSize);
  215691. else
  215692. outs.clear();
  215693. }
  215694. JUCE_CATCH_EXCEPTION
  215695. if (outputDevice != 0)
  215696. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  215697. }
  215698. }
  215699. String outputDeviceId, inputDeviceId;
  215700. String lastError;
  215701. private:
  215702. // Device stats...
  215703. ScopedPointer<WASAPIInputDevice> inputDevice;
  215704. ScopedPointer<WASAPIOutputDevice> outputDevice;
  215705. const bool useExclusiveMode;
  215706. double defaultSampleRate;
  215707. int minBufferSize, defaultBufferSize;
  215708. int latencyIn, latencyOut;
  215709. Array <double> sampleRates;
  215710. Array <int> bufferSizes;
  215711. // Active state...
  215712. bool isOpen_, isStarted;
  215713. int currentBufferSizeSamples;
  215714. double currentSampleRate;
  215715. AudioIODeviceCallback* callback;
  215716. CriticalSection startStopLock;
  215717. bool createDevices()
  215718. {
  215719. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215720. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215721. return false;
  215722. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215723. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  215724. return false;
  215725. UINT32 numDevices = 0;
  215726. if (! check (deviceCollection->GetCount (&numDevices)))
  215727. return false;
  215728. for (UINT32 i = 0; i < numDevices; ++i)
  215729. {
  215730. ComSmartPtr <IMMDevice> device;
  215731. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215732. continue;
  215733. const String deviceId (getDeviceID (device));
  215734. if (deviceId.isEmpty())
  215735. continue;
  215736. const EDataFlow flow = getDataFlow (device);
  215737. if (deviceId == inputDeviceId && flow == eCapture)
  215738. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  215739. else if (deviceId == outputDeviceId && flow == eRender)
  215740. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  215741. }
  215742. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  215743. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  215744. }
  215745. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice);
  215746. };
  215747. class WASAPIAudioIODeviceType : public AudioIODeviceType
  215748. {
  215749. public:
  215750. WASAPIAudioIODeviceType()
  215751. : AudioIODeviceType ("Windows Audio"),
  215752. hasScanned (false)
  215753. {
  215754. }
  215755. ~WASAPIAudioIODeviceType()
  215756. {
  215757. }
  215758. void scanForDevices()
  215759. {
  215760. hasScanned = true;
  215761. outputDeviceNames.clear();
  215762. inputDeviceNames.clear();
  215763. outputDeviceIds.clear();
  215764. inputDeviceIds.clear();
  215765. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215766. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215767. return;
  215768. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  215769. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215770. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215771. UINT32 numDevices = 0;
  215772. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  215773. && check (deviceCollection->GetCount (&numDevices))))
  215774. return;
  215775. for (UINT32 i = 0; i < numDevices; ++i)
  215776. {
  215777. ComSmartPtr <IMMDevice> device;
  215778. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215779. continue;
  215780. const String deviceId (getDeviceID (device));
  215781. DWORD state = 0;
  215782. if (! check (device->GetState (&state)))
  215783. continue;
  215784. if (state != DEVICE_STATE_ACTIVE)
  215785. continue;
  215786. String name;
  215787. {
  215788. ComSmartPtr <IPropertyStore> properties;
  215789. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  215790. continue;
  215791. PROPVARIANT value;
  215792. PropVariantInit (&value);
  215793. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215794. name = value.pwszVal;
  215795. PropVariantClear (&value);
  215796. }
  215797. const EDataFlow flow = getDataFlow (device);
  215798. if (flow == eRender)
  215799. {
  215800. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215801. outputDeviceIds.insert (index, deviceId);
  215802. outputDeviceNames.insert (index, name);
  215803. }
  215804. else if (flow == eCapture)
  215805. {
  215806. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215807. inputDeviceIds.insert (index, deviceId);
  215808. inputDeviceNames.insert (index, name);
  215809. }
  215810. }
  215811. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215812. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215813. }
  215814. const StringArray getDeviceNames (bool wantInputNames) const
  215815. {
  215816. jassert (hasScanned); // need to call scanForDevices() before doing this
  215817. return wantInputNames ? inputDeviceNames
  215818. : outputDeviceNames;
  215819. }
  215820. int getDefaultDeviceIndex (bool /*forInput*/) const
  215821. {
  215822. jassert (hasScanned); // need to call scanForDevices() before doing this
  215823. return 0;
  215824. }
  215825. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215826. {
  215827. jassert (hasScanned); // need to call scanForDevices() before doing this
  215828. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215829. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215830. : outputDeviceIds.indexOf (d->outputDeviceId));
  215831. }
  215832. bool hasSeparateInputsAndOutputs() const { return true; }
  215833. AudioIODevice* createDevice (const String& outputDeviceName,
  215834. const String& inputDeviceName)
  215835. {
  215836. jassert (hasScanned); // need to call scanForDevices() before doing this
  215837. const bool useExclusiveMode = false;
  215838. ScopedPointer<WASAPIAudioIODevice> device;
  215839. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215840. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215841. if (outputIndex >= 0 || inputIndex >= 0)
  215842. {
  215843. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215844. : inputDeviceName,
  215845. outputDeviceIds [outputIndex],
  215846. inputDeviceIds [inputIndex],
  215847. useExclusiveMode);
  215848. if (! device->initialise())
  215849. device = 0;
  215850. }
  215851. return device.release();
  215852. }
  215853. StringArray outputDeviceNames, outputDeviceIds;
  215854. StringArray inputDeviceNames, inputDeviceIds;
  215855. private:
  215856. bool hasScanned;
  215857. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215858. {
  215859. String s;
  215860. IMMDevice* dev = 0;
  215861. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215862. eMultimedia, &dev)))
  215863. {
  215864. WCHAR* deviceId = 0;
  215865. if (check (dev->GetId (&deviceId)))
  215866. {
  215867. s = String (deviceId);
  215868. CoTaskMemFree (deviceId);
  215869. }
  215870. dev->Release();
  215871. }
  215872. return s;
  215873. }
  215874. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType);
  215875. };
  215876. }
  215877. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  215878. {
  215879. return new WasapiClasses::WASAPIAudioIODeviceType();
  215880. }
  215881. #endif
  215882. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215883. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215884. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215885. // compiled on its own).
  215886. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215887. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215888. {
  215889. public:
  215890. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215891. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215892. const ComSmartPtr <IBaseFilter>& filter_,
  215893. int minWidth, int minHeight,
  215894. int maxWidth, int maxHeight)
  215895. : owner (owner_),
  215896. captureGraphBuilder (captureGraphBuilder_),
  215897. filter (filter_),
  215898. ok (false),
  215899. imageNeedsFlipping (false),
  215900. width (0),
  215901. height (0),
  215902. activeUsers (0),
  215903. recordNextFrameTime (false),
  215904. previewMaxFPS (60)
  215905. {
  215906. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215907. if (FAILED (hr))
  215908. return;
  215909. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215910. if (FAILED (hr))
  215911. return;
  215912. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  215913. if (FAILED (hr))
  215914. return;
  215915. {
  215916. ComSmartPtr <IAMStreamConfig> streamConfig;
  215917. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215918. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  215919. if (streamConfig != 0)
  215920. {
  215921. getVideoSizes (streamConfig);
  215922. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215923. return;
  215924. }
  215925. }
  215926. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215927. if (FAILED (hr))
  215928. return;
  215929. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215930. if (FAILED (hr))
  215931. return;
  215932. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215933. if (FAILED (hr))
  215934. return;
  215935. if (! connectFilters (filter, smartTee))
  215936. return;
  215937. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215938. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215939. if (FAILED (hr))
  215940. return;
  215941. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  215942. if (FAILED (hr))
  215943. return;
  215944. AM_MEDIA_TYPE mt;
  215945. zerostruct (mt);
  215946. mt.majortype = MEDIATYPE_Video;
  215947. mt.subtype = MEDIASUBTYPE_RGB24;
  215948. mt.formattype = FORMAT_VideoInfo;
  215949. sampleGrabber->SetMediaType (&mt);
  215950. callback = new GrabberCallback (*this);
  215951. hr = sampleGrabber->SetCallback (callback, 1);
  215952. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215953. if (FAILED (hr))
  215954. return;
  215955. ComSmartPtr <IPin> grabberInputPin;
  215956. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  215957. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  215958. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  215959. return;
  215960. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215961. if (FAILED (hr))
  215962. return;
  215963. zerostruct (mt);
  215964. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215965. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215966. width = pVih->bmiHeader.biWidth;
  215967. height = pVih->bmiHeader.biHeight;
  215968. ComSmartPtr <IBaseFilter> nullFilter;
  215969. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215970. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215971. if (connectFilters (sampleGrabberBase, nullFilter)
  215972. && addGraphToRot())
  215973. {
  215974. activeImage = Image (Image::RGB, width, height, true);
  215975. loadingImage = Image (Image::RGB, width, height, true);
  215976. ok = true;
  215977. }
  215978. }
  215979. ~DShowCameraDeviceInteral()
  215980. {
  215981. if (mediaControl != 0)
  215982. mediaControl->Stop();
  215983. removeGraphFromRot();
  215984. for (int i = viewerComps.size(); --i >= 0;)
  215985. viewerComps.getUnchecked(i)->ownerDeleted();
  215986. callback = 0;
  215987. graphBuilder = 0;
  215988. sampleGrabber = 0;
  215989. mediaControl = 0;
  215990. filter = 0;
  215991. captureGraphBuilder = 0;
  215992. smartTee = 0;
  215993. smartTeePreviewOutputPin = 0;
  215994. smartTeeCaptureOutputPin = 0;
  215995. asfWriter = 0;
  215996. }
  215997. void addUser()
  215998. {
  215999. if (ok && activeUsers++ == 0)
  216000. mediaControl->Run();
  216001. }
  216002. void removeUser()
  216003. {
  216004. if (ok && --activeUsers == 0)
  216005. mediaControl->Stop();
  216006. }
  216007. int getPreviewMaxFPS() const
  216008. {
  216009. return previewMaxFPS;
  216010. }
  216011. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216012. {
  216013. if (recordNextFrameTime)
  216014. {
  216015. const double defaultCameraLatency = 0.1;
  216016. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216017. recordNextFrameTime = false;
  216018. ComSmartPtr <IPin> pin;
  216019. if (getPin (filter, PINDIR_OUTPUT, pin))
  216020. {
  216021. ComSmartPtr <IAMPushSource> pushSource;
  216022. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  216023. if (pushSource != 0)
  216024. {
  216025. REFERENCE_TIME latency = 0;
  216026. hr = pushSource->GetLatency (&latency);
  216027. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216028. }
  216029. }
  216030. }
  216031. {
  216032. const int lineStride = width * 3;
  216033. const ScopedLock sl (imageSwapLock);
  216034. {
  216035. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216036. for (int i = 0; i < height; ++i)
  216037. memcpy (destData.getLinePointer ((height - 1) - i),
  216038. buffer + lineStride * i,
  216039. lineStride);
  216040. }
  216041. imageNeedsFlipping = true;
  216042. }
  216043. if (listeners.size() > 0)
  216044. callListeners (loadingImage);
  216045. sendChangeMessage();
  216046. }
  216047. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216048. {
  216049. if (imageNeedsFlipping)
  216050. {
  216051. const ScopedLock sl (imageSwapLock);
  216052. swapVariables (loadingImage, activeImage);
  216053. imageNeedsFlipping = false;
  216054. }
  216055. RectanglePlacement rp (RectanglePlacement::centred);
  216056. double dx = 0, dy = 0, dw = width, dh = height;
  216057. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216058. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216059. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216060. {
  216061. Graphics::ScopedSaveState ss (g);
  216062. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216063. g.fillAll (Colours::black);
  216064. }
  216065. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216066. }
  216067. bool createFileCaptureFilter (const File& file, int quality)
  216068. {
  216069. removeFileCaptureFilter();
  216070. file.deleteFile();
  216071. mediaControl->Stop();
  216072. firstRecordedTime = Time();
  216073. recordNextFrameTime = true;
  216074. previewMaxFPS = 60;
  216075. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216076. if (SUCCEEDED (hr))
  216077. {
  216078. ComSmartPtr <IFileSinkFilter> fileSink;
  216079. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  216080. if (SUCCEEDED (hr))
  216081. {
  216082. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216083. if (SUCCEEDED (hr))
  216084. {
  216085. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216086. if (SUCCEEDED (hr))
  216087. {
  216088. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216089. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  216090. asfConfig->SetIndexMode (true);
  216091. ComSmartPtr <IWMProfileManager> profileManager;
  216092. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  216093. // This gibberish is the DirectShow profile for a video-only wmv file.
  216094. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  216095. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  216096. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216097. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  216098. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216099. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  216100. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  216101. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  216102. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216103. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216104. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216105. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  216106. "biclrused=\"0\" biclrimportant=\"0\"/>"
  216107. "</videoinfoheader>"
  216108. "</wmmediatype>"
  216109. "</streamconfig>"
  216110. "</profile>");
  216111. const int fps[] = { 10, 15, 30 };
  216112. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  216113. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216114. maxFramesPerSecond = (quality >> 24) & 0xff;
  216115. prof = prof.replace ("$WIDTH", String (width))
  216116. .replace ("$HEIGHT", String (height))
  216117. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  216118. ComSmartPtr <IWMProfile> currentProfile;
  216119. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  216120. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216121. if (SUCCEEDED (hr))
  216122. {
  216123. ComSmartPtr <IPin> asfWriterInputPin;
  216124. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  216125. {
  216126. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216127. if (SUCCEEDED (hr) && ok && activeUsers > 0
  216128. && SUCCEEDED (mediaControl->Run()))
  216129. {
  216130. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  216131. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216132. previewMaxFPS = (quality >> 16) & 0xff;
  216133. return true;
  216134. }
  216135. }
  216136. }
  216137. }
  216138. }
  216139. }
  216140. }
  216141. removeFileCaptureFilter();
  216142. if (ok && activeUsers > 0)
  216143. mediaControl->Run();
  216144. return false;
  216145. }
  216146. void removeFileCaptureFilter()
  216147. {
  216148. mediaControl->Stop();
  216149. if (asfWriter != 0)
  216150. {
  216151. graphBuilder->RemoveFilter (asfWriter);
  216152. asfWriter = 0;
  216153. }
  216154. if (ok && activeUsers > 0)
  216155. mediaControl->Run();
  216156. previewMaxFPS = 60;
  216157. }
  216158. void addListener (CameraDevice::Listener* listenerToAdd)
  216159. {
  216160. const ScopedLock sl (listenerLock);
  216161. if (listeners.size() == 0)
  216162. addUser();
  216163. listeners.addIfNotAlreadyThere (listenerToAdd);
  216164. }
  216165. void removeListener (CameraDevice::Listener* listenerToRemove)
  216166. {
  216167. const ScopedLock sl (listenerLock);
  216168. listeners.removeValue (listenerToRemove);
  216169. if (listeners.size() == 0)
  216170. removeUser();
  216171. }
  216172. void callListeners (const Image& image)
  216173. {
  216174. const ScopedLock sl (listenerLock);
  216175. for (int i = listeners.size(); --i >= 0;)
  216176. {
  216177. CameraDevice::Listener* const l = listeners[i];
  216178. if (l != 0)
  216179. l->imageReceived (image);
  216180. }
  216181. }
  216182. class DShowCaptureViewerComp : public Component,
  216183. public ChangeListener
  216184. {
  216185. public:
  216186. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216187. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  216188. {
  216189. setOpaque (true);
  216190. owner->addChangeListener (this);
  216191. owner->addUser();
  216192. owner->viewerComps.add (this);
  216193. setSize (owner->width, owner->height);
  216194. }
  216195. ~DShowCaptureViewerComp()
  216196. {
  216197. if (owner != 0)
  216198. {
  216199. owner->viewerComps.removeValue (this);
  216200. owner->removeUser();
  216201. owner->removeChangeListener (this);
  216202. }
  216203. }
  216204. void ownerDeleted()
  216205. {
  216206. owner = 0;
  216207. }
  216208. void paint (Graphics& g)
  216209. {
  216210. g.setColour (Colours::black);
  216211. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216212. if (owner != 0)
  216213. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216214. else
  216215. g.fillAll (Colours::black);
  216216. }
  216217. void changeListenerCallback (ChangeBroadcaster*)
  216218. {
  216219. const int64 now = Time::currentTimeMillis();
  216220. if (now >= lastRepaintTime + (1000 / maxFPS))
  216221. {
  216222. lastRepaintTime = now;
  216223. repaint();
  216224. if (owner != 0)
  216225. maxFPS = owner->getPreviewMaxFPS();
  216226. }
  216227. }
  216228. private:
  216229. DShowCameraDeviceInteral* owner;
  216230. int maxFPS;
  216231. int64 lastRepaintTime;
  216232. };
  216233. bool ok;
  216234. int width, height;
  216235. Time firstRecordedTime;
  216236. Array <DShowCaptureViewerComp*> viewerComps;
  216237. private:
  216238. CameraDevice* const owner;
  216239. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216240. ComSmartPtr <IBaseFilter> filter;
  216241. ComSmartPtr <IBaseFilter> smartTee;
  216242. ComSmartPtr <IGraphBuilder> graphBuilder;
  216243. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216244. ComSmartPtr <IMediaControl> mediaControl;
  216245. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216246. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216247. ComSmartPtr <IBaseFilter> asfWriter;
  216248. int activeUsers;
  216249. Array <int> widths, heights;
  216250. DWORD graphRegistrationID;
  216251. CriticalSection imageSwapLock;
  216252. bool imageNeedsFlipping;
  216253. Image loadingImage;
  216254. Image activeImage;
  216255. bool recordNextFrameTime;
  216256. int previewMaxFPS;
  216257. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216258. {
  216259. widths.clear();
  216260. heights.clear();
  216261. int count = 0, size = 0;
  216262. streamConfig->GetNumberOfCapabilities (&count, &size);
  216263. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216264. {
  216265. for (int i = 0; i < count; ++i)
  216266. {
  216267. VIDEO_STREAM_CONFIG_CAPS scc;
  216268. AM_MEDIA_TYPE* config;
  216269. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216270. if (SUCCEEDED (hr))
  216271. {
  216272. const int w = scc.InputSize.cx;
  216273. const int h = scc.InputSize.cy;
  216274. bool duplicate = false;
  216275. for (int j = widths.size(); --j >= 0;)
  216276. {
  216277. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216278. {
  216279. duplicate = true;
  216280. break;
  216281. }
  216282. }
  216283. if (! duplicate)
  216284. {
  216285. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216286. widths.add (w);
  216287. heights.add (h);
  216288. }
  216289. deleteMediaType (config);
  216290. }
  216291. }
  216292. }
  216293. }
  216294. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216295. const int minWidth, const int minHeight,
  216296. const int maxWidth, const int maxHeight)
  216297. {
  216298. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216299. streamConfig->GetNumberOfCapabilities (&count, &size);
  216300. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216301. {
  216302. AM_MEDIA_TYPE* config;
  216303. VIDEO_STREAM_CONFIG_CAPS scc;
  216304. for (int i = 0; i < count; ++i)
  216305. {
  216306. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216307. if (SUCCEEDED (hr))
  216308. {
  216309. if (scc.InputSize.cx >= minWidth
  216310. && scc.InputSize.cy >= minHeight
  216311. && scc.InputSize.cx <= maxWidth
  216312. && scc.InputSize.cy <= maxHeight)
  216313. {
  216314. int area = scc.InputSize.cx * scc.InputSize.cy;
  216315. if (area > bestArea)
  216316. {
  216317. bestIndex = i;
  216318. bestArea = area;
  216319. }
  216320. }
  216321. deleteMediaType (config);
  216322. }
  216323. }
  216324. if (bestIndex >= 0)
  216325. {
  216326. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216327. hr = streamConfig->SetFormat (config);
  216328. deleteMediaType (config);
  216329. return SUCCEEDED (hr);
  216330. }
  216331. }
  216332. return false;
  216333. }
  216334. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  216335. {
  216336. ComSmartPtr <IEnumPins> enumerator;
  216337. ComSmartPtr <IPin> pin;
  216338. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  216339. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  216340. {
  216341. PIN_DIRECTION dir;
  216342. pin->QueryDirection (&dir);
  216343. if (wantedDirection == dir)
  216344. {
  216345. PIN_INFO info;
  216346. zerostruct (info);
  216347. pin->QueryPinInfo (&info);
  216348. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216349. {
  216350. result = pin;
  216351. return true;
  216352. }
  216353. }
  216354. }
  216355. return false;
  216356. }
  216357. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216358. {
  216359. ComSmartPtr <IPin> in, out;
  216360. return getPin (first, PINDIR_OUTPUT, out)
  216361. && getPin (second, PINDIR_INPUT, in)
  216362. && SUCCEEDED (graphBuilder->Connect (out, in));
  216363. }
  216364. bool addGraphToRot()
  216365. {
  216366. ComSmartPtr <IRunningObjectTable> rot;
  216367. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216368. return false;
  216369. ComSmartPtr <IMoniker> moniker;
  216370. WCHAR buffer[128];
  216371. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  216372. if (FAILED (hr))
  216373. return false;
  216374. graphRegistrationID = 0;
  216375. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216376. }
  216377. void removeGraphFromRot()
  216378. {
  216379. ComSmartPtr <IRunningObjectTable> rot;
  216380. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216381. rot->Revoke (graphRegistrationID);
  216382. }
  216383. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216384. {
  216385. if (pmt->cbFormat != 0)
  216386. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216387. if (pmt->pUnk != 0)
  216388. pmt->pUnk->Release();
  216389. CoTaskMemFree (pmt);
  216390. }
  216391. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216392. {
  216393. public:
  216394. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216395. : owner (owner_)
  216396. {
  216397. }
  216398. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216399. {
  216400. return E_FAIL;
  216401. }
  216402. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216403. {
  216404. owner.handleFrame (time, buffer, bufferSize);
  216405. return S_OK;
  216406. }
  216407. private:
  216408. DShowCameraDeviceInteral& owner;
  216409. GrabberCallback (const GrabberCallback&);
  216410. GrabberCallback& operator= (const GrabberCallback&);
  216411. };
  216412. ComSmartPtr <GrabberCallback> callback;
  216413. Array <CameraDevice::Listener*> listeners;
  216414. CriticalSection listenerLock;
  216415. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  216416. };
  216417. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216418. : name (name_)
  216419. {
  216420. isRecording = false;
  216421. }
  216422. CameraDevice::~CameraDevice()
  216423. {
  216424. stopRecording();
  216425. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216426. internal = 0;
  216427. }
  216428. Component* CameraDevice::createViewerComponent()
  216429. {
  216430. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216431. }
  216432. const String CameraDevice::getFileExtension()
  216433. {
  216434. return ".wmv";
  216435. }
  216436. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216437. {
  216438. stopRecording();
  216439. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216440. d->addUser();
  216441. isRecording = d->createFileCaptureFilter (file, quality);
  216442. }
  216443. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216444. {
  216445. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216446. return d->firstRecordedTime;
  216447. }
  216448. void CameraDevice::stopRecording()
  216449. {
  216450. if (isRecording)
  216451. {
  216452. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216453. d->removeFileCaptureFilter();
  216454. d->removeUser();
  216455. isRecording = false;
  216456. }
  216457. }
  216458. void CameraDevice::addListener (Listener* listenerToAdd)
  216459. {
  216460. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216461. if (listenerToAdd != 0)
  216462. d->addListener (listenerToAdd);
  216463. }
  216464. void CameraDevice::removeListener (Listener* listenerToRemove)
  216465. {
  216466. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216467. if (listenerToRemove != 0)
  216468. d->removeListener (listenerToRemove);
  216469. }
  216470. namespace
  216471. {
  216472. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216473. const int deviceIndexToOpen,
  216474. String& name)
  216475. {
  216476. int index = 0;
  216477. ComSmartPtr <IBaseFilter> result;
  216478. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216479. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216480. if (SUCCEEDED (hr))
  216481. {
  216482. ComSmartPtr <IEnumMoniker> enumerator;
  216483. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  216484. if (SUCCEEDED (hr) && enumerator != 0)
  216485. {
  216486. ComSmartPtr <IMoniker> moniker;
  216487. ULONG fetched;
  216488. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  216489. {
  216490. ComSmartPtr <IBaseFilter> captureFilter;
  216491. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  216492. if (SUCCEEDED (hr))
  216493. {
  216494. ComSmartPtr <IPropertyBag> propertyBag;
  216495. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  216496. if (SUCCEEDED (hr))
  216497. {
  216498. VARIANT var;
  216499. var.vt = VT_BSTR;
  216500. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216501. propertyBag = 0;
  216502. if (SUCCEEDED (hr))
  216503. {
  216504. if (names != 0)
  216505. names->add (var.bstrVal);
  216506. if (index == deviceIndexToOpen)
  216507. {
  216508. name = var.bstrVal;
  216509. result = captureFilter;
  216510. break;
  216511. }
  216512. ++index;
  216513. }
  216514. }
  216515. }
  216516. }
  216517. }
  216518. }
  216519. return result;
  216520. }
  216521. }
  216522. const StringArray CameraDevice::getAvailableDevices()
  216523. {
  216524. StringArray devs;
  216525. String dummy;
  216526. enumerateCameras (&devs, -1, dummy);
  216527. return devs;
  216528. }
  216529. CameraDevice* CameraDevice::openDevice (int index,
  216530. int minWidth, int minHeight,
  216531. int maxWidth, int maxHeight)
  216532. {
  216533. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216534. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216535. if (SUCCEEDED (hr))
  216536. {
  216537. String name;
  216538. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216539. if (filter != 0)
  216540. {
  216541. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216542. DShowCameraDeviceInteral* const intern
  216543. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216544. minWidth, minHeight, maxWidth, maxHeight);
  216545. cam->internal = intern;
  216546. if (intern->ok)
  216547. return cam.release();
  216548. }
  216549. }
  216550. return 0;
  216551. }
  216552. #endif
  216553. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216554. #endif
  216555. // Auto-link the other win32 libs that are needed by library calls..
  216556. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216557. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216558. // Auto-links to various win32 libs that are needed by library calls..
  216559. #pragma comment(lib, "kernel32.lib")
  216560. #pragma comment(lib, "user32.lib")
  216561. #pragma comment(lib, "shell32.lib")
  216562. #pragma comment(lib, "gdi32.lib")
  216563. #pragma comment(lib, "vfw32.lib")
  216564. #pragma comment(lib, "comdlg32.lib")
  216565. #pragma comment(lib, "winmm.lib")
  216566. #pragma comment(lib, "wininet.lib")
  216567. #pragma comment(lib, "ole32.lib")
  216568. #pragma comment(lib, "oleaut32.lib")
  216569. #pragma comment(lib, "advapi32.lib")
  216570. #pragma comment(lib, "ws2_32.lib")
  216571. #pragma comment(lib, "version.lib")
  216572. #ifdef _NATIVE_WCHAR_T_DEFINED
  216573. #ifdef _DEBUG
  216574. #pragma comment(lib, "comsuppwd.lib")
  216575. #else
  216576. #pragma comment(lib, "comsuppw.lib")
  216577. #endif
  216578. #else
  216579. #ifdef _DEBUG
  216580. #pragma comment(lib, "comsuppd.lib")
  216581. #else
  216582. #pragma comment(lib, "comsupp.lib")
  216583. #endif
  216584. #endif
  216585. #if JUCE_OPENGL
  216586. #pragma comment(lib, "OpenGL32.Lib")
  216587. #pragma comment(lib, "GlU32.Lib")
  216588. #endif
  216589. #if JUCE_QUICKTIME
  216590. #pragma comment (lib, "QTMLClient.lib")
  216591. #endif
  216592. #if JUCE_USE_CAMERA
  216593. #pragma comment (lib, "Strmiids.lib")
  216594. #pragma comment (lib, "wmvcore.lib")
  216595. #endif
  216596. #if JUCE_DIRECT2D
  216597. #pragma comment (lib, "Dwrite.lib")
  216598. #pragma comment (lib, "D2d1.lib")
  216599. #endif
  216600. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216601. #endif
  216602. END_JUCE_NAMESPACE
  216603. #endif
  216604. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  216605. #endif
  216606. #if JUCE_LINUX
  216607. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  216608. /*
  216609. This file wraps together all the mac-specific code, so that
  216610. we can include all the native headers just once, and compile all our
  216611. platform-specific stuff in one big lump, keeping it out of the way of
  216612. the rest of the codebase.
  216613. */
  216614. #if JUCE_LINUX
  216615. #undef JUCE_BUILD_NATIVE
  216616. #define JUCE_BUILD_NATIVE 1
  216617. BEGIN_JUCE_NAMESPACE
  216618. #define JUCE_INCLUDED_FILE 1
  216619. // Now include the actual code files..
  216620. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  216621. /*
  216622. This file contains posix routines that are common to both the Linux and Mac builds.
  216623. It gets included directly in the cpp files for these platforms.
  216624. */
  216625. CriticalSection::CriticalSection() throw()
  216626. {
  216627. pthread_mutexattr_t atts;
  216628. pthread_mutexattr_init (&atts);
  216629. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216630. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216631. pthread_mutex_init (&internal, &atts);
  216632. }
  216633. CriticalSection::~CriticalSection() throw()
  216634. {
  216635. pthread_mutex_destroy (&internal);
  216636. }
  216637. void CriticalSection::enter() const throw()
  216638. {
  216639. pthread_mutex_lock (&internal);
  216640. }
  216641. bool CriticalSection::tryEnter() const throw()
  216642. {
  216643. return pthread_mutex_trylock (&internal) == 0;
  216644. }
  216645. void CriticalSection::exit() const throw()
  216646. {
  216647. pthread_mutex_unlock (&internal);
  216648. }
  216649. class WaitableEventImpl
  216650. {
  216651. public:
  216652. WaitableEventImpl (const bool manualReset_)
  216653. : triggered (false),
  216654. manualReset (manualReset_)
  216655. {
  216656. pthread_cond_init (&condition, 0);
  216657. pthread_mutexattr_t atts;
  216658. pthread_mutexattr_init (&atts);
  216659. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216660. pthread_mutex_init (&mutex, &atts);
  216661. }
  216662. ~WaitableEventImpl()
  216663. {
  216664. pthread_cond_destroy (&condition);
  216665. pthread_mutex_destroy (&mutex);
  216666. }
  216667. bool wait (const int timeOutMillisecs) throw()
  216668. {
  216669. pthread_mutex_lock (&mutex);
  216670. if (! triggered)
  216671. {
  216672. if (timeOutMillisecs < 0)
  216673. {
  216674. do
  216675. {
  216676. pthread_cond_wait (&condition, &mutex);
  216677. }
  216678. while (! triggered);
  216679. }
  216680. else
  216681. {
  216682. struct timeval now;
  216683. gettimeofday (&now, 0);
  216684. struct timespec time;
  216685. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  216686. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  216687. if (time.tv_nsec >= 1000000000)
  216688. {
  216689. time.tv_nsec -= 1000000000;
  216690. time.tv_sec++;
  216691. }
  216692. do
  216693. {
  216694. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  216695. {
  216696. pthread_mutex_unlock (&mutex);
  216697. return false;
  216698. }
  216699. }
  216700. while (! triggered);
  216701. }
  216702. }
  216703. if (! manualReset)
  216704. triggered = false;
  216705. pthread_mutex_unlock (&mutex);
  216706. return true;
  216707. }
  216708. void signal() throw()
  216709. {
  216710. pthread_mutex_lock (&mutex);
  216711. triggered = true;
  216712. pthread_cond_broadcast (&condition);
  216713. pthread_mutex_unlock (&mutex);
  216714. }
  216715. void reset() throw()
  216716. {
  216717. pthread_mutex_lock (&mutex);
  216718. triggered = false;
  216719. pthread_mutex_unlock (&mutex);
  216720. }
  216721. private:
  216722. pthread_cond_t condition;
  216723. pthread_mutex_t mutex;
  216724. bool triggered;
  216725. const bool manualReset;
  216726. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  216727. };
  216728. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  216729. : internal (new WaitableEventImpl (manualReset))
  216730. {
  216731. }
  216732. WaitableEvent::~WaitableEvent() throw()
  216733. {
  216734. delete static_cast <WaitableEventImpl*> (internal);
  216735. }
  216736. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  216737. {
  216738. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  216739. }
  216740. void WaitableEvent::signal() const throw()
  216741. {
  216742. static_cast <WaitableEventImpl*> (internal)->signal();
  216743. }
  216744. void WaitableEvent::reset() const throw()
  216745. {
  216746. static_cast <WaitableEventImpl*> (internal)->reset();
  216747. }
  216748. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  216749. {
  216750. struct timespec time;
  216751. time.tv_sec = millisecs / 1000;
  216752. time.tv_nsec = (millisecs % 1000) * 1000000;
  216753. nanosleep (&time, 0);
  216754. }
  216755. const juce_wchar File::separator = '/';
  216756. const String File::separatorString ("/");
  216757. const File File::getCurrentWorkingDirectory()
  216758. {
  216759. HeapBlock<char> heapBuffer;
  216760. char localBuffer [1024];
  216761. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  216762. int bufferSize = 4096;
  216763. while (cwd == 0 && errno == ERANGE)
  216764. {
  216765. heapBuffer.malloc (bufferSize);
  216766. cwd = getcwd (heapBuffer, bufferSize - 1);
  216767. bufferSize += 1024;
  216768. }
  216769. return File (String::fromUTF8 (cwd));
  216770. }
  216771. bool File::setAsCurrentWorkingDirectory() const
  216772. {
  216773. return chdir (getFullPathName().toUTF8()) == 0;
  216774. }
  216775. namespace
  216776. {
  216777. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216778. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  216779. #else
  216780. typedef struct stat juce_statStruct;
  216781. #endif
  216782. bool juce_stat (const String& fileName, juce_statStruct& info)
  216783. {
  216784. return fileName.isNotEmpty()
  216785. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216786. && (stat64 (fileName.toUTF8(), &info) == 0);
  216787. #else
  216788. && (stat (fileName.toUTF8(), &info) == 0);
  216789. #endif
  216790. }
  216791. // if this file doesn't exist, find a parent of it that does..
  216792. bool juce_doStatFS (File f, struct statfs& result)
  216793. {
  216794. for (int i = 5; --i >= 0;)
  216795. {
  216796. if (f.exists())
  216797. break;
  216798. f = f.getParentDirectory();
  216799. }
  216800. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216801. }
  216802. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  216803. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216804. {
  216805. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216806. {
  216807. juce_statStruct info;
  216808. const bool statOk = juce_stat (path, info);
  216809. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216810. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216811. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  216812. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  216813. }
  216814. if (isReadOnly != 0)
  216815. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216816. }
  216817. }
  216818. bool File::isDirectory() const
  216819. {
  216820. juce_statStruct info;
  216821. return fullPath.isEmpty()
  216822. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  216823. }
  216824. bool File::exists() const
  216825. {
  216826. juce_statStruct info;
  216827. return fullPath.isNotEmpty()
  216828. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216829. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  216830. #else
  216831. && (lstat (fullPath.toUTF8(), &info) == 0);
  216832. #endif
  216833. }
  216834. bool File::existsAsFile() const
  216835. {
  216836. return exists() && ! isDirectory();
  216837. }
  216838. int64 File::getSize() const
  216839. {
  216840. juce_statStruct info;
  216841. return juce_stat (fullPath, info) ? info.st_size : 0;
  216842. }
  216843. bool File::hasWriteAccess() const
  216844. {
  216845. if (exists())
  216846. return access (fullPath.toUTF8(), W_OK) == 0;
  216847. if ((! isDirectory()) && fullPath.containsChar (separator))
  216848. return getParentDirectory().hasWriteAccess();
  216849. return false;
  216850. }
  216851. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  216852. {
  216853. juce_statStruct info;
  216854. if (! juce_stat (fullPath, info))
  216855. return false;
  216856. info.st_mode &= 0777; // Just permissions
  216857. if (shouldBeReadOnly)
  216858. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216859. else
  216860. // Give everybody write permission?
  216861. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216862. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216863. }
  216864. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216865. {
  216866. modificationTime = 0;
  216867. accessTime = 0;
  216868. creationTime = 0;
  216869. juce_statStruct info;
  216870. if (juce_stat (fullPath, info))
  216871. {
  216872. modificationTime = (int64) info.st_mtime * 1000;
  216873. accessTime = (int64) info.st_atime * 1000;
  216874. creationTime = (int64) info.st_ctime * 1000;
  216875. }
  216876. }
  216877. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216878. {
  216879. struct utimbuf times;
  216880. times.actime = (time_t) (accessTime / 1000);
  216881. times.modtime = (time_t) (modificationTime / 1000);
  216882. return utime (fullPath.toUTF8(), &times) == 0;
  216883. }
  216884. bool File::deleteFile() const
  216885. {
  216886. if (! exists())
  216887. return true;
  216888. else if (isDirectory())
  216889. return rmdir (fullPath.toUTF8()) == 0;
  216890. else
  216891. return remove (fullPath.toUTF8()) == 0;
  216892. }
  216893. bool File::moveInternal (const File& dest) const
  216894. {
  216895. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216896. return true;
  216897. if (hasWriteAccess() && copyInternal (dest))
  216898. {
  216899. if (deleteFile())
  216900. return true;
  216901. dest.deleteFile();
  216902. }
  216903. return false;
  216904. }
  216905. void File::createDirectoryInternal (const String& fileName) const
  216906. {
  216907. mkdir (fileName.toUTF8(), 0777);
  216908. }
  216909. int64 juce_fileSetPosition (void* handle, int64 pos)
  216910. {
  216911. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216912. return pos;
  216913. return -1;
  216914. }
  216915. void FileInputStream::openHandle()
  216916. {
  216917. totalSize = file.getSize();
  216918. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  216919. if (f != -1)
  216920. fileHandle = (void*) f;
  216921. }
  216922. void FileInputStream::closeHandle()
  216923. {
  216924. if (fileHandle != 0)
  216925. {
  216926. close ((int) (pointer_sized_int) fileHandle);
  216927. fileHandle = 0;
  216928. }
  216929. }
  216930. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  216931. {
  216932. if (fileHandle != 0)
  216933. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  216934. return 0;
  216935. }
  216936. void FileOutputStream::openHandle()
  216937. {
  216938. if (file.exists())
  216939. {
  216940. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216941. if (f != -1)
  216942. {
  216943. currentPosition = lseek (f, 0, SEEK_END);
  216944. if (currentPosition >= 0)
  216945. fileHandle = (void*) f;
  216946. else
  216947. close (f);
  216948. }
  216949. }
  216950. else
  216951. {
  216952. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  216953. if (f != -1)
  216954. fileHandle = (void*) f;
  216955. }
  216956. }
  216957. void FileOutputStream::closeHandle()
  216958. {
  216959. if (fileHandle != 0)
  216960. {
  216961. close ((int) (pointer_sized_int) fileHandle);
  216962. fileHandle = 0;
  216963. }
  216964. }
  216965. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  216966. {
  216967. if (fileHandle != 0)
  216968. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  216969. return 0;
  216970. }
  216971. void FileOutputStream::flushInternal()
  216972. {
  216973. if (fileHandle != 0)
  216974. fsync ((int) (pointer_sized_int) fileHandle);
  216975. }
  216976. const File juce_getExecutableFile()
  216977. {
  216978. Dl_info exeInfo;
  216979. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  216980. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216981. }
  216982. int64 File::getBytesFreeOnVolume() const
  216983. {
  216984. struct statfs buf;
  216985. if (juce_doStatFS (*this, buf))
  216986. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216987. return 0;
  216988. }
  216989. int64 File::getVolumeTotalSize() const
  216990. {
  216991. struct statfs buf;
  216992. if (juce_doStatFS (*this, buf))
  216993. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  216994. return 0;
  216995. }
  216996. const String File::getVolumeLabel() const
  216997. {
  216998. #if JUCE_MAC
  216999. struct VolAttrBuf
  217000. {
  217001. u_int32_t length;
  217002. attrreference_t mountPointRef;
  217003. char mountPointSpace [MAXPATHLEN];
  217004. } attrBuf;
  217005. struct attrlist attrList;
  217006. zerostruct (attrList);
  217007. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217008. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217009. File f (*this);
  217010. for (;;)
  217011. {
  217012. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217013. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217014. (int) attrBuf.mountPointRef.attr_length);
  217015. const File parent (f.getParentDirectory());
  217016. if (f == parent)
  217017. break;
  217018. f = parent;
  217019. }
  217020. #endif
  217021. return String::empty;
  217022. }
  217023. int File::getVolumeSerialNumber() const
  217024. {
  217025. return 0; // xxx
  217026. }
  217027. void juce_runSystemCommand (const String& command)
  217028. {
  217029. int result = system (command.toUTF8());
  217030. (void) result;
  217031. }
  217032. const String juce_getOutputFromCommand (const String& command)
  217033. {
  217034. // slight bodge here, as we just pipe the output into a temp file and read it...
  217035. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217036. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217037. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217038. String result (tempFile.loadFileAsString());
  217039. tempFile.deleteFile();
  217040. return result;
  217041. }
  217042. class InterProcessLock::Pimpl
  217043. {
  217044. public:
  217045. Pimpl (const String& name, const int timeOutMillisecs)
  217046. : handle (0), refCount (1)
  217047. {
  217048. #if JUCE_MAC
  217049. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217050. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217051. #else
  217052. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217053. #endif
  217054. temp.create();
  217055. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217056. if (handle != 0)
  217057. {
  217058. struct flock fl;
  217059. zerostruct (fl);
  217060. fl.l_whence = SEEK_SET;
  217061. fl.l_type = F_WRLCK;
  217062. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217063. for (;;)
  217064. {
  217065. const int result = fcntl (handle, F_SETLK, &fl);
  217066. if (result >= 0)
  217067. return;
  217068. if (errno != EINTR)
  217069. {
  217070. if (timeOutMillisecs == 0
  217071. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217072. break;
  217073. Thread::sleep (10);
  217074. }
  217075. }
  217076. }
  217077. closeFile();
  217078. }
  217079. ~Pimpl()
  217080. {
  217081. closeFile();
  217082. }
  217083. void closeFile()
  217084. {
  217085. if (handle != 0)
  217086. {
  217087. struct flock fl;
  217088. zerostruct (fl);
  217089. fl.l_whence = SEEK_SET;
  217090. fl.l_type = F_UNLCK;
  217091. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217092. {}
  217093. close (handle);
  217094. handle = 0;
  217095. }
  217096. }
  217097. int handle, refCount;
  217098. };
  217099. InterProcessLock::InterProcessLock (const String& name_)
  217100. : name (name_)
  217101. {
  217102. }
  217103. InterProcessLock::~InterProcessLock()
  217104. {
  217105. }
  217106. bool InterProcessLock::enter (const int timeOutMillisecs)
  217107. {
  217108. const ScopedLock sl (lock);
  217109. if (pimpl == 0)
  217110. {
  217111. pimpl = new Pimpl (name, timeOutMillisecs);
  217112. if (pimpl->handle == 0)
  217113. pimpl = 0;
  217114. }
  217115. else
  217116. {
  217117. pimpl->refCount++;
  217118. }
  217119. return pimpl != 0;
  217120. }
  217121. void InterProcessLock::exit()
  217122. {
  217123. const ScopedLock sl (lock);
  217124. // Trying to release the lock too many times!
  217125. jassert (pimpl != 0);
  217126. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217127. pimpl = 0;
  217128. }
  217129. void JUCE_API juce_threadEntryPoint (void*);
  217130. void* threadEntryProc (void* userData)
  217131. {
  217132. JUCE_AUTORELEASEPOOL
  217133. juce_threadEntryPoint (userData);
  217134. return 0;
  217135. }
  217136. void Thread::launchThread()
  217137. {
  217138. threadHandle_ = 0;
  217139. pthread_t handle = 0;
  217140. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  217141. {
  217142. pthread_detach (handle);
  217143. threadHandle_ = (void*) handle;
  217144. threadId_ = (ThreadID) threadHandle_;
  217145. }
  217146. }
  217147. void Thread::closeThreadHandle()
  217148. {
  217149. threadId_ = 0;
  217150. threadHandle_ = 0;
  217151. }
  217152. void Thread::killThread()
  217153. {
  217154. if (threadHandle_ != 0)
  217155. pthread_cancel ((pthread_t) threadHandle_);
  217156. }
  217157. void Thread::setCurrentThreadName (const String& /*name*/)
  217158. {
  217159. }
  217160. bool Thread::setThreadPriority (void* handle, int priority)
  217161. {
  217162. struct sched_param param;
  217163. int policy;
  217164. priority = jlimit (0, 10, priority);
  217165. if (handle == 0)
  217166. handle = (void*) pthread_self();
  217167. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217168. return false;
  217169. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217170. const int minPriority = sched_get_priority_min (policy);
  217171. const int maxPriority = sched_get_priority_max (policy);
  217172. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217173. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217174. }
  217175. Thread::ThreadID Thread::getCurrentThreadId()
  217176. {
  217177. return (ThreadID) pthread_self();
  217178. }
  217179. void Thread::yield()
  217180. {
  217181. sched_yield();
  217182. }
  217183. /* Remove this macro if you're having problems compiling the cpu affinity
  217184. calls (the API for these has changed about quite a bit in various Linux
  217185. versions, and a lot of distros seem to ship with obsolete versions)
  217186. */
  217187. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217188. #define SUPPORT_AFFINITIES 1
  217189. #endif
  217190. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217191. {
  217192. #if SUPPORT_AFFINITIES
  217193. cpu_set_t affinity;
  217194. CPU_ZERO (&affinity);
  217195. for (int i = 0; i < 32; ++i)
  217196. if ((affinityMask & (1 << i)) != 0)
  217197. CPU_SET (i, &affinity);
  217198. /*
  217199. N.B. If this line causes a compile error, then you've probably not got the latest
  217200. version of glibc installed.
  217201. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217202. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217203. */
  217204. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217205. sched_yield();
  217206. #else
  217207. /* affinities aren't supported because either the appropriate header files weren't found,
  217208. or the SUPPORT_AFFINITIES macro was turned off
  217209. */
  217210. jassertfalse;
  217211. (void) affinityMask;
  217212. #endif
  217213. }
  217214. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217215. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217216. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217217. // compiled on its own).
  217218. #if JUCE_INCLUDED_FILE
  217219. enum
  217220. {
  217221. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  217222. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  217223. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  217224. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  217225. };
  217226. bool File::copyInternal (const File& dest) const
  217227. {
  217228. FileInputStream in (*this);
  217229. if (dest.deleteFile())
  217230. {
  217231. {
  217232. FileOutputStream out (dest);
  217233. if (out.failedToOpen())
  217234. return false;
  217235. if (out.writeFromInputStream (in, -1) == getSize())
  217236. return true;
  217237. }
  217238. dest.deleteFile();
  217239. }
  217240. return false;
  217241. }
  217242. void File::findFileSystemRoots (Array<File>& destArray)
  217243. {
  217244. destArray.add (File ("/"));
  217245. }
  217246. bool File::isOnCDRomDrive() const
  217247. {
  217248. struct statfs buf;
  217249. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217250. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  217251. }
  217252. bool File::isOnHardDisk() const
  217253. {
  217254. struct statfs buf;
  217255. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217256. {
  217257. switch (buf.f_type)
  217258. {
  217259. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217260. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217261. case U_NFS_SUPER_MAGIC: // Network NFS
  217262. case U_SMB_SUPER_MAGIC: // Network Samba
  217263. return false;
  217264. default:
  217265. // Assume anything else is a hard-disk (but note it could
  217266. // be a RAM disk. There isn't a good way of determining
  217267. // this for sure)
  217268. return true;
  217269. }
  217270. }
  217271. // Assume so if this fails for some reason
  217272. return true;
  217273. }
  217274. bool File::isOnRemovableDrive() const
  217275. {
  217276. jassertfalse; // xxx not implemented for linux!
  217277. return false;
  217278. }
  217279. bool File::isHidden() const
  217280. {
  217281. return getFileName().startsWithChar ('.');
  217282. }
  217283. namespace
  217284. {
  217285. const File juce_readlink (const String& file, const File& defaultFile)
  217286. {
  217287. const int size = 8192;
  217288. HeapBlock<char> buffer;
  217289. buffer.malloc (size + 4);
  217290. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217291. if (numBytes > 0 && numBytes <= size)
  217292. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217293. return defaultFile;
  217294. }
  217295. }
  217296. const File File::getLinkedTarget() const
  217297. {
  217298. return juce_readlink (getFullPathName().toUTF8(), *this);
  217299. }
  217300. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217301. const File File::getSpecialLocation (const SpecialLocationType type)
  217302. {
  217303. switch (type)
  217304. {
  217305. case userHomeDirectory:
  217306. {
  217307. const char* homeDir = getenv ("HOME");
  217308. if (homeDir == 0)
  217309. {
  217310. struct passwd* const pw = getpwuid (getuid());
  217311. if (pw != 0)
  217312. homeDir = pw->pw_dir;
  217313. }
  217314. return File (String::fromUTF8 (homeDir));
  217315. }
  217316. case userDocumentsDirectory:
  217317. case userMusicDirectory:
  217318. case userMoviesDirectory:
  217319. case userApplicationDataDirectory:
  217320. return File ("~");
  217321. case userDesktopDirectory:
  217322. return File ("~/Desktop");
  217323. case commonApplicationDataDirectory:
  217324. return File ("/var");
  217325. case globalApplicationsDirectory:
  217326. return File ("/usr");
  217327. case tempDirectory:
  217328. {
  217329. File tmp ("/var/tmp");
  217330. if (! tmp.isDirectory())
  217331. {
  217332. tmp = "/tmp";
  217333. if (! tmp.isDirectory())
  217334. tmp = File::getCurrentWorkingDirectory();
  217335. }
  217336. return tmp;
  217337. }
  217338. case invokedExecutableFile:
  217339. if (juce_Argv0 != 0)
  217340. return File (String::fromUTF8 (juce_Argv0));
  217341. // deliberate fall-through...
  217342. case currentExecutableFile:
  217343. case currentApplicationFile:
  217344. return juce_getExecutableFile();
  217345. case hostApplicationPath:
  217346. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217347. default:
  217348. jassertfalse; // unknown type?
  217349. break;
  217350. }
  217351. return File::nonexistent;
  217352. }
  217353. const String File::getVersion() const
  217354. {
  217355. return String::empty; // xxx not yet implemented
  217356. }
  217357. bool File::moveToTrash() const
  217358. {
  217359. if (! exists())
  217360. return true;
  217361. File trashCan ("~/.Trash");
  217362. if (! trashCan.isDirectory())
  217363. trashCan = "~/.local/share/Trash/files";
  217364. if (! trashCan.isDirectory())
  217365. return false;
  217366. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217367. getFileExtension()));
  217368. }
  217369. class DirectoryIterator::NativeIterator::Pimpl
  217370. {
  217371. public:
  217372. Pimpl (const File& directory, const String& wildCard_)
  217373. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217374. wildCard (wildCard_),
  217375. dir (opendir (directory.getFullPathName().toUTF8()))
  217376. {
  217377. wildcardUTF8 = wildCard.toUTF8();
  217378. }
  217379. ~Pimpl()
  217380. {
  217381. if (dir != 0)
  217382. closedir (dir);
  217383. }
  217384. bool next (String& filenameFound,
  217385. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217386. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217387. {
  217388. if (dir != 0)
  217389. {
  217390. for (;;)
  217391. {
  217392. struct dirent* const de = readdir (dir);
  217393. if (de == 0)
  217394. break;
  217395. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217396. {
  217397. filenameFound = String::fromUTF8 (de->d_name);
  217398. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  217399. if (isHidden != 0)
  217400. *isHidden = filenameFound.startsWithChar ('.');
  217401. return true;
  217402. }
  217403. }
  217404. }
  217405. return false;
  217406. }
  217407. private:
  217408. String parentDir, wildCard;
  217409. const char* wildcardUTF8;
  217410. DIR* dir;
  217411. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  217412. };
  217413. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217414. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217415. {
  217416. }
  217417. DirectoryIterator::NativeIterator::~NativeIterator()
  217418. {
  217419. }
  217420. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217421. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217422. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217423. {
  217424. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217425. }
  217426. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217427. {
  217428. String cmdString (fileName.replace (" ", "\\ ",false));
  217429. cmdString << " " << parameters;
  217430. if (URL::isProbablyAWebsiteURL (fileName)
  217431. || cmdString.startsWithIgnoreCase ("file:")
  217432. || URL::isProbablyAnEmailAddress (fileName))
  217433. {
  217434. // create a command that tries to launch a bunch of likely browsers
  217435. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217436. StringArray cmdLines;
  217437. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217438. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217439. cmdString = cmdLines.joinIntoString (" || ");
  217440. }
  217441. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217442. const int cpid = fork();
  217443. if (cpid == 0)
  217444. {
  217445. setsid();
  217446. // Child process
  217447. execve (argv[0], (char**) argv, environ);
  217448. exit (0);
  217449. }
  217450. return cpid >= 0;
  217451. }
  217452. void File::revealToUser() const
  217453. {
  217454. if (isDirectory())
  217455. startAsProcess();
  217456. else if (getParentDirectory().exists())
  217457. getParentDirectory().startAsProcess();
  217458. }
  217459. #endif
  217460. /*** End of inlined file: juce_linux_Files.cpp ***/
  217461. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217462. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217463. // compiled on its own).
  217464. #if JUCE_INCLUDED_FILE
  217465. struct NamedPipeInternal
  217466. {
  217467. String pipeInName, pipeOutName;
  217468. int pipeIn, pipeOut;
  217469. bool volatile createdPipe, blocked, stopReadOperation;
  217470. static void signalHandler (int) {}
  217471. };
  217472. void NamedPipe::cancelPendingReads()
  217473. {
  217474. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217475. {
  217476. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217477. intern->stopReadOperation = true;
  217478. char buffer [1] = { 0 };
  217479. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217480. (void) bytesWritten;
  217481. int timeout = 2000;
  217482. while (intern->blocked && --timeout >= 0)
  217483. Thread::sleep (2);
  217484. intern->stopReadOperation = false;
  217485. }
  217486. }
  217487. void NamedPipe::close()
  217488. {
  217489. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217490. if (intern != 0)
  217491. {
  217492. internal = 0;
  217493. if (intern->pipeIn != -1)
  217494. ::close (intern->pipeIn);
  217495. if (intern->pipeOut != -1)
  217496. ::close (intern->pipeOut);
  217497. if (intern->createdPipe)
  217498. {
  217499. unlink (intern->pipeInName.toUTF8());
  217500. unlink (intern->pipeOutName.toUTF8());
  217501. }
  217502. delete intern;
  217503. }
  217504. }
  217505. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217506. {
  217507. close();
  217508. NamedPipeInternal* const intern = new NamedPipeInternal();
  217509. internal = intern;
  217510. intern->createdPipe = createPipe;
  217511. intern->blocked = false;
  217512. intern->stopReadOperation = false;
  217513. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217514. siginterrupt (SIGPIPE, 1);
  217515. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217516. intern->pipeInName = pipePath + "_in";
  217517. intern->pipeOutName = pipePath + "_out";
  217518. intern->pipeIn = -1;
  217519. intern->pipeOut = -1;
  217520. if (createPipe)
  217521. {
  217522. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217523. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217524. {
  217525. delete intern;
  217526. internal = 0;
  217527. return false;
  217528. }
  217529. }
  217530. return true;
  217531. }
  217532. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217533. {
  217534. int bytesRead = -1;
  217535. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217536. if (intern != 0)
  217537. {
  217538. intern->blocked = true;
  217539. if (intern->pipeIn == -1)
  217540. {
  217541. if (intern->createdPipe)
  217542. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217543. else
  217544. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217545. if (intern->pipeIn == -1)
  217546. {
  217547. intern->blocked = false;
  217548. return -1;
  217549. }
  217550. }
  217551. bytesRead = 0;
  217552. char* p = static_cast<char*> (destBuffer);
  217553. while (bytesRead < maxBytesToRead)
  217554. {
  217555. const int bytesThisTime = maxBytesToRead - bytesRead;
  217556. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217557. if (numRead <= 0 || intern->stopReadOperation)
  217558. {
  217559. bytesRead = -1;
  217560. break;
  217561. }
  217562. bytesRead += numRead;
  217563. p += bytesRead;
  217564. }
  217565. intern->blocked = false;
  217566. }
  217567. return bytesRead;
  217568. }
  217569. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217570. {
  217571. int bytesWritten = -1;
  217572. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217573. if (intern != 0)
  217574. {
  217575. if (intern->pipeOut == -1)
  217576. {
  217577. if (intern->createdPipe)
  217578. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217579. else
  217580. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217581. if (intern->pipeOut == -1)
  217582. {
  217583. return -1;
  217584. }
  217585. }
  217586. const char* p = static_cast<const char*> (sourceBuffer);
  217587. bytesWritten = 0;
  217588. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217589. while (bytesWritten < numBytesToWrite
  217590. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217591. {
  217592. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217593. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217594. if (numWritten <= 0)
  217595. {
  217596. bytesWritten = -1;
  217597. break;
  217598. }
  217599. bytesWritten += numWritten;
  217600. p += bytesWritten;
  217601. }
  217602. }
  217603. return bytesWritten;
  217604. }
  217605. #endif
  217606. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217607. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217608. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217609. // compiled on its own).
  217610. #if JUCE_INCLUDED_FILE
  217611. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  217612. {
  217613. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217614. if (s != -1)
  217615. {
  217616. char buf [1024];
  217617. struct ifconf ifc;
  217618. ifc.ifc_len = sizeof (buf);
  217619. ifc.ifc_buf = buf;
  217620. ioctl (s, SIOCGIFCONF, &ifc);
  217621. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217622. {
  217623. struct ifreq ifr;
  217624. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217625. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217626. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217627. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  217628. {
  217629. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  217630. }
  217631. }
  217632. close (s);
  217633. }
  217634. }
  217635. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217636. const String& emailSubject,
  217637. const String& bodyText,
  217638. const StringArray& filesToAttach)
  217639. {
  217640. jassertfalse; // xxx todo
  217641. return false;
  217642. }
  217643. class WebInputStream : public InputStream
  217644. {
  217645. public:
  217646. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  217647. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217648. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  217649. : socketHandle (-1), levelsOfRedirection (0),
  217650. address (address_), headers (headers_), postData (postData_), position (0),
  217651. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  217652. {
  217653. createConnection (progressCallback, progressCallbackContext);
  217654. if (responseHeaders != 0 && ! isError())
  217655. {
  217656. for (int i = 0; i < headerLines.size(); ++i)
  217657. {
  217658. const String& headersEntry = headerLines[i];
  217659. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217660. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217661. const String previousValue ((*responseHeaders) [key]);
  217662. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217663. }
  217664. }
  217665. }
  217666. ~WebInputStream()
  217667. {
  217668. closeSocket();
  217669. }
  217670. bool isError() const { return socketHandle < 0; }
  217671. bool isExhausted() { return finished; }
  217672. int64 getPosition() { return position; }
  217673. int64 getTotalLength()
  217674. {
  217675. jassertfalse; //xxx to do
  217676. return -1;
  217677. }
  217678. int read (void* buffer, int bytesToRead)
  217679. {
  217680. if (finished || isError())
  217681. return 0;
  217682. fd_set readbits;
  217683. FD_ZERO (&readbits);
  217684. FD_SET (socketHandle, &readbits);
  217685. struct timeval tv;
  217686. tv.tv_sec = jmax (1, timeOutMs / 1000);
  217687. tv.tv_usec = 0;
  217688. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217689. return 0; // (timeout)
  217690. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  217691. if (bytesRead == 0)
  217692. finished = true;
  217693. position += bytesRead;
  217694. return bytesRead;
  217695. }
  217696. bool setPosition (int64 wantedPos)
  217697. {
  217698. if (isError())
  217699. return false;
  217700. if (wantedPos != position)
  217701. {
  217702. finished = false;
  217703. if (wantedPos < position)
  217704. {
  217705. closeSocket();
  217706. position = 0;
  217707. createConnection (0, 0);
  217708. }
  217709. skipNextBytes (wantedPos - position);
  217710. }
  217711. return true;
  217712. }
  217713. private:
  217714. int socketHandle, levelsOfRedirection;
  217715. StringArray headerLines;
  217716. String address, headers;
  217717. MemoryBlock postData;
  217718. int64 position;
  217719. bool finished;
  217720. const bool isPost;
  217721. const int timeOutMs;
  217722. void closeSocket()
  217723. {
  217724. if (socketHandle >= 0)
  217725. close (socketHandle);
  217726. socketHandle = -1;
  217727. levelsOfRedirection = 0;
  217728. }
  217729. void createConnection (URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217730. {
  217731. closeSocket();
  217732. uint32 timeOutTime = Time::getMillisecondCounter();
  217733. if (timeOutMs == 0)
  217734. timeOutTime += 60000;
  217735. else if (timeOutMs < 0)
  217736. timeOutTime = 0xffffffff;
  217737. else
  217738. timeOutTime += timeOutMs;
  217739. String hostName, hostPath;
  217740. int hostPort;
  217741. if (! decomposeURL (address, hostName, hostPath, hostPort))
  217742. return;
  217743. const struct hostent* host = 0;
  217744. int port = 0;
  217745. String proxyName, proxyPath;
  217746. int proxyPort = 0;
  217747. String proxyURL (getenv ("http_proxy"));
  217748. if (proxyURL.startsWithIgnoreCase ("http://"))
  217749. {
  217750. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  217751. return;
  217752. host = gethostbyname (proxyName.toUTF8());
  217753. port = proxyPort;
  217754. }
  217755. else
  217756. {
  217757. host = gethostbyname (hostName.toUTF8());
  217758. port = hostPort;
  217759. }
  217760. if (host == 0)
  217761. return;
  217762. {
  217763. struct sockaddr_in socketAddress;
  217764. zerostruct (socketAddress);
  217765. memcpy (&socketAddress.sin_addr, host->h_addr, host->h_length);
  217766. socketAddress.sin_family = host->h_addrtype;
  217767. socketAddress.sin_port = htons (port);
  217768. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  217769. if (socketHandle == -1)
  217770. return;
  217771. int receiveBufferSize = 16384;
  217772. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  217773. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  217774. #if JUCE_MAC
  217775. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  217776. #endif
  217777. if (connect (socketHandle, (struct sockaddr*) &socketAddress, sizeof (socketAddress)) == -1)
  217778. {
  217779. closeSocket();
  217780. return;
  217781. }
  217782. }
  217783. {
  217784. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  217785. hostPath, address, headers, postData, isPost));
  217786. if (! sendHeader (socketHandle, requestHeader, timeOutTime, progressCallback, progressCallbackContext))
  217787. {
  217788. closeSocket();
  217789. return;
  217790. }
  217791. }
  217792. const String responseHeader (readResponse (socketHandle, timeOutTime));
  217793. if (responseHeader.isNotEmpty())
  217794. {
  217795. headerLines.clear();
  217796. headerLines.addLines (responseHeader);
  217797. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  217798. .substring (0, 3).getIntValue();
  217799. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  217800. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  217801. String location (findHeaderItem (headerLines, "Location:"));
  217802. if (statusCode >= 300 && statusCode < 400 && location.isNotEmpty())
  217803. {
  217804. if (! location.startsWithIgnoreCase ("http://"))
  217805. location = "http://" + location;
  217806. if (++levelsOfRedirection <= 3)
  217807. {
  217808. address = location;
  217809. createConnection (progressCallback, progressCallbackContext);
  217810. return;
  217811. }
  217812. }
  217813. else
  217814. {
  217815. levelsOfRedirection = 0;
  217816. return;
  217817. }
  217818. }
  217819. closeSocket();
  217820. }
  217821. static const String readResponse (const int socketHandle, const uint32 timeOutTime)
  217822. {
  217823. int bytesRead = 0, numConsecutiveLFs = 0;
  217824. MemoryBlock buffer (1024, true);
  217825. while (numConsecutiveLFs < 2 && bytesRead < 32768
  217826. && Time::getMillisecondCounter() <= timeOutTime)
  217827. {
  217828. fd_set readbits;
  217829. FD_ZERO (&readbits);
  217830. FD_SET (socketHandle, &readbits);
  217831. struct timeval tv;
  217832. tv.tv_sec = jmax (1, (int) (timeOutTime - Time::getMillisecondCounter()) / 1000);
  217833. tv.tv_usec = 0;
  217834. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217835. return String::empty; // (timeout)
  217836. buffer.ensureSize (bytesRead + 8, true);
  217837. char* const dest = (char*) buffer.getData() + bytesRead;
  217838. if (recv (socketHandle, dest, 1, 0) == -1)
  217839. return String::empty;
  217840. const char lastByte = *dest;
  217841. ++bytesRead;
  217842. if (lastByte == '\n')
  217843. ++numConsecutiveLFs;
  217844. else if (lastByte != '\r')
  217845. numConsecutiveLFs = 0;
  217846. }
  217847. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  217848. if (header.startsWithIgnoreCase ("HTTP/"))
  217849. return header.trimEnd();
  217850. return String::empty;
  217851. }
  217852. static const MemoryBlock createRequestHeader (const String& hostName, const int hostPort,
  217853. const String& proxyName, const int proxyPort,
  217854. const String& hostPath, const String& originalURL,
  217855. const String& headers, const MemoryBlock& postData,
  217856. const bool isPost)
  217857. {
  217858. String header (isPost ? "POST " : "GET ");
  217859. if (proxyName.isEmpty())
  217860. {
  217861. header << hostPath << " HTTP/1.0\r\nHost: "
  217862. << hostName << ':' << hostPort;
  217863. }
  217864. else
  217865. {
  217866. header << originalURL << " HTTP/1.0\r\nHost: "
  217867. << proxyName << ':' << proxyPort;
  217868. }
  217869. header << "\r\nUser-Agent: JUCE/" << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  217870. << "\r\nConnection: Close\r\nContent-Length: "
  217871. << postData.getSize() << "\r\n"
  217872. << headers << "\r\n";
  217873. MemoryBlock mb;
  217874. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  217875. mb.append (postData.getData(), postData.getSize());
  217876. return mb;
  217877. }
  217878. static bool sendHeader (int socketHandle, const MemoryBlock& requestHeader, const uint32 timeOutTime,
  217879. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217880. {
  217881. size_t totalHeaderSent = 0;
  217882. while (totalHeaderSent < requestHeader.getSize())
  217883. {
  217884. if (Time::getMillisecondCounter() > timeOutTime)
  217885. return false;
  217886. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  217887. if (send (socketHandle, static_cast <const char*> (requestHeader.getData()) + totalHeaderSent, numToSend, 0) != numToSend)
  217888. return false;
  217889. totalHeaderSent += numToSend;
  217890. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, totalHeaderSent, requestHeader.getSize()))
  217891. return false;
  217892. }
  217893. return true;
  217894. }
  217895. static bool decomposeURL (const String& url, String& host, String& path, int& port)
  217896. {
  217897. if (! url.startsWithIgnoreCase ("http://"))
  217898. return false;
  217899. const int nextSlash = url.indexOfChar (7, '/');
  217900. int nextColon = url.indexOfChar (7, ':');
  217901. if (nextColon > nextSlash && nextSlash > 0)
  217902. nextColon = -1;
  217903. if (nextColon >= 0)
  217904. {
  217905. host = url.substring (7, nextColon);
  217906. if (nextSlash >= 0)
  217907. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  217908. else
  217909. port = url.substring (nextColon + 1).getIntValue();
  217910. }
  217911. else
  217912. {
  217913. port = 80;
  217914. if (nextSlash >= 0)
  217915. host = url.substring (7, nextSlash);
  217916. else
  217917. host = url.substring (7);
  217918. }
  217919. if (nextSlash >= 0)
  217920. path = url.substring (nextSlash);
  217921. else
  217922. path = "/";
  217923. return true;
  217924. }
  217925. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  217926. {
  217927. for (int i = 0; i < lines.size(); ++i)
  217928. if (lines[i].startsWithIgnoreCase (itemName))
  217929. return lines[i].substring (itemName.length()).trim();
  217930. return String::empty;
  217931. }
  217932. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  217933. };
  217934. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  217935. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217936. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  217937. {
  217938. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  217939. progressCallback, progressCallbackContext,
  217940. headers, timeOutMs, responseHeaders));
  217941. return wi->isError() ? 0 : wi.release();
  217942. }
  217943. #endif
  217944. /*** End of inlined file: juce_linux_Network.cpp ***/
  217945. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217946. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217947. // compiled on its own).
  217948. #if JUCE_INCLUDED_FILE
  217949. void Logger::outputDebugString (const String& text)
  217950. {
  217951. std::cerr << text << std::endl;
  217952. }
  217953. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217954. {
  217955. return Linux;
  217956. }
  217957. const String SystemStats::getOperatingSystemName()
  217958. {
  217959. return "Linux";
  217960. }
  217961. bool SystemStats::isOperatingSystem64Bit()
  217962. {
  217963. #if JUCE_64BIT
  217964. return true;
  217965. #else
  217966. //xxx not sure how to find this out?..
  217967. return false;
  217968. #endif
  217969. }
  217970. namespace LinuxStatsHelpers
  217971. {
  217972. const String getCpuInfo (const char* const key)
  217973. {
  217974. StringArray lines;
  217975. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217976. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217977. if (lines[i].startsWithIgnoreCase (key))
  217978. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217979. return String::empty;
  217980. }
  217981. }
  217982. const String SystemStats::getCpuVendor()
  217983. {
  217984. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  217985. }
  217986. int SystemStats::getCpuSpeedInMegaherz()
  217987. {
  217988. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  217989. }
  217990. int SystemStats::getMemorySizeInMegabytes()
  217991. {
  217992. struct sysinfo sysi;
  217993. if (sysinfo (&sysi) == 0)
  217994. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  217995. return 0;
  217996. }
  217997. int SystemStats::getPageSize()
  217998. {
  217999. return sysconf (_SC_PAGESIZE);
  218000. }
  218001. const String SystemStats::getLogonName()
  218002. {
  218003. const char* user = getenv ("USER");
  218004. if (user == 0)
  218005. {
  218006. struct passwd* const pw = getpwuid (getuid());
  218007. if (pw != 0)
  218008. user = pw->pw_name;
  218009. }
  218010. return String::fromUTF8 (user);
  218011. }
  218012. const String SystemStats::getFullUserName()
  218013. {
  218014. return getLogonName();
  218015. }
  218016. void SystemStats::initialiseStats()
  218017. {
  218018. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  218019. cpuFlags.hasMMX = flags.contains ("mmx");
  218020. cpuFlags.hasSSE = flags.contains ("sse");
  218021. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218022. cpuFlags.has3DNow = flags.contains ("3dnow");
  218023. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  218024. }
  218025. void PlatformUtilities::fpuReset()
  218026. {
  218027. }
  218028. uint32 juce_millisecondsSinceStartup() throw()
  218029. {
  218030. timespec t;
  218031. clock_gettime (CLOCK_MONOTONIC, &t);
  218032. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  218033. }
  218034. int64 Time::getHighResolutionTicks() throw()
  218035. {
  218036. timespec t;
  218037. clock_gettime (CLOCK_MONOTONIC, &t);
  218038. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  218039. }
  218040. int64 Time::getHighResolutionTicksPerSecond() throw()
  218041. {
  218042. return 1000000; // (microseconds)
  218043. }
  218044. double Time::getMillisecondCounterHiRes() throw()
  218045. {
  218046. return getHighResolutionTicks() * 0.001;
  218047. }
  218048. bool Time::setSystemTimeToThisTime() const
  218049. {
  218050. timeval t;
  218051. t.tv_sec = millisSinceEpoch / 1000;
  218052. t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
  218053. return settimeofday (&t, 0) == 0;
  218054. }
  218055. #endif
  218056. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218057. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218058. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218059. // compiled on its own).
  218060. #if JUCE_INCLUDED_FILE
  218061. /*
  218062. Note that a lot of methods that you'd expect to find in this file actually
  218063. live in juce_posix_SharedCode.h!
  218064. */
  218065. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218066. void Process::setPriority (ProcessPriority prior)
  218067. {
  218068. struct sched_param param;
  218069. int policy, maxp, minp;
  218070. const int p = (int) prior;
  218071. if (p <= 1)
  218072. policy = SCHED_OTHER;
  218073. else
  218074. policy = SCHED_RR;
  218075. minp = sched_get_priority_min (policy);
  218076. maxp = sched_get_priority_max (policy);
  218077. if (p < 2)
  218078. param.sched_priority = 0;
  218079. else if (p == 2 )
  218080. // Set to middle of lower realtime priority range
  218081. param.sched_priority = minp + (maxp - minp) / 4;
  218082. else
  218083. // Set to middle of higher realtime priority range
  218084. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218085. pthread_setschedparam (pthread_self(), policy, &param);
  218086. }
  218087. void Process::terminate()
  218088. {
  218089. exit (0);
  218090. }
  218091. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  218092. {
  218093. static char testResult = 0;
  218094. if (testResult == 0)
  218095. {
  218096. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218097. if (testResult >= 0)
  218098. {
  218099. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218100. testResult = 1;
  218101. }
  218102. }
  218103. return testResult < 0;
  218104. }
  218105. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218106. {
  218107. return juce_isRunningUnderDebugger();
  218108. }
  218109. void Process::raisePrivilege()
  218110. {
  218111. // If running suid root, change effective user
  218112. // to root
  218113. if (geteuid() != 0 && getuid() == 0)
  218114. {
  218115. setreuid (geteuid(), getuid());
  218116. setregid (getegid(), getgid());
  218117. }
  218118. }
  218119. void Process::lowerPrivilege()
  218120. {
  218121. // If runing suid root, change effective user
  218122. // back to real user
  218123. if (geteuid() == 0 && getuid() != 0)
  218124. {
  218125. setreuid (geteuid(), getuid());
  218126. setregid (getegid(), getgid());
  218127. }
  218128. }
  218129. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218130. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218131. {
  218132. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218133. }
  218134. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218135. {
  218136. dlclose(handle);
  218137. }
  218138. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218139. {
  218140. return dlsym (libraryHandle, procedureName.toCString());
  218141. }
  218142. #endif
  218143. #endif
  218144. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218145. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218146. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218147. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218148. // compiled on its own).
  218149. #if JUCE_INCLUDED_FILE
  218150. extern Display* display;
  218151. extern Window juce_messageWindowHandle;
  218152. namespace ClipboardHelpers
  218153. {
  218154. static String localClipboardContent;
  218155. static Atom atom_UTF8_STRING;
  218156. static Atom atom_CLIPBOARD;
  218157. static Atom atom_TARGETS;
  218158. static void initSelectionAtoms()
  218159. {
  218160. static bool isInitialised = false;
  218161. if (! isInitialised)
  218162. {
  218163. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218164. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218165. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218166. }
  218167. }
  218168. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218169. // works only for strings shorter than 1000000 bytes
  218170. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218171. {
  218172. String returnData;
  218173. char* clipData;
  218174. Atom actualType;
  218175. int actualFormat;
  218176. unsigned long numItems, bytesLeft;
  218177. if (XGetWindowProperty (display, window, prop,
  218178. 0L /* offset */, 1000000 /* length (max) */, False,
  218179. AnyPropertyType /* format */,
  218180. &actualType, &actualFormat, &numItems, &bytesLeft,
  218181. (unsigned char**) &clipData) == Success)
  218182. {
  218183. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218184. returnData = String::fromUTF8 (clipData, numItems);
  218185. else if (actualType == XA_STRING && actualFormat == 8)
  218186. returnData = String (clipData, numItems);
  218187. if (clipData != 0)
  218188. XFree (clipData);
  218189. jassert (bytesLeft == 0 || numItems == 1000000);
  218190. }
  218191. XDeleteProperty (display, window, prop);
  218192. return returnData;
  218193. }
  218194. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218195. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218196. {
  218197. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218198. // The selection owner will be asked to set the JUCE_SEL property on the
  218199. // juce_messageWindowHandle with the selection content
  218200. XConvertSelection (display, selection, requestedFormat, property_name,
  218201. juce_messageWindowHandle, CurrentTime);
  218202. int count = 50; // will wait at most for 200 ms
  218203. while (--count >= 0)
  218204. {
  218205. XEvent event;
  218206. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218207. {
  218208. if (event.xselection.property == property_name)
  218209. {
  218210. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218211. selectionContent = readWindowProperty (event.xselection.requestor,
  218212. event.xselection.property,
  218213. requestedFormat);
  218214. return true;
  218215. }
  218216. else
  218217. {
  218218. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218219. }
  218220. }
  218221. // not very elegant.. we could do a select() or something like that...
  218222. // however clipboard content requesting is inherently slow on x11, it
  218223. // often takes 50ms or more so...
  218224. Thread::sleep (4);
  218225. }
  218226. return false;
  218227. }
  218228. }
  218229. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218230. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218231. {
  218232. ClipboardHelpers::initSelectionAtoms();
  218233. // the selection content is sent to the target window as a window property
  218234. XSelectionEvent reply;
  218235. reply.type = SelectionNotify;
  218236. reply.display = evt.display;
  218237. reply.requestor = evt.requestor;
  218238. reply.selection = evt.selection;
  218239. reply.target = evt.target;
  218240. reply.property = None; // == "fail"
  218241. reply.time = evt.time;
  218242. HeapBlock <char> data;
  218243. int propertyFormat = 0, numDataItems = 0;
  218244. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218245. {
  218246. if (evt.target == XA_STRING)
  218247. {
  218248. // format data according to system locale
  218249. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218250. data.calloc (numDataItems + 1);
  218251. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218252. propertyFormat = 8; // bits/item
  218253. }
  218254. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218255. {
  218256. // translate to utf8
  218257. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218258. data.calloc (numDataItems + 1);
  218259. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218260. propertyFormat = 8; // bits/item
  218261. }
  218262. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218263. {
  218264. // another application wants to know what we are able to send
  218265. numDataItems = 2;
  218266. propertyFormat = 32; // atoms are 32-bit
  218267. data.calloc (numDataItems * 4);
  218268. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218269. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218270. atoms[1] = XA_STRING;
  218271. }
  218272. }
  218273. else
  218274. {
  218275. DBG ("requested unsupported clipboard");
  218276. }
  218277. if (data != 0)
  218278. {
  218279. const int maxReasonableSelectionSize = 1000000;
  218280. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218281. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218282. {
  218283. XChangeProperty (evt.display, evt.requestor,
  218284. evt.property, evt.target,
  218285. propertyFormat /* 8 or 32 */, PropModeReplace,
  218286. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218287. reply.property = evt.property; // " == success"
  218288. }
  218289. }
  218290. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218291. }
  218292. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218293. {
  218294. ClipboardHelpers::initSelectionAtoms();
  218295. ClipboardHelpers::localClipboardContent = clipText;
  218296. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218297. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218298. }
  218299. const String SystemClipboard::getTextFromClipboard()
  218300. {
  218301. ClipboardHelpers::initSelectionAtoms();
  218302. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218303. level" clipboard that is supposed to be filled by ctrl-C
  218304. etc). When a clipboard manager is running, the content of this
  218305. selection is preserved even when the original selection owner
  218306. exits.
  218307. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218308. filled by good old x11 apps such as xterm)
  218309. */
  218310. String content;
  218311. Atom selection = XA_PRIMARY;
  218312. Window selectionOwner = None;
  218313. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218314. {
  218315. selection = ClipboardHelpers::atom_CLIPBOARD;
  218316. selectionOwner = XGetSelectionOwner (display, selection);
  218317. }
  218318. if (selectionOwner != None)
  218319. {
  218320. if (selectionOwner == juce_messageWindowHandle)
  218321. {
  218322. content = ClipboardHelpers::localClipboardContent;
  218323. }
  218324. else
  218325. {
  218326. // first try: we want an utf8 string
  218327. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218328. if (! ok)
  218329. {
  218330. // second chance, ask for a good old locale-dependent string ..
  218331. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218332. }
  218333. }
  218334. }
  218335. return content;
  218336. }
  218337. #endif
  218338. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218339. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218340. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218341. // compiled on its own).
  218342. #if JUCE_INCLUDED_FILE
  218343. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218344. #define JUCE_DEBUG_XERRORS 1
  218345. #endif
  218346. Display* display = 0;
  218347. Window juce_messageWindowHandle = None;
  218348. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218349. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218350. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218351. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218352. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218353. class InternalMessageQueue
  218354. {
  218355. public:
  218356. InternalMessageQueue()
  218357. : bytesInSocket (0),
  218358. totalEventCount (0)
  218359. {
  218360. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218361. (void) ret; jassert (ret == 0);
  218362. //setNonBlocking (fd[0]);
  218363. //setNonBlocking (fd[1]);
  218364. }
  218365. ~InternalMessageQueue()
  218366. {
  218367. close (fd[0]);
  218368. close (fd[1]);
  218369. clearSingletonInstance();
  218370. }
  218371. void postMessage (Message* msg)
  218372. {
  218373. const int maxBytesInSocketQueue = 128;
  218374. ScopedLock sl (lock);
  218375. queue.add (msg);
  218376. if (bytesInSocket < maxBytesInSocketQueue)
  218377. {
  218378. ++bytesInSocket;
  218379. ScopedUnlock ul (lock);
  218380. const unsigned char x = 0xff;
  218381. size_t bytesWritten = write (fd[0], &x, 1);
  218382. (void) bytesWritten;
  218383. }
  218384. }
  218385. bool isEmpty() const
  218386. {
  218387. ScopedLock sl (lock);
  218388. return queue.size() == 0;
  218389. }
  218390. bool dispatchNextEvent()
  218391. {
  218392. // This alternates between giving priority to XEvents or internal messages,
  218393. // to keep everything running smoothly..
  218394. if ((++totalEventCount & 1) != 0)
  218395. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218396. else
  218397. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218398. }
  218399. // Wait for an event (either XEvent, or an internal Message)
  218400. bool sleepUntilEvent (const int timeoutMs)
  218401. {
  218402. if (! isEmpty())
  218403. return true;
  218404. if (display != 0)
  218405. {
  218406. ScopedXLock xlock;
  218407. if (XPending (display))
  218408. return true;
  218409. }
  218410. struct timeval tv;
  218411. tv.tv_sec = 0;
  218412. tv.tv_usec = timeoutMs * 1000;
  218413. int fd0 = getWaitHandle();
  218414. int fdmax = fd0;
  218415. fd_set readset;
  218416. FD_ZERO (&readset);
  218417. FD_SET (fd0, &readset);
  218418. if (display != 0)
  218419. {
  218420. ScopedXLock xlock;
  218421. int fd1 = XConnectionNumber (display);
  218422. FD_SET (fd1, &readset);
  218423. fdmax = jmax (fd0, fd1);
  218424. }
  218425. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218426. return (ret > 0); // ret <= 0 if error or timeout
  218427. }
  218428. struct MessageThreadFuncCall
  218429. {
  218430. enum { uniqueID = 0x73774623 };
  218431. MessageCallbackFunction* func;
  218432. void* parameter;
  218433. void* result;
  218434. CriticalSection lock;
  218435. WaitableEvent event;
  218436. };
  218437. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218438. private:
  218439. CriticalSection lock;
  218440. ReferenceCountedArray <Message> queue;
  218441. int fd[2];
  218442. int bytesInSocket;
  218443. int totalEventCount;
  218444. int getWaitHandle() const throw() { return fd[1]; }
  218445. static bool setNonBlocking (int handle)
  218446. {
  218447. int socketFlags = fcntl (handle, F_GETFL, 0);
  218448. if (socketFlags == -1)
  218449. return false;
  218450. socketFlags |= O_NONBLOCK;
  218451. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218452. }
  218453. static bool dispatchNextXEvent()
  218454. {
  218455. if (display == 0)
  218456. return false;
  218457. XEvent evt;
  218458. {
  218459. ScopedXLock xlock;
  218460. if (! XPending (display))
  218461. return false;
  218462. XNextEvent (display, &evt);
  218463. }
  218464. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218465. juce_handleSelectionRequest (evt.xselectionrequest);
  218466. else if (evt.xany.window != juce_messageWindowHandle)
  218467. juce_windowMessageReceive (&evt);
  218468. return true;
  218469. }
  218470. const Message::Ptr popNextMessage()
  218471. {
  218472. const ScopedLock sl (lock);
  218473. if (bytesInSocket > 0)
  218474. {
  218475. --bytesInSocket;
  218476. const ScopedUnlock ul (lock);
  218477. unsigned char x;
  218478. size_t numBytes = read (fd[1], &x, 1);
  218479. (void) numBytes;
  218480. }
  218481. return queue.removeAndReturn (0);
  218482. }
  218483. bool dispatchNextInternalMessage()
  218484. {
  218485. const Message::Ptr msg (popNextMessage());
  218486. if (msg == 0)
  218487. return false;
  218488. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218489. {
  218490. // Handle callback message
  218491. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218492. call->result = (*(call->func)) (call->parameter);
  218493. call->event.signal();
  218494. }
  218495. else
  218496. {
  218497. // Handle "normal" messages
  218498. MessageManager::getInstance()->deliverMessage (msg);
  218499. }
  218500. return true;
  218501. }
  218502. };
  218503. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218504. namespace LinuxErrorHandling
  218505. {
  218506. static bool errorOccurred = false;
  218507. static bool keyboardBreakOccurred = false;
  218508. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218509. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218510. // Usually happens when client-server connection is broken
  218511. static int ioErrorHandler (Display* display)
  218512. {
  218513. DBG ("ERROR: connection to X server broken.. terminating.");
  218514. if (JUCEApplication::isStandaloneApp())
  218515. MessageManager::getInstance()->stopDispatchLoop();
  218516. errorOccurred = true;
  218517. return 0;
  218518. }
  218519. // A protocol error has occurred
  218520. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218521. {
  218522. #if JUCE_DEBUG_XERRORS
  218523. char errorStr[64] = { 0 };
  218524. char requestStr[64] = { 0 };
  218525. XGetErrorText (display, event->error_code, errorStr, 64);
  218526. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218527. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218528. #endif
  218529. return 0;
  218530. }
  218531. static void installXErrorHandlers()
  218532. {
  218533. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218534. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218535. }
  218536. static void removeXErrorHandlers()
  218537. {
  218538. if (JUCEApplication::isStandaloneApp())
  218539. {
  218540. XSetIOErrorHandler (oldIOErrorHandler);
  218541. oldIOErrorHandler = 0;
  218542. XSetErrorHandler (oldErrorHandler);
  218543. oldErrorHandler = 0;
  218544. }
  218545. }
  218546. static void keyboardBreakSignalHandler (int sig)
  218547. {
  218548. if (sig == SIGINT)
  218549. keyboardBreakOccurred = true;
  218550. }
  218551. static void installKeyboardBreakHandler()
  218552. {
  218553. struct sigaction saction;
  218554. sigset_t maskSet;
  218555. sigemptyset (&maskSet);
  218556. saction.sa_handler = keyboardBreakSignalHandler;
  218557. saction.sa_mask = maskSet;
  218558. saction.sa_flags = 0;
  218559. sigaction (SIGINT, &saction, 0);
  218560. }
  218561. }
  218562. void MessageManager::doPlatformSpecificInitialisation()
  218563. {
  218564. if (JUCEApplication::isStandaloneApp())
  218565. {
  218566. // Initialise xlib for multiple thread support
  218567. static bool initThreadCalled = false;
  218568. if (! initThreadCalled)
  218569. {
  218570. if (! XInitThreads())
  218571. {
  218572. // This is fatal! Print error and closedown
  218573. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218574. Process::terminate();
  218575. return;
  218576. }
  218577. initThreadCalled = true;
  218578. }
  218579. LinuxErrorHandling::installXErrorHandlers();
  218580. LinuxErrorHandling::installKeyboardBreakHandler();
  218581. }
  218582. // Create the internal message queue
  218583. InternalMessageQueue::getInstance();
  218584. // Try to connect to a display
  218585. String displayName (getenv ("DISPLAY"));
  218586. if (displayName.isEmpty())
  218587. displayName = ":0.0";
  218588. display = XOpenDisplay (displayName.toCString());
  218589. if (display != 0) // This is not fatal! we can run headless.
  218590. {
  218591. // Create a context to store user data associated with Windows we create in WindowDriver
  218592. windowHandleXContext = XUniqueContext();
  218593. // We're only interested in client messages for this window, which are always sent
  218594. XSetWindowAttributes swa;
  218595. swa.event_mask = NoEventMask;
  218596. // Create our message window (this will never be mapped)
  218597. const int screen = DefaultScreen (display);
  218598. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218599. 0, 0, 1, 1, 0, 0, InputOnly,
  218600. DefaultVisual (display, screen),
  218601. CWEventMask, &swa);
  218602. }
  218603. }
  218604. void MessageManager::doPlatformSpecificShutdown()
  218605. {
  218606. InternalMessageQueue::deleteInstance();
  218607. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218608. {
  218609. XDestroyWindow (display, juce_messageWindowHandle);
  218610. XCloseDisplay (display);
  218611. juce_messageWindowHandle = 0;
  218612. display = 0;
  218613. LinuxErrorHandling::removeXErrorHandlers();
  218614. }
  218615. }
  218616. bool juce_postMessageToSystemQueue (Message* message)
  218617. {
  218618. if (LinuxErrorHandling::errorOccurred)
  218619. return false;
  218620. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  218621. return true;
  218622. }
  218623. void MessageManager::broadcastMessage (const String& value)
  218624. {
  218625. /* TODO */
  218626. }
  218627. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  218628. {
  218629. if (LinuxErrorHandling::errorOccurred)
  218630. return 0;
  218631. if (isThisTheMessageThread())
  218632. return func (parameter);
  218633. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  218634. messageCallContext.func = func;
  218635. messageCallContext.parameter = parameter;
  218636. InternalMessageQueue::getInstanceWithoutCreating()
  218637. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  218638. 0, 0, &messageCallContext));
  218639. // Wait for it to complete before continuing
  218640. messageCallContext.event.wait();
  218641. return messageCallContext.result;
  218642. }
  218643. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  218644. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  218645. {
  218646. while (! LinuxErrorHandling::errorOccurred)
  218647. {
  218648. if (LinuxErrorHandling::keyboardBreakOccurred)
  218649. {
  218650. LinuxErrorHandling::errorOccurred = true;
  218651. if (JUCEApplication::isStandaloneApp())
  218652. Process::terminate();
  218653. break;
  218654. }
  218655. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  218656. return true;
  218657. if (returnIfNoPendingMessages)
  218658. break;
  218659. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  218660. }
  218661. return false;
  218662. }
  218663. #endif
  218664. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  218665. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  218666. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218667. // compiled on its own).
  218668. #if JUCE_INCLUDED_FILE
  218669. class FreeTypeFontFace
  218670. {
  218671. public:
  218672. enum FontStyle
  218673. {
  218674. Plain = 0,
  218675. Bold = 1,
  218676. Italic = 2
  218677. };
  218678. FreeTypeFontFace (const String& familyName)
  218679. : hasSerif (false),
  218680. monospaced (false)
  218681. {
  218682. family = familyName;
  218683. }
  218684. void setFileName (const String& name, const int faceIndex, FontStyle style)
  218685. {
  218686. if (names [(int) style].fileName.isEmpty())
  218687. {
  218688. names [(int) style].fileName = name;
  218689. names [(int) style].faceIndex = faceIndex;
  218690. }
  218691. }
  218692. const String& getFamilyName() const throw() { return family; }
  218693. const String& getFileName (const int style, int& faceIndex) const throw()
  218694. {
  218695. faceIndex = names[style].faceIndex;
  218696. return names[style].fileName;
  218697. }
  218698. void setMonospaced (bool mono) throw() { monospaced = mono; }
  218699. bool getMonospaced() const throw() { return monospaced; }
  218700. void setSerif (const bool serif) throw() { hasSerif = serif; }
  218701. bool getSerif() const throw() { return hasSerif; }
  218702. private:
  218703. String family;
  218704. struct FontNameIndex
  218705. {
  218706. String fileName;
  218707. int faceIndex;
  218708. };
  218709. FontNameIndex names[4];
  218710. bool hasSerif, monospaced;
  218711. };
  218712. class FreeTypeInterface : public DeletedAtShutdown
  218713. {
  218714. public:
  218715. FreeTypeInterface()
  218716. : ftLib (0),
  218717. lastFace (0),
  218718. lastBold (false),
  218719. lastItalic (false)
  218720. {
  218721. if (FT_Init_FreeType (&ftLib) != 0)
  218722. {
  218723. ftLib = 0;
  218724. DBG ("Failed to initialize FreeType");
  218725. }
  218726. StringArray fontDirs;
  218727. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  218728. fontDirs.removeEmptyStrings (true);
  218729. if (fontDirs.size() == 0)
  218730. {
  218731. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  218732. if (fontsInfo != 0)
  218733. {
  218734. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  218735. {
  218736. fontDirs.add (e->getAllSubText().trim());
  218737. }
  218738. }
  218739. }
  218740. if (fontDirs.size() == 0)
  218741. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  218742. for (int i = 0; i < fontDirs.size(); ++i)
  218743. enumerateFaces (fontDirs[i]);
  218744. }
  218745. ~FreeTypeInterface()
  218746. {
  218747. if (lastFace != 0)
  218748. FT_Done_Face (lastFace);
  218749. if (ftLib != 0)
  218750. FT_Done_FreeType (ftLib);
  218751. clearSingletonInstance();
  218752. }
  218753. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  218754. {
  218755. for (int i = 0; i < faces.size(); i++)
  218756. if (faces[i]->getFamilyName() == familyName)
  218757. return faces[i];
  218758. if (! create)
  218759. return 0;
  218760. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  218761. faces.add (newFace);
  218762. return newFace;
  218763. }
  218764. // Enumerate all font faces available in a given directory
  218765. void enumerateFaces (const String& path)
  218766. {
  218767. File dirPath (path);
  218768. if (path.isEmpty() || ! dirPath.isDirectory())
  218769. return;
  218770. DirectoryIterator di (dirPath, true);
  218771. while (di.next())
  218772. {
  218773. File possible (di.getFile());
  218774. if (possible.hasFileExtension ("ttf")
  218775. || possible.hasFileExtension ("pfb")
  218776. || possible.hasFileExtension ("pcf"))
  218777. {
  218778. FT_Face face;
  218779. int faceIndex = 0;
  218780. int numFaces = 0;
  218781. do
  218782. {
  218783. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  218784. faceIndex, &face) == 0)
  218785. {
  218786. if (faceIndex == 0)
  218787. numFaces = face->num_faces;
  218788. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  218789. {
  218790. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  218791. int style = (int) FreeTypeFontFace::Plain;
  218792. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  218793. style |= (int) FreeTypeFontFace::Bold;
  218794. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  218795. style |= (int) FreeTypeFontFace::Italic;
  218796. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  218797. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  218798. // Surely there must be a better way to do this?
  218799. const String name (face->family_name);
  218800. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  218801. || name.containsIgnoreCase ("Verdana")
  218802. || name.containsIgnoreCase ("Arial")));
  218803. }
  218804. FT_Done_Face (face);
  218805. }
  218806. ++faceIndex;
  218807. }
  218808. while (faceIndex < numFaces);
  218809. }
  218810. }
  218811. }
  218812. // Create a FreeType face object for a given font
  218813. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  218814. {
  218815. FT_Face face = 0;
  218816. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218817. {
  218818. face = lastFace;
  218819. }
  218820. else
  218821. {
  218822. if (lastFace != 0)
  218823. {
  218824. FT_Done_Face (lastFace);
  218825. lastFace = 0;
  218826. }
  218827. lastFontName = fontName;
  218828. lastBold = bold;
  218829. lastItalic = italic;
  218830. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218831. if (ftFace != 0)
  218832. {
  218833. int style = (int) FreeTypeFontFace::Plain;
  218834. if (bold)
  218835. style |= (int) FreeTypeFontFace::Bold;
  218836. if (italic)
  218837. style |= (int) FreeTypeFontFace::Italic;
  218838. int faceIndex;
  218839. String fileName (ftFace->getFileName (style, faceIndex));
  218840. if (fileName.isEmpty())
  218841. {
  218842. style ^= (int) FreeTypeFontFace::Bold;
  218843. fileName = ftFace->getFileName (style, faceIndex);
  218844. if (fileName.isEmpty())
  218845. {
  218846. style ^= (int) FreeTypeFontFace::Bold;
  218847. style ^= (int) FreeTypeFontFace::Italic;
  218848. fileName = ftFace->getFileName (style, faceIndex);
  218849. if (! fileName.length())
  218850. {
  218851. style ^= (int) FreeTypeFontFace::Bold;
  218852. fileName = ftFace->getFileName (style, faceIndex);
  218853. }
  218854. }
  218855. }
  218856. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218857. {
  218858. face = lastFace;
  218859. // If there isn't a unicode charmap then select the first one.
  218860. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218861. FT_Set_Charmap (face, face->charmaps[0]);
  218862. }
  218863. }
  218864. }
  218865. return face;
  218866. }
  218867. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218868. {
  218869. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218870. const float height = (float) (face->ascender - face->descender);
  218871. const float scaleX = 1.0f / height;
  218872. const float scaleY = -1.0f / height;
  218873. Path destShape;
  218874. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218875. || face->glyph->format != ft_glyph_format_outline)
  218876. {
  218877. return false;
  218878. }
  218879. const FT_Outline* const outline = &face->glyph->outline;
  218880. const short* const contours = outline->contours;
  218881. const char* const tags = outline->tags;
  218882. FT_Vector* const points = outline->points;
  218883. for (int c = 0; c < outline->n_contours; c++)
  218884. {
  218885. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218886. const int endPoint = contours[c];
  218887. for (int p = startPoint; p <= endPoint; p++)
  218888. {
  218889. const float x = scaleX * points[p].x;
  218890. const float y = scaleY * points[p].y;
  218891. if (p == startPoint)
  218892. {
  218893. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218894. {
  218895. float x2 = scaleX * points [endPoint].x;
  218896. float y2 = scaleY * points [endPoint].y;
  218897. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218898. {
  218899. x2 = (x + x2) * 0.5f;
  218900. y2 = (y + y2) * 0.5f;
  218901. }
  218902. destShape.startNewSubPath (x2, y2);
  218903. }
  218904. else
  218905. {
  218906. destShape.startNewSubPath (x, y);
  218907. }
  218908. }
  218909. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218910. {
  218911. if (p != startPoint)
  218912. destShape.lineTo (x, y);
  218913. }
  218914. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218915. {
  218916. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218917. float x2 = scaleX * points [nextIndex].x;
  218918. float y2 = scaleY * points [nextIndex].y;
  218919. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218920. {
  218921. x2 = (x + x2) * 0.5f;
  218922. y2 = (y + y2) * 0.5f;
  218923. }
  218924. else
  218925. {
  218926. ++p;
  218927. }
  218928. destShape.quadraticTo (x, y, x2, y2);
  218929. }
  218930. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218931. {
  218932. if (p >= endPoint)
  218933. return false;
  218934. const int next1 = p + 1;
  218935. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218936. const float x2 = scaleX * points [next1].x;
  218937. const float y2 = scaleY * points [next1].y;
  218938. const float x3 = scaleX * points [next2].x;
  218939. const float y3 = scaleY * points [next2].y;
  218940. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218941. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218942. return false;
  218943. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218944. p += 2;
  218945. }
  218946. }
  218947. destShape.closeSubPath();
  218948. }
  218949. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218950. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218951. addKerning (face, dest, character, glyphIndex);
  218952. return true;
  218953. }
  218954. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218955. {
  218956. const float height = (float) (face->ascender - face->descender);
  218957. uint32 rightGlyphIndex;
  218958. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218959. while (rightGlyphIndex != 0)
  218960. {
  218961. FT_Vector kerning;
  218962. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218963. {
  218964. if (kerning.x != 0)
  218965. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218966. }
  218967. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218968. }
  218969. }
  218970. // Add a glyph to a font
  218971. bool addGlyphToFont (const uint32 character, const String& fontName,
  218972. bool bold, bool italic, CustomTypeface& dest)
  218973. {
  218974. FT_Face face = createFT_Face (fontName, bold, italic);
  218975. return face != 0 && addGlyph (face, dest, character);
  218976. }
  218977. void getFamilyNames (StringArray& familyNames) const
  218978. {
  218979. for (int i = 0; i < faces.size(); i++)
  218980. familyNames.add (faces[i]->getFamilyName());
  218981. }
  218982. void getMonospacedNames (StringArray& monoSpaced) const
  218983. {
  218984. for (int i = 0; i < faces.size(); i++)
  218985. if (faces[i]->getMonospaced())
  218986. monoSpaced.add (faces[i]->getFamilyName());
  218987. }
  218988. void getSerifNames (StringArray& serif) const
  218989. {
  218990. for (int i = 0; i < faces.size(); i++)
  218991. if (faces[i]->getSerif())
  218992. serif.add (faces[i]->getFamilyName());
  218993. }
  218994. void getSansSerifNames (StringArray& sansSerif) const
  218995. {
  218996. for (int i = 0; i < faces.size(); i++)
  218997. if (! faces[i]->getSerif())
  218998. sansSerif.add (faces[i]->getFamilyName());
  218999. }
  219000. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219001. private:
  219002. FT_Library ftLib;
  219003. FT_Face lastFace;
  219004. String lastFontName;
  219005. bool lastBold, lastItalic;
  219006. OwnedArray<FreeTypeFontFace> faces;
  219007. };
  219008. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219009. class FreetypeTypeface : public CustomTypeface
  219010. {
  219011. public:
  219012. FreetypeTypeface (const Font& font)
  219013. {
  219014. FT_Face face = FreeTypeInterface::getInstance()
  219015. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219016. if (face == 0)
  219017. {
  219018. #if JUCE_DEBUG
  219019. String msg ("Failed to create typeface: ");
  219020. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219021. DBG (msg);
  219022. #endif
  219023. }
  219024. else
  219025. {
  219026. setCharacteristics (font.getTypefaceName(),
  219027. face->ascender / (float) (face->ascender - face->descender),
  219028. font.isBold(), font.isItalic(),
  219029. L' ');
  219030. }
  219031. }
  219032. bool loadGlyphIfPossible (juce_wchar character)
  219033. {
  219034. return FreeTypeInterface::getInstance()
  219035. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219036. }
  219037. };
  219038. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219039. {
  219040. return new FreetypeTypeface (font);
  219041. }
  219042. const StringArray Font::findAllTypefaceNames()
  219043. {
  219044. StringArray s;
  219045. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219046. s.sort (true);
  219047. return s;
  219048. }
  219049. namespace
  219050. {
  219051. const String pickBestFont (const StringArray& names,
  219052. const char* const choicesString)
  219053. {
  219054. StringArray choices;
  219055. choices.addTokens (String (choicesString), ",", String::empty);
  219056. choices.trim();
  219057. choices.removeEmptyStrings();
  219058. int i, j;
  219059. for (j = 0; j < choices.size(); ++j)
  219060. if (names.contains (choices[j], true))
  219061. return choices[j];
  219062. for (j = 0; j < choices.size(); ++j)
  219063. for (i = 0; i < names.size(); i++)
  219064. if (names[i].startsWithIgnoreCase (choices[j]))
  219065. return names[i];
  219066. for (j = 0; j < choices.size(); ++j)
  219067. for (i = 0; i < names.size(); i++)
  219068. if (names[i].containsIgnoreCase (choices[j]))
  219069. return names[i];
  219070. return names[0];
  219071. }
  219072. const String linux_getDefaultSansSerifFontName()
  219073. {
  219074. StringArray allFonts;
  219075. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219076. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219077. }
  219078. const String linux_getDefaultSerifFontName()
  219079. {
  219080. StringArray allFonts;
  219081. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219082. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219083. }
  219084. const String linux_getDefaultMonospacedFontName()
  219085. {
  219086. StringArray allFonts;
  219087. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219088. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219089. }
  219090. }
  219091. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  219092. {
  219093. defaultSans = linux_getDefaultSansSerifFontName();
  219094. defaultSerif = linux_getDefaultSerifFontName();
  219095. defaultFixed = linux_getDefaultMonospacedFontName();
  219096. }
  219097. #endif
  219098. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219099. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219100. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219101. // compiled on its own).
  219102. #if JUCE_INCLUDED_FILE
  219103. // These are defined in juce_linux_Messaging.cpp
  219104. extern Display* display;
  219105. extern XContext windowHandleXContext;
  219106. namespace Atoms
  219107. {
  219108. enum ProtocolItems
  219109. {
  219110. TAKE_FOCUS = 0,
  219111. DELETE_WINDOW = 1,
  219112. PING = 2
  219113. };
  219114. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219115. ActiveWin, Pid, WindowType, WindowState,
  219116. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219117. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219118. XdndActionDescription, XdndActionCopy,
  219119. allowedActions[5],
  219120. allowedMimeTypes[2];
  219121. const unsigned long DndVersion = 3;
  219122. static void initialiseAtoms()
  219123. {
  219124. static bool atomsInitialised = false;
  219125. if (! atomsInitialised)
  219126. {
  219127. atomsInitialised = true;
  219128. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219129. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219130. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219131. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219132. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219133. State = XInternAtom (display, "WM_STATE", True);
  219134. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219135. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219136. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219137. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219138. XdndAware = XInternAtom (display, "XdndAware", False);
  219139. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219140. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219141. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219142. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219143. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219144. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219145. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219146. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219147. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219148. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219149. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219150. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219151. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219152. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219153. allowedActions[1] = XdndActionCopy;
  219154. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219155. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219156. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219157. }
  219158. }
  219159. }
  219160. namespace Keys
  219161. {
  219162. enum MouseButtons
  219163. {
  219164. NoButton = 0,
  219165. LeftButton = 1,
  219166. MiddleButton = 2,
  219167. RightButton = 3,
  219168. WheelUp = 4,
  219169. WheelDown = 5
  219170. };
  219171. static int AltMask = 0;
  219172. static int NumLockMask = 0;
  219173. static bool numLock = false;
  219174. static bool capsLock = false;
  219175. static char keyStates [32];
  219176. static const int extendedKeyModifier = 0x10000000;
  219177. }
  219178. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219179. {
  219180. int keysym;
  219181. if (keyCode & Keys::extendedKeyModifier)
  219182. {
  219183. keysym = 0xff00 | (keyCode & 0xff);
  219184. }
  219185. else
  219186. {
  219187. keysym = keyCode;
  219188. if (keysym == (XK_Tab & 0xff)
  219189. || keysym == (XK_Return & 0xff)
  219190. || keysym == (XK_Escape & 0xff)
  219191. || keysym == (XK_BackSpace & 0xff))
  219192. {
  219193. keysym |= 0xff00;
  219194. }
  219195. }
  219196. ScopedXLock xlock;
  219197. const int keycode = XKeysymToKeycode (display, keysym);
  219198. const int keybyte = keycode >> 3;
  219199. const int keybit = (1 << (keycode & 7));
  219200. return (Keys::keyStates [keybyte] & keybit) != 0;
  219201. }
  219202. #if JUCE_USE_XSHM
  219203. namespace XSHMHelpers
  219204. {
  219205. static int trappedErrorCode = 0;
  219206. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219207. {
  219208. trappedErrorCode = err->error_code;
  219209. return 0;
  219210. }
  219211. static bool isShmAvailable() throw()
  219212. {
  219213. static bool isChecked = false;
  219214. static bool isAvailable = false;
  219215. if (! isChecked)
  219216. {
  219217. isChecked = true;
  219218. int major, minor;
  219219. Bool pixmaps;
  219220. ScopedXLock xlock;
  219221. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219222. {
  219223. trappedErrorCode = 0;
  219224. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219225. XShmSegmentInfo segmentInfo;
  219226. zerostruct (segmentInfo);
  219227. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219228. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219229. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219230. xImage->bytes_per_line * xImage->height,
  219231. IPC_CREAT | 0777)) >= 0)
  219232. {
  219233. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219234. if (segmentInfo.shmaddr != (void*) -1)
  219235. {
  219236. segmentInfo.readOnly = False;
  219237. xImage->data = segmentInfo.shmaddr;
  219238. XSync (display, False);
  219239. if (XShmAttach (display, &segmentInfo) != 0)
  219240. {
  219241. XSync (display, False);
  219242. XShmDetach (display, &segmentInfo);
  219243. isAvailable = true;
  219244. }
  219245. }
  219246. XFlush (display);
  219247. XDestroyImage (xImage);
  219248. shmdt (segmentInfo.shmaddr);
  219249. }
  219250. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219251. XSetErrorHandler (oldHandler);
  219252. if (trappedErrorCode != 0)
  219253. isAvailable = false;
  219254. }
  219255. }
  219256. return isAvailable;
  219257. }
  219258. }
  219259. #endif
  219260. #if JUCE_USE_XRENDER
  219261. namespace XRender
  219262. {
  219263. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219264. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219265. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219266. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219267. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219268. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219269. static tXRenderFindFormat xRenderFindFormat = 0;
  219270. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219271. static bool isAvailable()
  219272. {
  219273. static bool hasLoaded = false;
  219274. if (! hasLoaded)
  219275. {
  219276. ScopedXLock xlock;
  219277. hasLoaded = true;
  219278. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219279. if (h != 0)
  219280. {
  219281. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219282. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219283. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219284. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219285. }
  219286. if (xRenderQueryVersion != 0
  219287. && xRenderFindStandardFormat != 0
  219288. && xRenderFindFormat != 0
  219289. && xRenderFindVisualFormat != 0)
  219290. {
  219291. int major, minor;
  219292. if (xRenderQueryVersion (display, &major, &minor))
  219293. return true;
  219294. }
  219295. xRenderQueryVersion = 0;
  219296. }
  219297. return xRenderQueryVersion != 0;
  219298. }
  219299. static XRenderPictFormat* findPictureFormat()
  219300. {
  219301. ScopedXLock xlock;
  219302. XRenderPictFormat* pictFormat = 0;
  219303. if (isAvailable())
  219304. {
  219305. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219306. if (pictFormat == 0)
  219307. {
  219308. XRenderPictFormat desiredFormat;
  219309. desiredFormat.type = PictTypeDirect;
  219310. desiredFormat.depth = 32;
  219311. desiredFormat.direct.alphaMask = 0xff;
  219312. desiredFormat.direct.redMask = 0xff;
  219313. desiredFormat.direct.greenMask = 0xff;
  219314. desiredFormat.direct.blueMask = 0xff;
  219315. desiredFormat.direct.alpha = 24;
  219316. desiredFormat.direct.red = 16;
  219317. desiredFormat.direct.green = 8;
  219318. desiredFormat.direct.blue = 0;
  219319. pictFormat = xRenderFindFormat (display,
  219320. PictFormatType | PictFormatDepth
  219321. | PictFormatRedMask | PictFormatRed
  219322. | PictFormatGreenMask | PictFormatGreen
  219323. | PictFormatBlueMask | PictFormatBlue
  219324. | PictFormatAlphaMask | PictFormatAlpha,
  219325. &desiredFormat,
  219326. 0);
  219327. }
  219328. }
  219329. return pictFormat;
  219330. }
  219331. }
  219332. #endif
  219333. namespace Visuals
  219334. {
  219335. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219336. {
  219337. ScopedXLock xlock;
  219338. Visual* visual = 0;
  219339. int numVisuals = 0;
  219340. long desiredMask = VisualNoMask;
  219341. XVisualInfo desiredVisual;
  219342. desiredVisual.screen = DefaultScreen (display);
  219343. desiredVisual.depth = desiredDepth;
  219344. desiredMask = VisualScreenMask | VisualDepthMask;
  219345. if (desiredDepth == 32)
  219346. {
  219347. desiredVisual.c_class = TrueColor;
  219348. desiredVisual.red_mask = 0x00FF0000;
  219349. desiredVisual.green_mask = 0x0000FF00;
  219350. desiredVisual.blue_mask = 0x000000FF;
  219351. desiredVisual.bits_per_rgb = 8;
  219352. desiredMask |= VisualClassMask;
  219353. desiredMask |= VisualRedMaskMask;
  219354. desiredMask |= VisualGreenMaskMask;
  219355. desiredMask |= VisualBlueMaskMask;
  219356. desiredMask |= VisualBitsPerRGBMask;
  219357. }
  219358. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219359. desiredMask,
  219360. &desiredVisual,
  219361. &numVisuals);
  219362. if (xvinfos != 0)
  219363. {
  219364. for (int i = 0; i < numVisuals; i++)
  219365. {
  219366. if (xvinfos[i].depth == desiredDepth)
  219367. {
  219368. visual = xvinfos[i].visual;
  219369. break;
  219370. }
  219371. }
  219372. XFree (xvinfos);
  219373. }
  219374. return visual;
  219375. }
  219376. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219377. {
  219378. Visual* visual = 0;
  219379. if (desiredDepth == 32)
  219380. {
  219381. #if JUCE_USE_XSHM
  219382. if (XSHMHelpers::isShmAvailable())
  219383. {
  219384. #if JUCE_USE_XRENDER
  219385. if (XRender::isAvailable())
  219386. {
  219387. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219388. if (pictFormat != 0)
  219389. {
  219390. int numVisuals = 0;
  219391. XVisualInfo desiredVisual;
  219392. desiredVisual.screen = DefaultScreen (display);
  219393. desiredVisual.depth = 32;
  219394. desiredVisual.bits_per_rgb = 8;
  219395. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219396. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219397. &desiredVisual, &numVisuals);
  219398. if (xvinfos != 0)
  219399. {
  219400. for (int i = 0; i < numVisuals; ++i)
  219401. {
  219402. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219403. if (pictVisualFormat != 0
  219404. && pictVisualFormat->type == PictTypeDirect
  219405. && pictVisualFormat->direct.alphaMask)
  219406. {
  219407. visual = xvinfos[i].visual;
  219408. matchedDepth = 32;
  219409. break;
  219410. }
  219411. }
  219412. XFree (xvinfos);
  219413. }
  219414. }
  219415. }
  219416. #endif
  219417. if (visual == 0)
  219418. {
  219419. visual = findVisualWithDepth (32);
  219420. if (visual != 0)
  219421. matchedDepth = 32;
  219422. }
  219423. }
  219424. #endif
  219425. }
  219426. if (visual == 0 && desiredDepth >= 24)
  219427. {
  219428. visual = findVisualWithDepth (24);
  219429. if (visual != 0)
  219430. matchedDepth = 24;
  219431. }
  219432. if (visual == 0 && desiredDepth >= 16)
  219433. {
  219434. visual = findVisualWithDepth (16);
  219435. if (visual != 0)
  219436. matchedDepth = 16;
  219437. }
  219438. return visual;
  219439. }
  219440. }
  219441. class XBitmapImage : public Image::SharedImage
  219442. {
  219443. public:
  219444. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219445. const bool clearImage, const int imageDepth_, Visual* visual)
  219446. : Image::SharedImage (format_, w, h),
  219447. imageDepth (imageDepth_),
  219448. gc (None)
  219449. {
  219450. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219451. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219452. lineStride = ((w * pixelStride + 3) & ~3);
  219453. ScopedXLock xlock;
  219454. #if JUCE_USE_XSHM
  219455. usingXShm = false;
  219456. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219457. {
  219458. zerostruct (segmentInfo);
  219459. segmentInfo.shmid = -1;
  219460. segmentInfo.shmaddr = (char *) -1;
  219461. segmentInfo.readOnly = False;
  219462. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219463. if (xImage != 0)
  219464. {
  219465. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219466. xImage->bytes_per_line * xImage->height,
  219467. IPC_CREAT | 0777)) >= 0)
  219468. {
  219469. if (segmentInfo.shmid != -1)
  219470. {
  219471. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219472. if (segmentInfo.shmaddr != (void*) -1)
  219473. {
  219474. segmentInfo.readOnly = False;
  219475. xImage->data = segmentInfo.shmaddr;
  219476. imageData = (uint8*) segmentInfo.shmaddr;
  219477. if (XShmAttach (display, &segmentInfo) != 0)
  219478. usingXShm = true;
  219479. else
  219480. jassertfalse;
  219481. }
  219482. else
  219483. {
  219484. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219485. }
  219486. }
  219487. }
  219488. }
  219489. }
  219490. if (! usingXShm)
  219491. #endif
  219492. {
  219493. imageDataAllocated.malloc (lineStride * h);
  219494. imageData = imageDataAllocated;
  219495. if (format_ == Image::ARGB && clearImage)
  219496. zeromem (imageData, h * lineStride);
  219497. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219498. xImage->width = w;
  219499. xImage->height = h;
  219500. xImage->xoffset = 0;
  219501. xImage->format = ZPixmap;
  219502. xImage->data = (char*) imageData;
  219503. xImage->byte_order = ImageByteOrder (display);
  219504. xImage->bitmap_unit = BitmapUnit (display);
  219505. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219506. xImage->bitmap_pad = 32;
  219507. xImage->depth = pixelStride * 8;
  219508. xImage->bytes_per_line = lineStride;
  219509. xImage->bits_per_pixel = pixelStride * 8;
  219510. xImage->red_mask = 0x00FF0000;
  219511. xImage->green_mask = 0x0000FF00;
  219512. xImage->blue_mask = 0x000000FF;
  219513. if (imageDepth == 16)
  219514. {
  219515. const int pixelStride = 2;
  219516. const int lineStride = ((w * pixelStride + 3) & ~3);
  219517. imageData16Bit.malloc (lineStride * h);
  219518. xImage->data = imageData16Bit;
  219519. xImage->bitmap_pad = 16;
  219520. xImage->depth = pixelStride * 8;
  219521. xImage->bytes_per_line = lineStride;
  219522. xImage->bits_per_pixel = pixelStride * 8;
  219523. xImage->red_mask = visual->red_mask;
  219524. xImage->green_mask = visual->green_mask;
  219525. xImage->blue_mask = visual->blue_mask;
  219526. }
  219527. if (! XInitImage (xImage))
  219528. jassertfalse;
  219529. }
  219530. }
  219531. ~XBitmapImage()
  219532. {
  219533. ScopedXLock xlock;
  219534. if (gc != None)
  219535. XFreeGC (display, gc);
  219536. #if JUCE_USE_XSHM
  219537. if (usingXShm)
  219538. {
  219539. XShmDetach (display, &segmentInfo);
  219540. XFlush (display);
  219541. XDestroyImage (xImage);
  219542. shmdt (segmentInfo.shmaddr);
  219543. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219544. }
  219545. else
  219546. #endif
  219547. {
  219548. xImage->data = 0;
  219549. XDestroyImage (xImage);
  219550. }
  219551. }
  219552. Image::ImageType getType() const { return Image::NativeImage; }
  219553. LowLevelGraphicsContext* createLowLevelContext()
  219554. {
  219555. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219556. }
  219557. SharedImage* clone()
  219558. {
  219559. jassertfalse;
  219560. return 0;
  219561. }
  219562. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219563. {
  219564. ScopedXLock xlock;
  219565. if (gc == None)
  219566. {
  219567. XGCValues gcvalues;
  219568. gcvalues.foreground = None;
  219569. gcvalues.background = None;
  219570. gcvalues.function = GXcopy;
  219571. gcvalues.plane_mask = AllPlanes;
  219572. gcvalues.clip_mask = None;
  219573. gcvalues.graphics_exposures = False;
  219574. gc = XCreateGC (display, window,
  219575. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219576. &gcvalues);
  219577. }
  219578. if (imageDepth == 16)
  219579. {
  219580. const uint32 rMask = xImage->red_mask;
  219581. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219582. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219583. const uint32 gMask = xImage->green_mask;
  219584. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219585. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219586. const uint32 bMask = xImage->blue_mask;
  219587. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219588. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219589. const Image::BitmapData srcData (Image (this), false);
  219590. for (int y = sy; y < sy + dh; ++y)
  219591. {
  219592. const uint8* p = srcData.getPixelPointer (sx, y);
  219593. for (int x = sx; x < sx + dw; ++x)
  219594. {
  219595. const PixelRGB* const pixel = (const PixelRGB*) p;
  219596. p += srcData.pixelStride;
  219597. XPutPixel (xImage, x, y,
  219598. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219599. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219600. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219601. }
  219602. }
  219603. }
  219604. // blit results to screen.
  219605. #if JUCE_USE_XSHM
  219606. if (usingXShm)
  219607. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219608. else
  219609. #endif
  219610. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219611. }
  219612. private:
  219613. XImage* xImage;
  219614. const int imageDepth;
  219615. HeapBlock <uint8> imageDataAllocated;
  219616. HeapBlock <char> imageData16Bit;
  219617. GC gc;
  219618. #if JUCE_USE_XSHM
  219619. XShmSegmentInfo segmentInfo;
  219620. bool usingXShm;
  219621. #endif
  219622. static int getShiftNeeded (const uint32 mask) throw()
  219623. {
  219624. for (int i = 32; --i >= 0;)
  219625. if (((mask >> i) & 1) != 0)
  219626. return i - 7;
  219627. jassertfalse;
  219628. return 0;
  219629. }
  219630. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage);
  219631. };
  219632. namespace PixmapHelpers
  219633. {
  219634. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  219635. {
  219636. ScopedXLock xlock;
  219637. const int width = image.getWidth();
  219638. const int height = image.getHeight();
  219639. HeapBlock <uint32> colour (width * height);
  219640. int index = 0;
  219641. for (int y = 0; y < height; ++y)
  219642. for (int x = 0; x < width; ++x)
  219643. colour[index++] = image.getPixelAt (x, y).getARGB();
  219644. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219645. 0, reinterpret_cast<char*> (colour.getData()),
  219646. width, height, 32, 0);
  219647. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219648. width, height, 24);
  219649. GC gc = XCreateGC (display, pixmap, 0, 0);
  219650. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219651. XFreeGC (display, gc);
  219652. return pixmap;
  219653. }
  219654. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  219655. {
  219656. ScopedXLock xlock;
  219657. const int width = image.getWidth();
  219658. const int height = image.getHeight();
  219659. const int stride = (width + 7) >> 3;
  219660. HeapBlock <char> mask;
  219661. mask.calloc (stride * height);
  219662. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219663. for (int y = 0; y < height; ++y)
  219664. {
  219665. for (int x = 0; x < width; ++x)
  219666. {
  219667. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219668. const int offset = y * stride + (x >> 3);
  219669. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219670. mask[offset] |= bit;
  219671. }
  219672. }
  219673. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219674. mask.getData(), width, height, 1, 0, 1);
  219675. }
  219676. }
  219677. class LinuxComponentPeer : public ComponentPeer
  219678. {
  219679. public:
  219680. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  219681. : ComponentPeer (component, windowStyleFlags),
  219682. windowH (0),
  219683. parentWindow (0),
  219684. wx (0),
  219685. wy (0),
  219686. ww (0),
  219687. wh (0),
  219688. fullScreen (false),
  219689. mapped (false),
  219690. visual (0),
  219691. depth (0)
  219692. {
  219693. // it's dangerous to create a window on a thread other than the message thread..
  219694. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219695. repainter = new LinuxRepaintManager (this);
  219696. createWindow();
  219697. setTitle (component->getName());
  219698. }
  219699. ~LinuxComponentPeer()
  219700. {
  219701. // it's dangerous to delete a window on a thread other than the message thread..
  219702. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219703. deleteIconPixmaps();
  219704. destroyWindow();
  219705. windowH = 0;
  219706. }
  219707. void* getNativeHandle() const
  219708. {
  219709. return (void*) windowH;
  219710. }
  219711. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  219712. {
  219713. XPointer peer = 0;
  219714. ScopedXLock xlock;
  219715. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  219716. {
  219717. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  219718. peer = 0;
  219719. }
  219720. return (LinuxComponentPeer*) peer;
  219721. }
  219722. void setVisible (bool shouldBeVisible)
  219723. {
  219724. ScopedXLock xlock;
  219725. if (shouldBeVisible)
  219726. XMapWindow (display, windowH);
  219727. else
  219728. XUnmapWindow (display, windowH);
  219729. }
  219730. void setTitle (const String& title)
  219731. {
  219732. XTextProperty nameProperty;
  219733. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  219734. ScopedXLock xlock;
  219735. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219736. {
  219737. XSetWMName (display, windowH, &nameProperty);
  219738. XSetWMIconName (display, windowH, &nameProperty);
  219739. XFree (nameProperty.value);
  219740. }
  219741. }
  219742. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  219743. {
  219744. fullScreen = isNowFullScreen;
  219745. if (windowH != 0)
  219746. {
  219747. WeakReference<Component> deletionChecker (component);
  219748. wx = x;
  219749. wy = y;
  219750. ww = jmax (1, w);
  219751. wh = jmax (1, h);
  219752. ScopedXLock xlock;
  219753. // Make sure the Window manager does what we want
  219754. XSizeHints* hints = XAllocSizeHints();
  219755. hints->flags = USSize | USPosition;
  219756. hints->width = ww;
  219757. hints->height = wh;
  219758. hints->x = wx;
  219759. hints->y = wy;
  219760. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  219761. {
  219762. hints->min_width = hints->max_width = hints->width;
  219763. hints->min_height = hints->max_height = hints->height;
  219764. hints->flags |= PMinSize | PMaxSize;
  219765. }
  219766. XSetWMNormalHints (display, windowH, hints);
  219767. XFree (hints);
  219768. XMoveResizeWindow (display, windowH,
  219769. wx - windowBorder.getLeft(),
  219770. wy - windowBorder.getTop(), ww, wh);
  219771. if (deletionChecker != 0)
  219772. {
  219773. updateBorderSize();
  219774. handleMovedOrResized();
  219775. }
  219776. }
  219777. }
  219778. void setPosition (int x, int y) { setBounds (x, y, ww, wh, false); }
  219779. void setSize (int w, int h) { setBounds (wx, wy, w, h, false); }
  219780. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  219781. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  219782. const Point<int> localToGlobal (const Point<int>& relativePosition)
  219783. {
  219784. return relativePosition + getScreenPosition();
  219785. }
  219786. const Point<int> globalToLocal (const Point<int>& screenPosition)
  219787. {
  219788. return screenPosition - getScreenPosition();
  219789. }
  219790. void setAlpha (float newAlpha)
  219791. {
  219792. //xxx todo!
  219793. }
  219794. void setMinimised (bool shouldBeMinimised)
  219795. {
  219796. if (shouldBeMinimised)
  219797. {
  219798. Window root = RootWindow (display, DefaultScreen (display));
  219799. XClientMessageEvent clientMsg;
  219800. clientMsg.display = display;
  219801. clientMsg.window = windowH;
  219802. clientMsg.type = ClientMessage;
  219803. clientMsg.format = 32;
  219804. clientMsg.message_type = Atoms::ChangeState;
  219805. clientMsg.data.l[0] = IconicState;
  219806. ScopedXLock xlock;
  219807. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  219808. }
  219809. else
  219810. {
  219811. setVisible (true);
  219812. }
  219813. }
  219814. bool isMinimised() const
  219815. {
  219816. bool minimised = false;
  219817. unsigned char* stateProp;
  219818. unsigned long nitems, bytesLeft;
  219819. Atom actualType;
  219820. int actualFormat;
  219821. ScopedXLock xlock;
  219822. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  219823. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  219824. &stateProp) == Success
  219825. && actualType == Atoms::State
  219826. && actualFormat == 32
  219827. && nitems > 0)
  219828. {
  219829. if (((unsigned long*) stateProp)[0] == IconicState)
  219830. minimised = true;
  219831. XFree (stateProp);
  219832. }
  219833. return minimised;
  219834. }
  219835. void setFullScreen (const bool shouldBeFullScreen)
  219836. {
  219837. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  219838. setMinimised (false);
  219839. if (fullScreen != shouldBeFullScreen)
  219840. {
  219841. if (shouldBeFullScreen)
  219842. r = Desktop::getInstance().getMainMonitorArea();
  219843. if (! r.isEmpty())
  219844. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219845. getComponent()->repaint();
  219846. }
  219847. }
  219848. bool isFullScreen() const
  219849. {
  219850. return fullScreen;
  219851. }
  219852. bool isChildWindowOf (Window possibleParent) const
  219853. {
  219854. Window* windowList = 0;
  219855. uint32 windowListSize = 0;
  219856. Window parent, root;
  219857. ScopedXLock xlock;
  219858. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  219859. {
  219860. if (windowList != 0)
  219861. XFree (windowList);
  219862. return parent == possibleParent;
  219863. }
  219864. return false;
  219865. }
  219866. bool isFrontWindow() const
  219867. {
  219868. Window* windowList = 0;
  219869. uint32 windowListSize = 0;
  219870. bool result = false;
  219871. ScopedXLock xlock;
  219872. Window parent, root = RootWindow (display, DefaultScreen (display));
  219873. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219874. {
  219875. for (int i = windowListSize; --i >= 0;)
  219876. {
  219877. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219878. if (peer != 0)
  219879. {
  219880. result = (peer == this);
  219881. break;
  219882. }
  219883. }
  219884. }
  219885. if (windowList != 0)
  219886. XFree (windowList);
  219887. return result;
  219888. }
  219889. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219890. {
  219891. if (! (isPositiveAndBelow (position.getX(), ww) && isPositiveAndBelow (position.getY(), wh)))
  219892. return false;
  219893. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219894. {
  219895. Component* const c = Desktop::getInstance().getComponent (i);
  219896. if (c == getComponent())
  219897. break;
  219898. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  219899. return false;
  219900. }
  219901. if (trueIfInAChildWindow)
  219902. return true;
  219903. ::Window root, child;
  219904. unsigned int bw, depth;
  219905. int wx, wy, w, h;
  219906. ScopedXLock xlock;
  219907. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219908. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219909. &bw, &depth))
  219910. {
  219911. return false;
  219912. }
  219913. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  219914. return false;
  219915. return child == None;
  219916. }
  219917. const BorderSize getFrameSize() const
  219918. {
  219919. return BorderSize();
  219920. }
  219921. bool setAlwaysOnTop (bool alwaysOnTop)
  219922. {
  219923. return false;
  219924. }
  219925. void toFront (bool makeActive)
  219926. {
  219927. if (makeActive)
  219928. {
  219929. setVisible (true);
  219930. grabFocus();
  219931. }
  219932. XEvent ev;
  219933. ev.xclient.type = ClientMessage;
  219934. ev.xclient.serial = 0;
  219935. ev.xclient.send_event = True;
  219936. ev.xclient.message_type = Atoms::ActiveWin;
  219937. ev.xclient.window = windowH;
  219938. ev.xclient.format = 32;
  219939. ev.xclient.data.l[0] = 2;
  219940. ev.xclient.data.l[1] = CurrentTime;
  219941. ev.xclient.data.l[2] = 0;
  219942. ev.xclient.data.l[3] = 0;
  219943. ev.xclient.data.l[4] = 0;
  219944. {
  219945. ScopedXLock xlock;
  219946. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219947. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219948. XWindowAttributes attr;
  219949. XGetWindowAttributes (display, windowH, &attr);
  219950. if (component->isAlwaysOnTop())
  219951. XRaiseWindow (display, windowH);
  219952. XSync (display, False);
  219953. }
  219954. handleBroughtToFront();
  219955. }
  219956. void toBehind (ComponentPeer* other)
  219957. {
  219958. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219959. jassert (otherPeer != 0); // wrong type of window?
  219960. if (otherPeer != 0)
  219961. {
  219962. setMinimised (false);
  219963. Window newStack[] = { otherPeer->windowH, windowH };
  219964. ScopedXLock xlock;
  219965. XRestackWindows (display, newStack, 2);
  219966. }
  219967. }
  219968. bool isFocused() const
  219969. {
  219970. int revert = 0;
  219971. Window focusedWindow = 0;
  219972. ScopedXLock xlock;
  219973. XGetInputFocus (display, &focusedWindow, &revert);
  219974. return focusedWindow == windowH;
  219975. }
  219976. void grabFocus()
  219977. {
  219978. XWindowAttributes atts;
  219979. ScopedXLock xlock;
  219980. if (windowH != 0
  219981. && XGetWindowAttributes (display, windowH, &atts)
  219982. && atts.map_state == IsViewable
  219983. && ! isFocused())
  219984. {
  219985. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  219986. isActiveApplication = true;
  219987. }
  219988. }
  219989. void textInputRequired (const Point<int>&)
  219990. {
  219991. }
  219992. void repaint (const Rectangle<int>& area)
  219993. {
  219994. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  219995. }
  219996. void performAnyPendingRepaintsNow()
  219997. {
  219998. repainter->performAnyPendingRepaintsNow();
  219999. }
  220000. void setIcon (const Image& newIcon)
  220001. {
  220002. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220003. HeapBlock <unsigned long> data (dataSize);
  220004. int index = 0;
  220005. data[index++] = newIcon.getWidth();
  220006. data[index++] = newIcon.getHeight();
  220007. for (int y = 0; y < newIcon.getHeight(); ++y)
  220008. for (int x = 0; x < newIcon.getWidth(); ++x)
  220009. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220010. ScopedXLock xlock;
  220011. XChangeProperty (display, windowH,
  220012. XInternAtom (display, "_NET_WM_ICON", False),
  220013. XA_CARDINAL, 32, PropModeReplace,
  220014. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220015. deleteIconPixmaps();
  220016. XWMHints* wmHints = XGetWMHints (display, windowH);
  220017. if (wmHints == 0)
  220018. wmHints = XAllocWMHints();
  220019. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220020. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  220021. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  220022. XSetWMHints (display, windowH, wmHints);
  220023. XFree (wmHints);
  220024. XSync (display, False);
  220025. }
  220026. void deleteIconPixmaps()
  220027. {
  220028. ScopedXLock xlock;
  220029. XWMHints* wmHints = XGetWMHints (display, windowH);
  220030. if (wmHints != 0)
  220031. {
  220032. if ((wmHints->flags & IconPixmapHint) != 0)
  220033. {
  220034. wmHints->flags &= ~IconPixmapHint;
  220035. XFreePixmap (display, wmHints->icon_pixmap);
  220036. }
  220037. if ((wmHints->flags & IconMaskHint) != 0)
  220038. {
  220039. wmHints->flags &= ~IconMaskHint;
  220040. XFreePixmap (display, wmHints->icon_mask);
  220041. }
  220042. XSetWMHints (display, windowH, wmHints);
  220043. XFree (wmHints);
  220044. }
  220045. }
  220046. void handleWindowMessage (XEvent* event)
  220047. {
  220048. switch (event->xany.type)
  220049. {
  220050. case 2: /* KeyPress */ handleKeyPressEvent ((XKeyEvent*) &event->xkey); break;
  220051. case KeyRelease: handleKeyReleaseEvent ((const XKeyEvent*) &event->xkey); break;
  220052. case ButtonPress: handleButtonPressEvent ((const XButtonPressedEvent*) &event->xbutton); break;
  220053. case ButtonRelease: handleButtonReleaseEvent ((const XButtonReleasedEvent*) &event->xbutton); break;
  220054. case MotionNotify: handleMotionNotifyEvent ((const XPointerMovedEvent*) &event->xmotion); break;
  220055. case EnterNotify: handleEnterNotifyEvent ((const XEnterWindowEvent*) &event->xcrossing); break;
  220056. case LeaveNotify: handleLeaveNotifyEvent ((const XLeaveWindowEvent*) &event->xcrossing); break;
  220057. case FocusIn: handleFocusInEvent(); break;
  220058. case FocusOut: handleFocusOutEvent(); break;
  220059. case Expose: handleExposeEvent ((XExposeEvent*) &event->xexpose); break;
  220060. case MappingNotify: handleMappingNotify ((XMappingEvent*) &event->xmapping); break;
  220061. case ClientMessage: handleClientMessageEvent ((XClientMessageEvent*) &event->xclient, event); break;
  220062. case SelectionNotify: handleDragAndDropSelection (event); break;
  220063. case ConfigureNotify: handleConfigureNotifyEvent ((XConfigureEvent*) &event->xconfigure); break;
  220064. case ReparentNotify: handleReparentNotifyEvent(); break;
  220065. case GravityNotify: handleGravityNotify(); break;
  220066. case CirculateNotify:
  220067. case CreateNotify:
  220068. case DestroyNotify:
  220069. // Think we can ignore these
  220070. break;
  220071. case MapNotify:
  220072. mapped = true;
  220073. handleBroughtToFront();
  220074. break;
  220075. case UnmapNotify:
  220076. mapped = false;
  220077. break;
  220078. case SelectionClear:
  220079. case SelectionRequest:
  220080. break;
  220081. default:
  220082. #if JUCE_USE_XSHM
  220083. {
  220084. ScopedXLock xlock;
  220085. if (event->xany.type == XShmGetEventBase (display))
  220086. repainter->notifyPaintCompleted();
  220087. }
  220088. #endif
  220089. break;
  220090. }
  220091. }
  220092. void handleKeyPressEvent (XKeyEvent* const keyEvent)
  220093. {
  220094. char utf8 [64] = { 0 };
  220095. juce_wchar unicodeChar = 0;
  220096. int keyCode = 0;
  220097. bool keyDownChange = false;
  220098. KeySym sym;
  220099. {
  220100. ScopedXLock xlock;
  220101. updateKeyStates (keyEvent->keycode, true);
  220102. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220103. ::setlocale (LC_ALL, "");
  220104. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220105. ::setlocale (LC_ALL, oldLocale);
  220106. unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220107. keyCode = (int) unicodeChar;
  220108. if (keyCode < 0x20)
  220109. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220110. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220111. }
  220112. const ModifierKeys oldMods (currentModifiers);
  220113. bool keyPressed = false;
  220114. if ((sym & 0xff00) == 0xff00)
  220115. {
  220116. switch (sym) // Translate keypad
  220117. {
  220118. case XK_KP_Divide: keyCode = XK_slash; break;
  220119. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  220120. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  220121. case XK_KP_Add: keyCode = XK_plus; break;
  220122. case XK_KP_Enter: keyCode = XK_Return; break;
  220123. case XK_KP_Decimal: keyCode = Keys::numLock ? XK_period : XK_Delete; break;
  220124. case XK_KP_0: keyCode = Keys::numLock ? XK_0 : XK_Insert; break;
  220125. case XK_KP_1: keyCode = Keys::numLock ? XK_1 : XK_End; break;
  220126. case XK_KP_2: keyCode = Keys::numLock ? XK_2 : XK_Down; break;
  220127. case XK_KP_3: keyCode = Keys::numLock ? XK_3 : XK_Page_Down; break;
  220128. case XK_KP_4: keyCode = Keys::numLock ? XK_4 : XK_Left; break;
  220129. case XK_KP_5: keyCode = XK_5; break;
  220130. case XK_KP_6: keyCode = Keys::numLock ? XK_6 : XK_Right; break;
  220131. case XK_KP_7: keyCode = Keys::numLock ? XK_7 : XK_Home; break;
  220132. case XK_KP_8: keyCode = Keys::numLock ? XK_8 : XK_Up; break;
  220133. case XK_KP_9: keyCode = Keys::numLock ? XK_9 : XK_Page_Up; break;
  220134. default: break;
  220135. }
  220136. switch (sym)
  220137. {
  220138. case XK_Left:
  220139. case XK_Right:
  220140. case XK_Up:
  220141. case XK_Down:
  220142. case XK_Page_Up:
  220143. case XK_Page_Down:
  220144. case XK_End:
  220145. case XK_Home:
  220146. case XK_Delete:
  220147. case XK_Insert:
  220148. keyPressed = true;
  220149. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220150. break;
  220151. case XK_Tab:
  220152. case XK_Return:
  220153. case XK_Escape:
  220154. case XK_BackSpace:
  220155. keyPressed = true;
  220156. keyCode &= 0xff;
  220157. break;
  220158. default:
  220159. if (sym >= XK_F1 && sym <= XK_F16)
  220160. {
  220161. keyPressed = true;
  220162. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220163. }
  220164. break;
  220165. }
  220166. }
  220167. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220168. keyPressed = true;
  220169. if (oldMods != currentModifiers)
  220170. handleModifierKeysChange();
  220171. if (keyDownChange)
  220172. handleKeyUpOrDown (true);
  220173. if (keyPressed)
  220174. handleKeyPress (keyCode, unicodeChar);
  220175. }
  220176. void handleKeyReleaseEvent (const XKeyEvent* const keyEvent)
  220177. {
  220178. updateKeyStates (keyEvent->keycode, false);
  220179. KeySym sym;
  220180. {
  220181. ScopedXLock xlock;
  220182. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220183. }
  220184. const ModifierKeys oldMods (currentModifiers);
  220185. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220186. if (oldMods != currentModifiers)
  220187. handleModifierKeysChange();
  220188. if (keyDownChange)
  220189. handleKeyUpOrDown (false);
  220190. }
  220191. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent)
  220192. {
  220193. updateKeyModifiers (buttonPressEvent->state);
  220194. bool buttonMsg = false;
  220195. const int map = pointerMap [buttonPressEvent->button - Button1];
  220196. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220197. {
  220198. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220199. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220200. }
  220201. if (map == Keys::LeftButton)
  220202. {
  220203. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220204. buttonMsg = true;
  220205. }
  220206. else if (map == Keys::RightButton)
  220207. {
  220208. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220209. buttonMsg = true;
  220210. }
  220211. else if (map == Keys::MiddleButton)
  220212. {
  220213. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220214. buttonMsg = true;
  220215. }
  220216. if (buttonMsg)
  220217. {
  220218. toFront (true);
  220219. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220220. getEventTime (buttonPressEvent->time));
  220221. }
  220222. clearLastMousePos();
  220223. }
  220224. void handleButtonReleaseEvent (const XButtonReleasedEvent* const buttonRelEvent)
  220225. {
  220226. updateKeyModifiers (buttonRelEvent->state);
  220227. const int map = pointerMap [buttonRelEvent->button - Button1];
  220228. if (map == Keys::LeftButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220229. else if (map == Keys::RightButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220230. else if (map == Keys::MiddleButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220231. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220232. getEventTime (buttonRelEvent->time));
  220233. clearLastMousePos();
  220234. }
  220235. void handleMotionNotifyEvent (const XPointerMovedEvent* const movedEvent)
  220236. {
  220237. updateKeyModifiers (movedEvent->state);
  220238. const Point<int> mousePos (movedEvent->x_root, movedEvent->y_root);
  220239. if (lastMousePos != mousePos)
  220240. {
  220241. lastMousePos = mousePos;
  220242. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220243. {
  220244. Window wRoot = 0, wParent = 0;
  220245. {
  220246. ScopedXLock xlock;
  220247. unsigned int numChildren;
  220248. Window* wChild = 0;
  220249. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220250. }
  220251. if (wParent != 0
  220252. && wParent != windowH
  220253. && wParent != wRoot)
  220254. {
  220255. parentWindow = wParent;
  220256. updateBounds();
  220257. }
  220258. else
  220259. {
  220260. parentWindow = 0;
  220261. }
  220262. }
  220263. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220264. }
  220265. }
  220266. void handleEnterNotifyEvent (const XEnterWindowEvent* const enterEvent)
  220267. {
  220268. clearLastMousePos();
  220269. if (! currentModifiers.isAnyMouseButtonDown())
  220270. {
  220271. updateKeyModifiers (enterEvent->state);
  220272. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220273. }
  220274. }
  220275. void handleLeaveNotifyEvent (const XLeaveWindowEvent* const leaveEvent)
  220276. {
  220277. // Suppress the normal leave if we've got a pointer grab, or if
  220278. // it's a bogus one caused by clicking a mouse button when running
  220279. // in a Window manager
  220280. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220281. || leaveEvent->mode == NotifyUngrab)
  220282. {
  220283. updateKeyModifiers (leaveEvent->state);
  220284. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220285. }
  220286. }
  220287. void handleFocusInEvent()
  220288. {
  220289. isActiveApplication = true;
  220290. if (isFocused())
  220291. handleFocusGain();
  220292. }
  220293. void handleFocusOutEvent()
  220294. {
  220295. isActiveApplication = false;
  220296. if (! isFocused())
  220297. handleFocusLoss();
  220298. }
  220299. void handleExposeEvent (XExposeEvent* exposeEvent)
  220300. {
  220301. // Batch together all pending expose events
  220302. XEvent nextEvent;
  220303. ScopedXLock xlock;
  220304. if (exposeEvent->window != windowH)
  220305. {
  220306. Window child;
  220307. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220308. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220309. &child);
  220310. }
  220311. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220312. exposeEvent->width, exposeEvent->height));
  220313. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220314. {
  220315. XPeekEvent (display, (XEvent*) &nextEvent);
  220316. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent->window)
  220317. break;
  220318. XNextEvent (display, (XEvent*) &nextEvent);
  220319. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220320. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220321. nextExposeEvent->width, nextExposeEvent->height));
  220322. }
  220323. }
  220324. void handleConfigureNotifyEvent (XConfigureEvent* const confEvent)
  220325. {
  220326. updateBounds();
  220327. updateBorderSize();
  220328. handleMovedOrResized();
  220329. // if the native title bar is dragged, need to tell any active menus, etc.
  220330. if ((styleFlags & windowHasTitleBar) != 0
  220331. && component->isCurrentlyBlockedByAnotherModalComponent())
  220332. {
  220333. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220334. if (currentModalComp != 0)
  220335. currentModalComp->inputAttemptWhenModal();
  220336. }
  220337. if (confEvent->window == windowH
  220338. && confEvent->above != 0
  220339. && isFrontWindow())
  220340. {
  220341. handleBroughtToFront();
  220342. }
  220343. }
  220344. void handleReparentNotifyEvent()
  220345. {
  220346. parentWindow = 0;
  220347. Window wRoot = 0;
  220348. Window* wChild = 0;
  220349. unsigned int numChildren;
  220350. {
  220351. ScopedXLock xlock;
  220352. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220353. }
  220354. if (parentWindow == windowH || parentWindow == wRoot)
  220355. parentWindow = 0;
  220356. handleGravityNotify();
  220357. }
  220358. void handleGravityNotify()
  220359. {
  220360. updateBounds();
  220361. updateBorderSize();
  220362. handleMovedOrResized();
  220363. }
  220364. void handleMappingNotify (XMappingEvent* const mappingEvent)
  220365. {
  220366. if (mappingEvent->request != MappingPointer)
  220367. {
  220368. // Deal with modifier/keyboard mapping
  220369. ScopedXLock xlock;
  220370. XRefreshKeyboardMapping (mappingEvent);
  220371. updateModifierMappings();
  220372. }
  220373. }
  220374. void handleClientMessageEvent (XClientMessageEvent* const clientMsg, XEvent* event)
  220375. {
  220376. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220377. {
  220378. const Atom atom = (Atom) clientMsg->data.l[0];
  220379. if (atom == Atoms::ProtocolList [Atoms::PING])
  220380. {
  220381. Window root = RootWindow (display, DefaultScreen (display));
  220382. clientMsg->window = root;
  220383. XSendEvent (display, root, False, NoEventMask, event);
  220384. XFlush (display);
  220385. }
  220386. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220387. {
  220388. XWindowAttributes atts;
  220389. ScopedXLock xlock;
  220390. if (clientMsg->window != 0
  220391. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220392. {
  220393. if (atts.map_state == IsViewable)
  220394. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220395. }
  220396. }
  220397. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220398. {
  220399. handleUserClosingWindow();
  220400. }
  220401. }
  220402. else if (clientMsg->message_type == Atoms::XdndEnter)
  220403. {
  220404. handleDragAndDropEnter (clientMsg);
  220405. }
  220406. else if (clientMsg->message_type == Atoms::XdndLeave)
  220407. {
  220408. resetDragAndDrop();
  220409. }
  220410. else if (clientMsg->message_type == Atoms::XdndPosition)
  220411. {
  220412. handleDragAndDropPosition (clientMsg);
  220413. }
  220414. else if (clientMsg->message_type == Atoms::XdndDrop)
  220415. {
  220416. handleDragAndDropDrop (clientMsg);
  220417. }
  220418. else if (clientMsg->message_type == Atoms::XdndStatus)
  220419. {
  220420. handleDragAndDropStatus (clientMsg);
  220421. }
  220422. else if (clientMsg->message_type == Atoms::XdndFinished)
  220423. {
  220424. resetDragAndDrop();
  220425. }
  220426. }
  220427. void showMouseCursor (Cursor cursor) throw()
  220428. {
  220429. ScopedXLock xlock;
  220430. XDefineCursor (display, windowH, cursor);
  220431. }
  220432. void setTaskBarIcon (const Image& image)
  220433. {
  220434. ScopedXLock xlock;
  220435. taskbarImage = image;
  220436. Screen* const screen = XDefaultScreenOfDisplay (display);
  220437. const int screenNumber = XScreenNumberOfScreen (screen);
  220438. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220439. screenAtom << screenNumber;
  220440. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220441. XGrabServer (display);
  220442. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220443. if (managerWin != None)
  220444. XSelectInput (display, managerWin, StructureNotifyMask);
  220445. XUngrabServer (display);
  220446. XFlush (display);
  220447. if (managerWin != None)
  220448. {
  220449. XEvent ev;
  220450. zerostruct (ev);
  220451. ev.xclient.type = ClientMessage;
  220452. ev.xclient.window = managerWin;
  220453. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220454. ev.xclient.format = 32;
  220455. ev.xclient.data.l[0] = CurrentTime;
  220456. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220457. ev.xclient.data.l[2] = windowH;
  220458. ev.xclient.data.l[3] = 0;
  220459. ev.xclient.data.l[4] = 0;
  220460. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220461. XSync (display, False);
  220462. }
  220463. // For older KDE's ...
  220464. long atomData = 1;
  220465. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220466. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220467. // For more recent KDE's...
  220468. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220469. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220470. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220471. XSizeHints* hints = XAllocSizeHints();
  220472. hints->flags = PMinSize;
  220473. hints->min_width = 22;
  220474. hints->min_height = 22;
  220475. XSetWMNormalHints (display, windowH, hints);
  220476. XFree (hints);
  220477. }
  220478. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220479. bool dontRepaint;
  220480. static ModifierKeys currentModifiers;
  220481. static bool isActiveApplication;
  220482. private:
  220483. class LinuxRepaintManager : public Timer
  220484. {
  220485. public:
  220486. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220487. : peer (peer_),
  220488. lastTimeImageUsed (0)
  220489. {
  220490. #if JUCE_USE_XSHM
  220491. shmCompletedDrawing = true;
  220492. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220493. if (useARGBImagesForRendering)
  220494. {
  220495. ScopedXLock xlock;
  220496. XShmSegmentInfo segmentinfo;
  220497. XImage* const testImage
  220498. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220499. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220500. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220501. XDestroyImage (testImage);
  220502. }
  220503. #endif
  220504. }
  220505. void timerCallback()
  220506. {
  220507. #if JUCE_USE_XSHM
  220508. if (! shmCompletedDrawing)
  220509. return;
  220510. #endif
  220511. if (! regionsNeedingRepaint.isEmpty())
  220512. {
  220513. stopTimer();
  220514. performAnyPendingRepaintsNow();
  220515. }
  220516. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220517. {
  220518. stopTimer();
  220519. image = Image::null;
  220520. }
  220521. }
  220522. void repaint (const Rectangle<int>& area)
  220523. {
  220524. if (! isTimerRunning())
  220525. startTimer (repaintTimerPeriod);
  220526. regionsNeedingRepaint.add (area);
  220527. }
  220528. void performAnyPendingRepaintsNow()
  220529. {
  220530. #if JUCE_USE_XSHM
  220531. if (! shmCompletedDrawing)
  220532. {
  220533. startTimer (repaintTimerPeriod);
  220534. return;
  220535. }
  220536. #endif
  220537. peer->clearMaskedRegion();
  220538. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220539. regionsNeedingRepaint.clear();
  220540. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220541. if (! totalArea.isEmpty())
  220542. {
  220543. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220544. || image.getHeight() < totalArea.getHeight())
  220545. {
  220546. #if JUCE_USE_XSHM
  220547. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220548. : Image::RGB,
  220549. #else
  220550. image = Image (new XBitmapImage (Image::RGB,
  220551. #endif
  220552. (totalArea.getWidth() + 31) & ~31,
  220553. (totalArea.getHeight() + 31) & ~31,
  220554. false, peer->depth, peer->visual));
  220555. }
  220556. startTimer (repaintTimerPeriod);
  220557. RectangleList adjustedList (originalRepaintRegion);
  220558. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220559. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220560. if (peer->depth == 32)
  220561. {
  220562. RectangleList::Iterator i (originalRepaintRegion);
  220563. while (i.next())
  220564. image.clear (*i.getRectangle() - totalArea.getPosition());
  220565. }
  220566. peer->handlePaint (context);
  220567. if (! peer->maskedRegion.isEmpty())
  220568. originalRepaintRegion.subtract (peer->maskedRegion);
  220569. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220570. {
  220571. #if JUCE_USE_XSHM
  220572. shmCompletedDrawing = false;
  220573. #endif
  220574. const Rectangle<int>& r = *i.getRectangle();
  220575. static_cast<XBitmapImage*> (image.getSharedImage())
  220576. ->blitToWindow (peer->windowH,
  220577. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  220578. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  220579. }
  220580. }
  220581. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  220582. startTimer (repaintTimerPeriod);
  220583. }
  220584. #if JUCE_USE_XSHM
  220585. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  220586. #endif
  220587. private:
  220588. enum { repaintTimerPeriod = 1000 / 100 };
  220589. LinuxComponentPeer* const peer;
  220590. Image image;
  220591. uint32 lastTimeImageUsed;
  220592. RectangleList regionsNeedingRepaint;
  220593. #if JUCE_USE_XSHM
  220594. bool useARGBImagesForRendering, shmCompletedDrawing;
  220595. #endif
  220596. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  220597. };
  220598. ScopedPointer <LinuxRepaintManager> repainter;
  220599. friend class LinuxRepaintManager;
  220600. Window windowH, parentWindow;
  220601. int wx, wy, ww, wh;
  220602. Image taskbarImage;
  220603. bool fullScreen, mapped;
  220604. Visual* visual;
  220605. int depth;
  220606. BorderSize windowBorder;
  220607. struct MotifWmHints
  220608. {
  220609. unsigned long flags;
  220610. unsigned long functions;
  220611. unsigned long decorations;
  220612. long input_mode;
  220613. unsigned long status;
  220614. };
  220615. static void updateKeyStates (const int keycode, const bool press) throw()
  220616. {
  220617. const int keybyte = keycode >> 3;
  220618. const int keybit = (1 << (keycode & 7));
  220619. if (press)
  220620. Keys::keyStates [keybyte] |= keybit;
  220621. else
  220622. Keys::keyStates [keybyte] &= ~keybit;
  220623. }
  220624. static void updateKeyModifiers (const int status) throw()
  220625. {
  220626. int keyMods = 0;
  220627. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  220628. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  220629. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  220630. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  220631. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  220632. Keys::capsLock = ((status & LockMask) != 0);
  220633. }
  220634. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  220635. {
  220636. int modifier = 0;
  220637. bool isModifier = true;
  220638. switch (sym)
  220639. {
  220640. case XK_Shift_L:
  220641. case XK_Shift_R:
  220642. modifier = ModifierKeys::shiftModifier;
  220643. break;
  220644. case XK_Control_L:
  220645. case XK_Control_R:
  220646. modifier = ModifierKeys::ctrlModifier;
  220647. break;
  220648. case XK_Alt_L:
  220649. case XK_Alt_R:
  220650. modifier = ModifierKeys::altModifier;
  220651. break;
  220652. case XK_Num_Lock:
  220653. if (press)
  220654. Keys::numLock = ! Keys::numLock;
  220655. break;
  220656. case XK_Caps_Lock:
  220657. if (press)
  220658. Keys::capsLock = ! Keys::capsLock;
  220659. break;
  220660. case XK_Scroll_Lock:
  220661. break;
  220662. default:
  220663. isModifier = false;
  220664. break;
  220665. }
  220666. if (modifier != 0)
  220667. {
  220668. if (press)
  220669. currentModifiers = currentModifiers.withFlags (modifier);
  220670. else
  220671. currentModifiers = currentModifiers.withoutFlags (modifier);
  220672. }
  220673. return isModifier;
  220674. }
  220675. // Alt and Num lock are not defined by standard X
  220676. // modifier constants: check what they're mapped to
  220677. static void updateModifierMappings() throw()
  220678. {
  220679. ScopedXLock xlock;
  220680. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  220681. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  220682. Keys::AltMask = 0;
  220683. Keys::NumLockMask = 0;
  220684. XModifierKeymap* mapping = XGetModifierMapping (display);
  220685. if (mapping)
  220686. {
  220687. for (int i = 0; i < 8; i++)
  220688. {
  220689. if (mapping->modifiermap [i << 1] == altLeftCode)
  220690. Keys::AltMask = 1 << i;
  220691. else if (mapping->modifiermap [i << 1] == numLockCode)
  220692. Keys::NumLockMask = 1 << i;
  220693. }
  220694. XFreeModifiermap (mapping);
  220695. }
  220696. }
  220697. void removeWindowDecorations (Window wndH)
  220698. {
  220699. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220700. if (hints != None)
  220701. {
  220702. MotifWmHints motifHints;
  220703. zerostruct (motifHints);
  220704. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  220705. motifHints.decorations = 0;
  220706. ScopedXLock xlock;
  220707. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220708. (unsigned char*) &motifHints, 4);
  220709. }
  220710. hints = XInternAtom (display, "_WIN_HINTS", True);
  220711. if (hints != None)
  220712. {
  220713. long gnomeHints = 0;
  220714. ScopedXLock xlock;
  220715. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220716. (unsigned char*) &gnomeHints, 1);
  220717. }
  220718. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  220719. if (hints != None)
  220720. {
  220721. long kwmHints = 2; /*KDE_tinyDecoration*/
  220722. ScopedXLock xlock;
  220723. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220724. (unsigned char*) &kwmHints, 1);
  220725. }
  220726. }
  220727. void addWindowButtons (Window wndH)
  220728. {
  220729. ScopedXLock xlock;
  220730. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220731. if (hints != None)
  220732. {
  220733. MotifWmHints motifHints;
  220734. zerostruct (motifHints);
  220735. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  220736. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  220737. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  220738. if ((styleFlags & windowHasCloseButton) != 0)
  220739. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  220740. if ((styleFlags & windowHasMinimiseButton) != 0)
  220741. {
  220742. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  220743. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  220744. }
  220745. if ((styleFlags & windowHasMaximiseButton) != 0)
  220746. {
  220747. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  220748. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  220749. }
  220750. if ((styleFlags & windowIsResizable) != 0)
  220751. {
  220752. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  220753. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  220754. }
  220755. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  220756. }
  220757. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  220758. if (hints != None)
  220759. {
  220760. int netHints [6];
  220761. int num = 0;
  220762. if ((styleFlags & windowIsResizable) != 0)
  220763. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  220764. if ((styleFlags & windowHasMaximiseButton) != 0)
  220765. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  220766. if ((styleFlags & windowHasMinimiseButton) != 0)
  220767. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  220768. if ((styleFlags & windowHasCloseButton) != 0)
  220769. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  220770. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  220771. }
  220772. }
  220773. void setWindowType()
  220774. {
  220775. int netHints [2];
  220776. int numHints = 0;
  220777. if ((styleFlags & windowIsTemporary) != 0
  220778. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  220779. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  220780. else
  220781. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  220782. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  220783. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220784. (unsigned char*) &netHints, numHints);
  220785. numHints = 0;
  220786. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220787. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220788. if (component->isAlwaysOnTop())
  220789. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220790. if (numHints > 0)
  220791. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220792. (unsigned char*) &netHints, numHints);
  220793. }
  220794. void createWindow()
  220795. {
  220796. ScopedXLock xlock;
  220797. Atoms::initialiseAtoms();
  220798. resetDragAndDrop();
  220799. // Get defaults for various properties
  220800. const int screen = DefaultScreen (display);
  220801. Window root = RootWindow (display, screen);
  220802. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220803. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220804. if (visual == 0)
  220805. {
  220806. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220807. Process::terminate();
  220808. }
  220809. // Create and install a colormap suitable fr our visual
  220810. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220811. XInstallColormap (display, colormap);
  220812. // Set up the window attributes
  220813. XSetWindowAttributes swa;
  220814. swa.border_pixel = 0;
  220815. swa.background_pixmap = None;
  220816. swa.colormap = colormap;
  220817. swa.event_mask = getAllEventsMask();
  220818. windowH = XCreateWindow (display, root,
  220819. 0, 0, 1, 1,
  220820. 0, depth, InputOutput, visual,
  220821. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220822. &swa);
  220823. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220824. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220825. GrabModeAsync, GrabModeAsync, None, None);
  220826. // Set the window context to identify the window handle object
  220827. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220828. {
  220829. // Failed
  220830. jassertfalse;
  220831. Logger::outputDebugString ("Failed to create context information for window.\n");
  220832. XDestroyWindow (display, windowH);
  220833. windowH = 0;
  220834. return;
  220835. }
  220836. // Set window manager hints
  220837. XWMHints* wmHints = XAllocWMHints();
  220838. wmHints->flags = InputHint | StateHint;
  220839. wmHints->input = True; // Locally active input model
  220840. wmHints->initial_state = NormalState;
  220841. XSetWMHints (display, windowH, wmHints);
  220842. XFree (wmHints);
  220843. // Set the window type
  220844. setWindowType();
  220845. // Define decoration
  220846. if ((styleFlags & windowHasTitleBar) == 0)
  220847. removeWindowDecorations (windowH);
  220848. else
  220849. addWindowButtons (windowH);
  220850. setTitle (getComponent()->getName());
  220851. // Associate the PID, allowing to be shut down when something goes wrong
  220852. unsigned long pid = getpid();
  220853. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220854. (unsigned char*) &pid, 1);
  220855. // Set window manager protocols
  220856. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220857. (unsigned char*) Atoms::ProtocolList, 2);
  220858. // Set drag and drop flags
  220859. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220860. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220861. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220862. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220863. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220864. (const unsigned char*) "", 0);
  220865. unsigned long dndVersion = Atoms::DndVersion;
  220866. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220867. (const unsigned char*) &dndVersion, 1);
  220868. // Initialise the pointer and keyboard mapping
  220869. // This is not the same as the logical pointer mapping the X server uses:
  220870. // we don't mess with this.
  220871. static bool mappingInitialised = false;
  220872. if (! mappingInitialised)
  220873. {
  220874. mappingInitialised = true;
  220875. const int numButtons = XGetPointerMapping (display, 0, 0);
  220876. if (numButtons == 2)
  220877. {
  220878. pointerMap[0] = Keys::LeftButton;
  220879. pointerMap[1] = Keys::RightButton;
  220880. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220881. }
  220882. else if (numButtons >= 3)
  220883. {
  220884. pointerMap[0] = Keys::LeftButton;
  220885. pointerMap[1] = Keys::MiddleButton;
  220886. pointerMap[2] = Keys::RightButton;
  220887. if (numButtons >= 5)
  220888. {
  220889. pointerMap[3] = Keys::WheelUp;
  220890. pointerMap[4] = Keys::WheelDown;
  220891. }
  220892. }
  220893. updateModifierMappings();
  220894. }
  220895. }
  220896. void destroyWindow()
  220897. {
  220898. ScopedXLock xlock;
  220899. XPointer handlePointer;
  220900. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220901. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220902. XDestroyWindow (display, windowH);
  220903. // Wait for it to complete and then remove any events for this
  220904. // window from the event queue.
  220905. XSync (display, false);
  220906. XEvent event;
  220907. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220908. {}
  220909. }
  220910. static int getAllEventsMask() throw()
  220911. {
  220912. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220913. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220914. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220915. }
  220916. static int64 getEventTime (::Time t)
  220917. {
  220918. static int64 eventTimeOffset = 0x12345678;
  220919. const int64 thisMessageTime = t;
  220920. if (eventTimeOffset == 0x12345678)
  220921. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220922. return eventTimeOffset + thisMessageTime;
  220923. }
  220924. void updateBorderSize()
  220925. {
  220926. if ((styleFlags & windowHasTitleBar) == 0)
  220927. {
  220928. windowBorder = BorderSize (0);
  220929. }
  220930. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220931. {
  220932. ScopedXLock xlock;
  220933. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220934. if (hints != None)
  220935. {
  220936. unsigned char* data = 0;
  220937. unsigned long nitems, bytesLeft;
  220938. Atom actualType;
  220939. int actualFormat;
  220940. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220941. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220942. &data) == Success)
  220943. {
  220944. const unsigned long* const sizes = (const unsigned long*) data;
  220945. if (actualFormat == 32)
  220946. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  220947. (int) sizes[3], (int) sizes[1]);
  220948. XFree (data);
  220949. }
  220950. }
  220951. }
  220952. }
  220953. void updateBounds()
  220954. {
  220955. jassert (windowH != 0);
  220956. if (windowH != 0)
  220957. {
  220958. Window root, child;
  220959. unsigned int bw, depth;
  220960. ScopedXLock xlock;
  220961. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220962. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220963. &bw, &depth))
  220964. {
  220965. wx = wy = ww = wh = 0;
  220966. }
  220967. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220968. {
  220969. wx = wy = 0;
  220970. }
  220971. }
  220972. }
  220973. void resetDragAndDrop()
  220974. {
  220975. dragAndDropFiles.clear();
  220976. lastDropPos = Point<int> (-1, -1);
  220977. dragAndDropCurrentMimeType = 0;
  220978. dragAndDropSourceWindow = 0;
  220979. srcMimeTypeAtomList.clear();
  220980. }
  220981. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220982. {
  220983. msg.type = ClientMessage;
  220984. msg.display = display;
  220985. msg.window = dragAndDropSourceWindow;
  220986. msg.format = 32;
  220987. msg.data.l[0] = windowH;
  220988. ScopedXLock xlock;
  220989. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  220990. }
  220991. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  220992. {
  220993. XClientMessageEvent msg;
  220994. zerostruct (msg);
  220995. msg.message_type = Atoms::XdndStatus;
  220996. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  220997. msg.data.l[4] = dropAction;
  220998. sendDragAndDropMessage (msg);
  220999. }
  221000. void sendDragAndDropLeave()
  221001. {
  221002. XClientMessageEvent msg;
  221003. zerostruct (msg);
  221004. msg.message_type = Atoms::XdndLeave;
  221005. sendDragAndDropMessage (msg);
  221006. }
  221007. void sendDragAndDropFinish()
  221008. {
  221009. XClientMessageEvent msg;
  221010. zerostruct (msg);
  221011. msg.message_type = Atoms::XdndFinished;
  221012. sendDragAndDropMessage (msg);
  221013. }
  221014. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221015. {
  221016. if ((clientMsg->data.l[1] & 1) == 0)
  221017. {
  221018. sendDragAndDropLeave();
  221019. if (dragAndDropFiles.size() > 0)
  221020. handleFileDragExit (dragAndDropFiles);
  221021. dragAndDropFiles.clear();
  221022. }
  221023. }
  221024. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221025. {
  221026. if (dragAndDropSourceWindow == 0)
  221027. return;
  221028. dragAndDropSourceWindow = clientMsg->data.l[0];
  221029. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221030. (int) clientMsg->data.l[2] & 0xffff);
  221031. dropPos -= getScreenPosition();
  221032. if (lastDropPos != dropPos)
  221033. {
  221034. lastDropPos = dropPos;
  221035. dragAndDropTimestamp = clientMsg->data.l[3];
  221036. Atom targetAction = Atoms::XdndActionCopy;
  221037. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221038. {
  221039. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221040. {
  221041. targetAction = Atoms::allowedActions[i];
  221042. break;
  221043. }
  221044. }
  221045. sendDragAndDropStatus (true, targetAction);
  221046. if (dragAndDropFiles.size() == 0)
  221047. updateDraggedFileList (clientMsg);
  221048. if (dragAndDropFiles.size() > 0)
  221049. handleFileDragMove (dragAndDropFiles, dropPos);
  221050. }
  221051. }
  221052. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221053. {
  221054. if (dragAndDropFiles.size() == 0)
  221055. updateDraggedFileList (clientMsg);
  221056. const StringArray files (dragAndDropFiles);
  221057. const Point<int> lastPos (lastDropPos);
  221058. sendDragAndDropFinish();
  221059. resetDragAndDrop();
  221060. if (files.size() > 0)
  221061. handleFileDragDrop (files, lastPos);
  221062. }
  221063. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221064. {
  221065. dragAndDropFiles.clear();
  221066. srcMimeTypeAtomList.clear();
  221067. dragAndDropCurrentMimeType = 0;
  221068. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221069. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221070. {
  221071. dragAndDropSourceWindow = 0;
  221072. return;
  221073. }
  221074. dragAndDropSourceWindow = clientMsg->data.l[0];
  221075. if ((clientMsg->data.l[1] & 1) != 0)
  221076. {
  221077. Atom actual;
  221078. int format;
  221079. unsigned long count = 0, remaining = 0;
  221080. unsigned char* data = 0;
  221081. ScopedXLock xlock;
  221082. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221083. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221084. &count, &remaining, &data);
  221085. if (data != 0)
  221086. {
  221087. if (actual == XA_ATOM && format == 32 && count != 0)
  221088. {
  221089. const unsigned long* const types = (const unsigned long*) data;
  221090. for (unsigned int i = 0; i < count; ++i)
  221091. if (types[i] != None)
  221092. srcMimeTypeAtomList.add (types[i]);
  221093. }
  221094. XFree (data);
  221095. }
  221096. }
  221097. if (srcMimeTypeAtomList.size() == 0)
  221098. {
  221099. for (int i = 2; i < 5; ++i)
  221100. if (clientMsg->data.l[i] != None)
  221101. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221102. if (srcMimeTypeAtomList.size() == 0)
  221103. {
  221104. dragAndDropSourceWindow = 0;
  221105. return;
  221106. }
  221107. }
  221108. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221109. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221110. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221111. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221112. handleDragAndDropPosition (clientMsg);
  221113. }
  221114. void handleDragAndDropSelection (const XEvent* const evt)
  221115. {
  221116. dragAndDropFiles.clear();
  221117. if (evt->xselection.property != 0)
  221118. {
  221119. StringArray lines;
  221120. {
  221121. MemoryBlock dropData;
  221122. for (;;)
  221123. {
  221124. Atom actual;
  221125. uint8* data = 0;
  221126. unsigned long count = 0, remaining = 0;
  221127. int format = 0;
  221128. ScopedXLock xlock;
  221129. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221130. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221131. &format, &count, &remaining, &data) == Success)
  221132. {
  221133. dropData.append (data, count * format / 8);
  221134. XFree (data);
  221135. if (remaining == 0)
  221136. break;
  221137. }
  221138. else
  221139. {
  221140. XFree (data);
  221141. break;
  221142. }
  221143. }
  221144. lines.addLines (dropData.toString());
  221145. }
  221146. for (int i = 0; i < lines.size(); ++i)
  221147. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221148. dragAndDropFiles.trim();
  221149. dragAndDropFiles.removeEmptyStrings();
  221150. }
  221151. }
  221152. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221153. {
  221154. dragAndDropFiles.clear();
  221155. if (dragAndDropSourceWindow != None
  221156. && dragAndDropCurrentMimeType != 0)
  221157. {
  221158. dragAndDropTimestamp = clientMsg->data.l[2];
  221159. ScopedXLock xlock;
  221160. XConvertSelection (display,
  221161. Atoms::XdndSelection,
  221162. dragAndDropCurrentMimeType,
  221163. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221164. windowH,
  221165. dragAndDropTimestamp);
  221166. }
  221167. }
  221168. StringArray dragAndDropFiles;
  221169. int dragAndDropTimestamp;
  221170. Point<int> lastDropPos;
  221171. Atom dragAndDropCurrentMimeType;
  221172. Window dragAndDropSourceWindow;
  221173. Array <Atom> srcMimeTypeAtomList;
  221174. static int pointerMap[5];
  221175. static Point<int> lastMousePos;
  221176. static void clearLastMousePos() throw()
  221177. {
  221178. lastMousePos = Point<int> (0x100000, 0x100000);
  221179. }
  221180. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  221181. };
  221182. ModifierKeys LinuxComponentPeer::currentModifiers;
  221183. bool LinuxComponentPeer::isActiveApplication = false;
  221184. int LinuxComponentPeer::pointerMap[5];
  221185. Point<int> LinuxComponentPeer::lastMousePos;
  221186. bool Process::isForegroundProcess()
  221187. {
  221188. return LinuxComponentPeer::isActiveApplication;
  221189. }
  221190. void ModifierKeys::updateCurrentModifiers() throw()
  221191. {
  221192. currentModifiers = LinuxComponentPeer::currentModifiers;
  221193. }
  221194. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221195. {
  221196. Window root, child;
  221197. int x, y, winx, winy;
  221198. unsigned int mask;
  221199. int mouseMods = 0;
  221200. ScopedXLock xlock;
  221201. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221202. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221203. {
  221204. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221205. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221206. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221207. }
  221208. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221209. return LinuxComponentPeer::currentModifiers;
  221210. }
  221211. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221212. {
  221213. if (enableOrDisable)
  221214. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221215. }
  221216. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221217. {
  221218. return new LinuxComponentPeer (this, styleFlags);
  221219. }
  221220. // (this callback is hooked up in the messaging code)
  221221. void juce_windowMessageReceive (XEvent* event)
  221222. {
  221223. if (event->xany.window != None)
  221224. {
  221225. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221226. if (ComponentPeer::isValidPeer (peer))
  221227. peer->handleWindowMessage (event);
  221228. }
  221229. else
  221230. {
  221231. switch (event->xany.type)
  221232. {
  221233. case KeymapNotify:
  221234. {
  221235. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221236. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221237. break;
  221238. }
  221239. default:
  221240. break;
  221241. }
  221242. }
  221243. }
  221244. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221245. {
  221246. if (display == 0)
  221247. return;
  221248. #if JUCE_USE_XINERAMA
  221249. int major_opcode, first_event, first_error;
  221250. ScopedXLock xlock;
  221251. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221252. {
  221253. typedef Bool (*tXineramaIsActive) (Display*);
  221254. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221255. static tXineramaIsActive xXineramaIsActive = 0;
  221256. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221257. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221258. {
  221259. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221260. if (h == 0)
  221261. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221262. if (h != 0)
  221263. {
  221264. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221265. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221266. }
  221267. }
  221268. if (xXineramaIsActive != 0
  221269. && xXineramaQueryScreens != 0
  221270. && xXineramaIsActive (display))
  221271. {
  221272. int numMonitors = 0;
  221273. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221274. if (screens != 0)
  221275. {
  221276. for (int i = numMonitors; --i >= 0;)
  221277. {
  221278. int index = screens[i].screen_number;
  221279. if (index >= 0)
  221280. {
  221281. while (monitorCoords.size() < index)
  221282. monitorCoords.add (Rectangle<int>());
  221283. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221284. screens[i].y_org,
  221285. screens[i].width,
  221286. screens[i].height));
  221287. }
  221288. }
  221289. XFree (screens);
  221290. }
  221291. }
  221292. }
  221293. if (monitorCoords.size() == 0)
  221294. #endif
  221295. {
  221296. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221297. if (hints != None)
  221298. {
  221299. const int numMonitors = ScreenCount (display);
  221300. for (int i = 0; i < numMonitors; ++i)
  221301. {
  221302. Window root = RootWindow (display, i);
  221303. unsigned long nitems, bytesLeft;
  221304. Atom actualType;
  221305. int actualFormat;
  221306. unsigned char* data = 0;
  221307. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221308. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221309. &data) == Success)
  221310. {
  221311. const long* const position = (const long*) data;
  221312. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221313. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221314. position[2], position[3]));
  221315. XFree (data);
  221316. }
  221317. }
  221318. }
  221319. if (monitorCoords.size() == 0)
  221320. {
  221321. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221322. DisplayHeight (display, DefaultScreen (display))));
  221323. }
  221324. }
  221325. }
  221326. void Desktop::createMouseInputSources()
  221327. {
  221328. mouseSources.add (new MouseInputSource (0, true));
  221329. }
  221330. bool Desktop::canUseSemiTransparentWindows() throw()
  221331. {
  221332. int matchedDepth = 0;
  221333. const int desiredDepth = 32;
  221334. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221335. && (matchedDepth == desiredDepth);
  221336. }
  221337. const Point<int> MouseInputSource::getCurrentMousePosition()
  221338. {
  221339. Window root, child;
  221340. int x, y, winx, winy;
  221341. unsigned int mask;
  221342. ScopedXLock xlock;
  221343. if (XQueryPointer (display,
  221344. RootWindow (display, DefaultScreen (display)),
  221345. &root, &child,
  221346. &x, &y, &winx, &winy, &mask) == False)
  221347. {
  221348. // Pointer not on the default screen
  221349. x = y = -1;
  221350. }
  221351. return Point<int> (x, y);
  221352. }
  221353. void Desktop::setMousePosition (const Point<int>& newPosition)
  221354. {
  221355. ScopedXLock xlock;
  221356. Window root = RootWindow (display, DefaultScreen (display));
  221357. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221358. }
  221359. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  221360. {
  221361. return upright;
  221362. }
  221363. static bool screenSaverAllowed = true;
  221364. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221365. {
  221366. if (screenSaverAllowed != isEnabled)
  221367. {
  221368. screenSaverAllowed = isEnabled;
  221369. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221370. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221371. if (xScreenSaverSuspend == 0)
  221372. {
  221373. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221374. if (h != 0)
  221375. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221376. }
  221377. ScopedXLock xlock;
  221378. if (xScreenSaverSuspend != 0)
  221379. xScreenSaverSuspend (display, ! isEnabled);
  221380. }
  221381. }
  221382. bool Desktop::isScreenSaverEnabled()
  221383. {
  221384. return screenSaverAllowed;
  221385. }
  221386. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221387. {
  221388. ScopedXLock xlock;
  221389. const unsigned int imageW = image.getWidth();
  221390. const unsigned int imageH = image.getHeight();
  221391. #if JUCE_USE_XCURSOR
  221392. {
  221393. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221394. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221395. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221396. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221397. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221398. static tXcursorImageCreate xXcursorImageCreate = 0;
  221399. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221400. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221401. static bool hasBeenLoaded = false;
  221402. if (! hasBeenLoaded)
  221403. {
  221404. hasBeenLoaded = true;
  221405. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221406. if (h != 0)
  221407. {
  221408. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221409. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221410. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221411. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221412. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221413. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221414. || ! xXcursorSupportsARGB (display))
  221415. xXcursorSupportsARGB = 0;
  221416. }
  221417. }
  221418. if (xXcursorSupportsARGB != 0)
  221419. {
  221420. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221421. if (xcImage != 0)
  221422. {
  221423. xcImage->xhot = hotspotX;
  221424. xcImage->yhot = hotspotY;
  221425. XcursorPixel* dest = xcImage->pixels;
  221426. for (int y = 0; y < (int) imageH; ++y)
  221427. for (int x = 0; x < (int) imageW; ++x)
  221428. *dest++ = image.getPixelAt (x, y).getARGB();
  221429. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221430. xXcursorImageDestroy (xcImage);
  221431. if (result != 0)
  221432. return result;
  221433. }
  221434. }
  221435. }
  221436. #endif
  221437. Window root = RootWindow (display, DefaultScreen (display));
  221438. unsigned int cursorW, cursorH;
  221439. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221440. return 0;
  221441. Image im (Image::ARGB, cursorW, cursorH, true);
  221442. {
  221443. Graphics g (im);
  221444. if (imageW > cursorW || imageH > cursorH)
  221445. {
  221446. hotspotX = (hotspotX * cursorW) / imageW;
  221447. hotspotY = (hotspotY * cursorH) / imageH;
  221448. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221449. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221450. false);
  221451. }
  221452. else
  221453. {
  221454. g.drawImageAt (image, 0, 0);
  221455. }
  221456. }
  221457. const int stride = (cursorW + 7) >> 3;
  221458. HeapBlock <char> maskPlane, sourcePlane;
  221459. maskPlane.calloc (stride * cursorH);
  221460. sourcePlane.calloc (stride * cursorH);
  221461. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221462. for (int y = cursorH; --y >= 0;)
  221463. {
  221464. for (int x = cursorW; --x >= 0;)
  221465. {
  221466. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221467. const int offset = y * stride + (x >> 3);
  221468. const Colour c (im.getPixelAt (x, y));
  221469. if (c.getAlpha() >= 128)
  221470. maskPlane[offset] |= mask;
  221471. if (c.getBrightness() >= 0.5f)
  221472. sourcePlane[offset] |= mask;
  221473. }
  221474. }
  221475. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221476. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221477. XColor white, black;
  221478. black.red = black.green = black.blue = 0;
  221479. white.red = white.green = white.blue = 0xffff;
  221480. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221481. XFreePixmap (display, sourcePixmap);
  221482. XFreePixmap (display, maskPixmap);
  221483. return result;
  221484. }
  221485. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221486. {
  221487. ScopedXLock xlock;
  221488. if (cursorHandle != 0)
  221489. XFreeCursor (display, (Cursor) cursorHandle);
  221490. }
  221491. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221492. {
  221493. unsigned int shape;
  221494. switch (type)
  221495. {
  221496. case NormalCursor: return None; // Use parent cursor
  221497. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221498. case WaitCursor: shape = XC_watch; break;
  221499. case IBeamCursor: shape = XC_xterm; break;
  221500. case PointingHandCursor: shape = XC_hand2; break;
  221501. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221502. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221503. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221504. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221505. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221506. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221507. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221508. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221509. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221510. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221511. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221512. case CrosshairCursor: shape = XC_crosshair; break;
  221513. case DraggingHandCursor:
  221514. {
  221515. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221516. 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,
  221517. 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 };
  221518. const int dragHandDataSize = 99;
  221519. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221520. }
  221521. case CopyingCursor:
  221522. {
  221523. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221524. 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,
  221525. 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,
  221526. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221527. const int copyCursorSize = 119;
  221528. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221529. }
  221530. default:
  221531. jassertfalse;
  221532. return None;
  221533. }
  221534. ScopedXLock xlock;
  221535. return (void*) XCreateFontCursor (display, shape);
  221536. }
  221537. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221538. {
  221539. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221540. if (lp != 0)
  221541. lp->showMouseCursor ((Cursor) getHandle());
  221542. }
  221543. void MouseCursor::showInAllWindows() const
  221544. {
  221545. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221546. showInWindow (ComponentPeer::getPeer (i));
  221547. }
  221548. const Image juce_createIconForFile (const File& file)
  221549. {
  221550. return Image::null;
  221551. }
  221552. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221553. {
  221554. return createSoftwareImage (format, width, height, clearImage);
  221555. }
  221556. #if JUCE_OPENGL
  221557. class WindowedGLContext : public OpenGLContext
  221558. {
  221559. public:
  221560. WindowedGLContext (Component* const component,
  221561. const OpenGLPixelFormat& pixelFormat_,
  221562. GLXContext sharedContext)
  221563. : renderContext (0),
  221564. embeddedWindow (0),
  221565. pixelFormat (pixelFormat_),
  221566. swapInterval (0)
  221567. {
  221568. jassert (component != 0);
  221569. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221570. if (peer == 0)
  221571. return;
  221572. ScopedXLock xlock;
  221573. XSync (display, False);
  221574. GLint attribs [64];
  221575. int n = 0;
  221576. attribs[n++] = GLX_RGBA;
  221577. attribs[n++] = GLX_DOUBLEBUFFER;
  221578. attribs[n++] = GLX_RED_SIZE;
  221579. attribs[n++] = pixelFormat.redBits;
  221580. attribs[n++] = GLX_GREEN_SIZE;
  221581. attribs[n++] = pixelFormat.greenBits;
  221582. attribs[n++] = GLX_BLUE_SIZE;
  221583. attribs[n++] = pixelFormat.blueBits;
  221584. attribs[n++] = GLX_ALPHA_SIZE;
  221585. attribs[n++] = pixelFormat.alphaBits;
  221586. attribs[n++] = GLX_DEPTH_SIZE;
  221587. attribs[n++] = pixelFormat.depthBufferBits;
  221588. attribs[n++] = GLX_STENCIL_SIZE;
  221589. attribs[n++] = pixelFormat.stencilBufferBits;
  221590. attribs[n++] = GLX_ACCUM_RED_SIZE;
  221591. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221592. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  221593. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221594. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  221595. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221596. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  221597. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221598. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  221599. attribs[n++] = None;
  221600. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  221601. if (bestVisual == 0)
  221602. return;
  221603. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  221604. Window windowH = (Window) peer->getNativeHandle();
  221605. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  221606. XSetWindowAttributes swa;
  221607. swa.colormap = colourMap;
  221608. swa.border_pixel = 0;
  221609. swa.event_mask = ExposureMask | StructureNotifyMask;
  221610. embeddedWindow = XCreateWindow (display, windowH,
  221611. 0, 0, 1, 1, 0,
  221612. bestVisual->depth,
  221613. InputOutput,
  221614. bestVisual->visual,
  221615. CWBorderPixel | CWColormap | CWEventMask,
  221616. &swa);
  221617. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  221618. XMapWindow (display, embeddedWindow);
  221619. XFreeColormap (display, colourMap);
  221620. XFree (bestVisual);
  221621. XSync (display, False);
  221622. }
  221623. ~WindowedGLContext()
  221624. {
  221625. ScopedXLock xlock;
  221626. deleteContext();
  221627. XUnmapWindow (display, embeddedWindow);
  221628. XDestroyWindow (display, embeddedWindow);
  221629. }
  221630. void deleteContext()
  221631. {
  221632. makeInactive();
  221633. if (renderContext != 0)
  221634. {
  221635. ScopedXLock xlock;
  221636. glXDestroyContext (display, renderContext);
  221637. renderContext = 0;
  221638. }
  221639. }
  221640. bool makeActive() const throw()
  221641. {
  221642. jassert (renderContext != 0);
  221643. ScopedXLock xlock;
  221644. return glXMakeCurrent (display, embeddedWindow, renderContext)
  221645. && XSync (display, False);
  221646. }
  221647. bool makeInactive() const throw()
  221648. {
  221649. ScopedXLock xlock;
  221650. return (! isActive()) || glXMakeCurrent (display, None, 0);
  221651. }
  221652. bool isActive() const throw()
  221653. {
  221654. ScopedXLock xlock;
  221655. return glXGetCurrentContext() == renderContext;
  221656. }
  221657. const OpenGLPixelFormat getPixelFormat() const
  221658. {
  221659. return pixelFormat;
  221660. }
  221661. void* getRawContext() const throw()
  221662. {
  221663. return renderContext;
  221664. }
  221665. void updateWindowPosition (int x, int y, int w, int h, int)
  221666. {
  221667. ScopedXLock xlock;
  221668. XMoveResizeWindow (display, embeddedWindow,
  221669. x, y, jmax (1, w), jmax (1, h));
  221670. }
  221671. void swapBuffers()
  221672. {
  221673. ScopedXLock xlock;
  221674. glXSwapBuffers (display, embeddedWindow);
  221675. }
  221676. bool setSwapInterval (const int numFramesPerSwap)
  221677. {
  221678. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  221679. if (GLXSwapIntervalSGI != 0)
  221680. {
  221681. swapInterval = numFramesPerSwap;
  221682. GLXSwapIntervalSGI (numFramesPerSwap);
  221683. return true;
  221684. }
  221685. return false;
  221686. }
  221687. int getSwapInterval() const
  221688. {
  221689. return swapInterval;
  221690. }
  221691. void repaint()
  221692. {
  221693. }
  221694. GLXContext renderContext;
  221695. private:
  221696. Window embeddedWindow;
  221697. OpenGLPixelFormat pixelFormat;
  221698. int swapInterval;
  221699. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  221700. };
  221701. OpenGLContext* OpenGLComponent::createContext()
  221702. {
  221703. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  221704. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  221705. return (c->renderContext != 0) ? c.release() : 0;
  221706. }
  221707. void juce_glViewport (const int w, const int h)
  221708. {
  221709. glViewport (0, 0, w, h);
  221710. }
  221711. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  221712. OwnedArray <OpenGLPixelFormat>& results)
  221713. {
  221714. results.add (new OpenGLPixelFormat()); // xxx
  221715. }
  221716. #endif
  221717. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221718. {
  221719. jassertfalse; // not implemented!
  221720. return false;
  221721. }
  221722. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221723. {
  221724. jassertfalse; // not implemented!
  221725. return false;
  221726. }
  221727. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  221728. {
  221729. if (! isOnDesktop ())
  221730. addToDesktop (0);
  221731. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221732. if (wp != 0)
  221733. {
  221734. wp->setTaskBarIcon (newImage);
  221735. setVisible (true);
  221736. toFront (false);
  221737. repaint();
  221738. }
  221739. }
  221740. void SystemTrayIconComponent::paint (Graphics& g)
  221741. {
  221742. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221743. if (wp != 0)
  221744. {
  221745. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  221746. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221747. false);
  221748. }
  221749. }
  221750. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  221751. {
  221752. // xxx not yet implemented!
  221753. }
  221754. void PlatformUtilities::beep()
  221755. {
  221756. std::cout << "\a" << std::flush;
  221757. }
  221758. bool AlertWindow::showNativeDialogBox (const String& title,
  221759. const String& bodyText,
  221760. bool isOkCancel)
  221761. {
  221762. // use a non-native one for the time being..
  221763. if (isOkCancel)
  221764. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  221765. else
  221766. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  221767. return true;
  221768. }
  221769. const int KeyPress::spaceKey = XK_space & 0xff;
  221770. const int KeyPress::returnKey = XK_Return & 0xff;
  221771. const int KeyPress::escapeKey = XK_Escape & 0xff;
  221772. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  221773. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221774. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221775. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221776. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221777. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221778. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221779. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221780. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221781. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221782. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221783. const int KeyPress::tabKey = XK_Tab & 0xff;
  221784. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221785. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221786. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221787. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221788. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221789. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221790. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221791. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221792. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221793. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221794. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221795. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221796. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221797. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221798. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221799. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221800. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221801. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221802. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221803. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221804. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221805. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221806. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221807. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221808. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221809. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221810. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221811. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221812. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221813. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221814. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221815. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221816. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221817. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221818. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221819. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221820. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221821. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221822. #endif
  221823. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221824. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221825. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221826. // compiled on its own).
  221827. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221828. namespace
  221829. {
  221830. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221831. {
  221832. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221833. snd_pcm_hw_params_t* hwParams;
  221834. snd_pcm_hw_params_alloca (&hwParams);
  221835. for (int i = 0; ratesToTry[i] != 0; ++i)
  221836. {
  221837. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221838. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221839. {
  221840. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221841. }
  221842. }
  221843. }
  221844. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221845. {
  221846. snd_pcm_hw_params_t *params;
  221847. snd_pcm_hw_params_alloca (&params);
  221848. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221849. {
  221850. snd_pcm_hw_params_get_channels_min (params, minChans);
  221851. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221852. }
  221853. }
  221854. void getDeviceProperties (const String& deviceID,
  221855. unsigned int& minChansOut,
  221856. unsigned int& maxChansOut,
  221857. unsigned int& minChansIn,
  221858. unsigned int& maxChansIn,
  221859. Array <int>& rates)
  221860. {
  221861. if (deviceID.isEmpty())
  221862. return;
  221863. snd_ctl_t* handle;
  221864. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221865. {
  221866. snd_pcm_info_t* info;
  221867. snd_pcm_info_alloca (&info);
  221868. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221869. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221870. snd_pcm_info_set_subdevice (info, 0);
  221871. if (snd_ctl_pcm_info (handle, info) >= 0)
  221872. {
  221873. snd_pcm_t* pcmHandle;
  221874. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221875. {
  221876. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221877. getDeviceSampleRates (pcmHandle, rates);
  221878. snd_pcm_close (pcmHandle);
  221879. }
  221880. }
  221881. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221882. if (snd_ctl_pcm_info (handle, info) >= 0)
  221883. {
  221884. snd_pcm_t* pcmHandle;
  221885. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221886. {
  221887. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221888. if (rates.size() == 0)
  221889. getDeviceSampleRates (pcmHandle, rates);
  221890. snd_pcm_close (pcmHandle);
  221891. }
  221892. }
  221893. snd_ctl_close (handle);
  221894. }
  221895. }
  221896. }
  221897. class ALSADevice
  221898. {
  221899. public:
  221900. ALSADevice (const String& deviceID, bool forInput)
  221901. : handle (0),
  221902. bitDepth (16),
  221903. numChannelsRunning (0),
  221904. latency (0),
  221905. isInput (forInput),
  221906. isInterleaved (true)
  221907. {
  221908. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221909. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221910. SND_PCM_ASYNC));
  221911. }
  221912. ~ALSADevice()
  221913. {
  221914. if (handle != 0)
  221915. snd_pcm_close (handle);
  221916. }
  221917. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221918. {
  221919. if (handle == 0)
  221920. return false;
  221921. snd_pcm_hw_params_t* hwParams;
  221922. snd_pcm_hw_params_alloca (&hwParams);
  221923. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221924. return false;
  221925. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221926. isInterleaved = false;
  221927. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221928. isInterleaved = true;
  221929. else
  221930. {
  221931. jassertfalse;
  221932. return false;
  221933. }
  221934. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  221935. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  221936. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  221937. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  221938. SND_PCM_FORMAT_S32_BE, 32,
  221939. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  221940. SND_PCM_FORMAT_S24_3BE, 24,
  221941. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  221942. SND_PCM_FORMAT_S16_BE, 16 };
  221943. bitDepth = 0;
  221944. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  221945. {
  221946. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221947. {
  221948. bitDepth = formatsToTry [i + 1] & 255;
  221949. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  221950. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  221951. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  221952. break;
  221953. }
  221954. }
  221955. if (bitDepth == 0)
  221956. {
  221957. error = "device doesn't support a compatible PCM format";
  221958. DBG ("ALSA error: " + error + "\n");
  221959. return false;
  221960. }
  221961. int dir = 0;
  221962. unsigned int periods = 4;
  221963. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  221964. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  221965. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  221966. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  221967. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221968. || failed (snd_pcm_hw_params (handle, hwParams)))
  221969. {
  221970. return false;
  221971. }
  221972. snd_pcm_uframes_t frames = 0;
  221973. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  221974. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  221975. latency = 0;
  221976. else
  221977. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  221978. snd_pcm_sw_params_t* swParams;
  221979. snd_pcm_sw_params_alloca (&swParams);
  221980. snd_pcm_uframes_t boundary;
  221981. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221982. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221983. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221984. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221985. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221986. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221987. || failed (snd_pcm_sw_params (handle, swParams)))
  221988. {
  221989. return false;
  221990. }
  221991. #if 0
  221992. // enable this to dump the config of the devices that get opened
  221993. snd_output_t* out;
  221994. snd_output_stdio_attach (&out, stderr, 0);
  221995. snd_pcm_hw_params_dump (hwParams, out);
  221996. snd_pcm_sw_params_dump (swParams, out);
  221997. #endif
  221998. numChannelsRunning = numChannels;
  221999. return true;
  222000. }
  222001. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222002. {
  222003. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222004. float** const data = outputChannelBuffer.getArrayOfChannels();
  222005. snd_pcm_sframes_t numDone = 0;
  222006. if (isInterleaved)
  222007. {
  222008. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222009. for (int i = 0; i < numChannelsRunning; ++i)
  222010. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222011. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222012. }
  222013. else
  222014. {
  222015. for (int i = 0; i < numChannelsRunning; ++i)
  222016. converter->convertSamples (data[i], data[i], numSamples);
  222017. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222018. }
  222019. if (failed (numDone))
  222020. {
  222021. if (numDone == -EPIPE)
  222022. {
  222023. if (failed (snd_pcm_prepare (handle)))
  222024. return false;
  222025. }
  222026. else if (numDone != -ESTRPIPE)
  222027. return false;
  222028. }
  222029. return true;
  222030. }
  222031. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222032. {
  222033. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222034. float** const data = inputChannelBuffer.getArrayOfChannels();
  222035. if (isInterleaved)
  222036. {
  222037. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222038. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  222039. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222040. if (failed (num))
  222041. {
  222042. if (num == -EPIPE)
  222043. {
  222044. if (failed (snd_pcm_prepare (handle)))
  222045. return false;
  222046. }
  222047. else if (num != -ESTRPIPE)
  222048. return false;
  222049. }
  222050. for (int i = 0; i < numChannelsRunning; ++i)
  222051. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222052. }
  222053. else
  222054. {
  222055. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222056. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222057. return false;
  222058. for (int i = 0; i < numChannelsRunning; ++i)
  222059. converter->convertSamples (data[i], data[i], numSamples);
  222060. }
  222061. return true;
  222062. }
  222063. snd_pcm_t* handle;
  222064. String error;
  222065. int bitDepth, numChannelsRunning, latency;
  222066. private:
  222067. const bool isInput;
  222068. bool isInterleaved;
  222069. MemoryBlock scratch;
  222070. ScopedPointer<AudioData::Converter> converter;
  222071. template <class SampleType>
  222072. struct ConverterHelper
  222073. {
  222074. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222075. {
  222076. if (forInput)
  222077. {
  222078. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222079. if (isLittleEndian)
  222080. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222081. else
  222082. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222083. }
  222084. else
  222085. {
  222086. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222087. if (isLittleEndian)
  222088. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222089. else
  222090. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222091. }
  222092. }
  222093. };
  222094. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222095. {
  222096. switch (bitDepth)
  222097. {
  222098. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222099. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222100. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222101. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222102. default: jassertfalse; break; // unsupported format!
  222103. }
  222104. return 0;
  222105. }
  222106. bool failed (const int errorNum)
  222107. {
  222108. if (errorNum >= 0)
  222109. return false;
  222110. error = snd_strerror (errorNum);
  222111. DBG ("ALSA error: " + error + "\n");
  222112. return true;
  222113. }
  222114. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice);
  222115. };
  222116. class ALSAThread : public Thread
  222117. {
  222118. public:
  222119. ALSAThread (const String& inputId_,
  222120. const String& outputId_)
  222121. : Thread ("Juce ALSA"),
  222122. sampleRate (0),
  222123. bufferSize (0),
  222124. outputLatency (0),
  222125. inputLatency (0),
  222126. callback (0),
  222127. inputId (inputId_),
  222128. outputId (outputId_),
  222129. numCallbacks (0),
  222130. inputChannelBuffer (1, 1),
  222131. outputChannelBuffer (1, 1)
  222132. {
  222133. initialiseRatesAndChannels();
  222134. }
  222135. ~ALSAThread()
  222136. {
  222137. close();
  222138. }
  222139. void open (BigInteger inputChannels,
  222140. BigInteger outputChannels,
  222141. const double sampleRate_,
  222142. const int bufferSize_)
  222143. {
  222144. close();
  222145. error = String::empty;
  222146. sampleRate = sampleRate_;
  222147. bufferSize = bufferSize_;
  222148. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222149. inputChannelBuffer.clear();
  222150. inputChannelDataForCallback.clear();
  222151. currentInputChans.clear();
  222152. if (inputChannels.getHighestBit() >= 0)
  222153. {
  222154. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222155. {
  222156. if (inputChannels[i])
  222157. {
  222158. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222159. currentInputChans.setBit (i);
  222160. }
  222161. }
  222162. }
  222163. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222164. outputChannelBuffer.clear();
  222165. outputChannelDataForCallback.clear();
  222166. currentOutputChans.clear();
  222167. if (outputChannels.getHighestBit() >= 0)
  222168. {
  222169. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222170. {
  222171. if (outputChannels[i])
  222172. {
  222173. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222174. currentOutputChans.setBit (i);
  222175. }
  222176. }
  222177. }
  222178. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222179. {
  222180. outputDevice = new ALSADevice (outputId, false);
  222181. if (outputDevice->error.isNotEmpty())
  222182. {
  222183. error = outputDevice->error;
  222184. outputDevice = 0;
  222185. return;
  222186. }
  222187. currentOutputChans.setRange (0, minChansOut, true);
  222188. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222189. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222190. bufferSize))
  222191. {
  222192. error = outputDevice->error;
  222193. outputDevice = 0;
  222194. return;
  222195. }
  222196. outputLatency = outputDevice->latency;
  222197. }
  222198. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222199. {
  222200. inputDevice = new ALSADevice (inputId, true);
  222201. if (inputDevice->error.isNotEmpty())
  222202. {
  222203. error = inputDevice->error;
  222204. inputDevice = 0;
  222205. return;
  222206. }
  222207. currentInputChans.setRange (0, minChansIn, true);
  222208. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222209. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222210. bufferSize))
  222211. {
  222212. error = inputDevice->error;
  222213. inputDevice = 0;
  222214. return;
  222215. }
  222216. inputLatency = inputDevice->latency;
  222217. }
  222218. if (outputDevice == 0 && inputDevice == 0)
  222219. {
  222220. error = "no channels";
  222221. return;
  222222. }
  222223. if (outputDevice != 0 && inputDevice != 0)
  222224. {
  222225. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222226. }
  222227. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222228. return;
  222229. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222230. return;
  222231. startThread (9);
  222232. int count = 1000;
  222233. while (numCallbacks == 0)
  222234. {
  222235. sleep (5);
  222236. if (--count < 0 || ! isThreadRunning())
  222237. {
  222238. error = "device didn't start";
  222239. break;
  222240. }
  222241. }
  222242. }
  222243. void close()
  222244. {
  222245. stopThread (6000);
  222246. inputDevice = 0;
  222247. outputDevice = 0;
  222248. inputChannelBuffer.setSize (1, 1);
  222249. outputChannelBuffer.setSize (1, 1);
  222250. numCallbacks = 0;
  222251. }
  222252. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222253. {
  222254. const ScopedLock sl (callbackLock);
  222255. callback = newCallback;
  222256. }
  222257. void run()
  222258. {
  222259. while (! threadShouldExit())
  222260. {
  222261. if (inputDevice != 0)
  222262. {
  222263. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222264. {
  222265. DBG ("ALSA: read failure");
  222266. break;
  222267. }
  222268. }
  222269. if (threadShouldExit())
  222270. break;
  222271. {
  222272. const ScopedLock sl (callbackLock);
  222273. ++numCallbacks;
  222274. if (callback != 0)
  222275. {
  222276. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222277. inputChannelDataForCallback.size(),
  222278. outputChannelDataForCallback.getRawDataPointer(),
  222279. outputChannelDataForCallback.size(),
  222280. bufferSize);
  222281. }
  222282. else
  222283. {
  222284. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222285. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222286. }
  222287. }
  222288. if (outputDevice != 0)
  222289. {
  222290. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222291. if (threadShouldExit())
  222292. break;
  222293. failed (snd_pcm_avail_update (outputDevice->handle));
  222294. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222295. {
  222296. DBG ("ALSA: write failure");
  222297. break;
  222298. }
  222299. }
  222300. }
  222301. }
  222302. int getBitDepth() const throw()
  222303. {
  222304. if (outputDevice != 0)
  222305. return outputDevice->bitDepth;
  222306. if (inputDevice != 0)
  222307. return inputDevice->bitDepth;
  222308. return 16;
  222309. }
  222310. String error;
  222311. double sampleRate;
  222312. int bufferSize, outputLatency, inputLatency;
  222313. BigInteger currentInputChans, currentOutputChans;
  222314. Array <int> sampleRates;
  222315. StringArray channelNamesOut, channelNamesIn;
  222316. AudioIODeviceCallback* callback;
  222317. private:
  222318. const String inputId, outputId;
  222319. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222320. int numCallbacks;
  222321. CriticalSection callbackLock;
  222322. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222323. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222324. unsigned int minChansOut, maxChansOut;
  222325. unsigned int minChansIn, maxChansIn;
  222326. bool failed (const int errorNum)
  222327. {
  222328. if (errorNum >= 0)
  222329. return false;
  222330. error = snd_strerror (errorNum);
  222331. DBG ("ALSA error: " + error + "\n");
  222332. return true;
  222333. }
  222334. void initialiseRatesAndChannels()
  222335. {
  222336. sampleRates.clear();
  222337. channelNamesOut.clear();
  222338. channelNamesIn.clear();
  222339. minChansOut = 0;
  222340. maxChansOut = 0;
  222341. minChansIn = 0;
  222342. maxChansIn = 0;
  222343. unsigned int dummy = 0;
  222344. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222345. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222346. unsigned int i;
  222347. for (i = 0; i < maxChansOut; ++i)
  222348. channelNamesOut.add ("channel " + String ((int) i + 1));
  222349. for (i = 0; i < maxChansIn; ++i)
  222350. channelNamesIn.add ("channel " + String ((int) i + 1));
  222351. }
  222352. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread);
  222353. };
  222354. class ALSAAudioIODevice : public AudioIODevice
  222355. {
  222356. public:
  222357. ALSAAudioIODevice (const String& deviceName,
  222358. const String& inputId_,
  222359. const String& outputId_)
  222360. : AudioIODevice (deviceName, "ALSA"),
  222361. inputId (inputId_),
  222362. outputId (outputId_),
  222363. isOpen_ (false),
  222364. isStarted (false),
  222365. internal (inputId_, outputId_)
  222366. {
  222367. }
  222368. ~ALSAAudioIODevice()
  222369. {
  222370. }
  222371. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222372. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222373. int getNumSampleRates() { return internal.sampleRates.size(); }
  222374. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222375. int getDefaultBufferSize() { return 512; }
  222376. int getNumBufferSizesAvailable() { return 50; }
  222377. int getBufferSizeSamples (int index)
  222378. {
  222379. int n = 16;
  222380. for (int i = 0; i < index; ++i)
  222381. n += n < 64 ? 16
  222382. : (n < 512 ? 32
  222383. : (n < 1024 ? 64
  222384. : (n < 2048 ? 128 : 256)));
  222385. return n;
  222386. }
  222387. const String open (const BigInteger& inputChannels,
  222388. const BigInteger& outputChannels,
  222389. double sampleRate,
  222390. int bufferSizeSamples)
  222391. {
  222392. close();
  222393. if (bufferSizeSamples <= 0)
  222394. bufferSizeSamples = getDefaultBufferSize();
  222395. if (sampleRate <= 0)
  222396. {
  222397. for (int i = 0; i < getNumSampleRates(); ++i)
  222398. {
  222399. if (getSampleRate (i) >= 44100)
  222400. {
  222401. sampleRate = getSampleRate (i);
  222402. break;
  222403. }
  222404. }
  222405. }
  222406. internal.open (inputChannels, outputChannels,
  222407. sampleRate, bufferSizeSamples);
  222408. isOpen_ = internal.error.isEmpty();
  222409. return internal.error;
  222410. }
  222411. void close()
  222412. {
  222413. stop();
  222414. internal.close();
  222415. isOpen_ = false;
  222416. }
  222417. bool isOpen() { return isOpen_; }
  222418. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222419. const String getLastError() { return internal.error; }
  222420. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222421. double getCurrentSampleRate() { return internal.sampleRate; }
  222422. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222423. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222424. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222425. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222426. int getInputLatencyInSamples() { return internal.inputLatency; }
  222427. void start (AudioIODeviceCallback* callback)
  222428. {
  222429. if (! isOpen_)
  222430. callback = 0;
  222431. if (callback != 0)
  222432. callback->audioDeviceAboutToStart (this);
  222433. internal.setCallback (callback);
  222434. isStarted = (callback != 0);
  222435. }
  222436. void stop()
  222437. {
  222438. AudioIODeviceCallback* const oldCallback = internal.callback;
  222439. start (0);
  222440. if (oldCallback != 0)
  222441. oldCallback->audioDeviceStopped();
  222442. }
  222443. String inputId, outputId;
  222444. private:
  222445. bool isOpen_, isStarted;
  222446. ALSAThread internal;
  222447. };
  222448. class ALSAAudioIODeviceType : public AudioIODeviceType
  222449. {
  222450. public:
  222451. ALSAAudioIODeviceType()
  222452. : AudioIODeviceType ("ALSA"),
  222453. hasScanned (false)
  222454. {
  222455. }
  222456. ~ALSAAudioIODeviceType()
  222457. {
  222458. }
  222459. void scanForDevices()
  222460. {
  222461. if (hasScanned)
  222462. return;
  222463. hasScanned = true;
  222464. inputNames.clear();
  222465. inputIds.clear();
  222466. outputNames.clear();
  222467. outputIds.clear();
  222468. /* void** hints = 0;
  222469. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  222470. {
  222471. for (void** hint = hints; *hint != 0; ++hint)
  222472. {
  222473. const String name (getHint (*hint, "NAME"));
  222474. if (name.isNotEmpty())
  222475. {
  222476. const String ioid (getHint (*hint, "IOID"));
  222477. String desc (getHint (*hint, "DESC"));
  222478. if (desc.isEmpty())
  222479. desc = name;
  222480. desc = desc.replaceCharacters ("\n\r", " ");
  222481. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222482. if (ioid.isEmpty() || ioid == "Input")
  222483. {
  222484. inputNames.add (desc);
  222485. inputIds.add (name);
  222486. }
  222487. if (ioid.isEmpty() || ioid == "Output")
  222488. {
  222489. outputNames.add (desc);
  222490. outputIds.add (name);
  222491. }
  222492. }
  222493. }
  222494. snd_device_name_free_hint (hints);
  222495. }
  222496. */
  222497. snd_ctl_t* handle = 0;
  222498. snd_ctl_card_info_t* info = 0;
  222499. snd_ctl_card_info_alloca (&info);
  222500. int cardNum = -1;
  222501. while (outputIds.size() + inputIds.size() <= 32)
  222502. {
  222503. snd_card_next (&cardNum);
  222504. if (cardNum < 0)
  222505. break;
  222506. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222507. {
  222508. if (snd_ctl_card_info (handle, info) >= 0)
  222509. {
  222510. String cardId (snd_ctl_card_info_get_id (info));
  222511. if (cardId.removeCharacters ("0123456789").isEmpty())
  222512. cardId = String (cardNum);
  222513. int device = -1;
  222514. for (;;)
  222515. {
  222516. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222517. break;
  222518. String id, name;
  222519. id << "hw:" << cardId << ',' << device;
  222520. bool isInput, isOutput;
  222521. if (testDevice (id, isInput, isOutput))
  222522. {
  222523. name << snd_ctl_card_info_get_name (info);
  222524. if (name.isEmpty())
  222525. name = id;
  222526. if (isInput)
  222527. {
  222528. inputNames.add (name);
  222529. inputIds.add (id);
  222530. }
  222531. if (isOutput)
  222532. {
  222533. outputNames.add (name);
  222534. outputIds.add (id);
  222535. }
  222536. }
  222537. }
  222538. }
  222539. snd_ctl_close (handle);
  222540. }
  222541. }
  222542. inputNames.appendNumbersToDuplicates (false, true);
  222543. outputNames.appendNumbersToDuplicates (false, true);
  222544. }
  222545. const StringArray getDeviceNames (bool wantInputNames) const
  222546. {
  222547. jassert (hasScanned); // need to call scanForDevices() before doing this
  222548. return wantInputNames ? inputNames : outputNames;
  222549. }
  222550. int getDefaultDeviceIndex (bool forInput) const
  222551. {
  222552. jassert (hasScanned); // need to call scanForDevices() before doing this
  222553. return 0;
  222554. }
  222555. bool hasSeparateInputsAndOutputs() const { return true; }
  222556. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222557. {
  222558. jassert (hasScanned); // need to call scanForDevices() before doing this
  222559. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222560. if (d == 0)
  222561. return -1;
  222562. return asInput ? inputIds.indexOf (d->inputId)
  222563. : outputIds.indexOf (d->outputId);
  222564. }
  222565. AudioIODevice* createDevice (const String& outputDeviceName,
  222566. const String& inputDeviceName)
  222567. {
  222568. jassert (hasScanned); // need to call scanForDevices() before doing this
  222569. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222570. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222571. String deviceName (outputIndex >= 0 ? outputDeviceName
  222572. : inputDeviceName);
  222573. if (inputIndex >= 0 || outputIndex >= 0)
  222574. return new ALSAAudioIODevice (deviceName,
  222575. inputIds [inputIndex],
  222576. outputIds [outputIndex]);
  222577. return 0;
  222578. }
  222579. private:
  222580. StringArray inputNames, outputNames, inputIds, outputIds;
  222581. bool hasScanned;
  222582. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222583. {
  222584. unsigned int minChansOut = 0, maxChansOut = 0;
  222585. unsigned int minChansIn = 0, maxChansIn = 0;
  222586. Array <int> rates;
  222587. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222588. DBG ("ALSA device: " + id
  222589. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222590. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222591. + " rates=" + String (rates.size()));
  222592. isInput = maxChansIn > 0;
  222593. isOutput = maxChansOut > 0;
  222594. return (isInput || isOutput) && rates.size() > 0;
  222595. }
  222596. /*static const String getHint (void* hint, const char* type)
  222597. {
  222598. char* const n = snd_device_name_get_hint (hint, type);
  222599. const String s ((const char*) n);
  222600. free (n);
  222601. return s;
  222602. }*/
  222603. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType);
  222604. };
  222605. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  222606. {
  222607. return new ALSAAudioIODeviceType();
  222608. }
  222609. #endif
  222610. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222611. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222612. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222613. // compiled on its own).
  222614. #ifdef JUCE_INCLUDED_FILE
  222615. #if JUCE_JACK
  222616. static void* juce_libjack_handle = 0;
  222617. void* juce_load_jack_function (const char* const name)
  222618. {
  222619. if (juce_libjack_handle == 0)
  222620. return 0;
  222621. return dlsym (juce_libjack_handle, name);
  222622. }
  222623. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  222624. typedef return_type (*fn_name##_ptr_t)argument_types; \
  222625. return_type fn_name argument_types { \
  222626. static fn_name##_ptr_t fn = 0; \
  222627. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222628. if (fn) return (*fn)arguments; \
  222629. else return 0; \
  222630. }
  222631. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  222632. typedef void (*fn_name##_ptr_t)argument_types; \
  222633. void fn_name argument_types { \
  222634. static fn_name##_ptr_t fn = 0; \
  222635. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222636. if (fn) (*fn)arguments; \
  222637. }
  222638. 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));
  222639. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  222640. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  222641. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  222642. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  222643. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  222644. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  222645. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  222646. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  222647. 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));
  222648. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  222649. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  222650. 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));
  222651. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  222652. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  222653. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  222654. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  222655. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  222656. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  222657. #if JUCE_DEBUG
  222658. #define JACK_LOGGING_ENABLED 1
  222659. #endif
  222660. #if JACK_LOGGING_ENABLED
  222661. namespace
  222662. {
  222663. void jack_Log (const String& s)
  222664. {
  222665. std::cerr << s << std::endl;
  222666. }
  222667. void dumpJackErrorMessage (const jack_status_t status)
  222668. {
  222669. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  222670. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  222671. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  222672. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  222673. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  222674. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  222675. }
  222676. }
  222677. #else
  222678. #define dumpJackErrorMessage(a) {}
  222679. #define jack_Log(...) {}
  222680. #endif
  222681. #ifndef JUCE_JACK_CLIENT_NAME
  222682. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  222683. #endif
  222684. class JackAudioIODevice : public AudioIODevice
  222685. {
  222686. public:
  222687. JackAudioIODevice (const String& deviceName,
  222688. const String& inputId_,
  222689. const String& outputId_)
  222690. : AudioIODevice (deviceName, "JACK"),
  222691. inputId (inputId_),
  222692. outputId (outputId_),
  222693. isOpen_ (false),
  222694. callback (0),
  222695. totalNumberOfInputChannels (0),
  222696. totalNumberOfOutputChannels (0)
  222697. {
  222698. jassert (deviceName.isNotEmpty());
  222699. jack_status_t status;
  222700. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  222701. if (client == 0)
  222702. {
  222703. dumpJackErrorMessage (status);
  222704. }
  222705. else
  222706. {
  222707. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  222708. // open input ports
  222709. const StringArray inputChannels (getInputChannelNames());
  222710. for (int i = 0; i < inputChannels.size(); i++)
  222711. {
  222712. String inputName;
  222713. inputName << "in_" << ++totalNumberOfInputChannels;
  222714. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  222715. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  222716. }
  222717. // open output ports
  222718. const StringArray outputChannels (getOutputChannelNames());
  222719. for (int i = 0; i < outputChannels.size (); i++)
  222720. {
  222721. String outputName;
  222722. outputName << "out_" << ++totalNumberOfOutputChannels;
  222723. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  222724. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  222725. }
  222726. inChans.calloc (totalNumberOfInputChannels + 2);
  222727. outChans.calloc (totalNumberOfOutputChannels + 2);
  222728. }
  222729. }
  222730. ~JackAudioIODevice()
  222731. {
  222732. close();
  222733. if (client != 0)
  222734. {
  222735. JUCE_NAMESPACE::jack_client_close (client);
  222736. client = 0;
  222737. }
  222738. }
  222739. const StringArray getChannelNames (bool forInput) const
  222740. {
  222741. StringArray names;
  222742. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  222743. forInput ? JackPortIsInput : JackPortIsOutput);
  222744. if (ports != 0)
  222745. {
  222746. int j = 0;
  222747. while (ports[j] != 0)
  222748. {
  222749. const String portName (ports [j++]);
  222750. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222751. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  222752. }
  222753. free (ports);
  222754. }
  222755. return names;
  222756. }
  222757. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  222758. const StringArray getInputChannelNames() { return getChannelNames (true); }
  222759. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  222760. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  222761. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  222762. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  222763. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  222764. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  222765. double sampleRate, int bufferSizeSamples)
  222766. {
  222767. if (client == 0)
  222768. {
  222769. lastError = "No JACK client running";
  222770. return lastError;
  222771. }
  222772. lastError = String::empty;
  222773. close();
  222774. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  222775. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  222776. JUCE_NAMESPACE::jack_activate (client);
  222777. isOpen_ = true;
  222778. if (! inputChannels.isZero())
  222779. {
  222780. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222781. if (ports != 0)
  222782. {
  222783. const int numInputChannels = inputChannels.getHighestBit() + 1;
  222784. for (int i = 0; i < numInputChannels; ++i)
  222785. {
  222786. const String portName (ports[i]);
  222787. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222788. {
  222789. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  222790. if (error != 0)
  222791. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222792. }
  222793. }
  222794. free (ports);
  222795. }
  222796. }
  222797. if (! outputChannels.isZero())
  222798. {
  222799. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222800. if (ports != 0)
  222801. {
  222802. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222803. for (int i = 0; i < numOutputChannels; ++i)
  222804. {
  222805. const String portName (ports[i]);
  222806. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222807. {
  222808. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222809. if (error != 0)
  222810. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222811. }
  222812. }
  222813. free (ports);
  222814. }
  222815. }
  222816. return lastError;
  222817. }
  222818. void close()
  222819. {
  222820. stop();
  222821. if (client != 0)
  222822. {
  222823. JUCE_NAMESPACE::jack_deactivate (client);
  222824. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222825. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222826. }
  222827. isOpen_ = false;
  222828. }
  222829. void start (AudioIODeviceCallback* newCallback)
  222830. {
  222831. if (isOpen_ && newCallback != callback)
  222832. {
  222833. if (newCallback != 0)
  222834. newCallback->audioDeviceAboutToStart (this);
  222835. AudioIODeviceCallback* const oldCallback = callback;
  222836. {
  222837. const ScopedLock sl (callbackLock);
  222838. callback = newCallback;
  222839. }
  222840. if (oldCallback != 0)
  222841. oldCallback->audioDeviceStopped();
  222842. }
  222843. }
  222844. void stop()
  222845. {
  222846. start (0);
  222847. }
  222848. bool isOpen() { return isOpen_; }
  222849. bool isPlaying() { return callback != 0; }
  222850. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222851. double getCurrentSampleRate() { return getSampleRate (0); }
  222852. int getCurrentBitDepth() { return 32; }
  222853. const String getLastError() { return lastError; }
  222854. const BigInteger getActiveOutputChannels() const
  222855. {
  222856. BigInteger outputBits;
  222857. for (int i = 0; i < outputPorts.size(); i++)
  222858. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222859. outputBits.setBit (i);
  222860. return outputBits;
  222861. }
  222862. const BigInteger getActiveInputChannels() const
  222863. {
  222864. BigInteger inputBits;
  222865. for (int i = 0; i < inputPorts.size(); i++)
  222866. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222867. inputBits.setBit (i);
  222868. return inputBits;
  222869. }
  222870. int getOutputLatencyInSamples()
  222871. {
  222872. int latency = 0;
  222873. for (int i = 0; i < outputPorts.size(); i++)
  222874. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222875. return latency;
  222876. }
  222877. int getInputLatencyInSamples()
  222878. {
  222879. int latency = 0;
  222880. for (int i = 0; i < inputPorts.size(); i++)
  222881. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222882. return latency;
  222883. }
  222884. String inputId, outputId;
  222885. private:
  222886. void process (const int numSamples)
  222887. {
  222888. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222889. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222890. {
  222891. jack_default_audio_sample_t* in
  222892. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222893. if (in != 0)
  222894. inChans [numActiveInChans++] = (float*) in;
  222895. }
  222896. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222897. {
  222898. jack_default_audio_sample_t* out
  222899. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222900. if (out != 0)
  222901. outChans [numActiveOutChans++] = (float*) out;
  222902. }
  222903. const ScopedLock sl (callbackLock);
  222904. if (callback != 0)
  222905. {
  222906. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222907. outChans, numActiveOutChans, numSamples);
  222908. }
  222909. else
  222910. {
  222911. for (i = 0; i < numActiveOutChans; ++i)
  222912. zeromem (outChans[i], sizeof (float) * numSamples);
  222913. }
  222914. }
  222915. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222916. {
  222917. if (callbackArgument != 0)
  222918. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222919. return 0;
  222920. }
  222921. static void threadInitCallback (void* callbackArgument)
  222922. {
  222923. jack_Log ("JackAudioIODevice::initialise");
  222924. }
  222925. static void shutdownCallback (void* callbackArgument)
  222926. {
  222927. jack_Log ("JackAudioIODevice::shutdown");
  222928. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222929. if (device != 0)
  222930. {
  222931. device->client = 0;
  222932. device->close();
  222933. }
  222934. }
  222935. static void errorCallback (const char* msg)
  222936. {
  222937. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222938. }
  222939. bool isOpen_;
  222940. jack_client_t* client;
  222941. String lastError;
  222942. AudioIODeviceCallback* callback;
  222943. CriticalSection callbackLock;
  222944. HeapBlock <float*> inChans, outChans;
  222945. int totalNumberOfInputChannels;
  222946. int totalNumberOfOutputChannels;
  222947. Array<void*> inputPorts, outputPorts;
  222948. };
  222949. class JackAudioIODeviceType : public AudioIODeviceType
  222950. {
  222951. public:
  222952. JackAudioIODeviceType()
  222953. : AudioIODeviceType ("JACK"),
  222954. hasScanned (false)
  222955. {
  222956. }
  222957. ~JackAudioIODeviceType()
  222958. {
  222959. }
  222960. void scanForDevices()
  222961. {
  222962. hasScanned = true;
  222963. inputNames.clear();
  222964. inputIds.clear();
  222965. outputNames.clear();
  222966. outputIds.clear();
  222967. if (juce_libjack_handle == 0)
  222968. {
  222969. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  222970. if (juce_libjack_handle == 0)
  222971. return;
  222972. }
  222973. // open a dummy client
  222974. jack_status_t status;
  222975. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  222976. if (client == 0)
  222977. {
  222978. dumpJackErrorMessage (status);
  222979. }
  222980. else
  222981. {
  222982. // scan for output devices
  222983. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222984. if (ports != 0)
  222985. {
  222986. int j = 0;
  222987. while (ports[j] != 0)
  222988. {
  222989. String clientName (ports[j]);
  222990. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222991. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222992. && ! inputNames.contains (clientName))
  222993. {
  222994. inputNames.add (clientName);
  222995. inputIds.add (ports [j]);
  222996. }
  222997. ++j;
  222998. }
  222999. free (ports);
  223000. }
  223001. // scan for input devices
  223002. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223003. if (ports != 0)
  223004. {
  223005. int j = 0;
  223006. while (ports[j] != 0)
  223007. {
  223008. String clientName (ports[j]);
  223009. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223010. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223011. && ! outputNames.contains (clientName))
  223012. {
  223013. outputNames.add (clientName);
  223014. outputIds.add (ports [j]);
  223015. }
  223016. ++j;
  223017. }
  223018. free (ports);
  223019. }
  223020. JUCE_NAMESPACE::jack_client_close (client);
  223021. }
  223022. }
  223023. const StringArray getDeviceNames (bool wantInputNames) const
  223024. {
  223025. jassert (hasScanned); // need to call scanForDevices() before doing this
  223026. return wantInputNames ? inputNames : outputNames;
  223027. }
  223028. int getDefaultDeviceIndex (bool forInput) const
  223029. {
  223030. jassert (hasScanned); // need to call scanForDevices() before doing this
  223031. return 0;
  223032. }
  223033. bool hasSeparateInputsAndOutputs() const { return true; }
  223034. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223035. {
  223036. jassert (hasScanned); // need to call scanForDevices() before doing this
  223037. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223038. if (d == 0)
  223039. return -1;
  223040. return asInput ? inputIds.indexOf (d->inputId)
  223041. : outputIds.indexOf (d->outputId);
  223042. }
  223043. AudioIODevice* createDevice (const String& outputDeviceName,
  223044. const String& inputDeviceName)
  223045. {
  223046. jassert (hasScanned); // need to call scanForDevices() before doing this
  223047. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223048. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223049. if (inputIndex >= 0 || outputIndex >= 0)
  223050. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223051. : inputDeviceName,
  223052. inputIds [inputIndex],
  223053. outputIds [outputIndex]);
  223054. return 0;
  223055. }
  223056. private:
  223057. StringArray inputNames, outputNames, inputIds, outputIds;
  223058. bool hasScanned;
  223059. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  223060. };
  223061. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223062. {
  223063. return new JackAudioIODeviceType();
  223064. }
  223065. #else // if JACK is turned off..
  223066. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223067. #endif
  223068. #endif
  223069. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223070. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223071. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223072. // compiled on its own).
  223073. #if JUCE_INCLUDED_FILE
  223074. #if JUCE_ALSA
  223075. namespace
  223076. {
  223077. snd_seq_t* iterateMidiDevices (const bool forInput,
  223078. StringArray& deviceNamesFound,
  223079. const int deviceIndexToOpen)
  223080. {
  223081. snd_seq_t* returnedHandle = 0;
  223082. snd_seq_t* seqHandle;
  223083. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223084. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223085. {
  223086. snd_seq_system_info_t* systemInfo;
  223087. snd_seq_client_info_t* clientInfo;
  223088. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223089. {
  223090. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223091. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223092. {
  223093. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223094. while (--numClients >= 0 && returnedHandle == 0)
  223095. {
  223096. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223097. {
  223098. snd_seq_port_info_t* portInfo;
  223099. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223100. {
  223101. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223102. const int client = snd_seq_client_info_get_client (clientInfo);
  223103. snd_seq_port_info_set_client (portInfo, client);
  223104. snd_seq_port_info_set_port (portInfo, -1);
  223105. while (--numPorts >= 0)
  223106. {
  223107. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223108. && (snd_seq_port_info_get_capability (portInfo)
  223109. & (forInput ? SND_SEQ_PORT_CAP_READ
  223110. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223111. {
  223112. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223113. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223114. {
  223115. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223116. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223117. if (sourcePort != -1)
  223118. {
  223119. snd_seq_set_client_name (seqHandle,
  223120. forInput ? "Juce Midi Input"
  223121. : "Juce Midi Output");
  223122. const int portId
  223123. = snd_seq_create_simple_port (seqHandle,
  223124. forInput ? "Juce Midi In Port"
  223125. : "Juce Midi Out Port",
  223126. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223127. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223128. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223129. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223130. returnedHandle = seqHandle;
  223131. }
  223132. }
  223133. }
  223134. }
  223135. snd_seq_port_info_free (portInfo);
  223136. }
  223137. }
  223138. }
  223139. snd_seq_client_info_free (clientInfo);
  223140. }
  223141. snd_seq_system_info_free (systemInfo);
  223142. }
  223143. if (returnedHandle == 0)
  223144. snd_seq_close (seqHandle);
  223145. }
  223146. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223147. return returnedHandle;
  223148. }
  223149. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  223150. {
  223151. snd_seq_t* seqHandle = 0;
  223152. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223153. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223154. {
  223155. snd_seq_set_client_name (seqHandle,
  223156. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223157. const int portId
  223158. = snd_seq_create_simple_port (seqHandle,
  223159. forInput ? "in"
  223160. : "out",
  223161. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223162. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223163. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223164. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223165. if (portId < 0)
  223166. {
  223167. snd_seq_close (seqHandle);
  223168. seqHandle = 0;
  223169. }
  223170. }
  223171. return seqHandle;
  223172. }
  223173. }
  223174. class MidiOutputDevice
  223175. {
  223176. public:
  223177. MidiOutputDevice (MidiOutput* const midiOutput_,
  223178. snd_seq_t* const seqHandle_)
  223179. :
  223180. midiOutput (midiOutput_),
  223181. seqHandle (seqHandle_),
  223182. maxEventSize (16 * 1024)
  223183. {
  223184. jassert (seqHandle != 0 && midiOutput != 0);
  223185. snd_midi_event_new (maxEventSize, &midiParser);
  223186. }
  223187. ~MidiOutputDevice()
  223188. {
  223189. snd_midi_event_free (midiParser);
  223190. snd_seq_close (seqHandle);
  223191. }
  223192. void sendMessageNow (const MidiMessage& message)
  223193. {
  223194. if (message.getRawDataSize() > maxEventSize)
  223195. {
  223196. maxEventSize = message.getRawDataSize();
  223197. snd_midi_event_free (midiParser);
  223198. snd_midi_event_new (maxEventSize, &midiParser);
  223199. }
  223200. snd_seq_event_t event;
  223201. snd_seq_ev_clear (&event);
  223202. snd_midi_event_encode (midiParser,
  223203. message.getRawData(),
  223204. message.getRawDataSize(),
  223205. &event);
  223206. snd_midi_event_reset_encode (midiParser);
  223207. snd_seq_ev_set_source (&event, 0);
  223208. snd_seq_ev_set_subs (&event);
  223209. snd_seq_ev_set_direct (&event);
  223210. snd_seq_event_output (seqHandle, &event);
  223211. snd_seq_drain_output (seqHandle);
  223212. }
  223213. private:
  223214. MidiOutput* const midiOutput;
  223215. snd_seq_t* const seqHandle;
  223216. snd_midi_event_t* midiParser;
  223217. int maxEventSize;
  223218. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  223219. };
  223220. const StringArray MidiOutput::getDevices()
  223221. {
  223222. StringArray devices;
  223223. iterateMidiDevices (false, devices, -1);
  223224. return devices;
  223225. }
  223226. int MidiOutput::getDefaultDeviceIndex()
  223227. {
  223228. return 0;
  223229. }
  223230. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223231. {
  223232. MidiOutput* newDevice = 0;
  223233. StringArray devices;
  223234. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223235. if (handle != 0)
  223236. {
  223237. newDevice = new MidiOutput();
  223238. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223239. }
  223240. return newDevice;
  223241. }
  223242. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223243. {
  223244. MidiOutput* newDevice = 0;
  223245. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223246. if (handle != 0)
  223247. {
  223248. newDevice = new MidiOutput();
  223249. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223250. }
  223251. return newDevice;
  223252. }
  223253. MidiOutput::~MidiOutput()
  223254. {
  223255. delete static_cast <MidiOutputDevice*> (internal);
  223256. }
  223257. void MidiOutput::reset()
  223258. {
  223259. }
  223260. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223261. {
  223262. return false;
  223263. }
  223264. void MidiOutput::setVolume (float leftVol, float rightVol)
  223265. {
  223266. }
  223267. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223268. {
  223269. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223270. }
  223271. class MidiInputThread : public Thread
  223272. {
  223273. public:
  223274. MidiInputThread (MidiInput* const midiInput_,
  223275. snd_seq_t* const seqHandle_,
  223276. MidiInputCallback* const callback_)
  223277. : Thread ("Juce MIDI Input"),
  223278. midiInput (midiInput_),
  223279. seqHandle (seqHandle_),
  223280. callback (callback_)
  223281. {
  223282. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223283. }
  223284. ~MidiInputThread()
  223285. {
  223286. snd_seq_close (seqHandle);
  223287. }
  223288. void run()
  223289. {
  223290. const int maxEventSize = 16 * 1024;
  223291. snd_midi_event_t* midiParser;
  223292. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223293. {
  223294. HeapBlock <uint8> buffer (maxEventSize);
  223295. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223296. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223297. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223298. while (! threadShouldExit())
  223299. {
  223300. if (poll (pfd, numPfds, 500) > 0)
  223301. {
  223302. snd_seq_event_t* inputEvent = 0;
  223303. snd_seq_nonblock (seqHandle, 1);
  223304. do
  223305. {
  223306. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223307. {
  223308. // xxx what about SYSEXes that are too big for the buffer?
  223309. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223310. snd_midi_event_reset_decode (midiParser);
  223311. if (numBytes > 0)
  223312. {
  223313. const MidiMessage message ((const uint8*) buffer,
  223314. numBytes,
  223315. Time::getMillisecondCounter() * 0.001);
  223316. callback->handleIncomingMidiMessage (midiInput, message);
  223317. }
  223318. snd_seq_free_event (inputEvent);
  223319. }
  223320. }
  223321. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223322. snd_seq_free_event (inputEvent);
  223323. }
  223324. }
  223325. snd_midi_event_free (midiParser);
  223326. }
  223327. };
  223328. private:
  223329. MidiInput* const midiInput;
  223330. snd_seq_t* const seqHandle;
  223331. MidiInputCallback* const callback;
  223332. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputThread);
  223333. };
  223334. MidiInput::MidiInput (const String& name_)
  223335. : name (name_),
  223336. internal (0)
  223337. {
  223338. }
  223339. MidiInput::~MidiInput()
  223340. {
  223341. stop();
  223342. delete static_cast <MidiInputThread*> (internal);
  223343. }
  223344. void MidiInput::start()
  223345. {
  223346. static_cast <MidiInputThread*> (internal)->startThread();
  223347. }
  223348. void MidiInput::stop()
  223349. {
  223350. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223351. }
  223352. int MidiInput::getDefaultDeviceIndex()
  223353. {
  223354. return 0;
  223355. }
  223356. const StringArray MidiInput::getDevices()
  223357. {
  223358. StringArray devices;
  223359. iterateMidiDevices (true, devices, -1);
  223360. return devices;
  223361. }
  223362. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223363. {
  223364. MidiInput* newDevice = 0;
  223365. StringArray devices;
  223366. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223367. if (handle != 0)
  223368. {
  223369. newDevice = new MidiInput (devices [deviceIndex]);
  223370. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223371. }
  223372. return newDevice;
  223373. }
  223374. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223375. {
  223376. MidiInput* newDevice = 0;
  223377. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223378. if (handle != 0)
  223379. {
  223380. newDevice = new MidiInput (deviceName);
  223381. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223382. }
  223383. return newDevice;
  223384. }
  223385. #else
  223386. // (These are just stub functions if ALSA is unavailable...)
  223387. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223388. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223389. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223390. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223391. MidiOutput::~MidiOutput() {}
  223392. void MidiOutput::reset() {}
  223393. bool MidiOutput::getVolume (float&, float&) { return false; }
  223394. void MidiOutput::setVolume (float, float) {}
  223395. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223396. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223397. MidiInput::~MidiInput() {}
  223398. void MidiInput::start() {}
  223399. void MidiInput::stop() {}
  223400. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223401. const StringArray MidiInput::getDevices() { return StringArray(); }
  223402. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223403. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223404. #endif
  223405. #endif
  223406. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223407. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223408. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223409. // compiled on its own).
  223410. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223411. AudioCDReader::AudioCDReader()
  223412. : AudioFormatReader (0, "CD Audio")
  223413. {
  223414. }
  223415. const StringArray AudioCDReader::getAvailableCDNames()
  223416. {
  223417. StringArray names;
  223418. return names;
  223419. }
  223420. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223421. {
  223422. return 0;
  223423. }
  223424. AudioCDReader::~AudioCDReader()
  223425. {
  223426. }
  223427. void AudioCDReader::refreshTrackLengths()
  223428. {
  223429. }
  223430. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223431. int64 startSampleInFile, int numSamples)
  223432. {
  223433. return false;
  223434. }
  223435. bool AudioCDReader::isCDStillPresent() const
  223436. {
  223437. return false;
  223438. }
  223439. bool AudioCDReader::isTrackAudio (int trackNum) const
  223440. {
  223441. return false;
  223442. }
  223443. void AudioCDReader::enableIndexScanning (bool b)
  223444. {
  223445. }
  223446. int AudioCDReader::getLastIndex() const
  223447. {
  223448. return 0;
  223449. }
  223450. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223451. {
  223452. return Array<int>();
  223453. }
  223454. #endif
  223455. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223456. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223457. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223458. // compiled on its own).
  223459. #if JUCE_INCLUDED_FILE
  223460. void FileChooser::showPlatformDialog (Array<File>& results,
  223461. const String& title,
  223462. const File& file,
  223463. const String& filters,
  223464. bool isDirectory,
  223465. bool selectsFiles,
  223466. bool isSave,
  223467. bool warnAboutOverwritingExistingFiles,
  223468. bool selectMultipleFiles,
  223469. FilePreviewComponent* previewComponent)
  223470. {
  223471. const String separator (":");
  223472. String command ("zenity --file-selection");
  223473. if (title.isNotEmpty())
  223474. command << " --title=\"" << title << "\"";
  223475. if (file != File::nonexistent)
  223476. command << " --filename=\"" << file.getFullPathName () << "\"";
  223477. if (isDirectory)
  223478. command << " --directory";
  223479. if (isSave)
  223480. command << " --save";
  223481. if (selectMultipleFiles)
  223482. command << " --multiple --separator=\"" << separator << "\"";
  223483. command << " 2>&1";
  223484. MemoryOutputStream result;
  223485. int status = -1;
  223486. FILE* stream = popen (command.toUTF8(), "r");
  223487. if (stream != 0)
  223488. {
  223489. for (;;)
  223490. {
  223491. char buffer [1024];
  223492. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223493. if (bytesRead <= 0)
  223494. break;
  223495. result.write (buffer, bytesRead);
  223496. }
  223497. status = pclose (stream);
  223498. }
  223499. if (status == 0)
  223500. {
  223501. StringArray tokens;
  223502. if (selectMultipleFiles)
  223503. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223504. else
  223505. tokens.add (result.toUTF8());
  223506. for (int i = 0; i < tokens.size(); i++)
  223507. results.add (File (tokens[i]));
  223508. return;
  223509. }
  223510. //xxx ain't got one!
  223511. jassertfalse;
  223512. }
  223513. #endif
  223514. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223515. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223516. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223517. // compiled on its own).
  223518. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223519. /*
  223520. Sorry.. This class isn't implemented on Linux!
  223521. */
  223522. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223523. : browser (0),
  223524. blankPageShown (false),
  223525. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223526. {
  223527. setOpaque (true);
  223528. }
  223529. WebBrowserComponent::~WebBrowserComponent()
  223530. {
  223531. }
  223532. void WebBrowserComponent::goToURL (const String& url,
  223533. const StringArray* headers,
  223534. const MemoryBlock* postData)
  223535. {
  223536. lastURL = url;
  223537. lastHeaders.clear();
  223538. if (headers != 0)
  223539. lastHeaders = *headers;
  223540. lastPostData.setSize (0);
  223541. if (postData != 0)
  223542. lastPostData = *postData;
  223543. blankPageShown = false;
  223544. }
  223545. void WebBrowserComponent::stop()
  223546. {
  223547. }
  223548. void WebBrowserComponent::goBack()
  223549. {
  223550. lastURL = String::empty;
  223551. blankPageShown = false;
  223552. }
  223553. void WebBrowserComponent::goForward()
  223554. {
  223555. lastURL = String::empty;
  223556. }
  223557. void WebBrowserComponent::refresh()
  223558. {
  223559. }
  223560. void WebBrowserComponent::paint (Graphics& g)
  223561. {
  223562. g.fillAll (Colours::white);
  223563. }
  223564. void WebBrowserComponent::checkWindowAssociation()
  223565. {
  223566. }
  223567. void WebBrowserComponent::reloadLastURL()
  223568. {
  223569. if (lastURL.isNotEmpty())
  223570. {
  223571. goToURL (lastURL, &lastHeaders, &lastPostData);
  223572. lastURL = String::empty;
  223573. }
  223574. }
  223575. void WebBrowserComponent::parentHierarchyChanged()
  223576. {
  223577. checkWindowAssociation();
  223578. }
  223579. void WebBrowserComponent::resized()
  223580. {
  223581. }
  223582. void WebBrowserComponent::visibilityChanged()
  223583. {
  223584. checkWindowAssociation();
  223585. }
  223586. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223587. {
  223588. return true;
  223589. }
  223590. #endif
  223591. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223592. #endif
  223593. END_JUCE_NAMESPACE
  223594. #endif
  223595. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223596. #endif
  223597. #if JUCE_MAC || JUCE_IPHONE
  223598. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223599. /*
  223600. This file wraps together all the mac-specific code, so that
  223601. we can include all the native headers just once, and compile all our
  223602. platform-specific stuff in one big lump, keeping it out of the way of
  223603. the rest of the codebase.
  223604. */
  223605. #if JUCE_MAC || JUCE_IOS
  223606. #undef JUCE_BUILD_NATIVE
  223607. #define JUCE_BUILD_NATIVE 1
  223608. BEGIN_JUCE_NAMESPACE
  223609. #undef Point
  223610. namespace
  223611. {
  223612. template <class RectType>
  223613. const Rectangle<int> convertToRectInt (const RectType& r)
  223614. {
  223615. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  223616. }
  223617. template <class RectType>
  223618. const Rectangle<float> convertToRectFloat (const RectType& r)
  223619. {
  223620. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  223621. }
  223622. template <class RectType>
  223623. CGRect convertToCGRect (const RectType& r)
  223624. {
  223625. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  223626. }
  223627. }
  223628. class MessageQueue
  223629. {
  223630. public:
  223631. MessageQueue()
  223632. {
  223633. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4 && ! JUCE_IOS
  223634. runLoop = CFRunLoopGetMain();
  223635. #else
  223636. runLoop = CFRunLoopGetCurrent();
  223637. #endif
  223638. CFRunLoopSourceContext sourceContext;
  223639. zerostruct (sourceContext);
  223640. sourceContext.info = this;
  223641. sourceContext.perform = runLoopSourceCallback;
  223642. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  223643. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223644. }
  223645. ~MessageQueue()
  223646. {
  223647. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223648. CFRunLoopSourceInvalidate (runLoopSource);
  223649. CFRelease (runLoopSource);
  223650. }
  223651. void post (Message* const message)
  223652. {
  223653. messages.add (message);
  223654. CFRunLoopSourceSignal (runLoopSource);
  223655. CFRunLoopWakeUp (runLoop);
  223656. }
  223657. private:
  223658. ReferenceCountedArray <Message, CriticalSection> messages;
  223659. CriticalSection lock;
  223660. CFRunLoopRef runLoop;
  223661. CFRunLoopSourceRef runLoopSource;
  223662. bool deliverNextMessage()
  223663. {
  223664. const Message::Ptr nextMessage (messages.removeAndReturn (0));
  223665. if (nextMessage == 0)
  223666. return false;
  223667. const ScopedAutoReleasePool pool;
  223668. MessageManager::getInstance()->deliverMessage (nextMessage);
  223669. return true;
  223670. }
  223671. void runLoopCallback()
  223672. {
  223673. for (int i = 4; --i >= 0;)
  223674. if (! deliverNextMessage())
  223675. return;
  223676. CFRunLoopSourceSignal (runLoopSource);
  223677. CFRunLoopWakeUp (runLoop);
  223678. }
  223679. static void runLoopSourceCallback (void* info)
  223680. {
  223681. static_cast <MessageQueue*> (info)->runLoopCallback();
  223682. }
  223683. };
  223684. #define JUCE_INCLUDED_FILE 1
  223685. // Now include the actual code files..
  223686. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223687. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223688. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223689. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223690. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223691. actually calling into a similarly named class in the other module's address space.
  223692. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  223693. have unique names, and should avoid this problem.
  223694. If you're using the amalgamated version, you can just set this macro to something unique before
  223695. you include juce_amalgamated.cpp.
  223696. */
  223697. #ifndef JUCE_ObjCExtraSuffix
  223698. #define JUCE_ObjCExtraSuffix 3
  223699. #endif
  223700. #ifndef DOXYGEN
  223701. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  223702. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  223703. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  223704. #endif
  223705. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  223706. /*** Start of inlined file: juce_mac_Strings.mm ***/
  223707. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223708. // compiled on its own).
  223709. #if JUCE_INCLUDED_FILE
  223710. namespace
  223711. {
  223712. const String nsStringToJuce (NSString* s)
  223713. {
  223714. return String::fromUTF8 ([s UTF8String]);
  223715. }
  223716. NSString* juceStringToNS (const String& s)
  223717. {
  223718. return [NSString stringWithUTF8String: s.toUTF8()];
  223719. }
  223720. const String convertUTF16ToString (const UniChar* utf16)
  223721. {
  223722. String s;
  223723. while (*utf16 != 0)
  223724. s += (juce_wchar) *utf16++;
  223725. return s;
  223726. }
  223727. }
  223728. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  223729. {
  223730. String result;
  223731. if (cfString != 0)
  223732. {
  223733. CFRange range = { 0, CFStringGetLength (cfString) };
  223734. HeapBlock <UniChar> u (range.length + 1);
  223735. CFStringGetCharacters (cfString, range, u);
  223736. u[range.length] = 0;
  223737. result = convertUTF16ToString (u);
  223738. }
  223739. return result;
  223740. }
  223741. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  223742. {
  223743. const int len = s.length();
  223744. HeapBlock <UniChar> temp (len + 2);
  223745. for (int i = 0; i <= len; ++i)
  223746. temp[i] = s[i];
  223747. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  223748. }
  223749. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  223750. {
  223751. #if JUCE_IOS
  223752. const ScopedAutoReleasePool pool;
  223753. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  223754. #else
  223755. UnicodeMapping map;
  223756. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223757. kUnicodeNoSubset,
  223758. kTextEncodingDefaultFormat);
  223759. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223760. kUnicodeCanonicalCompVariant,
  223761. kTextEncodingDefaultFormat);
  223762. map.mappingVersion = kUnicodeUseLatestMapping;
  223763. UnicodeToTextInfo conversionInfo = 0;
  223764. String result;
  223765. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  223766. {
  223767. const int len = s.length();
  223768. HeapBlock <UniChar> tempIn, tempOut;
  223769. tempIn.calloc (len + 2);
  223770. tempOut.calloc (len + 2);
  223771. for (int i = 0; i <= len; ++i)
  223772. tempIn[i] = s[i];
  223773. ByteCount bytesRead = 0;
  223774. ByteCount outputBufferSize = 0;
  223775. if (ConvertFromUnicodeToText (conversionInfo,
  223776. len * sizeof (UniChar), tempIn,
  223777. kUnicodeDefaultDirectionMask,
  223778. 0, 0, 0, 0,
  223779. len * sizeof (UniChar), &bytesRead,
  223780. &outputBufferSize, tempOut) == noErr)
  223781. {
  223782. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  223783. juce_wchar* t = result;
  223784. unsigned int i;
  223785. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  223786. t[i] = (juce_wchar) tempOut[i];
  223787. t[i] = 0;
  223788. }
  223789. DisposeUnicodeToTextInfo (&conversionInfo);
  223790. }
  223791. return result;
  223792. #endif
  223793. }
  223794. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223795. void SystemClipboard::copyTextToClipboard (const String& text)
  223796. {
  223797. #if JUCE_IOS
  223798. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  223799. forPasteboardType: @"public.text"];
  223800. #else
  223801. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  223802. owner: nil];
  223803. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  223804. forType: NSStringPboardType];
  223805. #endif
  223806. }
  223807. const String SystemClipboard::getTextFromClipboard()
  223808. {
  223809. #if JUCE_IOS
  223810. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  223811. #else
  223812. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  223813. #endif
  223814. return text == 0 ? String::empty
  223815. : nsStringToJuce (text);
  223816. }
  223817. #endif
  223818. #endif
  223819. /*** End of inlined file: juce_mac_Strings.mm ***/
  223820. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  223821. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223822. // compiled on its own).
  223823. #if JUCE_INCLUDED_FILE
  223824. namespace SystemStatsHelpers
  223825. {
  223826. static int64 highResTimerFrequency = 0;
  223827. static double highResTimerToMillisecRatio = 0;
  223828. #if JUCE_INTEL
  223829. void doCPUID (uint32& a, uint32& b, uint32& c, uint32& d, uint32 type)
  223830. {
  223831. uint32 la = a, lb = b, lc = c, ld = d;
  223832. asm ("mov %%ebx, %%esi \n\t"
  223833. "cpuid \n\t"
  223834. "xchg %%esi, %%ebx"
  223835. : "=a" (la), "=S" (lb), "=c" (lc), "=d" (ld) : "a" (type)
  223836. #if JUCE_64BIT
  223837. , "b" (lb), "c" (lc), "d" (ld)
  223838. #endif
  223839. );
  223840. a = la; b = lb; c = lc; d = ld;
  223841. }
  223842. #endif
  223843. }
  223844. void SystemStats::initialiseStats()
  223845. {
  223846. using namespace SystemStatsHelpers;
  223847. static bool initialised = false;
  223848. if (! initialised)
  223849. {
  223850. initialised = true;
  223851. #if JUCE_MAC
  223852. [NSApplication sharedApplication];
  223853. #endif
  223854. #if JUCE_INTEL
  223855. uint32 familyModel = 0, extFeatures = 0, features = 0, dummy = 0;
  223856. doCPUID (familyModel, extFeatures, dummy, features, 1);
  223857. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223858. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223859. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223860. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223861. #else
  223862. cpuFlags.hasMMX = false;
  223863. cpuFlags.hasSSE = false;
  223864. cpuFlags.hasSSE2 = false;
  223865. cpuFlags.has3DNow = false;
  223866. #endif
  223867. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223868. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223869. #else
  223870. cpuFlags.numCpus = (int) MPProcessors();
  223871. #endif
  223872. mach_timebase_info_data_t timebase;
  223873. (void) mach_timebase_info (&timebase);
  223874. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223875. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223876. String s (SystemStats::getJUCEVersion());
  223877. rlimit lim;
  223878. getrlimit (RLIMIT_NOFILE, &lim);
  223879. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223880. setrlimit (RLIMIT_NOFILE, &lim);
  223881. }
  223882. }
  223883. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223884. {
  223885. return MacOSX;
  223886. }
  223887. const String SystemStats::getOperatingSystemName()
  223888. {
  223889. return "Mac OS X";
  223890. }
  223891. #if ! JUCE_IOS
  223892. int PlatformUtilities::getOSXMinorVersionNumber()
  223893. {
  223894. SInt32 versionMinor = 0;
  223895. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  223896. (void) err;
  223897. jassert (err == noErr);
  223898. return (int) versionMinor;
  223899. }
  223900. #endif
  223901. bool SystemStats::isOperatingSystem64Bit()
  223902. {
  223903. #if JUCE_IOS
  223904. return false;
  223905. #elif JUCE_64BIT
  223906. return true;
  223907. #else
  223908. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  223909. #endif
  223910. }
  223911. int SystemStats::getMemorySizeInMegabytes()
  223912. {
  223913. uint64 mem = 0;
  223914. size_t memSize = sizeof (mem);
  223915. int mib[] = { CTL_HW, HW_MEMSIZE };
  223916. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223917. return (int) (mem / (1024 * 1024));
  223918. }
  223919. const String SystemStats::getCpuVendor()
  223920. {
  223921. #if JUCE_INTEL
  223922. uint32 dummy = 0;
  223923. uint32 vendor[4];
  223924. zerostruct (vendor);
  223925. SystemStatsHelpers::doCPUID (dummy, vendor[0], vendor[2], vendor[1], 0);
  223926. return String (reinterpret_cast <const char*> (vendor), 12);
  223927. #else
  223928. return String::empty;
  223929. #endif
  223930. }
  223931. int SystemStats::getCpuSpeedInMegaherz()
  223932. {
  223933. uint64 speedHz = 0;
  223934. size_t speedSize = sizeof (speedHz);
  223935. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223936. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223937. #if JUCE_BIG_ENDIAN
  223938. if (speedSize == 4)
  223939. speedHz >>= 32;
  223940. #endif
  223941. return (int) (speedHz / 1000000);
  223942. }
  223943. const String SystemStats::getLogonName()
  223944. {
  223945. return nsStringToJuce (NSUserName());
  223946. }
  223947. const String SystemStats::getFullUserName()
  223948. {
  223949. return nsStringToJuce (NSFullUserName());
  223950. }
  223951. uint32 juce_millisecondsSinceStartup() throw()
  223952. {
  223953. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223954. }
  223955. double Time::getMillisecondCounterHiRes() throw()
  223956. {
  223957. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223958. }
  223959. int64 Time::getHighResolutionTicks() throw()
  223960. {
  223961. return (int64) mach_absolute_time();
  223962. }
  223963. int64 Time::getHighResolutionTicksPerSecond() throw()
  223964. {
  223965. return SystemStatsHelpers::highResTimerFrequency;
  223966. }
  223967. bool Time::setSystemTimeToThisTime() const
  223968. {
  223969. jassertfalse;
  223970. return false;
  223971. }
  223972. int SystemStats::getPageSize()
  223973. {
  223974. return (int) NSPageSize();
  223975. }
  223976. void PlatformUtilities::fpuReset()
  223977. {
  223978. }
  223979. #endif
  223980. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  223981. /*** Start of inlined file: juce_mac_Network.mm ***/
  223982. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223983. // compiled on its own).
  223984. #if JUCE_INCLUDED_FILE
  223985. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  223986. {
  223987. ifaddrs* addrs = 0;
  223988. if (getifaddrs (&addrs) == 0)
  223989. {
  223990. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  223991. {
  223992. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  223993. if (sto->ss_family == AF_LINK)
  223994. {
  223995. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  223996. #ifndef IFT_ETHER
  223997. #define IFT_ETHER 6
  223998. #endif
  223999. if (sadd->sdl_type == IFT_ETHER)
  224000. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  224001. }
  224002. }
  224003. freeifaddrs (addrs);
  224004. }
  224005. }
  224006. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224007. const String& emailSubject,
  224008. const String& bodyText,
  224009. const StringArray& filesToAttach)
  224010. {
  224011. #if JUCE_IOS
  224012. //xxx probably need to use MFMailComposeViewController
  224013. jassertfalse;
  224014. return false;
  224015. #else
  224016. const ScopedAutoReleasePool pool;
  224017. String script;
  224018. script << "tell application \"Mail\"\r\n"
  224019. "set newMessage to make new outgoing message with properties {subject:\""
  224020. << emailSubject.replace ("\"", "\\\"")
  224021. << "\", content:\""
  224022. << bodyText.replace ("\"", "\\\"")
  224023. << "\" & return & return}\r\n"
  224024. "tell newMessage\r\n"
  224025. "set visible to true\r\n"
  224026. "set sender to \"sdfsdfsdfewf\"\r\n"
  224027. "make new to recipient at end of to recipients with properties {address:\""
  224028. << targetEmailAddress
  224029. << "\"}\r\n";
  224030. for (int i = 0; i < filesToAttach.size(); ++i)
  224031. {
  224032. script << "tell content\r\n"
  224033. "make new attachment with properties {file name:\""
  224034. << filesToAttach[i].replace ("\"", "\\\"")
  224035. << "\"} at after the last paragraph\r\n"
  224036. "end tell\r\n";
  224037. }
  224038. script << "end tell\r\n"
  224039. "end tell\r\n";
  224040. NSAppleScript* s = [[NSAppleScript alloc]
  224041. initWithSource: juceStringToNS (script)];
  224042. NSDictionary* error = 0;
  224043. const bool ok = [s executeAndReturnError: &error] != nil;
  224044. [s release];
  224045. return ok;
  224046. #endif
  224047. }
  224048. END_JUCE_NAMESPACE
  224049. using namespace JUCE_NAMESPACE;
  224050. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224051. @interface JuceURLConnection : NSObject
  224052. {
  224053. @public
  224054. NSURLRequest* request;
  224055. NSURLConnection* connection;
  224056. NSMutableData* data;
  224057. Thread* runLoopThread;
  224058. bool initialised, hasFailed, hasFinished;
  224059. int position;
  224060. int64 contentLength;
  224061. NSDictionary* headers;
  224062. NSLock* dataLock;
  224063. }
  224064. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224065. - (void) dealloc;
  224066. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224067. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224068. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224069. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224070. - (BOOL) isOpen;
  224071. - (int) read: (char*) dest numBytes: (int) num;
  224072. - (int) readPosition;
  224073. - (void) stop;
  224074. - (void) createConnection;
  224075. @end
  224076. class JuceURLConnectionMessageThread : public Thread
  224077. {
  224078. public:
  224079. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224080. : Thread ("http connection"),
  224081. owner (owner_)
  224082. {
  224083. }
  224084. ~JuceURLConnectionMessageThread()
  224085. {
  224086. stopThread (10000);
  224087. }
  224088. void run()
  224089. {
  224090. [owner createConnection];
  224091. while (! threadShouldExit())
  224092. {
  224093. const ScopedAutoReleasePool pool;
  224094. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224095. }
  224096. }
  224097. private:
  224098. JuceURLConnection* owner;
  224099. };
  224100. @implementation JuceURLConnection
  224101. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224102. withCallback: (URL::OpenStreamProgressCallback*) callback
  224103. withContext: (void*) context;
  224104. {
  224105. [super init];
  224106. request = req;
  224107. [request retain];
  224108. data = [[NSMutableData data] retain];
  224109. dataLock = [[NSLock alloc] init];
  224110. connection = 0;
  224111. initialised = false;
  224112. hasFailed = false;
  224113. hasFinished = false;
  224114. contentLength = -1;
  224115. headers = 0;
  224116. runLoopThread = new JuceURLConnectionMessageThread (self);
  224117. runLoopThread->startThread();
  224118. while (runLoopThread->isThreadRunning() && ! initialised)
  224119. {
  224120. if (callback != 0)
  224121. callback (context, -1, (int) [[request HTTPBody] length]);
  224122. Thread::sleep (1);
  224123. }
  224124. return self;
  224125. }
  224126. - (void) dealloc
  224127. {
  224128. [self stop];
  224129. deleteAndZero (runLoopThread);
  224130. [connection release];
  224131. [data release];
  224132. [dataLock release];
  224133. [request release];
  224134. [headers release];
  224135. [super dealloc];
  224136. }
  224137. - (void) createConnection
  224138. {
  224139. NSUInteger oldRetainCount = [self retainCount];
  224140. connection = [[NSURLConnection alloc] initWithRequest: request
  224141. delegate: self];
  224142. if (oldRetainCount == [self retainCount])
  224143. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224144. if (connection == nil)
  224145. runLoopThread->signalThreadShouldExit();
  224146. }
  224147. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224148. {
  224149. (void) conn;
  224150. [dataLock lock];
  224151. [data setLength: 0];
  224152. [dataLock unlock];
  224153. initialised = true;
  224154. contentLength = [response expectedContentLength];
  224155. [headers release];
  224156. headers = 0;
  224157. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224158. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224159. }
  224160. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224161. {
  224162. (void) conn;
  224163. DBG (nsStringToJuce ([error description]));
  224164. hasFailed = true;
  224165. initialised = true;
  224166. if (runLoopThread != 0)
  224167. runLoopThread->signalThreadShouldExit();
  224168. }
  224169. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224170. {
  224171. (void) conn;
  224172. [dataLock lock];
  224173. [data appendData: newData];
  224174. [dataLock unlock];
  224175. initialised = true;
  224176. }
  224177. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224178. {
  224179. (void) conn;
  224180. hasFinished = true;
  224181. initialised = true;
  224182. if (runLoopThread != 0)
  224183. runLoopThread->signalThreadShouldExit();
  224184. }
  224185. - (BOOL) isOpen
  224186. {
  224187. return connection != 0 && ! hasFailed;
  224188. }
  224189. - (int) readPosition
  224190. {
  224191. return position;
  224192. }
  224193. - (int) read: (char*) dest numBytes: (int) numNeeded
  224194. {
  224195. int numDone = 0;
  224196. while (numNeeded > 0)
  224197. {
  224198. int available = jmin (numNeeded, (int) [data length]);
  224199. if (available > 0)
  224200. {
  224201. [dataLock lock];
  224202. [data getBytes: dest length: available];
  224203. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224204. [dataLock unlock];
  224205. numDone += available;
  224206. numNeeded -= available;
  224207. dest += available;
  224208. }
  224209. else
  224210. {
  224211. if (hasFailed || hasFinished)
  224212. break;
  224213. Thread::sleep (1);
  224214. }
  224215. }
  224216. position += numDone;
  224217. return numDone;
  224218. }
  224219. - (void) stop
  224220. {
  224221. [connection cancel];
  224222. if (runLoopThread != 0)
  224223. runLoopThread->stopThread (10000);
  224224. }
  224225. @end
  224226. BEGIN_JUCE_NAMESPACE
  224227. class WebInputStream : public InputStream
  224228. {
  224229. public:
  224230. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  224231. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  224232. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  224233. : connection (nil),
  224234. address (address_), headers (headers_), postData (postData_), position (0),
  224235. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  224236. {
  224237. JUCE_AUTORELEASEPOOL
  224238. connection = createConnection (progressCallback, progressCallbackContext);
  224239. if (responseHeaders != 0 && connection != 0 && connection->headers != 0)
  224240. {
  224241. NSEnumerator* enumerator = [connection->headers keyEnumerator];
  224242. NSString* key;
  224243. while ((key = [enumerator nextObject]) != nil)
  224244. responseHeaders->set (nsStringToJuce (key),
  224245. nsStringToJuce ((NSString*) [connection->headers objectForKey: key]));
  224246. }
  224247. }
  224248. ~WebInputStream()
  224249. {
  224250. close();
  224251. }
  224252. bool isError() const { return connection == nil; }
  224253. int64 getTotalLength() { return connection == nil ? -1 : connection->contentLength; }
  224254. bool isExhausted() { return finished; }
  224255. int64 getPosition() { return position; }
  224256. int read (void* buffer, int bytesToRead)
  224257. {
  224258. if (finished || isError())
  224259. {
  224260. return 0;
  224261. }
  224262. else
  224263. {
  224264. JUCE_AUTORELEASEPOOL
  224265. const int bytesRead = [connection read: static_cast <char*> (buffer) numBytes: bytesToRead];
  224266. position += bytesRead;
  224267. if (bytesRead == 0)
  224268. finished = true;
  224269. return bytesRead;
  224270. }
  224271. }
  224272. bool setPosition (int64 wantedPos)
  224273. {
  224274. if (wantedPos != position)
  224275. {
  224276. finished = false;
  224277. if (wantedPos < position)
  224278. {
  224279. close();
  224280. position = 0;
  224281. connection = createConnection (0, 0);
  224282. }
  224283. skipNextBytes (wantedPos - position);
  224284. }
  224285. return true;
  224286. }
  224287. private:
  224288. JuceURLConnection* connection;
  224289. String address, headers;
  224290. MemoryBlock postData;
  224291. int64 position;
  224292. bool finished;
  224293. const bool isPost;
  224294. const int timeOutMs;
  224295. void close()
  224296. {
  224297. [connection stop];
  224298. [connection release];
  224299. connection = nil;
  224300. }
  224301. JuceURLConnection* createConnection (URL::OpenStreamProgressCallback* progressCallback,
  224302. void* progressCallbackContext)
  224303. {
  224304. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (address)]
  224305. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224306. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224307. if (req == nil)
  224308. return 0;
  224309. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224310. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224311. StringArray headerLines;
  224312. headerLines.addLines (headers);
  224313. headerLines.removeEmptyStrings (true);
  224314. for (int i = 0; i < headerLines.size(); ++i)
  224315. {
  224316. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224317. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224318. if (key.isNotEmpty() && value.isNotEmpty())
  224319. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224320. }
  224321. if (isPost && postData.getSize() > 0)
  224322. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224323. length: postData.getSize()]];
  224324. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224325. withCallback: progressCallback
  224326. withContext: progressCallbackContext];
  224327. if ([s isOpen])
  224328. return s;
  224329. [s release];
  224330. return 0;
  224331. }
  224332. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  224333. };
  224334. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  224335. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  224336. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  224337. {
  224338. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  224339. progressCallback, progressCallbackContext,
  224340. headers, timeOutMs, responseHeaders));
  224341. return wi->isError() ? 0 : wi.release();
  224342. }
  224343. #endif
  224344. /*** End of inlined file: juce_mac_Network.mm ***/
  224345. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224346. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224347. // compiled on its own).
  224348. #if JUCE_INCLUDED_FILE
  224349. struct NamedPipeInternal
  224350. {
  224351. String pipeInName, pipeOutName;
  224352. int pipeIn, pipeOut;
  224353. bool volatile createdPipe, blocked, stopReadOperation;
  224354. static void signalHandler (int) {}
  224355. };
  224356. void NamedPipe::cancelPendingReads()
  224357. {
  224358. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224359. {
  224360. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224361. intern->stopReadOperation = true;
  224362. char buffer [1] = { 0 };
  224363. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224364. (void) bytesWritten;
  224365. int timeout = 2000;
  224366. while (intern->blocked && --timeout >= 0)
  224367. Thread::sleep (2);
  224368. intern->stopReadOperation = false;
  224369. }
  224370. }
  224371. void NamedPipe::close()
  224372. {
  224373. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224374. if (intern != 0)
  224375. {
  224376. internal = 0;
  224377. if (intern->pipeIn != -1)
  224378. ::close (intern->pipeIn);
  224379. if (intern->pipeOut != -1)
  224380. ::close (intern->pipeOut);
  224381. if (intern->createdPipe)
  224382. {
  224383. unlink (intern->pipeInName.toUTF8());
  224384. unlink (intern->pipeOutName.toUTF8());
  224385. }
  224386. delete intern;
  224387. }
  224388. }
  224389. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224390. {
  224391. close();
  224392. NamedPipeInternal* const intern = new NamedPipeInternal();
  224393. internal = intern;
  224394. intern->createdPipe = createPipe;
  224395. intern->blocked = false;
  224396. intern->stopReadOperation = false;
  224397. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224398. siginterrupt (SIGPIPE, 1);
  224399. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224400. intern->pipeInName = pipePath + "_in";
  224401. intern->pipeOutName = pipePath + "_out";
  224402. intern->pipeIn = -1;
  224403. intern->pipeOut = -1;
  224404. if (createPipe)
  224405. {
  224406. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224407. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224408. {
  224409. delete intern;
  224410. internal = 0;
  224411. return false;
  224412. }
  224413. }
  224414. return true;
  224415. }
  224416. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224417. {
  224418. int bytesRead = -1;
  224419. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224420. if (intern != 0)
  224421. {
  224422. intern->blocked = true;
  224423. if (intern->pipeIn == -1)
  224424. {
  224425. if (intern->createdPipe)
  224426. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224427. else
  224428. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224429. if (intern->pipeIn == -1)
  224430. {
  224431. intern->blocked = false;
  224432. return -1;
  224433. }
  224434. }
  224435. bytesRead = 0;
  224436. char* p = static_cast<char*> (destBuffer);
  224437. while (bytesRead < maxBytesToRead)
  224438. {
  224439. const int bytesThisTime = maxBytesToRead - bytesRead;
  224440. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224441. if (numRead <= 0 || intern->stopReadOperation)
  224442. {
  224443. bytesRead = -1;
  224444. break;
  224445. }
  224446. bytesRead += numRead;
  224447. p += bytesRead;
  224448. }
  224449. intern->blocked = false;
  224450. }
  224451. return bytesRead;
  224452. }
  224453. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224454. {
  224455. int bytesWritten = -1;
  224456. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224457. if (intern != 0)
  224458. {
  224459. if (intern->pipeOut == -1)
  224460. {
  224461. if (intern->createdPipe)
  224462. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224463. else
  224464. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224465. if (intern->pipeOut == -1)
  224466. {
  224467. return -1;
  224468. }
  224469. }
  224470. const char* p = static_cast<const char*> (sourceBuffer);
  224471. bytesWritten = 0;
  224472. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224473. while (bytesWritten < numBytesToWrite
  224474. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224475. {
  224476. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224477. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224478. if (numWritten <= 0)
  224479. {
  224480. bytesWritten = -1;
  224481. break;
  224482. }
  224483. bytesWritten += numWritten;
  224484. p += bytesWritten;
  224485. }
  224486. }
  224487. return bytesWritten;
  224488. }
  224489. #endif
  224490. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224491. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224492. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224493. // compiled on its own).
  224494. #if JUCE_INCLUDED_FILE
  224495. /*
  224496. Note that a lot of methods that you'd expect to find in this file actually
  224497. live in juce_posix_SharedCode.h!
  224498. */
  224499. bool Process::isForegroundProcess()
  224500. {
  224501. #if JUCE_MAC
  224502. return [NSApp isActive];
  224503. #else
  224504. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224505. #endif
  224506. }
  224507. void Process::raisePrivilege()
  224508. {
  224509. jassertfalse;
  224510. }
  224511. void Process::lowerPrivilege()
  224512. {
  224513. jassertfalse;
  224514. }
  224515. void Process::terminate()
  224516. {
  224517. exit (0);
  224518. }
  224519. void Process::setPriority (ProcessPriority)
  224520. {
  224521. // xxx
  224522. }
  224523. #endif
  224524. /*** End of inlined file: juce_mac_Threads.mm ***/
  224525. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224526. /*
  224527. This file contains posix routines that are common to both the Linux and Mac builds.
  224528. It gets included directly in the cpp files for these platforms.
  224529. */
  224530. CriticalSection::CriticalSection() throw()
  224531. {
  224532. pthread_mutexattr_t atts;
  224533. pthread_mutexattr_init (&atts);
  224534. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224535. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224536. pthread_mutex_init (&internal, &atts);
  224537. }
  224538. CriticalSection::~CriticalSection() throw()
  224539. {
  224540. pthread_mutex_destroy (&internal);
  224541. }
  224542. void CriticalSection::enter() const throw()
  224543. {
  224544. pthread_mutex_lock (&internal);
  224545. }
  224546. bool CriticalSection::tryEnter() const throw()
  224547. {
  224548. return pthread_mutex_trylock (&internal) == 0;
  224549. }
  224550. void CriticalSection::exit() const throw()
  224551. {
  224552. pthread_mutex_unlock (&internal);
  224553. }
  224554. class WaitableEventImpl
  224555. {
  224556. public:
  224557. WaitableEventImpl (const bool manualReset_)
  224558. : triggered (false),
  224559. manualReset (manualReset_)
  224560. {
  224561. pthread_cond_init (&condition, 0);
  224562. pthread_mutexattr_t atts;
  224563. pthread_mutexattr_init (&atts);
  224564. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224565. pthread_mutex_init (&mutex, &atts);
  224566. }
  224567. ~WaitableEventImpl()
  224568. {
  224569. pthread_cond_destroy (&condition);
  224570. pthread_mutex_destroy (&mutex);
  224571. }
  224572. bool wait (const int timeOutMillisecs) throw()
  224573. {
  224574. pthread_mutex_lock (&mutex);
  224575. if (! triggered)
  224576. {
  224577. if (timeOutMillisecs < 0)
  224578. {
  224579. do
  224580. {
  224581. pthread_cond_wait (&condition, &mutex);
  224582. }
  224583. while (! triggered);
  224584. }
  224585. else
  224586. {
  224587. struct timeval now;
  224588. gettimeofday (&now, 0);
  224589. struct timespec time;
  224590. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224591. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224592. if (time.tv_nsec >= 1000000000)
  224593. {
  224594. time.tv_nsec -= 1000000000;
  224595. time.tv_sec++;
  224596. }
  224597. do
  224598. {
  224599. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224600. {
  224601. pthread_mutex_unlock (&mutex);
  224602. return false;
  224603. }
  224604. }
  224605. while (! triggered);
  224606. }
  224607. }
  224608. if (! manualReset)
  224609. triggered = false;
  224610. pthread_mutex_unlock (&mutex);
  224611. return true;
  224612. }
  224613. void signal() throw()
  224614. {
  224615. pthread_mutex_lock (&mutex);
  224616. triggered = true;
  224617. pthread_cond_broadcast (&condition);
  224618. pthread_mutex_unlock (&mutex);
  224619. }
  224620. void reset() throw()
  224621. {
  224622. pthread_mutex_lock (&mutex);
  224623. triggered = false;
  224624. pthread_mutex_unlock (&mutex);
  224625. }
  224626. private:
  224627. pthread_cond_t condition;
  224628. pthread_mutex_t mutex;
  224629. bool triggered;
  224630. const bool manualReset;
  224631. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  224632. };
  224633. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224634. : internal (new WaitableEventImpl (manualReset))
  224635. {
  224636. }
  224637. WaitableEvent::~WaitableEvent() throw()
  224638. {
  224639. delete static_cast <WaitableEventImpl*> (internal);
  224640. }
  224641. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224642. {
  224643. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224644. }
  224645. void WaitableEvent::signal() const throw()
  224646. {
  224647. static_cast <WaitableEventImpl*> (internal)->signal();
  224648. }
  224649. void WaitableEvent::reset() const throw()
  224650. {
  224651. static_cast <WaitableEventImpl*> (internal)->reset();
  224652. }
  224653. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224654. {
  224655. struct timespec time;
  224656. time.tv_sec = millisecs / 1000;
  224657. time.tv_nsec = (millisecs % 1000) * 1000000;
  224658. nanosleep (&time, 0);
  224659. }
  224660. const juce_wchar File::separator = '/';
  224661. const String File::separatorString ("/");
  224662. const File File::getCurrentWorkingDirectory()
  224663. {
  224664. HeapBlock<char> heapBuffer;
  224665. char localBuffer [1024];
  224666. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224667. int bufferSize = 4096;
  224668. while (cwd == 0 && errno == ERANGE)
  224669. {
  224670. heapBuffer.malloc (bufferSize);
  224671. cwd = getcwd (heapBuffer, bufferSize - 1);
  224672. bufferSize += 1024;
  224673. }
  224674. return File (String::fromUTF8 (cwd));
  224675. }
  224676. bool File::setAsCurrentWorkingDirectory() const
  224677. {
  224678. return chdir (getFullPathName().toUTF8()) == 0;
  224679. }
  224680. namespace
  224681. {
  224682. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224683. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  224684. #else
  224685. typedef struct stat juce_statStruct;
  224686. #endif
  224687. bool juce_stat (const String& fileName, juce_statStruct& info)
  224688. {
  224689. return fileName.isNotEmpty()
  224690. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224691. && (stat64 (fileName.toUTF8(), &info) == 0);
  224692. #else
  224693. && (stat (fileName.toUTF8(), &info) == 0);
  224694. #endif
  224695. }
  224696. // if this file doesn't exist, find a parent of it that does..
  224697. bool juce_doStatFS (File f, struct statfs& result)
  224698. {
  224699. for (int i = 5; --i >= 0;)
  224700. {
  224701. if (f.exists())
  224702. break;
  224703. f = f.getParentDirectory();
  224704. }
  224705. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224706. }
  224707. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  224708. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224709. {
  224710. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224711. {
  224712. juce_statStruct info;
  224713. const bool statOk = juce_stat (path, info);
  224714. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224715. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224716. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  224717. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  224718. }
  224719. if (isReadOnly != 0)
  224720. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224721. }
  224722. }
  224723. bool File::isDirectory() const
  224724. {
  224725. juce_statStruct info;
  224726. return fullPath.isEmpty()
  224727. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224728. }
  224729. bool File::exists() const
  224730. {
  224731. juce_statStruct info;
  224732. return fullPath.isNotEmpty()
  224733. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224734. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  224735. #else
  224736. && (lstat (fullPath.toUTF8(), &info) == 0);
  224737. #endif
  224738. }
  224739. bool File::existsAsFile() const
  224740. {
  224741. return exists() && ! isDirectory();
  224742. }
  224743. int64 File::getSize() const
  224744. {
  224745. juce_statStruct info;
  224746. return juce_stat (fullPath, info) ? info.st_size : 0;
  224747. }
  224748. bool File::hasWriteAccess() const
  224749. {
  224750. if (exists())
  224751. return access (fullPath.toUTF8(), W_OK) == 0;
  224752. if ((! isDirectory()) && fullPath.containsChar (separator))
  224753. return getParentDirectory().hasWriteAccess();
  224754. return false;
  224755. }
  224756. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  224757. {
  224758. juce_statStruct info;
  224759. if (! juce_stat (fullPath, info))
  224760. return false;
  224761. info.st_mode &= 0777; // Just permissions
  224762. if (shouldBeReadOnly)
  224763. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224764. else
  224765. // Give everybody write permission?
  224766. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224767. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  224768. }
  224769. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  224770. {
  224771. modificationTime = 0;
  224772. accessTime = 0;
  224773. creationTime = 0;
  224774. juce_statStruct info;
  224775. if (juce_stat (fullPath, info))
  224776. {
  224777. modificationTime = (int64) info.st_mtime * 1000;
  224778. accessTime = (int64) info.st_atime * 1000;
  224779. creationTime = (int64) info.st_ctime * 1000;
  224780. }
  224781. }
  224782. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  224783. {
  224784. struct utimbuf times;
  224785. times.actime = (time_t) (accessTime / 1000);
  224786. times.modtime = (time_t) (modificationTime / 1000);
  224787. return utime (fullPath.toUTF8(), &times) == 0;
  224788. }
  224789. bool File::deleteFile() const
  224790. {
  224791. if (! exists())
  224792. return true;
  224793. else if (isDirectory())
  224794. return rmdir (fullPath.toUTF8()) == 0;
  224795. else
  224796. return remove (fullPath.toUTF8()) == 0;
  224797. }
  224798. bool File::moveInternal (const File& dest) const
  224799. {
  224800. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  224801. return true;
  224802. if (hasWriteAccess() && copyInternal (dest))
  224803. {
  224804. if (deleteFile())
  224805. return true;
  224806. dest.deleteFile();
  224807. }
  224808. return false;
  224809. }
  224810. void File::createDirectoryInternal (const String& fileName) const
  224811. {
  224812. mkdir (fileName.toUTF8(), 0777);
  224813. }
  224814. int64 juce_fileSetPosition (void* handle, int64 pos)
  224815. {
  224816. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  224817. return pos;
  224818. return -1;
  224819. }
  224820. void FileInputStream::openHandle()
  224821. {
  224822. totalSize = file.getSize();
  224823. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  224824. if (f != -1)
  224825. fileHandle = (void*) f;
  224826. }
  224827. void FileInputStream::closeHandle()
  224828. {
  224829. if (fileHandle != 0)
  224830. {
  224831. close ((int) (pointer_sized_int) fileHandle);
  224832. fileHandle = 0;
  224833. }
  224834. }
  224835. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  224836. {
  224837. if (fileHandle != 0)
  224838. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  224839. return 0;
  224840. }
  224841. void FileOutputStream::openHandle()
  224842. {
  224843. if (file.exists())
  224844. {
  224845. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  224846. if (f != -1)
  224847. {
  224848. currentPosition = lseek (f, 0, SEEK_END);
  224849. if (currentPosition >= 0)
  224850. fileHandle = (void*) f;
  224851. else
  224852. close (f);
  224853. }
  224854. }
  224855. else
  224856. {
  224857. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  224858. if (f != -1)
  224859. fileHandle = (void*) f;
  224860. }
  224861. }
  224862. void FileOutputStream::closeHandle()
  224863. {
  224864. if (fileHandle != 0)
  224865. {
  224866. close ((int) (pointer_sized_int) fileHandle);
  224867. fileHandle = 0;
  224868. }
  224869. }
  224870. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  224871. {
  224872. if (fileHandle != 0)
  224873. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  224874. return 0;
  224875. }
  224876. void FileOutputStream::flushInternal()
  224877. {
  224878. if (fileHandle != 0)
  224879. fsync ((int) (pointer_sized_int) fileHandle);
  224880. }
  224881. const File juce_getExecutableFile()
  224882. {
  224883. Dl_info exeInfo;
  224884. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  224885. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  224886. }
  224887. int64 File::getBytesFreeOnVolume() const
  224888. {
  224889. struct statfs buf;
  224890. if (juce_doStatFS (*this, buf))
  224891. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224892. return 0;
  224893. }
  224894. int64 File::getVolumeTotalSize() const
  224895. {
  224896. struct statfs buf;
  224897. if (juce_doStatFS (*this, buf))
  224898. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224899. return 0;
  224900. }
  224901. const String File::getVolumeLabel() const
  224902. {
  224903. #if JUCE_MAC
  224904. struct VolAttrBuf
  224905. {
  224906. u_int32_t length;
  224907. attrreference_t mountPointRef;
  224908. char mountPointSpace [MAXPATHLEN];
  224909. } attrBuf;
  224910. struct attrlist attrList;
  224911. zerostruct (attrList);
  224912. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224913. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224914. File f (*this);
  224915. for (;;)
  224916. {
  224917. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224918. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224919. (int) attrBuf.mountPointRef.attr_length);
  224920. const File parent (f.getParentDirectory());
  224921. if (f == parent)
  224922. break;
  224923. f = parent;
  224924. }
  224925. #endif
  224926. return String::empty;
  224927. }
  224928. int File::getVolumeSerialNumber() const
  224929. {
  224930. return 0; // xxx
  224931. }
  224932. void juce_runSystemCommand (const String& command)
  224933. {
  224934. int result = system (command.toUTF8());
  224935. (void) result;
  224936. }
  224937. const String juce_getOutputFromCommand (const String& command)
  224938. {
  224939. // slight bodge here, as we just pipe the output into a temp file and read it...
  224940. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224941. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224942. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224943. String result (tempFile.loadFileAsString());
  224944. tempFile.deleteFile();
  224945. return result;
  224946. }
  224947. class InterProcessLock::Pimpl
  224948. {
  224949. public:
  224950. Pimpl (const String& name, const int timeOutMillisecs)
  224951. : handle (0), refCount (1)
  224952. {
  224953. #if JUCE_MAC
  224954. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224955. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  224956. #else
  224957. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224958. #endif
  224959. temp.create();
  224960. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  224961. if (handle != 0)
  224962. {
  224963. struct flock fl;
  224964. zerostruct (fl);
  224965. fl.l_whence = SEEK_SET;
  224966. fl.l_type = F_WRLCK;
  224967. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224968. for (;;)
  224969. {
  224970. const int result = fcntl (handle, F_SETLK, &fl);
  224971. if (result >= 0)
  224972. return;
  224973. if (errno != EINTR)
  224974. {
  224975. if (timeOutMillisecs == 0
  224976. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224977. break;
  224978. Thread::sleep (10);
  224979. }
  224980. }
  224981. }
  224982. closeFile();
  224983. }
  224984. ~Pimpl()
  224985. {
  224986. closeFile();
  224987. }
  224988. void closeFile()
  224989. {
  224990. if (handle != 0)
  224991. {
  224992. struct flock fl;
  224993. zerostruct (fl);
  224994. fl.l_whence = SEEK_SET;
  224995. fl.l_type = F_UNLCK;
  224996. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  224997. {}
  224998. close (handle);
  224999. handle = 0;
  225000. }
  225001. }
  225002. int handle, refCount;
  225003. };
  225004. InterProcessLock::InterProcessLock (const String& name_)
  225005. : name (name_)
  225006. {
  225007. }
  225008. InterProcessLock::~InterProcessLock()
  225009. {
  225010. }
  225011. bool InterProcessLock::enter (const int timeOutMillisecs)
  225012. {
  225013. const ScopedLock sl (lock);
  225014. if (pimpl == 0)
  225015. {
  225016. pimpl = new Pimpl (name, timeOutMillisecs);
  225017. if (pimpl->handle == 0)
  225018. pimpl = 0;
  225019. }
  225020. else
  225021. {
  225022. pimpl->refCount++;
  225023. }
  225024. return pimpl != 0;
  225025. }
  225026. void InterProcessLock::exit()
  225027. {
  225028. const ScopedLock sl (lock);
  225029. // Trying to release the lock too many times!
  225030. jassert (pimpl != 0);
  225031. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225032. pimpl = 0;
  225033. }
  225034. void JUCE_API juce_threadEntryPoint (void*);
  225035. void* threadEntryProc (void* userData)
  225036. {
  225037. JUCE_AUTORELEASEPOOL
  225038. juce_threadEntryPoint (userData);
  225039. return 0;
  225040. }
  225041. void Thread::launchThread()
  225042. {
  225043. threadHandle_ = 0;
  225044. pthread_t handle = 0;
  225045. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  225046. {
  225047. pthread_detach (handle);
  225048. threadHandle_ = (void*) handle;
  225049. threadId_ = (ThreadID) threadHandle_;
  225050. }
  225051. }
  225052. void Thread::closeThreadHandle()
  225053. {
  225054. threadId_ = 0;
  225055. threadHandle_ = 0;
  225056. }
  225057. void Thread::killThread()
  225058. {
  225059. if (threadHandle_ != 0)
  225060. pthread_cancel ((pthread_t) threadHandle_);
  225061. }
  225062. void Thread::setCurrentThreadName (const String& /*name*/)
  225063. {
  225064. }
  225065. bool Thread::setThreadPriority (void* handle, int priority)
  225066. {
  225067. struct sched_param param;
  225068. int policy;
  225069. priority = jlimit (0, 10, priority);
  225070. if (handle == 0)
  225071. handle = (void*) pthread_self();
  225072. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225073. return false;
  225074. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225075. const int minPriority = sched_get_priority_min (policy);
  225076. const int maxPriority = sched_get_priority_max (policy);
  225077. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225078. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225079. }
  225080. Thread::ThreadID Thread::getCurrentThreadId()
  225081. {
  225082. return (ThreadID) pthread_self();
  225083. }
  225084. void Thread::yield()
  225085. {
  225086. sched_yield();
  225087. }
  225088. /* Remove this macro if you're having problems compiling the cpu affinity
  225089. calls (the API for these has changed about quite a bit in various Linux
  225090. versions, and a lot of distros seem to ship with obsolete versions)
  225091. */
  225092. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225093. #define SUPPORT_AFFINITIES 1
  225094. #endif
  225095. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225096. {
  225097. #if SUPPORT_AFFINITIES
  225098. cpu_set_t affinity;
  225099. CPU_ZERO (&affinity);
  225100. for (int i = 0; i < 32; ++i)
  225101. if ((affinityMask & (1 << i)) != 0)
  225102. CPU_SET (i, &affinity);
  225103. /*
  225104. N.B. If this line causes a compile error, then you've probably not got the latest
  225105. version of glibc installed.
  225106. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225107. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225108. */
  225109. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225110. sched_yield();
  225111. #else
  225112. /* affinities aren't supported because either the appropriate header files weren't found,
  225113. or the SUPPORT_AFFINITIES macro was turned off
  225114. */
  225115. jassertfalse;
  225116. (void) affinityMask;
  225117. #endif
  225118. }
  225119. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225120. /*** Start of inlined file: juce_mac_Files.mm ***/
  225121. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225122. // compiled on its own).
  225123. #if JUCE_INCLUDED_FILE
  225124. /*
  225125. Note that a lot of methods that you'd expect to find in this file actually
  225126. live in juce_posix_SharedCode.h!
  225127. */
  225128. bool File::copyInternal (const File& dest) const
  225129. {
  225130. const ScopedAutoReleasePool pool;
  225131. NSFileManager* fm = [NSFileManager defaultManager];
  225132. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225133. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225134. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225135. toPath: juceStringToNS (dest.getFullPathName())
  225136. error: nil];
  225137. #else
  225138. && [fm copyPath: juceStringToNS (fullPath)
  225139. toPath: juceStringToNS (dest.getFullPathName())
  225140. handler: nil];
  225141. #endif
  225142. }
  225143. void File::findFileSystemRoots (Array<File>& destArray)
  225144. {
  225145. destArray.add (File ("/"));
  225146. }
  225147. namespace FileHelpers
  225148. {
  225149. bool isFileOnDriveType (const File& f, const char* const* types)
  225150. {
  225151. struct statfs buf;
  225152. if (juce_doStatFS (f, buf))
  225153. {
  225154. const String type (buf.f_fstypename);
  225155. while (*types != 0)
  225156. if (type.equalsIgnoreCase (*types++))
  225157. return true;
  225158. }
  225159. return false;
  225160. }
  225161. bool isHiddenFile (const String& path)
  225162. {
  225163. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225164. const ScopedAutoReleasePool pool;
  225165. NSNumber* hidden = nil;
  225166. NSError* err = nil;
  225167. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225168. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225169. && [hidden boolValue];
  225170. #else
  225171. #if JUCE_IOS
  225172. return File (path).getFileName().startsWithChar ('.');
  225173. #else
  225174. FSRef ref;
  225175. LSItemInfoRecord info;
  225176. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225177. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225178. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225179. #endif
  225180. #endif
  225181. }
  225182. #if JUCE_IOS
  225183. const String getIOSSystemLocation (NSSearchPathDirectory type)
  225184. {
  225185. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  225186. objectAtIndex: 0]);
  225187. }
  225188. #endif
  225189. bool launchExecutable (const String& pathAndArguments)
  225190. {
  225191. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225192. const int cpid = fork();
  225193. if (cpid == 0)
  225194. {
  225195. // Child process
  225196. if (execve (argv[0], (char**) argv, 0) < 0)
  225197. exit (0);
  225198. }
  225199. else
  225200. {
  225201. if (cpid < 0)
  225202. return false;
  225203. }
  225204. return true;
  225205. }
  225206. }
  225207. bool File::isOnCDRomDrive() const
  225208. {
  225209. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225210. return FileHelpers::isFileOnDriveType (*this, cdTypes);
  225211. }
  225212. bool File::isOnHardDisk() const
  225213. {
  225214. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225215. return ! (isOnCDRomDrive() || FileHelpers::isFileOnDriveType (*this, nonHDTypes));
  225216. }
  225217. bool File::isOnRemovableDrive() const
  225218. {
  225219. #if JUCE_IOS
  225220. return false; // xxx is this possible?
  225221. #else
  225222. const ScopedAutoReleasePool pool;
  225223. BOOL removable = false;
  225224. [[NSWorkspace sharedWorkspace]
  225225. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225226. isRemovable: &removable
  225227. isWritable: nil
  225228. isUnmountable: nil
  225229. description: nil
  225230. type: nil];
  225231. return removable;
  225232. #endif
  225233. }
  225234. bool File::isHidden() const
  225235. {
  225236. return FileHelpers::isHiddenFile (getFullPathName());
  225237. }
  225238. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225239. const File File::getSpecialLocation (const SpecialLocationType type)
  225240. {
  225241. const ScopedAutoReleasePool pool;
  225242. String resultPath;
  225243. switch (type)
  225244. {
  225245. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225246. #if JUCE_IOS
  225247. case userDocumentsDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDocumentDirectory); break;
  225248. case userDesktopDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDesktopDirectory); break;
  225249. case tempDirectory:
  225250. {
  225251. File tmp (FileHelpers::getIOSSystemLocation (NSCachesDirectory));
  225252. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  225253. tmp.createDirectory();
  225254. return tmp.getFullPathName();
  225255. }
  225256. #else
  225257. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225258. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225259. case tempDirectory:
  225260. {
  225261. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225262. tmp.createDirectory();
  225263. return tmp.getFullPathName();
  225264. }
  225265. #endif
  225266. case userMusicDirectory: resultPath = "~/Music"; break;
  225267. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225268. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225269. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225270. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225271. case invokedExecutableFile:
  225272. if (juce_Argv0 != 0)
  225273. return File (String::fromUTF8 (juce_Argv0));
  225274. // deliberate fall-through...
  225275. case currentExecutableFile:
  225276. return juce_getExecutableFile();
  225277. case currentApplicationFile:
  225278. {
  225279. const File exe (juce_getExecutableFile());
  225280. const File parent (exe.getParentDirectory());
  225281. #if JUCE_IOS
  225282. return parent;
  225283. #else
  225284. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225285. ? parent.getParentDirectory().getParentDirectory()
  225286. : exe;
  225287. #endif
  225288. }
  225289. case hostApplicationPath:
  225290. {
  225291. unsigned int size = 8192;
  225292. HeapBlock<char> buffer;
  225293. buffer.calloc (size + 8);
  225294. _NSGetExecutablePath (buffer.getData(), &size);
  225295. return String::fromUTF8 (buffer, size);
  225296. }
  225297. default:
  225298. jassertfalse; // unknown type?
  225299. break;
  225300. }
  225301. if (resultPath.isNotEmpty())
  225302. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225303. return File::nonexistent;
  225304. }
  225305. const String File::getVersion() const
  225306. {
  225307. const ScopedAutoReleasePool pool;
  225308. String result;
  225309. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225310. if (bundle != 0)
  225311. {
  225312. NSDictionary* info = [bundle infoDictionary];
  225313. if (info != 0)
  225314. {
  225315. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225316. if (name != nil)
  225317. result = nsStringToJuce (name);
  225318. }
  225319. }
  225320. return result;
  225321. }
  225322. const File File::getLinkedTarget() const
  225323. {
  225324. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225325. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225326. #else
  225327. // (the cast here avoids a deprecation warning)
  225328. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225329. #endif
  225330. if (dest != nil)
  225331. return File (nsStringToJuce (dest));
  225332. return *this;
  225333. }
  225334. bool File::moveToTrash() const
  225335. {
  225336. if (! exists())
  225337. return true;
  225338. #if JUCE_IOS
  225339. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225340. #else
  225341. const ScopedAutoReleasePool pool;
  225342. NSString* p = juceStringToNS (getFullPathName());
  225343. return [[NSWorkspace sharedWorkspace]
  225344. performFileOperation: NSWorkspaceRecycleOperation
  225345. source: [p stringByDeletingLastPathComponent]
  225346. destination: @""
  225347. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225348. tag: nil ];
  225349. #endif
  225350. }
  225351. class DirectoryIterator::NativeIterator::Pimpl
  225352. {
  225353. public:
  225354. Pimpl (const File& directory, const String& wildCard_)
  225355. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225356. wildCard (wildCard_),
  225357. enumerator (0)
  225358. {
  225359. const ScopedAutoReleasePool pool;
  225360. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225361. wildcardUTF8 = wildCard.toUTF8();
  225362. }
  225363. ~Pimpl()
  225364. {
  225365. [enumerator release];
  225366. }
  225367. bool next (String& filenameFound,
  225368. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225369. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225370. {
  225371. const ScopedAutoReleasePool pool;
  225372. for (;;)
  225373. {
  225374. NSString* file;
  225375. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225376. return false;
  225377. [enumerator skipDescendents];
  225378. filenameFound = nsStringToJuce (file);
  225379. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225380. continue;
  225381. const String path (parentDir + filenameFound);
  225382. updateStatInfoForFile (path, isDir, fileSize, modTime, creationTime, isReadOnly);
  225383. if (isHidden != 0)
  225384. *isHidden = FileHelpers::isHiddenFile (path);
  225385. return true;
  225386. }
  225387. }
  225388. private:
  225389. String parentDir, wildCard;
  225390. const char* wildcardUTF8;
  225391. NSDirectoryEnumerator* enumerator;
  225392. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  225393. };
  225394. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225395. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225396. {
  225397. }
  225398. DirectoryIterator::NativeIterator::~NativeIterator()
  225399. {
  225400. }
  225401. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225402. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225403. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225404. {
  225405. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225406. }
  225407. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225408. {
  225409. #if JUCE_IOS
  225410. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225411. #else
  225412. const ScopedAutoReleasePool pool;
  225413. if (parameters.isEmpty())
  225414. {
  225415. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225416. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225417. }
  225418. bool ok = false;
  225419. if (PlatformUtilities::isBundle (fileName))
  225420. {
  225421. NSMutableArray* urls = [NSMutableArray array];
  225422. StringArray docs;
  225423. docs.addTokens (parameters, true);
  225424. for (int i = 0; i < docs.size(); ++i)
  225425. [urls addObject: juceStringToNS (docs[i])];
  225426. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225427. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225428. options: 0
  225429. additionalEventParamDescriptor: nil
  225430. launchIdentifiers: nil];
  225431. }
  225432. else if (File (fileName).exists())
  225433. {
  225434. ok = FileHelpers::launchExecutable ("\"" + fileName + "\" " + parameters);
  225435. }
  225436. return ok;
  225437. #endif
  225438. }
  225439. void File::revealToUser() const
  225440. {
  225441. #if ! JUCE_IOS
  225442. if (exists())
  225443. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225444. else if (getParentDirectory().exists())
  225445. getParentDirectory().revealToUser();
  225446. #endif
  225447. }
  225448. #if ! JUCE_IOS
  225449. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225450. {
  225451. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225452. }
  225453. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225454. {
  225455. char path [2048];
  225456. zerostruct (path);
  225457. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225458. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225459. return String::empty;
  225460. }
  225461. #endif
  225462. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225463. {
  225464. const ScopedAutoReleasePool pool;
  225465. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225466. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225467. #else
  225468. // (the cast here avoids a deprecation warning)
  225469. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225470. #endif
  225471. return [fileDict fileHFSTypeCode];
  225472. }
  225473. bool PlatformUtilities::isBundle (const String& filename)
  225474. {
  225475. #if JUCE_IOS
  225476. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225477. #else
  225478. const ScopedAutoReleasePool pool;
  225479. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225480. #endif
  225481. }
  225482. #endif
  225483. /*** End of inlined file: juce_mac_Files.mm ***/
  225484. #if JUCE_IOS
  225485. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  225486. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225487. // compiled on its own).
  225488. #if JUCE_INCLUDED_FILE
  225489. END_JUCE_NAMESPACE
  225490. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225491. {
  225492. }
  225493. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225494. - (void) applicationWillTerminate: (UIApplication*) application;
  225495. @end
  225496. @implementation JuceAppStartupDelegate
  225497. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225498. {
  225499. initialiseJuce_GUI();
  225500. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225501. exit (0);
  225502. }
  225503. - (void) applicationWillTerminate: (UIApplication*) application
  225504. {
  225505. JUCEApplication::appWillTerminateByForce();
  225506. }
  225507. @end
  225508. BEGIN_JUCE_NAMESPACE
  225509. int juce_iOSMain (int argc, const char* argv[])
  225510. {
  225511. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225512. }
  225513. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225514. {
  225515. pool = [[NSAutoreleasePool alloc] init];
  225516. }
  225517. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225518. {
  225519. [((NSAutoreleasePool*) pool) release];
  225520. }
  225521. void PlatformUtilities::beep()
  225522. {
  225523. //xxx
  225524. //AudioServicesPlaySystemSound ();
  225525. }
  225526. void PlatformUtilities::addItemToDock (const File& file)
  225527. {
  225528. }
  225529. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225530. END_JUCE_NAMESPACE
  225531. @interface JuceAlertBoxDelegate : NSObject
  225532. {
  225533. @public
  225534. bool clickedOk;
  225535. }
  225536. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225537. @end
  225538. @implementation JuceAlertBoxDelegate
  225539. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225540. {
  225541. clickedOk = (buttonIndex == 0);
  225542. alertView.hidden = true;
  225543. }
  225544. @end
  225545. BEGIN_JUCE_NAMESPACE
  225546. // (This function is used directly by other bits of code)
  225547. bool juce_iPhoneShowModalAlert (const String& title,
  225548. const String& bodyText,
  225549. NSString* okButtonText,
  225550. NSString* cancelButtonText)
  225551. {
  225552. const ScopedAutoReleasePool pool;
  225553. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225554. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225555. message: juceStringToNS (bodyText)
  225556. delegate: callback
  225557. cancelButtonTitle: okButtonText
  225558. otherButtonTitles: cancelButtonText, nil];
  225559. [alert retain];
  225560. [alert show];
  225561. while (! alert.hidden && alert.superview != nil)
  225562. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225563. const bool result = callback->clickedOk;
  225564. [alert release];
  225565. [callback release];
  225566. return result;
  225567. }
  225568. bool AlertWindow::showNativeDialogBox (const String& title,
  225569. const String& bodyText,
  225570. bool isOkCancel)
  225571. {
  225572. return juce_iPhoneShowModalAlert (title, bodyText,
  225573. @"OK",
  225574. isOkCancel ? @"Cancel" : nil);
  225575. }
  225576. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225577. {
  225578. jassertfalse; // no such thing on the iphone!
  225579. return false;
  225580. }
  225581. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225582. {
  225583. jassertfalse; // no such thing on the iphone!
  225584. return false;
  225585. }
  225586. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225587. {
  225588. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225589. }
  225590. bool Desktop::isScreenSaverEnabled()
  225591. {
  225592. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225593. }
  225594. #endif
  225595. #endif
  225596. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  225597. #else
  225598. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225599. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225600. // compiled on its own).
  225601. #if JUCE_INCLUDED_FILE
  225602. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225603. {
  225604. pool = [[NSAutoreleasePool alloc] init];
  225605. }
  225606. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225607. {
  225608. [((NSAutoreleasePool*) pool) release];
  225609. }
  225610. void PlatformUtilities::beep()
  225611. {
  225612. NSBeep();
  225613. }
  225614. void PlatformUtilities::addItemToDock (const File& file)
  225615. {
  225616. // check that it's not already there...
  225617. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225618. .containsIgnoreCase (file.getFullPathName()))
  225619. {
  225620. 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>"
  225621. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225622. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225623. }
  225624. }
  225625. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225626. bool AlertWindow::showNativeDialogBox (const String& title,
  225627. const String& bodyText,
  225628. bool isOkCancel)
  225629. {
  225630. const ScopedAutoReleasePool pool;
  225631. return NSRunAlertPanel (juceStringToNS (title),
  225632. juceStringToNS (bodyText),
  225633. @"Ok",
  225634. isOkCancel ? @"Cancel" : nil,
  225635. nil) == NSAlertDefaultReturn;
  225636. }
  225637. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225638. {
  225639. if (files.size() == 0)
  225640. return false;
  225641. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225642. if (draggingSource == 0)
  225643. {
  225644. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225645. return false;
  225646. }
  225647. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225648. if (sourceComp == 0)
  225649. {
  225650. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225651. return false;
  225652. }
  225653. const ScopedAutoReleasePool pool;
  225654. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225655. if (view == 0)
  225656. return false;
  225657. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225658. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225659. owner: nil];
  225660. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225661. for (int i = 0; i < files.size(); ++i)
  225662. [filesArray addObject: juceStringToNS (files[i])];
  225663. [pboard setPropertyList: filesArray
  225664. forType: NSFilenamesPboardType];
  225665. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225666. fromView: nil];
  225667. dragPosition.x -= 16;
  225668. dragPosition.y -= 16;
  225669. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225670. at: dragPosition
  225671. offset: NSMakeSize (0, 0)
  225672. event: [[view window] currentEvent]
  225673. pasteboard: pboard
  225674. source: view
  225675. slideBack: YES];
  225676. return true;
  225677. }
  225678. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225679. {
  225680. jassertfalse; // not implemented!
  225681. return false;
  225682. }
  225683. bool Desktop::canUseSemiTransparentWindows() throw()
  225684. {
  225685. return true;
  225686. }
  225687. const Point<int> MouseInputSource::getCurrentMousePosition()
  225688. {
  225689. const ScopedAutoReleasePool pool;
  225690. const NSPoint p ([NSEvent mouseLocation]);
  225691. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225692. }
  225693. void Desktop::setMousePosition (const Point<int>& newPosition)
  225694. {
  225695. // this rubbish needs to be done around the warp call, to avoid causing a
  225696. // bizarre glitch..
  225697. CGAssociateMouseAndMouseCursorPosition (false);
  225698. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225699. CGAssociateMouseAndMouseCursorPosition (true);
  225700. }
  225701. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  225702. {
  225703. return upright;
  225704. }
  225705. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225706. class ScreenSaverDefeater : public Timer,
  225707. public DeletedAtShutdown
  225708. {
  225709. public:
  225710. ScreenSaverDefeater()
  225711. {
  225712. startTimer (10000);
  225713. timerCallback();
  225714. }
  225715. ~ScreenSaverDefeater() {}
  225716. void timerCallback()
  225717. {
  225718. if (Process::isForegroundProcess())
  225719. UpdateSystemActivity (UsrActivity);
  225720. }
  225721. };
  225722. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225723. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225724. {
  225725. if (isEnabled)
  225726. deleteAndZero (screenSaverDefeater);
  225727. else if (screenSaverDefeater == 0)
  225728. screenSaverDefeater = new ScreenSaverDefeater();
  225729. }
  225730. bool Desktop::isScreenSaverEnabled()
  225731. {
  225732. return screenSaverDefeater == 0;
  225733. }
  225734. #else
  225735. static IOPMAssertionID screenSaverDisablerID = 0;
  225736. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225737. {
  225738. if (isEnabled)
  225739. {
  225740. if (screenSaverDisablerID != 0)
  225741. {
  225742. IOPMAssertionRelease (screenSaverDisablerID);
  225743. screenSaverDisablerID = 0;
  225744. }
  225745. }
  225746. else
  225747. {
  225748. if (screenSaverDisablerID == 0)
  225749. {
  225750. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225751. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225752. CFSTR ("Juce"), &screenSaverDisablerID);
  225753. #else
  225754. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225755. &screenSaverDisablerID);
  225756. #endif
  225757. }
  225758. }
  225759. }
  225760. bool Desktop::isScreenSaverEnabled()
  225761. {
  225762. return screenSaverDisablerID == 0;
  225763. }
  225764. #endif
  225765. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  225766. {
  225767. const ScopedAutoReleasePool pool;
  225768. monitorCoords.clear();
  225769. NSArray* screens = [NSScreen screens];
  225770. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  225771. for (unsigned int i = 0; i < [screens count]; ++i)
  225772. {
  225773. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  225774. NSRect r = clipToWorkArea ? [s visibleFrame]
  225775. : [s frame];
  225776. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  225777. monitorCoords.add (convertToRectInt (r));
  225778. }
  225779. jassert (monitorCoords.size() > 0);
  225780. }
  225781. #endif
  225782. #endif
  225783. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  225784. #endif
  225785. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  225786. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225787. // compiled on its own).
  225788. #if JUCE_INCLUDED_FILE
  225789. void Logger::outputDebugString (const String& text)
  225790. {
  225791. std::cerr << text << std::endl;
  225792. }
  225793. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  225794. {
  225795. static char testResult = 0;
  225796. if (testResult == 0)
  225797. {
  225798. struct kinfo_proc info;
  225799. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  225800. size_t sz = sizeof (info);
  225801. sysctl (m, 4, &info, &sz, 0, 0);
  225802. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  225803. }
  225804. return testResult > 0;
  225805. }
  225806. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  225807. {
  225808. return juce_isRunningUnderDebugger();
  225809. }
  225810. #endif
  225811. /*** End of inlined file: juce_mac_Debugging.mm ***/
  225812. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225813. #if JUCE_IOS
  225814. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225815. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225816. // compiled on its own).
  225817. #if JUCE_INCLUDED_FILE
  225818. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225819. #define SUPPORT_10_4_FONTS 1
  225820. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225821. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225822. #define SUPPORT_ONLY_10_4_FONTS 1
  225823. #endif
  225824. END_JUCE_NAMESPACE
  225825. @interface NSFont (PrivateHack)
  225826. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225827. @end
  225828. BEGIN_JUCE_NAMESPACE
  225829. #endif
  225830. class MacTypeface : public Typeface
  225831. {
  225832. public:
  225833. MacTypeface (const Font& font)
  225834. : Typeface (font.getTypefaceName())
  225835. {
  225836. const ScopedAutoReleasePool pool;
  225837. renderingTransform = CGAffineTransformIdentity;
  225838. bool needsItalicTransform = false;
  225839. #if JUCE_IOS
  225840. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225841. if (font.isItalic() || font.isBold())
  225842. {
  225843. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225844. for (NSString* i in familyFonts)
  225845. {
  225846. const String fn (nsStringToJuce (i));
  225847. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225848. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225849. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225850. || afterDash.containsIgnoreCase ("italic")
  225851. || fn.endsWithIgnoreCase ("oblique")
  225852. || fn.endsWithIgnoreCase ("italic");
  225853. if (probablyBold == font.isBold()
  225854. && probablyItalic == font.isItalic())
  225855. {
  225856. fontName = i;
  225857. needsItalicTransform = false;
  225858. break;
  225859. }
  225860. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225861. {
  225862. fontName = i;
  225863. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225864. }
  225865. }
  225866. if (needsItalicTransform)
  225867. renderingTransform.c = 0.15f;
  225868. }
  225869. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225870. const int ascender = abs (CGFontGetAscent (fontRef));
  225871. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225872. ascent = ascender / totalHeight;
  225873. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225874. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225875. #else
  225876. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225877. if (font.isItalic())
  225878. {
  225879. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225880. toHaveTrait: NSItalicFontMask];
  225881. if (newFont == nsFont)
  225882. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225883. nsFont = newFont;
  225884. }
  225885. if (font.isBold())
  225886. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225887. [nsFont retain];
  225888. ascent = std::abs ((float) [nsFont ascender]);
  225889. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  225890. ascent /= totalSize;
  225891. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225892. if (needsItalicTransform)
  225893. {
  225894. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225895. renderingTransform.c = 0.15f;
  225896. }
  225897. #if SUPPORT_ONLY_10_4_FONTS
  225898. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225899. if (atsFont == 0)
  225900. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225901. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225902. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225903. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225904. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225905. #else
  225906. #if SUPPORT_10_4_FONTS
  225907. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225908. {
  225909. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225910. if (atsFont == 0)
  225911. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225912. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225913. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225914. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225915. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225916. }
  225917. else
  225918. #endif
  225919. {
  225920. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  225921. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  225922. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225923. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  225924. }
  225925. #endif
  225926. #endif
  225927. }
  225928. ~MacTypeface()
  225929. {
  225930. #if ! JUCE_IOS
  225931. [nsFont release];
  225932. #endif
  225933. if (fontRef != 0)
  225934. CGFontRelease (fontRef);
  225935. }
  225936. float getAscent() const
  225937. {
  225938. return ascent;
  225939. }
  225940. float getDescent() const
  225941. {
  225942. return 1.0f - ascent;
  225943. }
  225944. float getStringWidth (const String& text)
  225945. {
  225946. if (fontRef == 0 || text.isEmpty())
  225947. return 0;
  225948. const int length = text.length();
  225949. HeapBlock <CGGlyph> glyphs;
  225950. createGlyphsForString (text, length, glyphs);
  225951. float x = 0;
  225952. #if SUPPORT_ONLY_10_4_FONTS
  225953. HeapBlock <NSSize> advances (length);
  225954. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225955. for (int i = 0; i < length; ++i)
  225956. x += advances[i].width;
  225957. #else
  225958. #if SUPPORT_10_4_FONTS
  225959. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225960. {
  225961. HeapBlock <NSSize> advances (length);
  225962. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225963. for (int i = 0; i < length; ++i)
  225964. x += advances[i].width;
  225965. }
  225966. else
  225967. #endif
  225968. {
  225969. HeapBlock <int> advances (length);
  225970. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225971. for (int i = 0; i < length; ++i)
  225972. x += advances[i];
  225973. }
  225974. #endif
  225975. return x * unitsToHeightScaleFactor;
  225976. }
  225977. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225978. {
  225979. xOffsets.add (0);
  225980. if (fontRef == 0 || text.isEmpty())
  225981. return;
  225982. const int length = text.length();
  225983. HeapBlock <CGGlyph> glyphs;
  225984. createGlyphsForString (text, length, glyphs);
  225985. #if SUPPORT_ONLY_10_4_FONTS
  225986. HeapBlock <NSSize> advances (length);
  225987. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225988. int x = 0;
  225989. for (int i = 0; i < length; ++i)
  225990. {
  225991. x += advances[i].width;
  225992. xOffsets.add (x * unitsToHeightScaleFactor);
  225993. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  225994. }
  225995. #else
  225996. #if SUPPORT_10_4_FONTS
  225997. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225998. {
  225999. HeapBlock <NSSize> advances (length);
  226000. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226001. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226002. float x = 0;
  226003. for (int i = 0; i < length; ++i)
  226004. {
  226005. x += advances[i].width;
  226006. xOffsets.add (x * unitsToHeightScaleFactor);
  226007. resultGlyphs.add (nsGlyphs[i]);
  226008. }
  226009. }
  226010. else
  226011. #endif
  226012. {
  226013. HeapBlock <int> advances (length);
  226014. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226015. {
  226016. int x = 0;
  226017. for (int i = 0; i < length; ++i)
  226018. {
  226019. x += advances [i];
  226020. xOffsets.add (x * unitsToHeightScaleFactor);
  226021. resultGlyphs.add (glyphs[i]);
  226022. }
  226023. }
  226024. }
  226025. #endif
  226026. }
  226027. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226028. {
  226029. #if JUCE_IOS
  226030. return false;
  226031. #else
  226032. if (nsFont == 0)
  226033. return false;
  226034. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226035. jassert (path.isEmpty());
  226036. const ScopedAutoReleasePool pool;
  226037. NSBezierPath* bez = [NSBezierPath bezierPath];
  226038. [bez moveToPoint: NSMakePoint (0, 0)];
  226039. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226040. inFont: nsFont];
  226041. for (int i = 0; i < [bez elementCount]; ++i)
  226042. {
  226043. NSPoint p[3];
  226044. switch ([bez elementAtIndex: i associatedPoints: p])
  226045. {
  226046. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  226047. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  226048. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  226049. (float) p[1].x, (float) -p[1].y,
  226050. (float) p[2].x, (float) -p[2].y); break;
  226051. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  226052. default: jassertfalse; break;
  226053. }
  226054. }
  226055. path.applyTransform (pathTransform);
  226056. return true;
  226057. #endif
  226058. }
  226059. CGFontRef fontRef;
  226060. float fontHeightToCGSizeFactor;
  226061. CGAffineTransform renderingTransform;
  226062. private:
  226063. float ascent, unitsToHeightScaleFactor;
  226064. #if JUCE_IOS
  226065. #else
  226066. NSFont* nsFont;
  226067. AffineTransform pathTransform;
  226068. #endif
  226069. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226070. {
  226071. #if SUPPORT_10_4_FONTS
  226072. #if ! SUPPORT_ONLY_10_4_FONTS
  226073. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226074. #endif
  226075. {
  226076. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226077. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226078. for (int i = 0; i < length; ++i)
  226079. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226080. return;
  226081. }
  226082. #endif
  226083. #if ! SUPPORT_ONLY_10_4_FONTS
  226084. if (charToGlyphMapper == 0)
  226085. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226086. glyphs.malloc (length);
  226087. for (int i = 0; i < length; ++i)
  226088. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226089. #endif
  226090. }
  226091. #if ! SUPPORT_ONLY_10_4_FONTS
  226092. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226093. class CharToGlyphMapper
  226094. {
  226095. public:
  226096. CharToGlyphMapper (CGFontRef fontRef)
  226097. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226098. idRangeOffset (0), glyphIndexes (0)
  226099. {
  226100. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226101. if (cmapTable != 0)
  226102. {
  226103. const int numSubtables = getValue16 (cmapTable, 2);
  226104. for (int i = 0; i < numSubtables; ++i)
  226105. {
  226106. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226107. {
  226108. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226109. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226110. {
  226111. const int length = getValue16 (cmapTable, offset + 2);
  226112. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226113. segCount = segCountX2 / 2;
  226114. const int endCodeOffset = offset + 14;
  226115. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226116. const int idDeltaOffset = startCodeOffset + segCountX2;
  226117. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226118. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226119. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226120. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226121. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226122. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226123. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226124. }
  226125. break;
  226126. }
  226127. }
  226128. CFRelease (cmapTable);
  226129. }
  226130. }
  226131. ~CharToGlyphMapper()
  226132. {
  226133. if (endCode != 0)
  226134. {
  226135. CFRelease (endCode);
  226136. CFRelease (startCode);
  226137. CFRelease (idDelta);
  226138. CFRelease (idRangeOffset);
  226139. CFRelease (glyphIndexes);
  226140. }
  226141. }
  226142. int getGlyphForCharacter (const juce_wchar c) const
  226143. {
  226144. for (int i = 0; i < segCount; ++i)
  226145. {
  226146. if (getValue16 (endCode, i * 2) >= c)
  226147. {
  226148. const int start = getValue16 (startCode, i * 2);
  226149. if (start > c)
  226150. break;
  226151. const int delta = getValue16 (idDelta, i * 2);
  226152. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226153. if (rangeOffset == 0)
  226154. return delta + c;
  226155. else
  226156. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226157. }
  226158. }
  226159. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226160. return jmax (-1, (int) c - 29);
  226161. }
  226162. private:
  226163. int segCount;
  226164. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226165. static uint16 getValue16 (CFDataRef data, const int index)
  226166. {
  226167. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226168. }
  226169. static uint32 getValue32 (CFDataRef data, const int index)
  226170. {
  226171. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226172. }
  226173. };
  226174. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226175. #endif
  226176. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  226177. };
  226178. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226179. {
  226180. return new MacTypeface (font);
  226181. }
  226182. const StringArray Font::findAllTypefaceNames()
  226183. {
  226184. StringArray names;
  226185. const ScopedAutoReleasePool pool;
  226186. #if JUCE_IOS
  226187. NSArray* fonts = [UIFont familyNames];
  226188. #else
  226189. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226190. #endif
  226191. for (unsigned int i = 0; i < [fonts count]; ++i)
  226192. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226193. names.sort (true);
  226194. return names;
  226195. }
  226196. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  226197. {
  226198. #if JUCE_IOS
  226199. defaultSans = "Helvetica";
  226200. defaultSerif = "Times New Roman";
  226201. defaultFixed = "Courier New";
  226202. #else
  226203. defaultSans = "Lucida Grande";
  226204. defaultSerif = "Times New Roman";
  226205. defaultFixed = "Monaco";
  226206. #endif
  226207. defaultFallback = "Arial Unicode MS";
  226208. }
  226209. #endif
  226210. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226211. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226212. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226213. // compiled on its own).
  226214. #if JUCE_INCLUDED_FILE
  226215. class CoreGraphicsImage : public Image::SharedImage
  226216. {
  226217. public:
  226218. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226219. : Image::SharedImage (format_, width_, height_)
  226220. {
  226221. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226222. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226223. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226224. imageData = imageDataAllocated;
  226225. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226226. : CGColorSpaceCreateDeviceRGB();
  226227. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226228. colourSpace, getCGImageFlags (format_));
  226229. CGColorSpaceRelease (colourSpace);
  226230. }
  226231. ~CoreGraphicsImage()
  226232. {
  226233. CGContextRelease (context);
  226234. }
  226235. Image::ImageType getType() const { return Image::NativeImage; }
  226236. LowLevelGraphicsContext* createLowLevelContext();
  226237. SharedImage* clone()
  226238. {
  226239. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226240. memcpy (im->imageData, imageData, lineStride * height);
  226241. return im;
  226242. }
  226243. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226244. {
  226245. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226246. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226247. {
  226248. return CGBitmapContextCreateImage (nativeImage->context);
  226249. }
  226250. else
  226251. {
  226252. const Image::BitmapData srcData (juceImage, false);
  226253. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226254. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226255. 8, srcData.pixelStride * 8, srcData.lineStride,
  226256. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226257. 0, true, kCGRenderingIntentDefault);
  226258. CGDataProviderRelease (provider);
  226259. return imageRef;
  226260. }
  226261. }
  226262. #if JUCE_MAC
  226263. static NSImage* createNSImage (const Image& image)
  226264. {
  226265. const ScopedAutoReleasePool pool;
  226266. NSImage* im = [[NSImage alloc] init];
  226267. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226268. [im lockFocus];
  226269. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226270. CGImageRef imageRef = createImage (image, false, colourSpace);
  226271. CGColorSpaceRelease (colourSpace);
  226272. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226273. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226274. CGImageRelease (imageRef);
  226275. [im unlockFocus];
  226276. return im;
  226277. }
  226278. #endif
  226279. CGContextRef context;
  226280. HeapBlock<uint8> imageDataAllocated;
  226281. private:
  226282. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226283. {
  226284. #if JUCE_BIG_ENDIAN
  226285. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226286. #else
  226287. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226288. #endif
  226289. }
  226290. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  226291. };
  226292. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226293. {
  226294. #if USE_COREGRAPHICS_RENDERING
  226295. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226296. #else
  226297. return createSoftwareImage (format, width, height, clearImage);
  226298. #endif
  226299. }
  226300. class CoreGraphicsContext : public LowLevelGraphicsContext
  226301. {
  226302. public:
  226303. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226304. : context (context_),
  226305. flipHeight (flipHeight_),
  226306. lastClipRectIsValid (false),
  226307. state (new SavedState()),
  226308. numGradientLookupEntries (0)
  226309. {
  226310. CGContextRetain (context);
  226311. CGContextSaveGState(context);
  226312. CGContextSetShouldSmoothFonts (context, true);
  226313. CGContextSetShouldAntialias (context, true);
  226314. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226315. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226316. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226317. gradientCallbacks.version = 0;
  226318. gradientCallbacks.evaluate = gradientCallback;
  226319. gradientCallbacks.releaseInfo = 0;
  226320. setFont (Font());
  226321. }
  226322. ~CoreGraphicsContext()
  226323. {
  226324. CGContextRestoreGState (context);
  226325. CGContextRelease (context);
  226326. CGColorSpaceRelease (rgbColourSpace);
  226327. CGColorSpaceRelease (greyColourSpace);
  226328. }
  226329. bool isVectorDevice() const { return false; }
  226330. void setOrigin (int x, int y)
  226331. {
  226332. CGContextTranslateCTM (context, x, -y);
  226333. if (lastClipRectIsValid)
  226334. lastClipRect.translate (-x, -y);
  226335. }
  226336. void addTransform (const AffineTransform& transform)
  226337. {
  226338. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  226339. .translated (0, flipHeight)
  226340. .followedBy (transform)
  226341. .translated (0, -flipHeight)
  226342. .scaled (1.0f, -1.0f));
  226343. lastClipRectIsValid = false;
  226344. }
  226345. float getScaleFactor()
  226346. {
  226347. CGAffineTransform t = CGContextGetCTM (context);
  226348. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  226349. }
  226350. bool clipToRectangle (const Rectangle<int>& r)
  226351. {
  226352. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226353. if (lastClipRectIsValid)
  226354. {
  226355. // This is actually incorrect, because the actual clip region may be complex, and
  226356. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226357. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226358. // when calculating the resultant clip bounds, and makes the same mistake!
  226359. lastClipRect = lastClipRect.getIntersection (r);
  226360. return ! lastClipRect.isEmpty();
  226361. }
  226362. return ! isClipEmpty();
  226363. }
  226364. bool clipToRectangleList (const RectangleList& clipRegion)
  226365. {
  226366. if (clipRegion.isEmpty())
  226367. {
  226368. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226369. lastClipRectIsValid = true;
  226370. lastClipRect = Rectangle<int>();
  226371. return false;
  226372. }
  226373. else
  226374. {
  226375. const int numRects = clipRegion.getNumRectangles();
  226376. HeapBlock <CGRect> rects (numRects);
  226377. for (int i = 0; i < numRects; ++i)
  226378. {
  226379. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226380. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226381. }
  226382. CGContextClipToRects (context, rects, numRects);
  226383. lastClipRectIsValid = false;
  226384. return ! isClipEmpty();
  226385. }
  226386. }
  226387. void excludeClipRectangle (const Rectangle<int>& r)
  226388. {
  226389. RectangleList remaining (getClipBounds());
  226390. remaining.subtract (r);
  226391. clipToRectangleList (remaining);
  226392. lastClipRectIsValid = false;
  226393. }
  226394. void clipToPath (const Path& path, const AffineTransform& transform)
  226395. {
  226396. createPath (path, transform);
  226397. CGContextClip (context);
  226398. lastClipRectIsValid = false;
  226399. }
  226400. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226401. {
  226402. if (! transform.isSingularity())
  226403. {
  226404. Image singleChannelImage (sourceImage);
  226405. if (sourceImage.getFormat() != Image::SingleChannel)
  226406. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226407. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226408. flip();
  226409. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226410. applyTransform (t);
  226411. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226412. CGContextClipToMask (context, r, image);
  226413. applyTransform (t.inverted());
  226414. flip();
  226415. CGImageRelease (image);
  226416. lastClipRectIsValid = false;
  226417. }
  226418. }
  226419. bool clipRegionIntersects (const Rectangle<int>& r)
  226420. {
  226421. return getClipBounds().intersects (r);
  226422. }
  226423. const Rectangle<int> getClipBounds() const
  226424. {
  226425. if (! lastClipRectIsValid)
  226426. {
  226427. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226428. lastClipRectIsValid = true;
  226429. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226430. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226431. roundToInt (bounds.size.width),
  226432. roundToInt (bounds.size.height));
  226433. }
  226434. return lastClipRect;
  226435. }
  226436. bool isClipEmpty() const
  226437. {
  226438. return getClipBounds().isEmpty();
  226439. }
  226440. void saveState()
  226441. {
  226442. CGContextSaveGState (context);
  226443. stateStack.add (new SavedState (*state));
  226444. }
  226445. void restoreState()
  226446. {
  226447. CGContextRestoreGState (context);
  226448. SavedState* const top = stateStack.getLast();
  226449. if (top != 0)
  226450. {
  226451. state = top;
  226452. stateStack.removeLast (1, false);
  226453. lastClipRectIsValid = false;
  226454. }
  226455. else
  226456. {
  226457. jassertfalse; // trying to pop with an empty stack!
  226458. }
  226459. }
  226460. void beginTransparencyLayer (float opacity)
  226461. {
  226462. saveState();
  226463. CGContextSetAlpha (context, opacity);
  226464. CGContextBeginTransparencyLayer (context, 0);
  226465. }
  226466. void endTransparencyLayer()
  226467. {
  226468. CGContextEndTransparencyLayer (context);
  226469. restoreState();
  226470. }
  226471. void setFill (const FillType& fillType)
  226472. {
  226473. state->fillType = fillType;
  226474. if (fillType.isColour())
  226475. {
  226476. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226477. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226478. CGContextSetAlpha (context, 1.0f);
  226479. }
  226480. }
  226481. void setOpacity (float newOpacity)
  226482. {
  226483. state->fillType.setOpacity (newOpacity);
  226484. setFill (state->fillType);
  226485. }
  226486. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226487. {
  226488. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226489. ? kCGInterpolationLow
  226490. : kCGInterpolationHigh);
  226491. }
  226492. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226493. {
  226494. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226495. }
  226496. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226497. {
  226498. if (replaceExistingContents)
  226499. {
  226500. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226501. CGContextClearRect (context, cgRect);
  226502. #else
  226503. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226504. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226505. CGContextClearRect (context, cgRect);
  226506. else
  226507. #endif
  226508. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226509. #endif
  226510. fillCGRect (cgRect, false);
  226511. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226512. }
  226513. else
  226514. {
  226515. if (state->fillType.isColour())
  226516. {
  226517. CGContextFillRect (context, cgRect);
  226518. }
  226519. else if (state->fillType.isGradient())
  226520. {
  226521. CGContextSaveGState (context);
  226522. CGContextClipToRect (context, cgRect);
  226523. drawGradient();
  226524. CGContextRestoreGState (context);
  226525. }
  226526. else
  226527. {
  226528. CGContextSaveGState (context);
  226529. CGContextClipToRect (context, cgRect);
  226530. drawImage (state->fillType.image, state->fillType.transform, true);
  226531. CGContextRestoreGState (context);
  226532. }
  226533. }
  226534. }
  226535. void fillPath (const Path& path, const AffineTransform& transform)
  226536. {
  226537. CGContextSaveGState (context);
  226538. if (state->fillType.isColour())
  226539. {
  226540. flip();
  226541. applyTransform (transform);
  226542. createPath (path);
  226543. if (path.isUsingNonZeroWinding())
  226544. CGContextFillPath (context);
  226545. else
  226546. CGContextEOFillPath (context);
  226547. }
  226548. else
  226549. {
  226550. createPath (path, transform);
  226551. if (path.isUsingNonZeroWinding())
  226552. CGContextClip (context);
  226553. else
  226554. CGContextEOClip (context);
  226555. if (state->fillType.isGradient())
  226556. drawGradient();
  226557. else
  226558. drawImage (state->fillType.image, state->fillType.transform, true);
  226559. }
  226560. CGContextRestoreGState (context);
  226561. }
  226562. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226563. {
  226564. const int iw = sourceImage.getWidth();
  226565. const int ih = sourceImage.getHeight();
  226566. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226567. CGContextSaveGState (context);
  226568. CGContextSetAlpha (context, state->fillType.getOpacity());
  226569. flip();
  226570. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226571. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226572. if (fillEntireClipAsTiles)
  226573. {
  226574. #if JUCE_IOS
  226575. CGContextDrawTiledImage (context, imageRect, image);
  226576. #else
  226577. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226578. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226579. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226580. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226581. CGContextDrawTiledImage (context, imageRect, image);
  226582. else
  226583. #endif
  226584. {
  226585. // Fallback to manually doing a tiled fill on 10.4
  226586. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226587. int x = 0, y = 0;
  226588. while (x > clip.origin.x) x -= iw;
  226589. while (y > clip.origin.y) y -= ih;
  226590. const int right = (int) (clip.origin.x + clip.size.width);
  226591. const int bottom = (int) (clip.origin.y + clip.size.height);
  226592. while (y < bottom)
  226593. {
  226594. for (int x2 = x; x2 < right; x2 += iw)
  226595. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226596. y += ih;
  226597. }
  226598. }
  226599. #endif
  226600. }
  226601. else
  226602. {
  226603. CGContextDrawImage (context, imageRect, image);
  226604. }
  226605. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226606. CGContextRestoreGState (context);
  226607. }
  226608. void drawLine (const Line<float>& line)
  226609. {
  226610. if (state->fillType.isColour())
  226611. {
  226612. CGContextSetLineCap (context, kCGLineCapSquare);
  226613. CGContextSetLineWidth (context, 1.0f);
  226614. CGContextSetRGBStrokeColor (context,
  226615. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226616. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226617. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226618. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226619. CGContextStrokeLineSegments (context, cgLine, 1);
  226620. }
  226621. else
  226622. {
  226623. Path p;
  226624. p.addLineSegment (line, 1.0f);
  226625. fillPath (p, AffineTransform::identity);
  226626. }
  226627. }
  226628. void drawVerticalLine (const int x, float top, float bottom)
  226629. {
  226630. if (state->fillType.isColour())
  226631. {
  226632. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226633. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226634. #else
  226635. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226636. // the x co-ord slightly to trick it..
  226637. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226638. #endif
  226639. }
  226640. else
  226641. {
  226642. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226643. }
  226644. }
  226645. void drawHorizontalLine (const int y, float left, float right)
  226646. {
  226647. if (state->fillType.isColour())
  226648. {
  226649. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226650. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226651. #else
  226652. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226653. // the x co-ord slightly to trick it..
  226654. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226655. #endif
  226656. }
  226657. else
  226658. {
  226659. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226660. }
  226661. }
  226662. void setFont (const Font& newFont)
  226663. {
  226664. if (state->font != newFont)
  226665. {
  226666. state->fontRef = 0;
  226667. state->font = newFont;
  226668. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226669. if (mf != 0)
  226670. {
  226671. state->fontRef = mf->fontRef;
  226672. CGContextSetFont (context, state->fontRef);
  226673. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226674. state->fontTransform = mf->renderingTransform;
  226675. state->fontTransform.a *= state->font.getHorizontalScale();
  226676. CGContextSetTextMatrix (context, state->fontTransform);
  226677. }
  226678. }
  226679. }
  226680. const Font getFont()
  226681. {
  226682. return state->font;
  226683. }
  226684. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226685. {
  226686. if (state->fontRef != 0 && state->fillType.isColour())
  226687. {
  226688. if (transform.isOnlyTranslation())
  226689. {
  226690. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226691. CGGlyph g = glyphNumber;
  226692. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226693. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226694. }
  226695. else
  226696. {
  226697. CGContextSaveGState (context);
  226698. flip();
  226699. applyTransform (transform);
  226700. CGAffineTransform t = state->fontTransform;
  226701. t.d = -t.d;
  226702. CGContextSetTextMatrix (context, t);
  226703. CGGlyph g = glyphNumber;
  226704. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226705. CGContextRestoreGState (context);
  226706. }
  226707. }
  226708. else
  226709. {
  226710. Path p;
  226711. Font& f = state->font;
  226712. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226713. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226714. .followedBy (transform));
  226715. }
  226716. }
  226717. private:
  226718. CGContextRef context;
  226719. const CGFloat flipHeight;
  226720. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226721. CGFunctionCallbacks gradientCallbacks;
  226722. mutable Rectangle<int> lastClipRect;
  226723. mutable bool lastClipRectIsValid;
  226724. struct SavedState
  226725. {
  226726. SavedState()
  226727. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226728. {
  226729. }
  226730. SavedState (const SavedState& other)
  226731. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226732. fontTransform (other.fontTransform)
  226733. {
  226734. }
  226735. FillType fillType;
  226736. Font font;
  226737. CGFontRef fontRef;
  226738. CGAffineTransform fontTransform;
  226739. };
  226740. ScopedPointer <SavedState> state;
  226741. OwnedArray <SavedState> stateStack;
  226742. HeapBlock <PixelARGB> gradientLookupTable;
  226743. int numGradientLookupEntries;
  226744. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226745. {
  226746. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226747. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226748. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226749. colour.unpremultiply();
  226750. outData[0] = colour.getRed() / 255.0f;
  226751. outData[1] = colour.getGreen() / 255.0f;
  226752. outData[2] = colour.getBlue() / 255.0f;
  226753. outData[3] = colour.getAlpha() / 255.0f;
  226754. }
  226755. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226756. {
  226757. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  226758. CGShadingRef result = 0;
  226759. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226760. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  226761. if (gradient.isRadial)
  226762. {
  226763. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226764. p1, gradient.point1.getDistanceFrom (gradient.point2),
  226765. function, true, true);
  226766. }
  226767. else
  226768. {
  226769. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226770. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  226771. function, true, true);
  226772. }
  226773. CGFunctionRelease (function);
  226774. return result;
  226775. }
  226776. void drawGradient()
  226777. {
  226778. flip();
  226779. applyTransform (state->fillType.transform);
  226780. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226781. // you draw a gradient with high quality interp enabled).
  226782. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226783. CGContextSetAlpha (context, state->fillType.getOpacity());
  226784. CGContextDrawShading (context, shading);
  226785. CGShadingRelease (shading);
  226786. }
  226787. void createPath (const Path& path) const
  226788. {
  226789. CGContextBeginPath (context);
  226790. Path::Iterator i (path);
  226791. while (i.next())
  226792. {
  226793. switch (i.elementType)
  226794. {
  226795. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  226796. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  226797. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  226798. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  226799. case Path::Iterator::closePath: CGContextClosePath (context); break;
  226800. default: jassertfalse; break;
  226801. }
  226802. }
  226803. }
  226804. void createPath (const Path& path, const AffineTransform& transform) const
  226805. {
  226806. CGContextBeginPath (context);
  226807. Path::Iterator i (path);
  226808. while (i.next())
  226809. {
  226810. switch (i.elementType)
  226811. {
  226812. case Path::Iterator::startNewSubPath:
  226813. transform.transformPoint (i.x1, i.y1);
  226814. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226815. break;
  226816. case Path::Iterator::lineTo:
  226817. transform.transformPoint (i.x1, i.y1);
  226818. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226819. break;
  226820. case Path::Iterator::quadraticTo:
  226821. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  226822. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226823. break;
  226824. case Path::Iterator::cubicTo:
  226825. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226826. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226827. break;
  226828. case Path::Iterator::closePath:
  226829. CGContextClosePath (context); break;
  226830. default:
  226831. jassertfalse;
  226832. break;
  226833. }
  226834. }
  226835. }
  226836. void flip() const
  226837. {
  226838. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226839. }
  226840. void applyTransform (const AffineTransform& transform) const
  226841. {
  226842. CGAffineTransform t;
  226843. t.a = transform.mat00;
  226844. t.b = transform.mat10;
  226845. t.c = transform.mat01;
  226846. t.d = transform.mat11;
  226847. t.tx = transform.mat02;
  226848. t.ty = transform.mat12;
  226849. CGContextConcatCTM (context, t);
  226850. }
  226851. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  226852. };
  226853. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226854. {
  226855. return new CoreGraphicsContext (context, height);
  226856. }
  226857. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  226858. const Image juce_loadWithCoreImage (InputStream& input)
  226859. {
  226860. MemoryBlock data;
  226861. input.readIntoMemoryBlock (data, -1);
  226862. #if JUCE_IOS
  226863. JUCE_AUTORELEASEPOOL
  226864. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  226865. length: data.getSize()
  226866. freeWhenDone: NO]];
  226867. if (image != nil)
  226868. {
  226869. CGImageRef loadedImage = image.CGImage;
  226870. #else
  226871. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  226872. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  226873. CGDataProviderRelease (provider);
  226874. if (imageSource != 0)
  226875. {
  226876. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  226877. CFRelease (imageSource);
  226878. #endif
  226879. if (loadedImage != 0)
  226880. {
  226881. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  226882. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  226883. && alphaInfo != kCGImageAlphaNoneSkipLast
  226884. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  226885. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  226886. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  226887. hasAlphaChan, Image::NativeImage);
  226888. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  226889. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  226890. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  226891. CGContextFlush (cgImage->context);
  226892. #if ! JUCE_IOS
  226893. CFRelease (loadedImage);
  226894. #endif
  226895. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  226896. // to find out whether the file they just loaded the image from had an alpha channel or not.
  226897. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  226898. return image;
  226899. }
  226900. }
  226901. return Image::null;
  226902. }
  226903. #endif
  226904. #endif
  226905. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226906. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226907. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226908. // compiled on its own).
  226909. #if JUCE_INCLUDED_FILE
  226910. class UIViewComponentPeer;
  226911. END_JUCE_NAMESPACE
  226912. #define JuceUIView MakeObjCClassName(JuceUIView)
  226913. @interface JuceUIView : UIView <UITextViewDelegate>
  226914. {
  226915. @public
  226916. UIViewComponentPeer* owner;
  226917. UITextView* hiddenTextView;
  226918. }
  226919. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  226920. - (void) dealloc;
  226921. - (void) drawRect: (CGRect) r;
  226922. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  226923. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  226924. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  226925. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  226926. - (BOOL) becomeFirstResponder;
  226927. - (BOOL) resignFirstResponder;
  226928. - (BOOL) canBecomeFirstResponder;
  226929. - (void) asyncRepaint: (id) rect;
  226930. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  226931. @end
  226932. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  226933. @interface JuceUIViewController : UIViewController
  226934. {
  226935. }
  226936. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  226937. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  226938. @end
  226939. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  226940. @interface JuceUIWindow : UIWindow
  226941. {
  226942. @private
  226943. UIViewComponentPeer* owner;
  226944. bool isZooming;
  226945. }
  226946. - (void) setOwner: (UIViewComponentPeer*) owner;
  226947. - (void) becomeKeyWindow;
  226948. @end
  226949. BEGIN_JUCE_NAMESPACE
  226950. class UIViewComponentPeer : public ComponentPeer,
  226951. public FocusChangeListener
  226952. {
  226953. public:
  226954. UIViewComponentPeer (Component* const component,
  226955. const int windowStyleFlags,
  226956. UIView* viewToAttachTo);
  226957. ~UIViewComponentPeer();
  226958. void* getNativeHandle() const;
  226959. void setVisible (bool shouldBeVisible);
  226960. void setTitle (const String& title);
  226961. void setPosition (int x, int y);
  226962. void setSize (int w, int h);
  226963. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  226964. const Rectangle<int> getBounds() const;
  226965. const Rectangle<int> getBounds (const bool global) const;
  226966. const Point<int> getScreenPosition() const;
  226967. const Point<int> localToGlobal (const Point<int>& relativePosition);
  226968. const Point<int> globalToLocal (const Point<int>& screenPosition);
  226969. void setAlpha (float newAlpha);
  226970. void setMinimised (bool shouldBeMinimised);
  226971. bool isMinimised() const;
  226972. void setFullScreen (bool shouldBeFullScreen);
  226973. bool isFullScreen() const;
  226974. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  226975. const BorderSize getFrameSize() const;
  226976. bool setAlwaysOnTop (bool alwaysOnTop);
  226977. void toFront (bool makeActiveWindow);
  226978. void toBehind (ComponentPeer* other);
  226979. void setIcon (const Image& newIcon);
  226980. virtual void drawRect (CGRect r);
  226981. virtual bool canBecomeKeyWindow();
  226982. virtual bool windowShouldClose();
  226983. virtual void redirectMovedOrResized();
  226984. virtual CGRect constrainRect (CGRect r);
  226985. virtual void viewFocusGain();
  226986. virtual void viewFocusLoss();
  226987. bool isFocused() const;
  226988. void grabFocus();
  226989. void textInputRequired (const Point<int>& position);
  226990. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  226991. void updateHiddenTextContent (TextInputTarget* target);
  226992. void globalFocusChanged (Component*);
  226993. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  226994. virtual void displayRotated();
  226995. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  226996. void repaint (const Rectangle<int>& area);
  226997. void performAnyPendingRepaintsNow();
  226998. UIWindow* window;
  226999. JuceUIView* view;
  227000. JuceUIViewController* controller;
  227001. bool isSharedWindow, fullScreen, insideDrawRect;
  227002. static ModifierKeys currentModifiers;
  227003. static int64 getMouseTime (UIEvent* e)
  227004. {
  227005. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227006. + (int64) ([e timestamp] * 1000.0);
  227007. }
  227008. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  227009. {
  227010. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227011. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227012. {
  227013. case UIInterfaceOrientationPortrait:
  227014. return r;
  227015. case UIInterfaceOrientationPortraitUpsideDown:
  227016. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227017. r.getWidth(), r.getHeight());
  227018. case UIInterfaceOrientationLandscapeLeft:
  227019. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  227020. r.getHeight(), r.getWidth());
  227021. case UIInterfaceOrientationLandscapeRight:
  227022. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  227023. r.getHeight(), r.getWidth());
  227024. default: jassertfalse; // unknown orientation!
  227025. }
  227026. return r;
  227027. }
  227028. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  227029. {
  227030. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227031. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227032. {
  227033. case UIInterfaceOrientationPortrait:
  227034. return r;
  227035. case UIInterfaceOrientationPortraitUpsideDown:
  227036. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227037. r.getWidth(), r.getHeight());
  227038. case UIInterfaceOrientationLandscapeLeft:
  227039. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  227040. r.getHeight(), r.getWidth());
  227041. case UIInterfaceOrientationLandscapeRight:
  227042. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  227043. r.getHeight(), r.getWidth());
  227044. default: jassertfalse; // unknown orientation!
  227045. }
  227046. return r;
  227047. }
  227048. Array <UITouch*> currentTouches;
  227049. private:
  227050. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer);
  227051. };
  227052. END_JUCE_NAMESPACE
  227053. @implementation JuceUIViewController
  227054. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  227055. {
  227056. JuceUIView* juceView = (JuceUIView*) [self view];
  227057. jassert (juceView != 0 && juceView->owner != 0);
  227058. return juceView->owner->shouldRotate (interfaceOrientation);
  227059. }
  227060. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  227061. {
  227062. JuceUIView* juceView = (JuceUIView*) [self view];
  227063. jassert (juceView != 0 && juceView->owner != 0);
  227064. juceView->owner->displayRotated();
  227065. }
  227066. @end
  227067. @implementation JuceUIView
  227068. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227069. withFrame: (CGRect) frame
  227070. {
  227071. [super initWithFrame: frame];
  227072. owner = owner_;
  227073. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227074. [self addSubview: hiddenTextView];
  227075. hiddenTextView.delegate = self;
  227076. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227077. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227078. return self;
  227079. }
  227080. - (void) dealloc
  227081. {
  227082. [hiddenTextView removeFromSuperview];
  227083. [hiddenTextView release];
  227084. [super dealloc];
  227085. }
  227086. - (void) drawRect: (CGRect) r
  227087. {
  227088. if (owner != 0)
  227089. owner->drawRect (r);
  227090. }
  227091. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227092. {
  227093. return false;
  227094. }
  227095. ModifierKeys UIViewComponentPeer::currentModifiers;
  227096. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227097. {
  227098. return UIViewComponentPeer::currentModifiers;
  227099. }
  227100. void ModifierKeys::updateCurrentModifiers() throw()
  227101. {
  227102. currentModifiers = UIViewComponentPeer::currentModifiers;
  227103. }
  227104. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227105. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227106. {
  227107. if (owner != 0)
  227108. owner->handleTouches (event, true, false, false);
  227109. }
  227110. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227111. {
  227112. if (owner != 0)
  227113. owner->handleTouches (event, false, false, false);
  227114. }
  227115. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227116. {
  227117. if (owner != 0)
  227118. owner->handleTouches (event, false, true, false);
  227119. }
  227120. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227121. {
  227122. if (owner != 0)
  227123. owner->handleTouches (event, false, true, true);
  227124. [self touchesEnded: touches withEvent: event];
  227125. }
  227126. - (BOOL) becomeFirstResponder
  227127. {
  227128. if (owner != 0)
  227129. owner->viewFocusGain();
  227130. return true;
  227131. }
  227132. - (BOOL) resignFirstResponder
  227133. {
  227134. if (owner != 0)
  227135. owner->viewFocusLoss();
  227136. return true;
  227137. }
  227138. - (BOOL) canBecomeFirstResponder
  227139. {
  227140. return owner != 0 && owner->canBecomeKeyWindow();
  227141. }
  227142. - (void) asyncRepaint: (id) rect
  227143. {
  227144. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227145. [self setNeedsDisplayInRect: *r];
  227146. }
  227147. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227148. {
  227149. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227150. nsStringToJuce (text));
  227151. }
  227152. @end
  227153. @implementation JuceUIWindow
  227154. - (void) setOwner: (UIViewComponentPeer*) owner_
  227155. {
  227156. owner = owner_;
  227157. isZooming = false;
  227158. }
  227159. - (void) becomeKeyWindow
  227160. {
  227161. [super becomeKeyWindow];
  227162. if (owner != 0)
  227163. owner->grabFocus();
  227164. }
  227165. @end
  227166. BEGIN_JUCE_NAMESPACE
  227167. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227168. const int windowStyleFlags,
  227169. UIView* viewToAttachTo)
  227170. : ComponentPeer (component, windowStyleFlags),
  227171. window (0),
  227172. view (0), controller (0),
  227173. isSharedWindow (viewToAttachTo != 0),
  227174. fullScreen (false),
  227175. insideDrawRect (false)
  227176. {
  227177. CGRect r = convertToCGRect (component->getLocalBounds());
  227178. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227179. if (isSharedWindow)
  227180. {
  227181. window = [viewToAttachTo window];
  227182. [viewToAttachTo addSubview: view];
  227183. setVisible (component->isVisible());
  227184. }
  227185. else
  227186. {
  227187. controller = [[JuceUIViewController alloc] init];
  227188. controller.view = view;
  227189. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  227190. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227191. window = [[JuceUIWindow alloc] init];
  227192. window.frame = r;
  227193. window.opaque = component->isOpaque();
  227194. view.opaque = component->isOpaque();
  227195. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227196. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227197. [((JuceUIWindow*) window) setOwner: this];
  227198. if (component->isAlwaysOnTop())
  227199. window.windowLevel = UIWindowLevelAlert;
  227200. [window addSubview: view];
  227201. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227202. view.hidden = ! component->isVisible();
  227203. window.hidden = ! component->isVisible();
  227204. view.multipleTouchEnabled = YES;
  227205. }
  227206. setTitle (component->getName());
  227207. Desktop::getInstance().addFocusChangeListener (this);
  227208. }
  227209. UIViewComponentPeer::~UIViewComponentPeer()
  227210. {
  227211. Desktop::getInstance().removeFocusChangeListener (this);
  227212. view->owner = 0;
  227213. [view removeFromSuperview];
  227214. [view release];
  227215. [controller release];
  227216. if (! isSharedWindow)
  227217. {
  227218. [((JuceUIWindow*) window) setOwner: 0];
  227219. [window release];
  227220. }
  227221. }
  227222. void* UIViewComponentPeer::getNativeHandle() const
  227223. {
  227224. return view;
  227225. }
  227226. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227227. {
  227228. view.hidden = ! shouldBeVisible;
  227229. if (! isSharedWindow)
  227230. window.hidden = ! shouldBeVisible;
  227231. }
  227232. void UIViewComponentPeer::setTitle (const String& title)
  227233. {
  227234. // xxx is this possible?
  227235. }
  227236. void UIViewComponentPeer::setPosition (int x, int y)
  227237. {
  227238. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227239. }
  227240. void UIViewComponentPeer::setSize (int w, int h)
  227241. {
  227242. setBounds (component->getX(), component->getY(), w, h, false);
  227243. }
  227244. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227245. {
  227246. fullScreen = isNowFullScreen;
  227247. w = jmax (0, w);
  227248. h = jmax (0, h);
  227249. if (isSharedWindow)
  227250. {
  227251. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  227252. if ([view frame].size.width != r.size.width
  227253. || [view frame].size.height != r.size.height)
  227254. [view setNeedsDisplay];
  227255. view.frame = r;
  227256. }
  227257. else
  227258. {
  227259. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  227260. window.frame = convertToCGRect (bounds);
  227261. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  227262. handleMovedOrResized();
  227263. }
  227264. }
  227265. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227266. {
  227267. CGRect r = [view frame];
  227268. if (global && [view window] != 0)
  227269. {
  227270. r = [view convertRect: r toView: nil];
  227271. CGRect wr = [[view window] frame];
  227272. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  227273. r.origin.x = windowBounds.getX();
  227274. r.origin.y = windowBounds.getY();
  227275. }
  227276. return convertToRectInt (r);
  227277. }
  227278. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227279. {
  227280. return getBounds (! isSharedWindow);
  227281. }
  227282. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227283. {
  227284. return getBounds (true).getPosition();
  227285. }
  227286. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  227287. {
  227288. return relativePosition + getScreenPosition();
  227289. }
  227290. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  227291. {
  227292. return screenPosition - getScreenPosition();
  227293. }
  227294. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227295. {
  227296. if (constrainer != 0)
  227297. {
  227298. CGRect current = [window frame];
  227299. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227300. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227301. Rectangle<int> pos (convertToRectInt (r));
  227302. Rectangle<int> original (convertToRectInt (current));
  227303. constrainer->checkBounds (pos, original,
  227304. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227305. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227306. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227307. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227308. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227309. r.origin.x = pos.getX();
  227310. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227311. r.size.width = pos.getWidth();
  227312. r.size.height = pos.getHeight();
  227313. }
  227314. return r;
  227315. }
  227316. void UIViewComponentPeer::setAlpha (float newAlpha)
  227317. {
  227318. [[view window] setAlpha: (CGFloat) newAlpha];
  227319. }
  227320. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227321. {
  227322. }
  227323. bool UIViewComponentPeer::isMinimised() const
  227324. {
  227325. return false;
  227326. }
  227327. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227328. {
  227329. if (! isSharedWindow)
  227330. {
  227331. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  227332. : lastNonFullscreenBounds);
  227333. if ((! shouldBeFullScreen) && r.isEmpty())
  227334. r = getBounds();
  227335. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227336. if (! r.isEmpty())
  227337. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227338. component->repaint();
  227339. }
  227340. }
  227341. bool UIViewComponentPeer::isFullScreen() const
  227342. {
  227343. return fullScreen;
  227344. }
  227345. namespace
  227346. {
  227347. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  227348. {
  227349. switch (interfaceOrientation)
  227350. {
  227351. case UIInterfaceOrientationPortrait: return Desktop::upright;
  227352. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  227353. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  227354. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  227355. default: jassertfalse; // unknown orientation!
  227356. }
  227357. return Desktop::upright;
  227358. }
  227359. }
  227360. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  227361. {
  227362. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  227363. }
  227364. void UIViewComponentPeer::displayRotated()
  227365. {
  227366. const Rectangle<int> oldArea (component->getBounds());
  227367. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  227368. Desktop::getInstance().refreshMonitorSizes();
  227369. if (fullScreen)
  227370. {
  227371. fullScreen = false;
  227372. setFullScreen (true);
  227373. }
  227374. else
  227375. {
  227376. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  227377. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  227378. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  227379. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  227380. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  227381. setBounds ((int) (l * newDesktop.getWidth()),
  227382. (int) (t * newDesktop.getHeight()),
  227383. (int) ((r - l) * newDesktop.getWidth()),
  227384. (int) ((b - t) * newDesktop.getHeight()),
  227385. false);
  227386. }
  227387. }
  227388. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227389. {
  227390. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  227391. && isPositiveAndBelow (position.getY(), component->getHeight())))
  227392. return false;
  227393. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  227394. withEvent: nil];
  227395. if (trueIfInAChildWindow)
  227396. return v != nil;
  227397. return v == view;
  227398. }
  227399. const BorderSize UIViewComponentPeer::getFrameSize() const
  227400. {
  227401. return BorderSize();
  227402. }
  227403. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227404. {
  227405. if (! isSharedWindow)
  227406. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227407. return true;
  227408. }
  227409. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227410. {
  227411. if (isSharedWindow)
  227412. [[view superview] bringSubviewToFront: view];
  227413. if (window != 0 && component->isVisible())
  227414. [window makeKeyAndVisible];
  227415. }
  227416. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227417. {
  227418. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227419. jassert (otherPeer != 0); // wrong type of window?
  227420. if (otherPeer != 0)
  227421. {
  227422. if (isSharedWindow)
  227423. {
  227424. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227425. }
  227426. else
  227427. {
  227428. jassertfalse; // don't know how to do this
  227429. }
  227430. }
  227431. }
  227432. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227433. {
  227434. // to do..
  227435. }
  227436. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227437. {
  227438. NSArray* touches = [[event touchesForView: view] allObjects];
  227439. for (unsigned int i = 0; i < [touches count]; ++i)
  227440. {
  227441. UITouch* touch = [touches objectAtIndex: i];
  227442. CGPoint p = [touch locationInView: view];
  227443. const Point<int> pos ((int) p.x, (int) p.y);
  227444. juce_lastMousePos = pos + getScreenPosition();
  227445. const int64 time = getMouseTime (event);
  227446. int touchIndex = currentTouches.indexOf (touch);
  227447. if (touchIndex < 0)
  227448. {
  227449. touchIndex = currentTouches.size();
  227450. currentTouches.add (touch);
  227451. }
  227452. if (isDown)
  227453. {
  227454. currentModifiers = currentModifiers.withoutMouseButtons();
  227455. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227456. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227457. }
  227458. else if (isUp)
  227459. {
  227460. currentModifiers = currentModifiers.withoutMouseButtons();
  227461. currentTouches.remove (touchIndex);
  227462. }
  227463. if (isCancel)
  227464. currentTouches.clear();
  227465. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227466. }
  227467. }
  227468. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227469. void UIViewComponentPeer::viewFocusGain()
  227470. {
  227471. if (currentlyFocusedPeer != this)
  227472. {
  227473. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227474. currentlyFocusedPeer->handleFocusLoss();
  227475. currentlyFocusedPeer = this;
  227476. handleFocusGain();
  227477. }
  227478. }
  227479. void UIViewComponentPeer::viewFocusLoss()
  227480. {
  227481. if (currentlyFocusedPeer == this)
  227482. {
  227483. currentlyFocusedPeer = 0;
  227484. handleFocusLoss();
  227485. }
  227486. }
  227487. void juce_HandleProcessFocusChange()
  227488. {
  227489. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227490. {
  227491. if (Process::isForegroundProcess())
  227492. {
  227493. currentlyFocusedPeer->handleFocusGain();
  227494. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  227495. }
  227496. else
  227497. {
  227498. currentlyFocusedPeer->handleFocusLoss();
  227499. // turn kiosk mode off if we lose focus..
  227500. Desktop::getInstance().setKioskModeComponent (0);
  227501. }
  227502. }
  227503. }
  227504. bool UIViewComponentPeer::isFocused() const
  227505. {
  227506. return isSharedWindow ? this == currentlyFocusedPeer
  227507. : (window != 0 && [window isKeyWindow]);
  227508. }
  227509. void UIViewComponentPeer::grabFocus()
  227510. {
  227511. if (window != 0)
  227512. {
  227513. [window makeKeyWindow];
  227514. viewFocusGain();
  227515. }
  227516. }
  227517. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227518. {
  227519. }
  227520. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227521. {
  227522. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227523. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227524. }
  227525. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227526. {
  227527. TextInputTarget* const target = findCurrentTextInputTarget();
  227528. if (target != 0)
  227529. {
  227530. const Range<int> currentSelection (target->getHighlightedRegion());
  227531. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227532. if (currentSelection.isEmpty())
  227533. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227534. target->insertTextAtCaret (text);
  227535. updateHiddenTextContent (target);
  227536. }
  227537. return NO;
  227538. }
  227539. void UIViewComponentPeer::globalFocusChanged (Component*)
  227540. {
  227541. TextInputTarget* const target = findCurrentTextInputTarget();
  227542. if (target != 0)
  227543. {
  227544. Component* comp = dynamic_cast<Component*> (target);
  227545. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  227546. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227547. updateHiddenTextContent (target);
  227548. [view->hiddenTextView becomeFirstResponder];
  227549. }
  227550. else
  227551. {
  227552. [view->hiddenTextView resignFirstResponder];
  227553. }
  227554. }
  227555. void UIViewComponentPeer::drawRect (CGRect r)
  227556. {
  227557. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227558. return;
  227559. CGContextRef cg = UIGraphicsGetCurrentContext();
  227560. if (! component->isOpaque())
  227561. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227562. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227563. CoreGraphicsContext g (cg, view.bounds.size.height);
  227564. insideDrawRect = true;
  227565. handlePaint (g);
  227566. insideDrawRect = false;
  227567. }
  227568. bool UIViewComponentPeer::canBecomeKeyWindow()
  227569. {
  227570. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227571. }
  227572. bool UIViewComponentPeer::windowShouldClose()
  227573. {
  227574. if (! isValidPeer (this))
  227575. return YES;
  227576. handleUserClosingWindow();
  227577. return NO;
  227578. }
  227579. void UIViewComponentPeer::redirectMovedOrResized()
  227580. {
  227581. handleMovedOrResized();
  227582. }
  227583. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227584. {
  227585. }
  227586. class AsyncRepaintMessage : public CallbackMessage
  227587. {
  227588. public:
  227589. UIViewComponentPeer* const peer;
  227590. const Rectangle<int> rect;
  227591. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227592. : peer (peer_), rect (rect_)
  227593. {
  227594. }
  227595. void messageCallback()
  227596. {
  227597. if (ComponentPeer::isValidPeer (peer))
  227598. peer->repaint (rect);
  227599. }
  227600. };
  227601. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227602. {
  227603. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227604. {
  227605. (new AsyncRepaintMessage (this, area))->post();
  227606. }
  227607. else
  227608. {
  227609. [view setNeedsDisplayInRect: convertToCGRect (area)];
  227610. }
  227611. }
  227612. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227613. {
  227614. }
  227615. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227616. {
  227617. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227618. }
  227619. const Image juce_createIconForFile (const File& file)
  227620. {
  227621. return Image::null;
  227622. }
  227623. void Desktop::createMouseInputSources()
  227624. {
  227625. for (int i = 0; i < 10; ++i)
  227626. mouseSources.add (new MouseInputSource (i, false));
  227627. }
  227628. bool Desktop::canUseSemiTransparentWindows() throw()
  227629. {
  227630. return true;
  227631. }
  227632. const Point<int> MouseInputSource::getCurrentMousePosition()
  227633. {
  227634. return juce_lastMousePos;
  227635. }
  227636. void Desktop::setMousePosition (const Point<int>&)
  227637. {
  227638. }
  227639. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  227640. {
  227641. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  227642. }
  227643. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  227644. {
  227645. const ScopedAutoReleasePool pool;
  227646. monitorCoords.clear();
  227647. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  227648. : [[UIScreen mainScreen] bounds];
  227649. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  227650. }
  227651. const int KeyPress::spaceKey = ' ';
  227652. const int KeyPress::returnKey = 0x0d;
  227653. const int KeyPress::escapeKey = 0x1b;
  227654. const int KeyPress::backspaceKey = 0x7f;
  227655. const int KeyPress::leftKey = 0x1000;
  227656. const int KeyPress::rightKey = 0x1001;
  227657. const int KeyPress::upKey = 0x1002;
  227658. const int KeyPress::downKey = 0x1003;
  227659. const int KeyPress::pageUpKey = 0x1004;
  227660. const int KeyPress::pageDownKey = 0x1005;
  227661. const int KeyPress::endKey = 0x1006;
  227662. const int KeyPress::homeKey = 0x1007;
  227663. const int KeyPress::deleteKey = 0x1008;
  227664. const int KeyPress::insertKey = -1;
  227665. const int KeyPress::tabKey = 9;
  227666. const int KeyPress::F1Key = 0x2001;
  227667. const int KeyPress::F2Key = 0x2002;
  227668. const int KeyPress::F3Key = 0x2003;
  227669. const int KeyPress::F4Key = 0x2004;
  227670. const int KeyPress::F5Key = 0x2005;
  227671. const int KeyPress::F6Key = 0x2006;
  227672. const int KeyPress::F7Key = 0x2007;
  227673. const int KeyPress::F8Key = 0x2008;
  227674. const int KeyPress::F9Key = 0x2009;
  227675. const int KeyPress::F10Key = 0x200a;
  227676. const int KeyPress::F11Key = 0x200b;
  227677. const int KeyPress::F12Key = 0x200c;
  227678. const int KeyPress::F13Key = 0x200d;
  227679. const int KeyPress::F14Key = 0x200e;
  227680. const int KeyPress::F15Key = 0x200f;
  227681. const int KeyPress::F16Key = 0x2010;
  227682. const int KeyPress::numberPad0 = 0x30020;
  227683. const int KeyPress::numberPad1 = 0x30021;
  227684. const int KeyPress::numberPad2 = 0x30022;
  227685. const int KeyPress::numberPad3 = 0x30023;
  227686. const int KeyPress::numberPad4 = 0x30024;
  227687. const int KeyPress::numberPad5 = 0x30025;
  227688. const int KeyPress::numberPad6 = 0x30026;
  227689. const int KeyPress::numberPad7 = 0x30027;
  227690. const int KeyPress::numberPad8 = 0x30028;
  227691. const int KeyPress::numberPad9 = 0x30029;
  227692. const int KeyPress::numberPadAdd = 0x3002a;
  227693. const int KeyPress::numberPadSubtract = 0x3002b;
  227694. const int KeyPress::numberPadMultiply = 0x3002c;
  227695. const int KeyPress::numberPadDivide = 0x3002d;
  227696. const int KeyPress::numberPadSeparator = 0x3002e;
  227697. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227698. const int KeyPress::numberPadEquals = 0x30030;
  227699. const int KeyPress::numberPadDelete = 0x30031;
  227700. const int KeyPress::playKey = 0x30000;
  227701. const int KeyPress::stopKey = 0x30001;
  227702. const int KeyPress::fastForwardKey = 0x30002;
  227703. const int KeyPress::rewindKey = 0x30003;
  227704. #endif
  227705. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227706. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  227707. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227708. // compiled on its own).
  227709. #if JUCE_INCLUDED_FILE
  227710. struct CallbackMessagePayload
  227711. {
  227712. MessageCallbackFunction* function;
  227713. void* parameter;
  227714. void* volatile result;
  227715. bool volatile hasBeenExecuted;
  227716. };
  227717. END_JUCE_NAMESPACE
  227718. @interface JuceCustomMessageHandler : NSObject
  227719. {
  227720. }
  227721. - (void) performCallback: (id) info;
  227722. @end
  227723. @implementation JuceCustomMessageHandler
  227724. - (void) performCallback: (id) info
  227725. {
  227726. if ([info isKindOfClass: [NSData class]])
  227727. {
  227728. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227729. if (pl != 0)
  227730. {
  227731. pl->result = (*pl->function) (pl->parameter);
  227732. pl->hasBeenExecuted = true;
  227733. }
  227734. }
  227735. else
  227736. {
  227737. jassertfalse; // should never get here!
  227738. }
  227739. }
  227740. @end
  227741. BEGIN_JUCE_NAMESPACE
  227742. void MessageManager::runDispatchLoop()
  227743. {
  227744. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227745. runDispatchLoopUntil (-1);
  227746. }
  227747. void MessageManager::stopDispatchLoop()
  227748. {
  227749. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227750. exit (0); // iPhone apps get no mercy..
  227751. }
  227752. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227753. {
  227754. const ScopedAutoReleasePool pool;
  227755. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227756. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227757. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227758. while (! quitMessagePosted)
  227759. {
  227760. const ScopedAutoReleasePool pool;
  227761. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227762. beforeDate: endDate];
  227763. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227764. break;
  227765. }
  227766. return ! quitMessagePosted;
  227767. }
  227768. struct MessageDispatchSystem
  227769. {
  227770. MessageDispatchSystem()
  227771. : juceCustomMessageHandler (0)
  227772. {
  227773. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227774. }
  227775. ~MessageDispatchSystem()
  227776. {
  227777. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227778. [juceCustomMessageHandler release];
  227779. }
  227780. JuceCustomMessageHandler* juceCustomMessageHandler;
  227781. MessageQueue messageQueue;
  227782. };
  227783. static MessageDispatchSystem* dispatcher = 0;
  227784. void MessageManager::doPlatformSpecificInitialisation()
  227785. {
  227786. if (dispatcher == 0)
  227787. dispatcher = new MessageDispatchSystem();
  227788. }
  227789. void MessageManager::doPlatformSpecificShutdown()
  227790. {
  227791. deleteAndZero (dispatcher);
  227792. }
  227793. bool juce_postMessageToSystemQueue (Message* message)
  227794. {
  227795. if (dispatcher != 0)
  227796. dispatcher->messageQueue.post (message);
  227797. return true;
  227798. }
  227799. void MessageManager::broadcastMessage (const String& value)
  227800. {
  227801. }
  227802. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  227803. {
  227804. if (isThisTheMessageThread())
  227805. {
  227806. return (*callback) (data);
  227807. }
  227808. else
  227809. {
  227810. jassert (dispatcher != 0); // trying to call this when the juce system isn't initialised..
  227811. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227812. // deadlock because the message manager is blocked from running, so can never
  227813. // call your function..
  227814. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227815. const ScopedAutoReleasePool pool;
  227816. CallbackMessagePayload cmp;
  227817. cmp.function = callback;
  227818. cmp.parameter = data;
  227819. cmp.result = 0;
  227820. cmp.hasBeenExecuted = false;
  227821. [dispatcher->juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227822. withObject: [NSData dataWithBytesNoCopy: &cmp
  227823. length: sizeof (cmp)
  227824. freeWhenDone: NO]
  227825. waitUntilDone: YES];
  227826. return cmp.result;
  227827. }
  227828. }
  227829. #endif
  227830. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  227831. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227832. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227833. // compiled on its own).
  227834. #if JUCE_INCLUDED_FILE
  227835. #if JUCE_MAC
  227836. END_JUCE_NAMESPACE
  227837. using namespace JUCE_NAMESPACE;
  227838. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227839. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227840. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227841. #else
  227842. @interface JuceFileChooserDelegate : NSObject
  227843. #endif
  227844. {
  227845. StringArray* filters;
  227846. }
  227847. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227848. - (void) dealloc;
  227849. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227850. @end
  227851. @implementation JuceFileChooserDelegate
  227852. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227853. {
  227854. [super init];
  227855. filters = filters_;
  227856. return self;
  227857. }
  227858. - (void) dealloc
  227859. {
  227860. delete filters;
  227861. [super dealloc];
  227862. }
  227863. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227864. {
  227865. (void) sender;
  227866. const File f (nsStringToJuce (filename));
  227867. for (int i = filters->size(); --i >= 0;)
  227868. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  227869. return true;
  227870. return f.isDirectory();
  227871. }
  227872. @end
  227873. BEGIN_JUCE_NAMESPACE
  227874. void FileChooser::showPlatformDialog (Array<File>& results,
  227875. const String& title,
  227876. const File& currentFileOrDirectory,
  227877. const String& filter,
  227878. bool selectsDirectory,
  227879. bool selectsFiles,
  227880. bool isSaveDialogue,
  227881. bool /*warnAboutOverwritingExistingFiles*/,
  227882. bool selectMultipleFiles,
  227883. FilePreviewComponent* /*extraInfoComponent*/)
  227884. {
  227885. const ScopedAutoReleasePool pool;
  227886. StringArray* filters = new StringArray();
  227887. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  227888. filters->trim();
  227889. filters->removeEmptyStrings();
  227890. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  227891. [delegate autorelease];
  227892. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  227893. : [NSOpenPanel openPanel];
  227894. [panel setTitle: juceStringToNS (title)];
  227895. if (! isSaveDialogue)
  227896. {
  227897. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227898. [openPanel setCanChooseDirectories: selectsDirectory];
  227899. [openPanel setCanChooseFiles: selectsFiles];
  227900. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  227901. }
  227902. [panel setDelegate: delegate];
  227903. if (isSaveDialogue || selectsDirectory)
  227904. [panel setCanCreateDirectories: YES];
  227905. String directory, filename;
  227906. if (currentFileOrDirectory.isDirectory())
  227907. {
  227908. directory = currentFileOrDirectory.getFullPathName();
  227909. }
  227910. else
  227911. {
  227912. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  227913. filename = currentFileOrDirectory.getFileName();
  227914. }
  227915. if ([panel runModalForDirectory: juceStringToNS (directory)
  227916. file: juceStringToNS (filename)]
  227917. == NSOKButton)
  227918. {
  227919. if (isSaveDialogue)
  227920. {
  227921. results.add (File (nsStringToJuce ([panel filename])));
  227922. }
  227923. else
  227924. {
  227925. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227926. NSArray* urls = [openPanel filenames];
  227927. for (unsigned int i = 0; i < [urls count]; ++i)
  227928. {
  227929. NSString* f = [urls objectAtIndex: i];
  227930. results.add (File (nsStringToJuce (f)));
  227931. }
  227932. }
  227933. }
  227934. [panel setDelegate: nil];
  227935. }
  227936. #else
  227937. void FileChooser::showPlatformDialog (Array<File>& results,
  227938. const String& title,
  227939. const File& currentFileOrDirectory,
  227940. const String& filter,
  227941. bool selectsDirectory,
  227942. bool selectsFiles,
  227943. bool isSaveDialogue,
  227944. bool warnAboutOverwritingExistingFiles,
  227945. bool selectMultipleFiles,
  227946. FilePreviewComponent* extraInfoComponent)
  227947. {
  227948. const ScopedAutoReleasePool pool;
  227949. jassertfalse; //xxx to do
  227950. }
  227951. #endif
  227952. #endif
  227953. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  227954. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  227955. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227956. // compiled on its own).
  227957. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  227958. #if JUCE_MAC
  227959. END_JUCE_NAMESPACE
  227960. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  227961. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  227962. {
  227963. CriticalSection* contextLock;
  227964. bool needsUpdate;
  227965. }
  227966. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  227967. - (bool) makeActive;
  227968. - (void) makeInactive;
  227969. - (void) reshape;
  227970. @end
  227971. @implementation ThreadSafeNSOpenGLView
  227972. - (id) initWithFrame: (NSRect) frameRect
  227973. pixelFormat: (NSOpenGLPixelFormat*) format
  227974. {
  227975. contextLock = new CriticalSection();
  227976. self = [super initWithFrame: frameRect pixelFormat: format];
  227977. if (self != nil)
  227978. [[NSNotificationCenter defaultCenter] addObserver: self
  227979. selector: @selector (_surfaceNeedsUpdate:)
  227980. name: NSViewGlobalFrameDidChangeNotification
  227981. object: self];
  227982. return self;
  227983. }
  227984. - (void) dealloc
  227985. {
  227986. [[NSNotificationCenter defaultCenter] removeObserver: self];
  227987. delete contextLock;
  227988. [super dealloc];
  227989. }
  227990. - (bool) makeActive
  227991. {
  227992. const ScopedLock sl (*contextLock);
  227993. if ([self openGLContext] == 0)
  227994. return false;
  227995. [[self openGLContext] makeCurrentContext];
  227996. if (needsUpdate)
  227997. {
  227998. [super update];
  227999. needsUpdate = false;
  228000. }
  228001. return true;
  228002. }
  228003. - (void) makeInactive
  228004. {
  228005. const ScopedLock sl (*contextLock);
  228006. [NSOpenGLContext clearCurrentContext];
  228007. }
  228008. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228009. {
  228010. (void) notification;
  228011. const ScopedLock sl (*contextLock);
  228012. needsUpdate = true;
  228013. }
  228014. - (void) update
  228015. {
  228016. const ScopedLock sl (*contextLock);
  228017. needsUpdate = true;
  228018. }
  228019. - (void) reshape
  228020. {
  228021. const ScopedLock sl (*contextLock);
  228022. needsUpdate = true;
  228023. }
  228024. @end
  228025. BEGIN_JUCE_NAMESPACE
  228026. class WindowedGLContext : public OpenGLContext
  228027. {
  228028. public:
  228029. WindowedGLContext (Component& component,
  228030. const OpenGLPixelFormat& pixelFormat_,
  228031. NSOpenGLContext* sharedContext)
  228032. : renderContext (0),
  228033. pixelFormat (pixelFormat_)
  228034. {
  228035. NSOpenGLPixelFormatAttribute attribs [64];
  228036. int n = 0;
  228037. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228038. attribs[n++] = NSOpenGLPFAAccelerated;
  228039. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228040. attribs[n++] = NSOpenGLPFAColorSize;
  228041. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228042. pixelFormat.greenBits,
  228043. pixelFormat.blueBits);
  228044. attribs[n++] = NSOpenGLPFAAlphaSize;
  228045. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228046. attribs[n++] = NSOpenGLPFADepthSize;
  228047. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228048. attribs[n++] = NSOpenGLPFAStencilSize;
  228049. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228050. attribs[n++] = NSOpenGLPFAAccumSize;
  228051. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228052. pixelFormat.accumulationBufferGreenBits,
  228053. pixelFormat.accumulationBufferBlueBits,
  228054. pixelFormat.accumulationBufferAlphaBits);
  228055. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228056. attribs[n++] = NSOpenGLPFASampleBuffers;
  228057. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228058. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228059. attribs[n++] = NSOpenGLPFANoRecovery;
  228060. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228061. NSOpenGLPixelFormat* format
  228062. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228063. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228064. pixelFormat: format];
  228065. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228066. shareContext: sharedContext] autorelease];
  228067. const GLint swapInterval = 1;
  228068. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228069. [view setOpenGLContext: renderContext];
  228070. [format release];
  228071. viewHolder = new NSViewComponentInternal (view, component);
  228072. }
  228073. ~WindowedGLContext()
  228074. {
  228075. deleteContext();
  228076. viewHolder = 0;
  228077. }
  228078. void deleteContext()
  228079. {
  228080. makeInactive();
  228081. [renderContext clearDrawable];
  228082. [renderContext setView: nil];
  228083. [view setOpenGLContext: nil];
  228084. renderContext = nil;
  228085. }
  228086. bool makeActive() const throw()
  228087. {
  228088. jassert (renderContext != 0);
  228089. if ([renderContext view] != view)
  228090. [renderContext setView: view];
  228091. [view makeActive];
  228092. return isActive();
  228093. }
  228094. bool makeInactive() const throw()
  228095. {
  228096. [view makeInactive];
  228097. return true;
  228098. }
  228099. bool isActive() const throw()
  228100. {
  228101. return [NSOpenGLContext currentContext] == renderContext;
  228102. }
  228103. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228104. void* getRawContext() const throw() { return renderContext; }
  228105. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  228106. {
  228107. }
  228108. void swapBuffers()
  228109. {
  228110. [renderContext flushBuffer];
  228111. }
  228112. bool setSwapInterval (const int numFramesPerSwap)
  228113. {
  228114. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228115. forParameter: NSOpenGLCPSwapInterval];
  228116. return true;
  228117. }
  228118. int getSwapInterval() const
  228119. {
  228120. GLint numFrames = 0;
  228121. [renderContext getValues: &numFrames
  228122. forParameter: NSOpenGLCPSwapInterval];
  228123. return numFrames;
  228124. }
  228125. void repaint()
  228126. {
  228127. // we need to invalidate the juce view that holds this gl view, to make it
  228128. // cause a repaint callback
  228129. NSView* v = (NSView*) viewHolder->view;
  228130. NSRect r = [v frame];
  228131. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228132. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228133. // repaint message, thus never causing our paint() callback, and never repainting
  228134. // the comp. So invalidating just a little bit around the edge helps..
  228135. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228136. }
  228137. void* getNativeWindowHandle() const { return viewHolder->view; }
  228138. NSOpenGLContext* renderContext;
  228139. ThreadSafeNSOpenGLView* view;
  228140. private:
  228141. OpenGLPixelFormat pixelFormat;
  228142. ScopedPointer <NSViewComponentInternal> viewHolder;
  228143. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  228144. };
  228145. OpenGLContext* OpenGLComponent::createContext()
  228146. {
  228147. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  228148. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228149. return (c->renderContext != 0) ? c.release() : 0;
  228150. }
  228151. void* OpenGLComponent::getNativeWindowHandle() const
  228152. {
  228153. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228154. : 0;
  228155. }
  228156. void juce_glViewport (const int w, const int h)
  228157. {
  228158. glViewport (0, 0, w, h);
  228159. }
  228160. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228161. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228162. {
  228163. /* GLint attribs [64];
  228164. int n = 0;
  228165. attribs[n++] = AGL_RGBA;
  228166. attribs[n++] = AGL_DOUBLEBUFFER;
  228167. attribs[n++] = AGL_ACCELERATED;
  228168. attribs[n++] = AGL_NO_RECOVERY;
  228169. attribs[n++] = AGL_NONE;
  228170. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228171. while (p != 0)
  228172. {
  228173. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228174. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228175. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228176. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228177. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228178. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228179. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228180. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228181. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228182. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228183. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228184. results.add (pf);
  228185. p = aglNextPixelFormat (p);
  228186. }*/
  228187. //jassertfalse // can't see how you do this in cocoa!
  228188. }
  228189. #else
  228190. END_JUCE_NAMESPACE
  228191. @interface JuceGLView : UIView
  228192. {
  228193. }
  228194. + (Class) layerClass;
  228195. @end
  228196. @implementation JuceGLView
  228197. + (Class) layerClass
  228198. {
  228199. return [CAEAGLLayer class];
  228200. }
  228201. @end
  228202. BEGIN_JUCE_NAMESPACE
  228203. class GLESContext : public OpenGLContext
  228204. {
  228205. public:
  228206. GLESContext (UIViewComponentPeer* peer,
  228207. Component* const component_,
  228208. const OpenGLPixelFormat& pixelFormat_,
  228209. const GLESContext* const sharedContext,
  228210. NSUInteger apiType)
  228211. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228212. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228213. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228214. {
  228215. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228216. view.opaque = YES;
  228217. view.hidden = NO;
  228218. view.backgroundColor = [UIColor blackColor];
  228219. view.userInteractionEnabled = NO;
  228220. glLayer = (CAEAGLLayer*) [view layer];
  228221. [peer->view addSubview: view];
  228222. if (sharedContext != 0)
  228223. context = [[EAGLContext alloc] initWithAPI: apiType
  228224. sharegroup: [sharedContext->context sharegroup]];
  228225. else
  228226. context = [[EAGLContext alloc] initWithAPI: apiType];
  228227. createGLBuffers();
  228228. }
  228229. ~GLESContext()
  228230. {
  228231. deleteContext();
  228232. [view removeFromSuperview];
  228233. [view release];
  228234. freeGLBuffers();
  228235. }
  228236. void deleteContext()
  228237. {
  228238. makeInactive();
  228239. [context release];
  228240. context = nil;
  228241. }
  228242. bool makeActive() const throw()
  228243. {
  228244. jassert (context != 0);
  228245. [EAGLContext setCurrentContext: context];
  228246. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228247. return true;
  228248. }
  228249. void swapBuffers()
  228250. {
  228251. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228252. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228253. }
  228254. bool makeInactive() const throw()
  228255. {
  228256. return [EAGLContext setCurrentContext: nil];
  228257. }
  228258. bool isActive() const throw()
  228259. {
  228260. return [EAGLContext currentContext] == context;
  228261. }
  228262. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228263. void* getRawContext() const throw() { return glLayer; }
  228264. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228265. {
  228266. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228267. if (lastWidth != w || lastHeight != h)
  228268. {
  228269. lastWidth = w;
  228270. lastHeight = h;
  228271. freeGLBuffers();
  228272. createGLBuffers();
  228273. }
  228274. }
  228275. bool setSwapInterval (const int numFramesPerSwap)
  228276. {
  228277. numFrames = numFramesPerSwap;
  228278. return true;
  228279. }
  228280. int getSwapInterval() const
  228281. {
  228282. return numFrames;
  228283. }
  228284. void repaint()
  228285. {
  228286. }
  228287. void createGLBuffers()
  228288. {
  228289. makeActive();
  228290. glGenFramebuffersOES (1, &frameBufferHandle);
  228291. glGenRenderbuffersOES (1, &colorBufferHandle);
  228292. glGenRenderbuffersOES (1, &depthBufferHandle);
  228293. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228294. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228295. GLint width, height;
  228296. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228297. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228298. if (useDepthBuffer)
  228299. {
  228300. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228301. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228302. }
  228303. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228304. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228305. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228306. if (useDepthBuffer)
  228307. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228308. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228309. }
  228310. void freeGLBuffers()
  228311. {
  228312. if (frameBufferHandle != 0)
  228313. {
  228314. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228315. frameBufferHandle = 0;
  228316. }
  228317. if (colorBufferHandle != 0)
  228318. {
  228319. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228320. colorBufferHandle = 0;
  228321. }
  228322. if (depthBufferHandle != 0)
  228323. {
  228324. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228325. depthBufferHandle = 0;
  228326. }
  228327. }
  228328. private:
  228329. WeakReference<Component> component;
  228330. OpenGLPixelFormat pixelFormat;
  228331. JuceGLView* view;
  228332. CAEAGLLayer* glLayer;
  228333. EAGLContext* context;
  228334. bool useDepthBuffer;
  228335. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228336. int numFrames;
  228337. int lastWidth, lastHeight;
  228338. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  228339. };
  228340. OpenGLContext* OpenGLComponent::createContext()
  228341. {
  228342. ScopedAutoReleasePool pool;
  228343. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228344. if (peer != 0)
  228345. return new GLESContext (peer, this, preferredPixelFormat,
  228346. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228347. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228348. return 0;
  228349. }
  228350. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228351. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228352. {
  228353. }
  228354. void juce_glViewport (const int w, const int h)
  228355. {
  228356. glViewport (0, 0, w, h);
  228357. }
  228358. #endif
  228359. #endif
  228360. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228361. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228362. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228363. // compiled on its own).
  228364. #if JUCE_INCLUDED_FILE
  228365. #if JUCE_MAC
  228366. namespace MouseCursorHelpers
  228367. {
  228368. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228369. {
  228370. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228371. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228372. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228373. [im release];
  228374. return c;
  228375. }
  228376. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228377. {
  228378. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228379. BufferedInputStream buf (fileStream, 4096);
  228380. PNGImageFormat pngFormat;
  228381. Image im (pngFormat.decodeImage (buf));
  228382. if (im.isValid())
  228383. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228384. jassertfalse;
  228385. return 0;
  228386. }
  228387. }
  228388. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228389. {
  228390. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228391. }
  228392. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228393. {
  228394. const ScopedAutoReleasePool pool;
  228395. NSCursor* c = 0;
  228396. switch (type)
  228397. {
  228398. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228399. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228400. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228401. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228402. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228403. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228404. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228405. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228406. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228407. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228408. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228409. case UpDownResizeCursor:
  228410. case TopEdgeResizeCursor:
  228411. case BottomEdgeResizeCursor:
  228412. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228413. case TopLeftCornerResizeCursor:
  228414. case BottomRightCornerResizeCursor:
  228415. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228416. case TopRightCornerResizeCursor:
  228417. case BottomLeftCornerResizeCursor:
  228418. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228419. case UpDownLeftRightResizeCursor:
  228420. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228421. default:
  228422. jassertfalse;
  228423. break;
  228424. }
  228425. [c retain];
  228426. return c;
  228427. }
  228428. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228429. {
  228430. [((NSCursor*) cursorHandle) release];
  228431. }
  228432. void MouseCursor::showInAllWindows() const
  228433. {
  228434. showInWindow (0);
  228435. }
  228436. void MouseCursor::showInWindow (ComponentPeer*) const
  228437. {
  228438. NSCursor* c = (NSCursor*) getHandle();
  228439. if (c == 0)
  228440. c = [NSCursor arrowCursor];
  228441. [c set];
  228442. }
  228443. #else
  228444. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228445. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228446. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228447. void MouseCursor::showInAllWindows() const {}
  228448. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228449. #endif
  228450. #endif
  228451. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228452. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228453. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228454. // compiled on its own).
  228455. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228456. #if JUCE_MAC
  228457. END_JUCE_NAMESPACE
  228458. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228459. @interface DownloadClickDetector : NSObject
  228460. {
  228461. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228462. }
  228463. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228464. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228465. request: (NSURLRequest*) request
  228466. frame: (WebFrame*) frame
  228467. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228468. @end
  228469. @implementation DownloadClickDetector
  228470. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228471. {
  228472. [super init];
  228473. ownerComponent = ownerComponent_;
  228474. return self;
  228475. }
  228476. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228477. request: (NSURLRequest*) request
  228478. frame: (WebFrame*) frame
  228479. decisionListener: (id <WebPolicyDecisionListener>) listener
  228480. {
  228481. (void) sender;
  228482. (void) request;
  228483. (void) frame;
  228484. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228485. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228486. [listener use];
  228487. else
  228488. [listener ignore];
  228489. }
  228490. @end
  228491. BEGIN_JUCE_NAMESPACE
  228492. class WebBrowserComponentInternal : public NSViewComponent
  228493. {
  228494. public:
  228495. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228496. {
  228497. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228498. frameName: @""
  228499. groupName: @""];
  228500. setView (webView);
  228501. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228502. [webView setPolicyDelegate: clickListener];
  228503. }
  228504. ~WebBrowserComponentInternal()
  228505. {
  228506. [webView setPolicyDelegate: nil];
  228507. [clickListener release];
  228508. setView (0);
  228509. }
  228510. void goToURL (const String& url,
  228511. const StringArray* headers,
  228512. const MemoryBlock* postData)
  228513. {
  228514. NSMutableURLRequest* r
  228515. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228516. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228517. timeoutInterval: 30.0];
  228518. if (postData != 0 && postData->getSize() > 0)
  228519. {
  228520. [r setHTTPMethod: @"POST"];
  228521. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228522. length: postData->getSize()]];
  228523. }
  228524. if (headers != 0)
  228525. {
  228526. for (int i = 0; i < headers->size(); ++i)
  228527. {
  228528. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228529. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228530. [r setValue: juceStringToNS (headerValue)
  228531. forHTTPHeaderField: juceStringToNS (headerName)];
  228532. }
  228533. }
  228534. stop();
  228535. [[webView mainFrame] loadRequest: r];
  228536. }
  228537. void goBack()
  228538. {
  228539. [webView goBack];
  228540. }
  228541. void goForward()
  228542. {
  228543. [webView goForward];
  228544. }
  228545. void stop()
  228546. {
  228547. [webView stopLoading: nil];
  228548. }
  228549. void refresh()
  228550. {
  228551. [webView reload: nil];
  228552. }
  228553. void mouseMove (const MouseEvent&)
  228554. {
  228555. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  228556. // them work is to push them via this non-public method..
  228557. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  228558. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  228559. }
  228560. private:
  228561. WebView* webView;
  228562. DownloadClickDetector* clickListener;
  228563. };
  228564. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228565. : browser (0),
  228566. blankPageShown (false),
  228567. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228568. {
  228569. setOpaque (true);
  228570. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228571. }
  228572. WebBrowserComponent::~WebBrowserComponent()
  228573. {
  228574. deleteAndZero (browser);
  228575. }
  228576. void WebBrowserComponent::goToURL (const String& url,
  228577. const StringArray* headers,
  228578. const MemoryBlock* postData)
  228579. {
  228580. lastURL = url;
  228581. lastHeaders.clear();
  228582. if (headers != 0)
  228583. lastHeaders = *headers;
  228584. lastPostData.setSize (0);
  228585. if (postData != 0)
  228586. lastPostData = *postData;
  228587. blankPageShown = false;
  228588. browser->goToURL (url, headers, postData);
  228589. }
  228590. void WebBrowserComponent::stop()
  228591. {
  228592. browser->stop();
  228593. }
  228594. void WebBrowserComponent::goBack()
  228595. {
  228596. lastURL = String::empty;
  228597. blankPageShown = false;
  228598. browser->goBack();
  228599. }
  228600. void WebBrowserComponent::goForward()
  228601. {
  228602. lastURL = String::empty;
  228603. browser->goForward();
  228604. }
  228605. void WebBrowserComponent::refresh()
  228606. {
  228607. browser->refresh();
  228608. }
  228609. void WebBrowserComponent::paint (Graphics&)
  228610. {
  228611. }
  228612. void WebBrowserComponent::checkWindowAssociation()
  228613. {
  228614. if (isShowing())
  228615. {
  228616. if (blankPageShown)
  228617. goBack();
  228618. }
  228619. else
  228620. {
  228621. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228622. {
  228623. // when the component becomes invisible, some stuff like flash
  228624. // carries on playing audio, so we need to force it onto a blank
  228625. // page to avoid this, (and send it back when it's made visible again).
  228626. blankPageShown = true;
  228627. browser->goToURL ("about:blank", 0, 0);
  228628. }
  228629. }
  228630. }
  228631. void WebBrowserComponent::reloadLastURL()
  228632. {
  228633. if (lastURL.isNotEmpty())
  228634. {
  228635. goToURL (lastURL, &lastHeaders, &lastPostData);
  228636. lastURL = String::empty;
  228637. }
  228638. }
  228639. void WebBrowserComponent::parentHierarchyChanged()
  228640. {
  228641. checkWindowAssociation();
  228642. }
  228643. void WebBrowserComponent::resized()
  228644. {
  228645. browser->setSize (getWidth(), getHeight());
  228646. }
  228647. void WebBrowserComponent::visibilityChanged()
  228648. {
  228649. checkWindowAssociation();
  228650. }
  228651. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228652. {
  228653. return true;
  228654. }
  228655. #else
  228656. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228657. {
  228658. }
  228659. WebBrowserComponent::~WebBrowserComponent()
  228660. {
  228661. }
  228662. void WebBrowserComponent::goToURL (const String& url,
  228663. const StringArray* headers,
  228664. const MemoryBlock* postData)
  228665. {
  228666. }
  228667. void WebBrowserComponent::stop()
  228668. {
  228669. }
  228670. void WebBrowserComponent::goBack()
  228671. {
  228672. }
  228673. void WebBrowserComponent::goForward()
  228674. {
  228675. }
  228676. void WebBrowserComponent::refresh()
  228677. {
  228678. }
  228679. void WebBrowserComponent::paint (Graphics& g)
  228680. {
  228681. }
  228682. void WebBrowserComponent::checkWindowAssociation()
  228683. {
  228684. }
  228685. void WebBrowserComponent::reloadLastURL()
  228686. {
  228687. }
  228688. void WebBrowserComponent::parentHierarchyChanged()
  228689. {
  228690. }
  228691. void WebBrowserComponent::resized()
  228692. {
  228693. }
  228694. void WebBrowserComponent::visibilityChanged()
  228695. {
  228696. }
  228697. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228698. {
  228699. return true;
  228700. }
  228701. #endif
  228702. #endif
  228703. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228704. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  228705. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228706. // compiled on its own).
  228707. #if JUCE_INCLUDED_FILE
  228708. class IPhoneAudioIODevice : public AudioIODevice
  228709. {
  228710. public:
  228711. IPhoneAudioIODevice (const String& deviceName)
  228712. : AudioIODevice (deviceName, "Audio"),
  228713. actualBufferSize (0),
  228714. isRunning (false),
  228715. audioUnit (0),
  228716. callback (0),
  228717. floatData (1, 2)
  228718. {
  228719. numInputChannels = 2;
  228720. numOutputChannels = 2;
  228721. preferredBufferSize = 0;
  228722. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228723. updateDeviceInfo();
  228724. }
  228725. ~IPhoneAudioIODevice()
  228726. {
  228727. close();
  228728. }
  228729. const StringArray getOutputChannelNames()
  228730. {
  228731. StringArray s;
  228732. s.add ("Left");
  228733. s.add ("Right");
  228734. return s;
  228735. }
  228736. const StringArray getInputChannelNames()
  228737. {
  228738. StringArray s;
  228739. if (audioInputIsAvailable)
  228740. {
  228741. s.add ("Left");
  228742. s.add ("Right");
  228743. }
  228744. return s;
  228745. }
  228746. int getNumSampleRates()
  228747. {
  228748. return 1;
  228749. }
  228750. double getSampleRate (int index)
  228751. {
  228752. return sampleRate;
  228753. }
  228754. int getNumBufferSizesAvailable()
  228755. {
  228756. return 1;
  228757. }
  228758. int getBufferSizeSamples (int index)
  228759. {
  228760. return getDefaultBufferSize();
  228761. }
  228762. int getDefaultBufferSize()
  228763. {
  228764. return 1024;
  228765. }
  228766. const String open (const BigInteger& inputChannels,
  228767. const BigInteger& outputChannels,
  228768. double sampleRate,
  228769. int bufferSize)
  228770. {
  228771. close();
  228772. lastError = String::empty;
  228773. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228774. // xxx set up channel mapping
  228775. activeOutputChans = outputChannels;
  228776. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228777. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228778. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228779. activeInputChans = inputChannels;
  228780. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228781. numInputChannels = activeInputChans.countNumberOfSetBits();
  228782. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228783. AudioSessionSetActive (true);
  228784. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228785. : kAudioSessionCategory_MediaPlayback;
  228786. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228787. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228788. fixAudioRouteIfSetToReceiver();
  228789. updateDeviceInfo();
  228790. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228791. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228792. actualBufferSize = preferredBufferSize;
  228793. prepareFloatBuffers();
  228794. isRunning = true;
  228795. propertyChanged (0, 0, 0); // creates and starts the AU
  228796. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228797. return lastError;
  228798. }
  228799. void close()
  228800. {
  228801. if (isRunning)
  228802. {
  228803. isRunning = false;
  228804. AudioSessionSetActive (false);
  228805. if (audioUnit != 0)
  228806. {
  228807. AudioComponentInstanceDispose (audioUnit);
  228808. audioUnit = 0;
  228809. }
  228810. }
  228811. }
  228812. bool isOpen()
  228813. {
  228814. return isRunning;
  228815. }
  228816. int getCurrentBufferSizeSamples()
  228817. {
  228818. return actualBufferSize;
  228819. }
  228820. double getCurrentSampleRate()
  228821. {
  228822. return sampleRate;
  228823. }
  228824. int getCurrentBitDepth()
  228825. {
  228826. return 16;
  228827. }
  228828. const BigInteger getActiveOutputChannels() const
  228829. {
  228830. return activeOutputChans;
  228831. }
  228832. const BigInteger getActiveInputChannels() const
  228833. {
  228834. return activeInputChans;
  228835. }
  228836. int getOutputLatencyInSamples()
  228837. {
  228838. return 0; //xxx
  228839. }
  228840. int getInputLatencyInSamples()
  228841. {
  228842. return 0; //xxx
  228843. }
  228844. void start (AudioIODeviceCallback* callback_)
  228845. {
  228846. if (isRunning && callback != callback_)
  228847. {
  228848. if (callback_ != 0)
  228849. callback_->audioDeviceAboutToStart (this);
  228850. const ScopedLock sl (callbackLock);
  228851. callback = callback_;
  228852. }
  228853. }
  228854. void stop()
  228855. {
  228856. if (isRunning)
  228857. {
  228858. AudioIODeviceCallback* lastCallback;
  228859. {
  228860. const ScopedLock sl (callbackLock);
  228861. lastCallback = callback;
  228862. callback = 0;
  228863. }
  228864. if (lastCallback != 0)
  228865. lastCallback->audioDeviceStopped();
  228866. }
  228867. }
  228868. bool isPlaying()
  228869. {
  228870. return isRunning && callback != 0;
  228871. }
  228872. const String getLastError()
  228873. {
  228874. return lastError;
  228875. }
  228876. private:
  228877. CriticalSection callbackLock;
  228878. Float64 sampleRate;
  228879. int numInputChannels, numOutputChannels;
  228880. int preferredBufferSize;
  228881. int actualBufferSize;
  228882. bool isRunning;
  228883. String lastError;
  228884. AudioStreamBasicDescription format;
  228885. AudioUnit audioUnit;
  228886. UInt32 audioInputIsAvailable;
  228887. AudioIODeviceCallback* callback;
  228888. BigInteger activeOutputChans, activeInputChans;
  228889. AudioSampleBuffer floatData;
  228890. float* inputChannels[3];
  228891. float* outputChannels[3];
  228892. bool monoInputChannelNumber, monoOutputChannelNumber;
  228893. void prepareFloatBuffers()
  228894. {
  228895. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  228896. zerostruct (inputChannels);
  228897. zerostruct (outputChannels);
  228898. for (int i = 0; i < numInputChannels; ++i)
  228899. inputChannels[i] = floatData.getSampleData (i);
  228900. for (int i = 0; i < numOutputChannels; ++i)
  228901. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  228902. }
  228903. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228904. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228905. {
  228906. OSStatus err = noErr;
  228907. if (audioInputIsAvailable)
  228908. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  228909. const ScopedLock sl (callbackLock);
  228910. if (callback != 0)
  228911. {
  228912. if (audioInputIsAvailable && numInputChannels > 0)
  228913. {
  228914. short* shortData = (short*) ioData->mBuffers[0].mData;
  228915. if (numInputChannels >= 2)
  228916. {
  228917. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228918. {
  228919. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228920. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  228921. }
  228922. }
  228923. else
  228924. {
  228925. if (monoInputChannelNumber > 0)
  228926. ++shortData;
  228927. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228928. {
  228929. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228930. ++shortData;
  228931. }
  228932. }
  228933. }
  228934. else
  228935. {
  228936. for (int i = numInputChannels; --i >= 0;)
  228937. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  228938. }
  228939. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  228940. outputChannels, numOutputChannels,
  228941. (int) inNumberFrames);
  228942. short* shortData = (short*) ioData->mBuffers[0].mData;
  228943. int n = 0;
  228944. if (numOutputChannels >= 2)
  228945. {
  228946. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228947. {
  228948. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  228949. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  228950. }
  228951. }
  228952. else if (numOutputChannels == 1)
  228953. {
  228954. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228955. {
  228956. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  228957. shortData [n++] = s;
  228958. shortData [n++] = s;
  228959. }
  228960. }
  228961. else
  228962. {
  228963. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228964. }
  228965. }
  228966. else
  228967. {
  228968. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228969. }
  228970. return err;
  228971. }
  228972. void updateDeviceInfo()
  228973. {
  228974. UInt32 size = sizeof (sampleRate);
  228975. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  228976. size = sizeof (audioInputIsAvailable);
  228977. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  228978. }
  228979. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228980. {
  228981. if (! isRunning)
  228982. return;
  228983. if (inPropertyValue != 0)
  228984. {
  228985. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  228986. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  228987. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  228988. SInt32 routeChangeReason;
  228989. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  228990. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  228991. fixAudioRouteIfSetToReceiver();
  228992. }
  228993. updateDeviceInfo();
  228994. createAudioUnit();
  228995. AudioSessionSetActive (true);
  228996. if (audioUnit != 0)
  228997. {
  228998. UInt32 formatSize = sizeof (format);
  228999. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229000. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229001. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229002. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229003. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229004. AudioOutputUnitStart (audioUnit);
  229005. }
  229006. }
  229007. void interruptionListener (UInt32 inInterruption)
  229008. {
  229009. /*if (inInterruption == kAudioSessionBeginInterruption)
  229010. {
  229011. isRunning = false;
  229012. AudioOutputUnitStop (audioUnit);
  229013. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229014. "This could have been interrupted by another application or by unplugging a headset",
  229015. @"Resume",
  229016. @"Cancel"))
  229017. {
  229018. isRunning = true;
  229019. propertyChanged (0, 0, 0);
  229020. }
  229021. }*/
  229022. if (inInterruption == kAudioSessionEndInterruption)
  229023. {
  229024. isRunning = true;
  229025. AudioSessionSetActive (true);
  229026. AudioOutputUnitStart (audioUnit);
  229027. }
  229028. }
  229029. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229030. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229031. {
  229032. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229033. }
  229034. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229035. {
  229036. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229037. }
  229038. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229039. {
  229040. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229041. }
  229042. void resetFormat (const int numChannels)
  229043. {
  229044. memset (&format, 0, sizeof (format));
  229045. format.mFormatID = kAudioFormatLinearPCM;
  229046. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229047. format.mBitsPerChannel = 8 * sizeof (short);
  229048. format.mChannelsPerFrame = 2;
  229049. format.mFramesPerPacket = 1;
  229050. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229051. }
  229052. bool createAudioUnit()
  229053. {
  229054. if (audioUnit != 0)
  229055. {
  229056. AudioComponentInstanceDispose (audioUnit);
  229057. audioUnit = 0;
  229058. }
  229059. resetFormat (2);
  229060. AudioComponentDescription desc;
  229061. desc.componentType = kAudioUnitType_Output;
  229062. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229063. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229064. desc.componentFlags = 0;
  229065. desc.componentFlagsMask = 0;
  229066. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229067. AudioComponentInstanceNew (comp, &audioUnit);
  229068. if (audioUnit == 0)
  229069. return false;
  229070. const UInt32 one = 1;
  229071. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229072. AudioChannelLayout layout;
  229073. layout.mChannelBitmap = 0;
  229074. layout.mNumberChannelDescriptions = 0;
  229075. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229076. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229077. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229078. AURenderCallbackStruct inputProc;
  229079. inputProc.inputProc = processStatic;
  229080. inputProc.inputProcRefCon = this;
  229081. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229082. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229083. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229084. AudioUnitInitialize (audioUnit);
  229085. return true;
  229086. }
  229087. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229088. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229089. static void fixAudioRouteIfSetToReceiver()
  229090. {
  229091. CFStringRef audioRoute = 0;
  229092. UInt32 propertySize = sizeof (audioRoute);
  229093. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229094. {
  229095. NSString* route = (NSString*) audioRoute;
  229096. //DBG ("audio route: " + nsStringToJuce (route));
  229097. if ([route hasPrefix: @"Receiver"])
  229098. {
  229099. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229100. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229101. }
  229102. CFRelease (audioRoute);
  229103. }
  229104. }
  229105. JUCE_DECLARE_NON_COPYABLE (IPhoneAudioIODevice);
  229106. };
  229107. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229108. {
  229109. public:
  229110. IPhoneAudioIODeviceType()
  229111. : AudioIODeviceType ("iPhone Audio")
  229112. {
  229113. }
  229114. void scanForDevices()
  229115. {
  229116. }
  229117. const StringArray getDeviceNames (bool wantInputNames) const
  229118. {
  229119. StringArray s;
  229120. s.add ("iPhone Audio");
  229121. return s;
  229122. }
  229123. int getDefaultDeviceIndex (bool forInput) const
  229124. {
  229125. return 0;
  229126. }
  229127. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229128. {
  229129. return device != 0 ? 0 : -1;
  229130. }
  229131. bool hasSeparateInputsAndOutputs() const { return false; }
  229132. AudioIODevice* createDevice (const String& outputDeviceName,
  229133. const String& inputDeviceName)
  229134. {
  229135. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229136. {
  229137. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229138. : inputDeviceName);
  229139. }
  229140. return 0;
  229141. }
  229142. private:
  229143. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IPhoneAudioIODeviceType);
  229144. };
  229145. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229146. {
  229147. return new IPhoneAudioIODeviceType();
  229148. }
  229149. #endif
  229150. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229151. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229152. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229153. // compiled on its own).
  229154. #if JUCE_INCLUDED_FILE
  229155. #if JUCE_MAC
  229156. namespace CoreMidiHelpers
  229157. {
  229158. bool logError (const OSStatus err, const int lineNum)
  229159. {
  229160. if (err == noErr)
  229161. return true;
  229162. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229163. jassertfalse;
  229164. return false;
  229165. }
  229166. #undef CHECK_ERROR
  229167. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229168. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229169. {
  229170. String result;
  229171. CFStringRef str = 0;
  229172. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229173. if (str != 0)
  229174. {
  229175. result = PlatformUtilities::cfStringToJuceString (str);
  229176. CFRelease (str);
  229177. str = 0;
  229178. }
  229179. MIDIEntityRef entity = 0;
  229180. MIDIEndpointGetEntity (endpoint, &entity);
  229181. if (entity == 0)
  229182. return result; // probably virtual
  229183. if (result.isEmpty())
  229184. {
  229185. // endpoint name has zero length - try the entity
  229186. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229187. if (str != 0)
  229188. {
  229189. result += PlatformUtilities::cfStringToJuceString (str);
  229190. CFRelease (str);
  229191. str = 0;
  229192. }
  229193. }
  229194. // now consider the device's name
  229195. MIDIDeviceRef device = 0;
  229196. MIDIEntityGetDevice (entity, &device);
  229197. if (device == 0)
  229198. return result;
  229199. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229200. if (str != 0)
  229201. {
  229202. const String s (PlatformUtilities::cfStringToJuceString (str));
  229203. CFRelease (str);
  229204. // if an external device has only one entity, throw away
  229205. // the endpoint name and just use the device name
  229206. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229207. {
  229208. result = s;
  229209. }
  229210. else if (! result.startsWithIgnoreCase (s))
  229211. {
  229212. // prepend the device name to the entity name
  229213. result = (s + " " + result).trimEnd();
  229214. }
  229215. }
  229216. return result;
  229217. }
  229218. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229219. {
  229220. String result;
  229221. // Does the endpoint have connections?
  229222. CFDataRef connections = 0;
  229223. int numConnections = 0;
  229224. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229225. if (connections != 0)
  229226. {
  229227. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229228. if (numConnections > 0)
  229229. {
  229230. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229231. for (int i = 0; i < numConnections; ++i, ++pid)
  229232. {
  229233. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229234. MIDIObjectRef connObject;
  229235. MIDIObjectType connObjectType;
  229236. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229237. if (err == noErr)
  229238. {
  229239. String s;
  229240. if (connObjectType == kMIDIObjectType_ExternalSource
  229241. || connObjectType == kMIDIObjectType_ExternalDestination)
  229242. {
  229243. // Connected to an external device's endpoint (10.3 and later).
  229244. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229245. }
  229246. else
  229247. {
  229248. // Connected to an external device (10.2) (or something else, catch-all)
  229249. CFStringRef str = 0;
  229250. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229251. if (str != 0)
  229252. {
  229253. s = PlatformUtilities::cfStringToJuceString (str);
  229254. CFRelease (str);
  229255. }
  229256. }
  229257. if (s.isNotEmpty())
  229258. {
  229259. if (result.isNotEmpty())
  229260. result += ", ";
  229261. result += s;
  229262. }
  229263. }
  229264. }
  229265. }
  229266. CFRelease (connections);
  229267. }
  229268. if (result.isNotEmpty())
  229269. return result;
  229270. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229271. return getEndpointName (endpoint, false);
  229272. }
  229273. MIDIClientRef getGlobalMidiClient()
  229274. {
  229275. static MIDIClientRef globalMidiClient = 0;
  229276. if (globalMidiClient == 0)
  229277. {
  229278. String name ("JUCE");
  229279. if (JUCEApplication::getInstance() != 0)
  229280. name = JUCEApplication::getInstance()->getApplicationName();
  229281. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229282. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229283. CFRelease (appName);
  229284. }
  229285. return globalMidiClient;
  229286. }
  229287. class MidiPortAndEndpoint
  229288. {
  229289. public:
  229290. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229291. : port (port_), endPoint (endPoint_)
  229292. {
  229293. }
  229294. ~MidiPortAndEndpoint()
  229295. {
  229296. if (port != 0)
  229297. MIDIPortDispose (port);
  229298. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229299. MIDIEndpointDispose (endPoint);
  229300. }
  229301. void send (const MIDIPacketList* const packets)
  229302. {
  229303. if (port != 0)
  229304. MIDISend (port, endPoint, packets);
  229305. else
  229306. MIDIReceived (endPoint, packets);
  229307. }
  229308. MIDIPortRef port;
  229309. MIDIEndpointRef endPoint;
  229310. };
  229311. class MidiPortAndCallback;
  229312. CriticalSection callbackLock;
  229313. Array<MidiPortAndCallback*> activeCallbacks;
  229314. class MidiPortAndCallback
  229315. {
  229316. public:
  229317. MidiPortAndCallback (MidiInputCallback& callback_)
  229318. : input (0), active (false), callback (callback_), concatenator (2048)
  229319. {
  229320. }
  229321. ~MidiPortAndCallback()
  229322. {
  229323. active = false;
  229324. {
  229325. const ScopedLock sl (callbackLock);
  229326. activeCallbacks.removeValue (this);
  229327. }
  229328. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229329. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229330. }
  229331. void handlePackets (const MIDIPacketList* const pktlist)
  229332. {
  229333. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229334. const ScopedLock sl (callbackLock);
  229335. if (activeCallbacks.contains (this) && active)
  229336. {
  229337. const MIDIPacket* packet = &pktlist->packet[0];
  229338. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229339. {
  229340. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229341. input, callback);
  229342. packet = MIDIPacketNext (packet);
  229343. }
  229344. }
  229345. }
  229346. MidiInput* input;
  229347. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229348. volatile bool active;
  229349. private:
  229350. MidiInputCallback& callback;
  229351. MidiDataConcatenator concatenator;
  229352. };
  229353. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229354. {
  229355. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229356. }
  229357. }
  229358. const StringArray MidiOutput::getDevices()
  229359. {
  229360. StringArray s;
  229361. const ItemCount num = MIDIGetNumberOfDestinations();
  229362. for (ItemCount i = 0; i < num; ++i)
  229363. {
  229364. MIDIEndpointRef dest = MIDIGetDestination (i);
  229365. if (dest != 0)
  229366. {
  229367. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229368. if (name.isEmpty())
  229369. name = "<error>";
  229370. s.add (name);
  229371. }
  229372. else
  229373. {
  229374. s.add ("<error>");
  229375. }
  229376. }
  229377. return s;
  229378. }
  229379. int MidiOutput::getDefaultDeviceIndex()
  229380. {
  229381. return 0;
  229382. }
  229383. MidiOutput* MidiOutput::openDevice (int index)
  229384. {
  229385. MidiOutput* mo = 0;
  229386. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  229387. {
  229388. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229389. CFStringRef pname;
  229390. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229391. {
  229392. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229393. MIDIPortRef port;
  229394. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229395. {
  229396. mo = new MidiOutput();
  229397. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229398. }
  229399. CFRelease (pname);
  229400. }
  229401. }
  229402. return mo;
  229403. }
  229404. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229405. {
  229406. MidiOutput* mo = 0;
  229407. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229408. MIDIEndpointRef endPoint;
  229409. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229410. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229411. {
  229412. mo = new MidiOutput();
  229413. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229414. }
  229415. CFRelease (name);
  229416. return mo;
  229417. }
  229418. MidiOutput::~MidiOutput()
  229419. {
  229420. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229421. }
  229422. void MidiOutput::reset()
  229423. {
  229424. }
  229425. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229426. {
  229427. return false;
  229428. }
  229429. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229430. {
  229431. }
  229432. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229433. {
  229434. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229435. if (message.isSysEx())
  229436. {
  229437. const int maxPacketSize = 256;
  229438. int pos = 0, bytesLeft = message.getRawDataSize();
  229439. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229440. HeapBlock <MIDIPacketList> packets;
  229441. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229442. packets->numPackets = numPackets;
  229443. MIDIPacket* p = packets->packet;
  229444. for (int i = 0; i < numPackets; ++i)
  229445. {
  229446. p->timeStamp = AudioGetCurrentHostTime();
  229447. p->length = jmin (maxPacketSize, bytesLeft);
  229448. memcpy (p->data, message.getRawData() + pos, p->length);
  229449. pos += p->length;
  229450. bytesLeft -= p->length;
  229451. p = MIDIPacketNext (p);
  229452. }
  229453. mpe->send (packets);
  229454. }
  229455. else
  229456. {
  229457. MIDIPacketList packets;
  229458. packets.numPackets = 1;
  229459. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  229460. packets.packet[0].length = message.getRawDataSize();
  229461. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229462. mpe->send (&packets);
  229463. }
  229464. }
  229465. const StringArray MidiInput::getDevices()
  229466. {
  229467. StringArray s;
  229468. const ItemCount num = MIDIGetNumberOfSources();
  229469. for (ItemCount i = 0; i < num; ++i)
  229470. {
  229471. MIDIEndpointRef source = MIDIGetSource (i);
  229472. if (source != 0)
  229473. {
  229474. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229475. if (name.isEmpty())
  229476. name = "<error>";
  229477. s.add (name);
  229478. }
  229479. else
  229480. {
  229481. s.add ("<error>");
  229482. }
  229483. }
  229484. return s;
  229485. }
  229486. int MidiInput::getDefaultDeviceIndex()
  229487. {
  229488. return 0;
  229489. }
  229490. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229491. {
  229492. jassert (callback != 0);
  229493. using namespace CoreMidiHelpers;
  229494. MidiInput* newInput = 0;
  229495. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  229496. {
  229497. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229498. if (endPoint != 0)
  229499. {
  229500. CFStringRef name;
  229501. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229502. {
  229503. MIDIClientRef client = getGlobalMidiClient();
  229504. if (client != 0)
  229505. {
  229506. MIDIPortRef port;
  229507. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229508. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229509. {
  229510. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229511. {
  229512. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229513. newInput = new MidiInput (getDevices() [index]);
  229514. mpc->input = newInput;
  229515. newInput->internal = mpc;
  229516. const ScopedLock sl (callbackLock);
  229517. activeCallbacks.add (mpc.release());
  229518. }
  229519. else
  229520. {
  229521. CHECK_ERROR (MIDIPortDispose (port));
  229522. }
  229523. }
  229524. }
  229525. }
  229526. CFRelease (name);
  229527. }
  229528. }
  229529. return newInput;
  229530. }
  229531. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229532. {
  229533. jassert (callback != 0);
  229534. using namespace CoreMidiHelpers;
  229535. MidiInput* mi = 0;
  229536. MIDIClientRef client = getGlobalMidiClient();
  229537. if (client != 0)
  229538. {
  229539. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229540. mpc->active = false;
  229541. MIDIEndpointRef endPoint;
  229542. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229543. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229544. {
  229545. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229546. mi = new MidiInput (deviceName);
  229547. mpc->input = mi;
  229548. mi->internal = mpc;
  229549. const ScopedLock sl (callbackLock);
  229550. activeCallbacks.add (mpc.release());
  229551. }
  229552. CFRelease (name);
  229553. }
  229554. return mi;
  229555. }
  229556. MidiInput::MidiInput (const String& name_)
  229557. : name (name_)
  229558. {
  229559. }
  229560. MidiInput::~MidiInput()
  229561. {
  229562. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229563. }
  229564. void MidiInput::start()
  229565. {
  229566. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229567. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229568. }
  229569. void MidiInput::stop()
  229570. {
  229571. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229572. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229573. }
  229574. #undef CHECK_ERROR
  229575. #else // Stubs for iOS...
  229576. MidiOutput::~MidiOutput() {}
  229577. void MidiOutput::reset() {}
  229578. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229579. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229580. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229581. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229582. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229583. const StringArray MidiInput::getDevices() { return StringArray(); }
  229584. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229585. #endif
  229586. #endif
  229587. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229588. #else
  229589. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229590. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229591. // compiled on its own).
  229592. #if JUCE_INCLUDED_FILE
  229593. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229594. #define SUPPORT_10_4_FONTS 1
  229595. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229596. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229597. #define SUPPORT_ONLY_10_4_FONTS 1
  229598. #endif
  229599. END_JUCE_NAMESPACE
  229600. @interface NSFont (PrivateHack)
  229601. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229602. @end
  229603. BEGIN_JUCE_NAMESPACE
  229604. #endif
  229605. class MacTypeface : public Typeface
  229606. {
  229607. public:
  229608. MacTypeface (const Font& font)
  229609. : Typeface (font.getTypefaceName())
  229610. {
  229611. const ScopedAutoReleasePool pool;
  229612. renderingTransform = CGAffineTransformIdentity;
  229613. bool needsItalicTransform = false;
  229614. #if JUCE_IOS
  229615. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229616. if (font.isItalic() || font.isBold())
  229617. {
  229618. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229619. for (NSString* i in familyFonts)
  229620. {
  229621. const String fn (nsStringToJuce (i));
  229622. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229623. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229624. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229625. || afterDash.containsIgnoreCase ("italic")
  229626. || fn.endsWithIgnoreCase ("oblique")
  229627. || fn.endsWithIgnoreCase ("italic");
  229628. if (probablyBold == font.isBold()
  229629. && probablyItalic == font.isItalic())
  229630. {
  229631. fontName = i;
  229632. needsItalicTransform = false;
  229633. break;
  229634. }
  229635. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229636. {
  229637. fontName = i;
  229638. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229639. }
  229640. }
  229641. if (needsItalicTransform)
  229642. renderingTransform.c = 0.15f;
  229643. }
  229644. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229645. const int ascender = abs (CGFontGetAscent (fontRef));
  229646. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229647. ascent = ascender / totalHeight;
  229648. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229649. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229650. #else
  229651. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229652. if (font.isItalic())
  229653. {
  229654. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229655. toHaveTrait: NSItalicFontMask];
  229656. if (newFont == nsFont)
  229657. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229658. nsFont = newFont;
  229659. }
  229660. if (font.isBold())
  229661. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229662. [nsFont retain];
  229663. ascent = std::abs ((float) [nsFont ascender]);
  229664. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229665. ascent /= totalSize;
  229666. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229667. if (needsItalicTransform)
  229668. {
  229669. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229670. renderingTransform.c = 0.15f;
  229671. }
  229672. #if SUPPORT_ONLY_10_4_FONTS
  229673. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229674. if (atsFont == 0)
  229675. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229676. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229677. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229678. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229679. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229680. #else
  229681. #if SUPPORT_10_4_FONTS
  229682. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229683. {
  229684. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229685. if (atsFont == 0)
  229686. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229687. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229688. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229689. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229690. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229691. }
  229692. else
  229693. #endif
  229694. {
  229695. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229696. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229697. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229698. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229699. }
  229700. #endif
  229701. #endif
  229702. }
  229703. ~MacTypeface()
  229704. {
  229705. #if ! JUCE_IOS
  229706. [nsFont release];
  229707. #endif
  229708. if (fontRef != 0)
  229709. CGFontRelease (fontRef);
  229710. }
  229711. float getAscent() const
  229712. {
  229713. return ascent;
  229714. }
  229715. float getDescent() const
  229716. {
  229717. return 1.0f - ascent;
  229718. }
  229719. float getStringWidth (const String& text)
  229720. {
  229721. if (fontRef == 0 || text.isEmpty())
  229722. return 0;
  229723. const int length = text.length();
  229724. HeapBlock <CGGlyph> glyphs;
  229725. createGlyphsForString (text, length, glyphs);
  229726. float x = 0;
  229727. #if SUPPORT_ONLY_10_4_FONTS
  229728. HeapBlock <NSSize> advances (length);
  229729. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229730. for (int i = 0; i < length; ++i)
  229731. x += advances[i].width;
  229732. #else
  229733. #if SUPPORT_10_4_FONTS
  229734. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229735. {
  229736. HeapBlock <NSSize> advances (length);
  229737. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229738. for (int i = 0; i < length; ++i)
  229739. x += advances[i].width;
  229740. }
  229741. else
  229742. #endif
  229743. {
  229744. HeapBlock <int> advances (length);
  229745. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229746. for (int i = 0; i < length; ++i)
  229747. x += advances[i];
  229748. }
  229749. #endif
  229750. return x * unitsToHeightScaleFactor;
  229751. }
  229752. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229753. {
  229754. xOffsets.add (0);
  229755. if (fontRef == 0 || text.isEmpty())
  229756. return;
  229757. const int length = text.length();
  229758. HeapBlock <CGGlyph> glyphs;
  229759. createGlyphsForString (text, length, glyphs);
  229760. #if SUPPORT_ONLY_10_4_FONTS
  229761. HeapBlock <NSSize> advances (length);
  229762. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229763. int x = 0;
  229764. for (int i = 0; i < length; ++i)
  229765. {
  229766. x += advances[i].width;
  229767. xOffsets.add (x * unitsToHeightScaleFactor);
  229768. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  229769. }
  229770. #else
  229771. #if SUPPORT_10_4_FONTS
  229772. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229773. {
  229774. HeapBlock <NSSize> advances (length);
  229775. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229776. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  229777. float x = 0;
  229778. for (int i = 0; i < length; ++i)
  229779. {
  229780. x += advances[i].width;
  229781. xOffsets.add (x * unitsToHeightScaleFactor);
  229782. resultGlyphs.add (nsGlyphs[i]);
  229783. }
  229784. }
  229785. else
  229786. #endif
  229787. {
  229788. HeapBlock <int> advances (length);
  229789. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229790. {
  229791. int x = 0;
  229792. for (int i = 0; i < length; ++i)
  229793. {
  229794. x += advances [i];
  229795. xOffsets.add (x * unitsToHeightScaleFactor);
  229796. resultGlyphs.add (glyphs[i]);
  229797. }
  229798. }
  229799. }
  229800. #endif
  229801. }
  229802. bool getOutlineForGlyph (int glyphNumber, Path& path)
  229803. {
  229804. #if JUCE_IOS
  229805. return false;
  229806. #else
  229807. if (nsFont == 0)
  229808. return false;
  229809. // we might need to apply a transform to the path, so it mustn't have anything else in it
  229810. jassert (path.isEmpty());
  229811. const ScopedAutoReleasePool pool;
  229812. NSBezierPath* bez = [NSBezierPath bezierPath];
  229813. [bez moveToPoint: NSMakePoint (0, 0)];
  229814. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  229815. inFont: nsFont];
  229816. for (int i = 0; i < [bez elementCount]; ++i)
  229817. {
  229818. NSPoint p[3];
  229819. switch ([bez elementAtIndex: i associatedPoints: p])
  229820. {
  229821. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  229822. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  229823. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  229824. (float) p[1].x, (float) -p[1].y,
  229825. (float) p[2].x, (float) -p[2].y); break;
  229826. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  229827. default: jassertfalse; break;
  229828. }
  229829. }
  229830. path.applyTransform (pathTransform);
  229831. return true;
  229832. #endif
  229833. }
  229834. CGFontRef fontRef;
  229835. float fontHeightToCGSizeFactor;
  229836. CGAffineTransform renderingTransform;
  229837. private:
  229838. float ascent, unitsToHeightScaleFactor;
  229839. #if JUCE_IOS
  229840. #else
  229841. NSFont* nsFont;
  229842. AffineTransform pathTransform;
  229843. #endif
  229844. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  229845. {
  229846. #if SUPPORT_10_4_FONTS
  229847. #if ! SUPPORT_ONLY_10_4_FONTS
  229848. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229849. #endif
  229850. {
  229851. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  229852. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229853. for (int i = 0; i < length; ++i)
  229854. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  229855. return;
  229856. }
  229857. #endif
  229858. #if ! SUPPORT_ONLY_10_4_FONTS
  229859. if (charToGlyphMapper == 0)
  229860. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  229861. glyphs.malloc (length);
  229862. for (int i = 0; i < length; ++i)
  229863. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  229864. #endif
  229865. }
  229866. #if ! SUPPORT_ONLY_10_4_FONTS
  229867. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  229868. class CharToGlyphMapper
  229869. {
  229870. public:
  229871. CharToGlyphMapper (CGFontRef fontRef)
  229872. : segCount (0), endCode (0), startCode (0), idDelta (0),
  229873. idRangeOffset (0), glyphIndexes (0)
  229874. {
  229875. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  229876. if (cmapTable != 0)
  229877. {
  229878. const int numSubtables = getValue16 (cmapTable, 2);
  229879. for (int i = 0; i < numSubtables; ++i)
  229880. {
  229881. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  229882. {
  229883. const int offset = getValue32 (cmapTable, i * 8 + 8);
  229884. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  229885. {
  229886. const int length = getValue16 (cmapTable, offset + 2);
  229887. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  229888. segCount = segCountX2 / 2;
  229889. const int endCodeOffset = offset + 14;
  229890. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  229891. const int idDeltaOffset = startCodeOffset + segCountX2;
  229892. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  229893. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  229894. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  229895. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  229896. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  229897. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  229898. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  229899. }
  229900. break;
  229901. }
  229902. }
  229903. CFRelease (cmapTable);
  229904. }
  229905. }
  229906. ~CharToGlyphMapper()
  229907. {
  229908. if (endCode != 0)
  229909. {
  229910. CFRelease (endCode);
  229911. CFRelease (startCode);
  229912. CFRelease (idDelta);
  229913. CFRelease (idRangeOffset);
  229914. CFRelease (glyphIndexes);
  229915. }
  229916. }
  229917. int getGlyphForCharacter (const juce_wchar c) const
  229918. {
  229919. for (int i = 0; i < segCount; ++i)
  229920. {
  229921. if (getValue16 (endCode, i * 2) >= c)
  229922. {
  229923. const int start = getValue16 (startCode, i * 2);
  229924. if (start > c)
  229925. break;
  229926. const int delta = getValue16 (idDelta, i * 2);
  229927. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  229928. if (rangeOffset == 0)
  229929. return delta + c;
  229930. else
  229931. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  229932. }
  229933. }
  229934. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  229935. return jmax (-1, (int) c - 29);
  229936. }
  229937. private:
  229938. int segCount;
  229939. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  229940. static uint16 getValue16 (CFDataRef data, const int index)
  229941. {
  229942. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  229943. }
  229944. static uint32 getValue32 (CFDataRef data, const int index)
  229945. {
  229946. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  229947. }
  229948. };
  229949. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  229950. #endif
  229951. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  229952. };
  229953. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  229954. {
  229955. return new MacTypeface (font);
  229956. }
  229957. const StringArray Font::findAllTypefaceNames()
  229958. {
  229959. StringArray names;
  229960. const ScopedAutoReleasePool pool;
  229961. #if JUCE_IOS
  229962. NSArray* fonts = [UIFont familyNames];
  229963. #else
  229964. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  229965. #endif
  229966. for (unsigned int i = 0; i < [fonts count]; ++i)
  229967. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  229968. names.sort (true);
  229969. return names;
  229970. }
  229971. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  229972. {
  229973. #if JUCE_IOS
  229974. defaultSans = "Helvetica";
  229975. defaultSerif = "Times New Roman";
  229976. defaultFixed = "Courier New";
  229977. #else
  229978. defaultSans = "Lucida Grande";
  229979. defaultSerif = "Times New Roman";
  229980. defaultFixed = "Monaco";
  229981. #endif
  229982. defaultFallback = "Arial Unicode MS";
  229983. }
  229984. #endif
  229985. /*** End of inlined file: juce_mac_Fonts.mm ***/
  229986. // (must go before juce_mac_CoreGraphicsContext.mm)
  229987. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229988. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229989. // compiled on its own).
  229990. #if JUCE_INCLUDED_FILE
  229991. class CoreGraphicsImage : public Image::SharedImage
  229992. {
  229993. public:
  229994. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  229995. : Image::SharedImage (format_, width_, height_)
  229996. {
  229997. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  229998. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  229999. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230000. imageData = imageDataAllocated;
  230001. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230002. : CGColorSpaceCreateDeviceRGB();
  230003. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230004. colourSpace, getCGImageFlags (format_));
  230005. CGColorSpaceRelease (colourSpace);
  230006. }
  230007. ~CoreGraphicsImage()
  230008. {
  230009. CGContextRelease (context);
  230010. }
  230011. Image::ImageType getType() const { return Image::NativeImage; }
  230012. LowLevelGraphicsContext* createLowLevelContext();
  230013. SharedImage* clone()
  230014. {
  230015. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230016. memcpy (im->imageData, imageData, lineStride * height);
  230017. return im;
  230018. }
  230019. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230020. {
  230021. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230022. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230023. {
  230024. return CGBitmapContextCreateImage (nativeImage->context);
  230025. }
  230026. else
  230027. {
  230028. const Image::BitmapData srcData (juceImage, false);
  230029. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230030. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230031. 8, srcData.pixelStride * 8, srcData.lineStride,
  230032. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230033. 0, true, kCGRenderingIntentDefault);
  230034. CGDataProviderRelease (provider);
  230035. return imageRef;
  230036. }
  230037. }
  230038. #if JUCE_MAC
  230039. static NSImage* createNSImage (const Image& image)
  230040. {
  230041. const ScopedAutoReleasePool pool;
  230042. NSImage* im = [[NSImage alloc] init];
  230043. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230044. [im lockFocus];
  230045. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230046. CGImageRef imageRef = createImage (image, false, colourSpace);
  230047. CGColorSpaceRelease (colourSpace);
  230048. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230049. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230050. CGImageRelease (imageRef);
  230051. [im unlockFocus];
  230052. return im;
  230053. }
  230054. #endif
  230055. CGContextRef context;
  230056. HeapBlock<uint8> imageDataAllocated;
  230057. private:
  230058. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230059. {
  230060. #if JUCE_BIG_ENDIAN
  230061. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230062. #else
  230063. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230064. #endif
  230065. }
  230066. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  230067. };
  230068. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230069. {
  230070. #if USE_COREGRAPHICS_RENDERING
  230071. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230072. #else
  230073. return createSoftwareImage (format, width, height, clearImage);
  230074. #endif
  230075. }
  230076. class CoreGraphicsContext : public LowLevelGraphicsContext
  230077. {
  230078. public:
  230079. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230080. : context (context_),
  230081. flipHeight (flipHeight_),
  230082. lastClipRectIsValid (false),
  230083. state (new SavedState()),
  230084. numGradientLookupEntries (0)
  230085. {
  230086. CGContextRetain (context);
  230087. CGContextSaveGState(context);
  230088. CGContextSetShouldSmoothFonts (context, true);
  230089. CGContextSetShouldAntialias (context, true);
  230090. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230091. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230092. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230093. gradientCallbacks.version = 0;
  230094. gradientCallbacks.evaluate = gradientCallback;
  230095. gradientCallbacks.releaseInfo = 0;
  230096. setFont (Font());
  230097. }
  230098. ~CoreGraphicsContext()
  230099. {
  230100. CGContextRestoreGState (context);
  230101. CGContextRelease (context);
  230102. CGColorSpaceRelease (rgbColourSpace);
  230103. CGColorSpaceRelease (greyColourSpace);
  230104. }
  230105. bool isVectorDevice() const { return false; }
  230106. void setOrigin (int x, int y)
  230107. {
  230108. CGContextTranslateCTM (context, x, -y);
  230109. if (lastClipRectIsValid)
  230110. lastClipRect.translate (-x, -y);
  230111. }
  230112. void addTransform (const AffineTransform& transform)
  230113. {
  230114. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  230115. .translated (0, flipHeight)
  230116. .followedBy (transform)
  230117. .translated (0, -flipHeight)
  230118. .scaled (1.0f, -1.0f));
  230119. lastClipRectIsValid = false;
  230120. }
  230121. float getScaleFactor()
  230122. {
  230123. CGAffineTransform t = CGContextGetCTM (context);
  230124. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  230125. }
  230126. bool clipToRectangle (const Rectangle<int>& r)
  230127. {
  230128. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230129. if (lastClipRectIsValid)
  230130. {
  230131. // This is actually incorrect, because the actual clip region may be complex, and
  230132. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230133. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230134. // when calculating the resultant clip bounds, and makes the same mistake!
  230135. lastClipRect = lastClipRect.getIntersection (r);
  230136. return ! lastClipRect.isEmpty();
  230137. }
  230138. return ! isClipEmpty();
  230139. }
  230140. bool clipToRectangleList (const RectangleList& clipRegion)
  230141. {
  230142. if (clipRegion.isEmpty())
  230143. {
  230144. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230145. lastClipRectIsValid = true;
  230146. lastClipRect = Rectangle<int>();
  230147. return false;
  230148. }
  230149. else
  230150. {
  230151. const int numRects = clipRegion.getNumRectangles();
  230152. HeapBlock <CGRect> rects (numRects);
  230153. for (int i = 0; i < numRects; ++i)
  230154. {
  230155. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230156. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230157. }
  230158. CGContextClipToRects (context, rects, numRects);
  230159. lastClipRectIsValid = false;
  230160. return ! isClipEmpty();
  230161. }
  230162. }
  230163. void excludeClipRectangle (const Rectangle<int>& r)
  230164. {
  230165. RectangleList remaining (getClipBounds());
  230166. remaining.subtract (r);
  230167. clipToRectangleList (remaining);
  230168. lastClipRectIsValid = false;
  230169. }
  230170. void clipToPath (const Path& path, const AffineTransform& transform)
  230171. {
  230172. createPath (path, transform);
  230173. CGContextClip (context);
  230174. lastClipRectIsValid = false;
  230175. }
  230176. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230177. {
  230178. if (! transform.isSingularity())
  230179. {
  230180. Image singleChannelImage (sourceImage);
  230181. if (sourceImage.getFormat() != Image::SingleChannel)
  230182. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230183. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230184. flip();
  230185. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230186. applyTransform (t);
  230187. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230188. CGContextClipToMask (context, r, image);
  230189. applyTransform (t.inverted());
  230190. flip();
  230191. CGImageRelease (image);
  230192. lastClipRectIsValid = false;
  230193. }
  230194. }
  230195. bool clipRegionIntersects (const Rectangle<int>& r)
  230196. {
  230197. return getClipBounds().intersects (r);
  230198. }
  230199. const Rectangle<int> getClipBounds() const
  230200. {
  230201. if (! lastClipRectIsValid)
  230202. {
  230203. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230204. lastClipRectIsValid = true;
  230205. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230206. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230207. roundToInt (bounds.size.width),
  230208. roundToInt (bounds.size.height));
  230209. }
  230210. return lastClipRect;
  230211. }
  230212. bool isClipEmpty() const
  230213. {
  230214. return getClipBounds().isEmpty();
  230215. }
  230216. void saveState()
  230217. {
  230218. CGContextSaveGState (context);
  230219. stateStack.add (new SavedState (*state));
  230220. }
  230221. void restoreState()
  230222. {
  230223. CGContextRestoreGState (context);
  230224. SavedState* const top = stateStack.getLast();
  230225. if (top != 0)
  230226. {
  230227. state = top;
  230228. stateStack.removeLast (1, false);
  230229. lastClipRectIsValid = false;
  230230. }
  230231. else
  230232. {
  230233. jassertfalse; // trying to pop with an empty stack!
  230234. }
  230235. }
  230236. void beginTransparencyLayer (float opacity)
  230237. {
  230238. saveState();
  230239. CGContextSetAlpha (context, opacity);
  230240. CGContextBeginTransparencyLayer (context, 0);
  230241. }
  230242. void endTransparencyLayer()
  230243. {
  230244. CGContextEndTransparencyLayer (context);
  230245. restoreState();
  230246. }
  230247. void setFill (const FillType& fillType)
  230248. {
  230249. state->fillType = fillType;
  230250. if (fillType.isColour())
  230251. {
  230252. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230253. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230254. CGContextSetAlpha (context, 1.0f);
  230255. }
  230256. }
  230257. void setOpacity (float newOpacity)
  230258. {
  230259. state->fillType.setOpacity (newOpacity);
  230260. setFill (state->fillType);
  230261. }
  230262. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230263. {
  230264. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230265. ? kCGInterpolationLow
  230266. : kCGInterpolationHigh);
  230267. }
  230268. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230269. {
  230270. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230271. }
  230272. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230273. {
  230274. if (replaceExistingContents)
  230275. {
  230276. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230277. CGContextClearRect (context, cgRect);
  230278. #else
  230279. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230280. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230281. CGContextClearRect (context, cgRect);
  230282. else
  230283. #endif
  230284. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230285. #endif
  230286. fillCGRect (cgRect, false);
  230287. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230288. }
  230289. else
  230290. {
  230291. if (state->fillType.isColour())
  230292. {
  230293. CGContextFillRect (context, cgRect);
  230294. }
  230295. else if (state->fillType.isGradient())
  230296. {
  230297. CGContextSaveGState (context);
  230298. CGContextClipToRect (context, cgRect);
  230299. drawGradient();
  230300. CGContextRestoreGState (context);
  230301. }
  230302. else
  230303. {
  230304. CGContextSaveGState (context);
  230305. CGContextClipToRect (context, cgRect);
  230306. drawImage (state->fillType.image, state->fillType.transform, true);
  230307. CGContextRestoreGState (context);
  230308. }
  230309. }
  230310. }
  230311. void fillPath (const Path& path, const AffineTransform& transform)
  230312. {
  230313. CGContextSaveGState (context);
  230314. if (state->fillType.isColour())
  230315. {
  230316. flip();
  230317. applyTransform (transform);
  230318. createPath (path);
  230319. if (path.isUsingNonZeroWinding())
  230320. CGContextFillPath (context);
  230321. else
  230322. CGContextEOFillPath (context);
  230323. }
  230324. else
  230325. {
  230326. createPath (path, transform);
  230327. if (path.isUsingNonZeroWinding())
  230328. CGContextClip (context);
  230329. else
  230330. CGContextEOClip (context);
  230331. if (state->fillType.isGradient())
  230332. drawGradient();
  230333. else
  230334. drawImage (state->fillType.image, state->fillType.transform, true);
  230335. }
  230336. CGContextRestoreGState (context);
  230337. }
  230338. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230339. {
  230340. const int iw = sourceImage.getWidth();
  230341. const int ih = sourceImage.getHeight();
  230342. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230343. CGContextSaveGState (context);
  230344. CGContextSetAlpha (context, state->fillType.getOpacity());
  230345. flip();
  230346. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230347. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230348. if (fillEntireClipAsTiles)
  230349. {
  230350. #if JUCE_IOS
  230351. CGContextDrawTiledImage (context, imageRect, image);
  230352. #else
  230353. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230354. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230355. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230356. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230357. CGContextDrawTiledImage (context, imageRect, image);
  230358. else
  230359. #endif
  230360. {
  230361. // Fallback to manually doing a tiled fill on 10.4
  230362. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230363. int x = 0, y = 0;
  230364. while (x > clip.origin.x) x -= iw;
  230365. while (y > clip.origin.y) y -= ih;
  230366. const int right = (int) (clip.origin.x + clip.size.width);
  230367. const int bottom = (int) (clip.origin.y + clip.size.height);
  230368. while (y < bottom)
  230369. {
  230370. for (int x2 = x; x2 < right; x2 += iw)
  230371. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230372. y += ih;
  230373. }
  230374. }
  230375. #endif
  230376. }
  230377. else
  230378. {
  230379. CGContextDrawImage (context, imageRect, image);
  230380. }
  230381. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230382. CGContextRestoreGState (context);
  230383. }
  230384. void drawLine (const Line<float>& line)
  230385. {
  230386. if (state->fillType.isColour())
  230387. {
  230388. CGContextSetLineCap (context, kCGLineCapSquare);
  230389. CGContextSetLineWidth (context, 1.0f);
  230390. CGContextSetRGBStrokeColor (context,
  230391. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230392. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230393. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230394. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230395. CGContextStrokeLineSegments (context, cgLine, 1);
  230396. }
  230397. else
  230398. {
  230399. Path p;
  230400. p.addLineSegment (line, 1.0f);
  230401. fillPath (p, AffineTransform::identity);
  230402. }
  230403. }
  230404. void drawVerticalLine (const int x, float top, float bottom)
  230405. {
  230406. if (state->fillType.isColour())
  230407. {
  230408. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230409. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230410. #else
  230411. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230412. // the x co-ord slightly to trick it..
  230413. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230414. #endif
  230415. }
  230416. else
  230417. {
  230418. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230419. }
  230420. }
  230421. void drawHorizontalLine (const int y, float left, float right)
  230422. {
  230423. if (state->fillType.isColour())
  230424. {
  230425. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230426. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230427. #else
  230428. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230429. // the x co-ord slightly to trick it..
  230430. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230431. #endif
  230432. }
  230433. else
  230434. {
  230435. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230436. }
  230437. }
  230438. void setFont (const Font& newFont)
  230439. {
  230440. if (state->font != newFont)
  230441. {
  230442. state->fontRef = 0;
  230443. state->font = newFont;
  230444. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230445. if (mf != 0)
  230446. {
  230447. state->fontRef = mf->fontRef;
  230448. CGContextSetFont (context, state->fontRef);
  230449. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230450. state->fontTransform = mf->renderingTransform;
  230451. state->fontTransform.a *= state->font.getHorizontalScale();
  230452. CGContextSetTextMatrix (context, state->fontTransform);
  230453. }
  230454. }
  230455. }
  230456. const Font getFont()
  230457. {
  230458. return state->font;
  230459. }
  230460. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230461. {
  230462. if (state->fontRef != 0 && state->fillType.isColour())
  230463. {
  230464. if (transform.isOnlyTranslation())
  230465. {
  230466. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230467. CGGlyph g = glyphNumber;
  230468. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230469. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230470. }
  230471. else
  230472. {
  230473. CGContextSaveGState (context);
  230474. flip();
  230475. applyTransform (transform);
  230476. CGAffineTransform t = state->fontTransform;
  230477. t.d = -t.d;
  230478. CGContextSetTextMatrix (context, t);
  230479. CGGlyph g = glyphNumber;
  230480. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230481. CGContextRestoreGState (context);
  230482. }
  230483. }
  230484. else
  230485. {
  230486. Path p;
  230487. Font& f = state->font;
  230488. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230489. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230490. .followedBy (transform));
  230491. }
  230492. }
  230493. private:
  230494. CGContextRef context;
  230495. const CGFloat flipHeight;
  230496. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230497. CGFunctionCallbacks gradientCallbacks;
  230498. mutable Rectangle<int> lastClipRect;
  230499. mutable bool lastClipRectIsValid;
  230500. struct SavedState
  230501. {
  230502. SavedState()
  230503. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230504. {
  230505. }
  230506. SavedState (const SavedState& other)
  230507. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230508. fontTransform (other.fontTransform)
  230509. {
  230510. }
  230511. FillType fillType;
  230512. Font font;
  230513. CGFontRef fontRef;
  230514. CGAffineTransform fontTransform;
  230515. };
  230516. ScopedPointer <SavedState> state;
  230517. OwnedArray <SavedState> stateStack;
  230518. HeapBlock <PixelARGB> gradientLookupTable;
  230519. int numGradientLookupEntries;
  230520. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230521. {
  230522. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230523. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230524. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230525. colour.unpremultiply();
  230526. outData[0] = colour.getRed() / 255.0f;
  230527. outData[1] = colour.getGreen() / 255.0f;
  230528. outData[2] = colour.getBlue() / 255.0f;
  230529. outData[3] = colour.getAlpha() / 255.0f;
  230530. }
  230531. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230532. {
  230533. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  230534. CGShadingRef result = 0;
  230535. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230536. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230537. if (gradient.isRadial)
  230538. {
  230539. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230540. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230541. function, true, true);
  230542. }
  230543. else
  230544. {
  230545. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230546. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230547. function, true, true);
  230548. }
  230549. CGFunctionRelease (function);
  230550. return result;
  230551. }
  230552. void drawGradient()
  230553. {
  230554. flip();
  230555. applyTransform (state->fillType.transform);
  230556. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230557. // you draw a gradient with high quality interp enabled).
  230558. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230559. CGContextSetAlpha (context, state->fillType.getOpacity());
  230560. CGContextDrawShading (context, shading);
  230561. CGShadingRelease (shading);
  230562. }
  230563. void createPath (const Path& path) const
  230564. {
  230565. CGContextBeginPath (context);
  230566. Path::Iterator i (path);
  230567. while (i.next())
  230568. {
  230569. switch (i.elementType)
  230570. {
  230571. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230572. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230573. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230574. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230575. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230576. default: jassertfalse; break;
  230577. }
  230578. }
  230579. }
  230580. void createPath (const Path& path, const AffineTransform& transform) const
  230581. {
  230582. CGContextBeginPath (context);
  230583. Path::Iterator i (path);
  230584. while (i.next())
  230585. {
  230586. switch (i.elementType)
  230587. {
  230588. case Path::Iterator::startNewSubPath:
  230589. transform.transformPoint (i.x1, i.y1);
  230590. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230591. break;
  230592. case Path::Iterator::lineTo:
  230593. transform.transformPoint (i.x1, i.y1);
  230594. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230595. break;
  230596. case Path::Iterator::quadraticTo:
  230597. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230598. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230599. break;
  230600. case Path::Iterator::cubicTo:
  230601. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230602. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230603. break;
  230604. case Path::Iterator::closePath:
  230605. CGContextClosePath (context); break;
  230606. default:
  230607. jassertfalse;
  230608. break;
  230609. }
  230610. }
  230611. }
  230612. void flip() const
  230613. {
  230614. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230615. }
  230616. void applyTransform (const AffineTransform& transform) const
  230617. {
  230618. CGAffineTransform t;
  230619. t.a = transform.mat00;
  230620. t.b = transform.mat10;
  230621. t.c = transform.mat01;
  230622. t.d = transform.mat11;
  230623. t.tx = transform.mat02;
  230624. t.ty = transform.mat12;
  230625. CGContextConcatCTM (context, t);
  230626. }
  230627. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  230628. };
  230629. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230630. {
  230631. return new CoreGraphicsContext (context, height);
  230632. }
  230633. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230634. const Image juce_loadWithCoreImage (InputStream& input)
  230635. {
  230636. MemoryBlock data;
  230637. input.readIntoMemoryBlock (data, -1);
  230638. #if JUCE_IOS
  230639. JUCE_AUTORELEASEPOOL
  230640. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230641. length: data.getSize()
  230642. freeWhenDone: NO]];
  230643. if (image != nil)
  230644. {
  230645. CGImageRef loadedImage = image.CGImage;
  230646. #else
  230647. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230648. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230649. CGDataProviderRelease (provider);
  230650. if (imageSource != 0)
  230651. {
  230652. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230653. CFRelease (imageSource);
  230654. #endif
  230655. if (loadedImage != 0)
  230656. {
  230657. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  230658. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  230659. && alphaInfo != kCGImageAlphaNoneSkipLast
  230660. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  230661. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  230662. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230663. hasAlphaChan, Image::NativeImage);
  230664. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230665. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230666. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230667. CGContextFlush (cgImage->context);
  230668. #if ! JUCE_IOS
  230669. CFRelease (loadedImage);
  230670. #endif
  230671. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  230672. // to find out whether the file they just loaded the image from had an alpha channel or not.
  230673. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  230674. return image;
  230675. }
  230676. }
  230677. return Image::null;
  230678. }
  230679. #endif
  230680. #endif
  230681. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230682. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230683. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230684. // compiled on its own).
  230685. #if JUCE_INCLUDED_FILE
  230686. class NSViewComponentPeer;
  230687. END_JUCE_NAMESPACE
  230688. @interface NSEvent (JuceDeviceDelta)
  230689. - (float) deviceDeltaX;
  230690. - (float) deviceDeltaY;
  230691. @end
  230692. #define JuceNSView MakeObjCClassName(JuceNSView)
  230693. @interface JuceNSView : NSView<NSTextInput>
  230694. {
  230695. @public
  230696. NSViewComponentPeer* owner;
  230697. NSNotificationCenter* notificationCenter;
  230698. String* stringBeingComposed;
  230699. bool textWasInserted;
  230700. }
  230701. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230702. - (void) dealloc;
  230703. - (BOOL) isOpaque;
  230704. - (void) drawRect: (NSRect) r;
  230705. - (void) mouseDown: (NSEvent*) ev;
  230706. - (void) asyncMouseDown: (NSEvent*) ev;
  230707. - (void) mouseUp: (NSEvent*) ev;
  230708. - (void) asyncMouseUp: (NSEvent*) ev;
  230709. - (void) mouseDragged: (NSEvent*) ev;
  230710. - (void) mouseMoved: (NSEvent*) ev;
  230711. - (void) mouseEntered: (NSEvent*) ev;
  230712. - (void) mouseExited: (NSEvent*) ev;
  230713. - (void) rightMouseDown: (NSEvent*) ev;
  230714. - (void) rightMouseDragged: (NSEvent*) ev;
  230715. - (void) rightMouseUp: (NSEvent*) ev;
  230716. - (void) otherMouseDown: (NSEvent*) ev;
  230717. - (void) otherMouseDragged: (NSEvent*) ev;
  230718. - (void) otherMouseUp: (NSEvent*) ev;
  230719. - (void) scrollWheel: (NSEvent*) ev;
  230720. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230721. - (void) frameChanged: (NSNotification*) n;
  230722. - (void) viewDidMoveToWindow;
  230723. - (void) keyDown: (NSEvent*) ev;
  230724. - (void) keyUp: (NSEvent*) ev;
  230725. // NSTextInput Methods
  230726. - (void) insertText: (id) aString;
  230727. - (void) doCommandBySelector: (SEL) aSelector;
  230728. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230729. - (void) unmarkText;
  230730. - (BOOL) hasMarkedText;
  230731. - (long) conversationIdentifier;
  230732. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230733. - (NSRange) markedRange;
  230734. - (NSRange) selectedRange;
  230735. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230736. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230737. - (NSArray*) validAttributesForMarkedText;
  230738. - (void) flagsChanged: (NSEvent*) ev;
  230739. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230740. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230741. #endif
  230742. - (BOOL) becomeFirstResponder;
  230743. - (BOOL) resignFirstResponder;
  230744. - (BOOL) acceptsFirstResponder;
  230745. - (void) asyncRepaint: (id) rect;
  230746. - (NSArray*) getSupportedDragTypes;
  230747. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230748. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230749. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230750. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230751. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230752. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230753. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230754. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230755. @end
  230756. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230757. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230758. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230759. #else
  230760. @interface JuceNSWindow : NSWindow
  230761. #endif
  230762. {
  230763. @private
  230764. NSViewComponentPeer* owner;
  230765. bool isZooming;
  230766. }
  230767. - (void) setOwner: (NSViewComponentPeer*) owner;
  230768. - (BOOL) canBecomeKeyWindow;
  230769. - (void) becomeKeyWindow;
  230770. - (BOOL) windowShouldClose: (id) window;
  230771. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230772. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230773. - (void) zoom: (id) sender;
  230774. @end
  230775. BEGIN_JUCE_NAMESPACE
  230776. class NSViewComponentPeer : public ComponentPeer
  230777. {
  230778. public:
  230779. NSViewComponentPeer (Component* const component,
  230780. const int windowStyleFlags,
  230781. NSView* viewToAttachTo);
  230782. ~NSViewComponentPeer();
  230783. void* getNativeHandle() const;
  230784. void setVisible (bool shouldBeVisible);
  230785. void setTitle (const String& title);
  230786. void setPosition (int x, int y);
  230787. void setSize (int w, int h);
  230788. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230789. const Rectangle<int> getBounds (const bool global) const;
  230790. const Rectangle<int> getBounds() const;
  230791. const Point<int> getScreenPosition() const;
  230792. const Point<int> localToGlobal (const Point<int>& relativePosition);
  230793. const Point<int> globalToLocal (const Point<int>& screenPosition);
  230794. void setAlpha (float newAlpha);
  230795. void setMinimised (bool shouldBeMinimised);
  230796. bool isMinimised() const;
  230797. void setFullScreen (bool shouldBeFullScreen);
  230798. bool isFullScreen() const;
  230799. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  230800. const BorderSize getFrameSize() const;
  230801. bool setAlwaysOnTop (bool alwaysOnTop);
  230802. void toFront (bool makeActiveWindow);
  230803. void toBehind (ComponentPeer* other);
  230804. void setIcon (const Image& newIcon);
  230805. const StringArray getAvailableRenderingEngines();
  230806. int getCurrentRenderingEngine() throw();
  230807. void setCurrentRenderingEngine (int index);
  230808. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230809. for example having more than one juce plugin loaded into a host, then when a
  230810. method is called, the actual code that runs might actually be in a different module
  230811. than the one you expect... So any calls to library functions or statics that are
  230812. made inside obj-c methods will probably end up getting executed in a different DLL's
  230813. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230814. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230815. virtual methods of an object that's known to live inside the right module's space.
  230816. */
  230817. virtual void redirectMouseDown (NSEvent* ev);
  230818. virtual void redirectMouseUp (NSEvent* ev);
  230819. virtual void redirectMouseDrag (NSEvent* ev);
  230820. virtual void redirectMouseMove (NSEvent* ev);
  230821. virtual void redirectMouseEnter (NSEvent* ev);
  230822. virtual void redirectMouseExit (NSEvent* ev);
  230823. virtual void redirectMouseWheel (NSEvent* ev);
  230824. void sendMouseEvent (NSEvent* ev);
  230825. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  230826. virtual bool redirectKeyDown (NSEvent* ev);
  230827. virtual bool redirectKeyUp (NSEvent* ev);
  230828. virtual void redirectModKeyChange (NSEvent* ev);
  230829. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230830. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  230831. #endif
  230832. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  230833. virtual bool isOpaque();
  230834. virtual void drawRect (NSRect r);
  230835. virtual bool canBecomeKeyWindow();
  230836. virtual bool windowShouldClose();
  230837. virtual void redirectMovedOrResized();
  230838. virtual void viewMovedToWindow();
  230839. virtual NSRect constrainRect (NSRect r);
  230840. static void showArrowCursorIfNeeded();
  230841. static void updateModifiers (NSEvent* e);
  230842. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  230843. static int getKeyCodeFromEvent (NSEvent* ev)
  230844. {
  230845. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230846. int keyCode = unmodified[0];
  230847. if (keyCode == 0x19) // (backwards-tab)
  230848. keyCode = '\t';
  230849. else if (keyCode == 0x03) // (enter)
  230850. keyCode = '\r';
  230851. else
  230852. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  230853. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  230854. {
  230855. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  230856. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  230857. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  230858. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  230859. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  230860. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  230861. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  230862. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  230863. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  230864. if (keyCode == numPadConversions [i])
  230865. keyCode = numPadConversions [i + 1];
  230866. }
  230867. return keyCode;
  230868. }
  230869. static int64 getMouseTime (NSEvent* e)
  230870. {
  230871. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  230872. + (int64) ([e timestamp] * 1000.0);
  230873. }
  230874. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  230875. {
  230876. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  230877. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  230878. }
  230879. static int getModifierForButtonNumber (const NSInteger num)
  230880. {
  230881. return num == 0 ? ModifierKeys::leftButtonModifier
  230882. : (num == 1 ? ModifierKeys::rightButtonModifier
  230883. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  230884. }
  230885. virtual void viewFocusGain();
  230886. virtual void viewFocusLoss();
  230887. bool isFocused() const;
  230888. void grabFocus();
  230889. void textInputRequired (const Point<int>& position);
  230890. void repaint (const Rectangle<int>& area);
  230891. void performAnyPendingRepaintsNow();
  230892. NSWindow* window;
  230893. JuceNSView* view;
  230894. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  230895. static ModifierKeys currentModifiers;
  230896. static ComponentPeer* currentlyFocusedPeer;
  230897. static Array<int> keysCurrentlyDown;
  230898. private:
  230899. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  230900. };
  230901. END_JUCE_NAMESPACE
  230902. @implementation JuceNSView
  230903. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  230904. withFrame: (NSRect) frame
  230905. {
  230906. [super initWithFrame: frame];
  230907. owner = owner_;
  230908. stringBeingComposed = 0;
  230909. textWasInserted = false;
  230910. notificationCenter = [NSNotificationCenter defaultCenter];
  230911. [notificationCenter addObserver: self
  230912. selector: @selector (frameChanged:)
  230913. name: NSViewFrameDidChangeNotification
  230914. object: self];
  230915. if (! owner_->isSharedWindow)
  230916. {
  230917. [notificationCenter addObserver: self
  230918. selector: @selector (frameChanged:)
  230919. name: NSWindowDidMoveNotification
  230920. object: owner_->window];
  230921. }
  230922. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  230923. return self;
  230924. }
  230925. - (void) dealloc
  230926. {
  230927. [notificationCenter removeObserver: self];
  230928. delete stringBeingComposed;
  230929. [super dealloc];
  230930. }
  230931. - (void) drawRect: (NSRect) r
  230932. {
  230933. if (owner != 0)
  230934. owner->drawRect (r);
  230935. }
  230936. - (BOOL) isOpaque
  230937. {
  230938. return owner == 0 || owner->isOpaque();
  230939. }
  230940. - (void) mouseDown: (NSEvent*) ev
  230941. {
  230942. if (JUCEApplication::isStandaloneApp())
  230943. [self asyncMouseDown: ev];
  230944. else
  230945. // In some host situations, the host will stop modal loops from working
  230946. // correctly if they're called from a mouse event, so we'll trigger
  230947. // the event asynchronously..
  230948. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  230949. withObject: ev
  230950. waitUntilDone: NO];
  230951. }
  230952. - (void) asyncMouseDown: (NSEvent*) ev
  230953. {
  230954. if (owner != 0)
  230955. owner->redirectMouseDown (ev);
  230956. }
  230957. - (void) mouseUp: (NSEvent*) ev
  230958. {
  230959. if (! JUCEApplication::isStandaloneApp())
  230960. [self asyncMouseUp: ev];
  230961. else
  230962. // In some host situations, the host will stop modal loops from working
  230963. // correctly if they're called from a mouse event, so we'll trigger
  230964. // the event asynchronously..
  230965. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  230966. withObject: ev
  230967. waitUntilDone: NO];
  230968. }
  230969. - (void) asyncMouseUp: (NSEvent*) ev
  230970. {
  230971. if (owner != 0)
  230972. owner->redirectMouseUp (ev);
  230973. }
  230974. - (void) mouseDragged: (NSEvent*) ev
  230975. {
  230976. if (owner != 0)
  230977. owner->redirectMouseDrag (ev);
  230978. }
  230979. - (void) mouseMoved: (NSEvent*) ev
  230980. {
  230981. if (owner != 0)
  230982. owner->redirectMouseMove (ev);
  230983. }
  230984. - (void) mouseEntered: (NSEvent*) ev
  230985. {
  230986. if (owner != 0)
  230987. owner->redirectMouseEnter (ev);
  230988. }
  230989. - (void) mouseExited: (NSEvent*) ev
  230990. {
  230991. if (owner != 0)
  230992. owner->redirectMouseExit (ev);
  230993. }
  230994. - (void) rightMouseDown: (NSEvent*) ev
  230995. {
  230996. [self mouseDown: ev];
  230997. }
  230998. - (void) rightMouseDragged: (NSEvent*) ev
  230999. {
  231000. [self mouseDragged: ev];
  231001. }
  231002. - (void) rightMouseUp: (NSEvent*) ev
  231003. {
  231004. [self mouseUp: ev];
  231005. }
  231006. - (void) otherMouseDown: (NSEvent*) ev
  231007. {
  231008. [self mouseDown: ev];
  231009. }
  231010. - (void) otherMouseDragged: (NSEvent*) ev
  231011. {
  231012. [self mouseDragged: ev];
  231013. }
  231014. - (void) otherMouseUp: (NSEvent*) ev
  231015. {
  231016. [self mouseUp: ev];
  231017. }
  231018. - (void) scrollWheel: (NSEvent*) ev
  231019. {
  231020. if (owner != 0)
  231021. owner->redirectMouseWheel (ev);
  231022. }
  231023. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231024. {
  231025. (void) ev;
  231026. return YES;
  231027. }
  231028. - (void) frameChanged: (NSNotification*) n
  231029. {
  231030. (void) n;
  231031. if (owner != 0)
  231032. owner->redirectMovedOrResized();
  231033. }
  231034. - (void) viewDidMoveToWindow
  231035. {
  231036. if (owner != 0)
  231037. owner->viewMovedToWindow();
  231038. }
  231039. - (void) asyncRepaint: (id) rect
  231040. {
  231041. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231042. [self setNeedsDisplayInRect: *r];
  231043. }
  231044. - (void) keyDown: (NSEvent*) ev
  231045. {
  231046. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231047. textWasInserted = false;
  231048. if (target != 0)
  231049. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231050. else
  231051. deleteAndZero (stringBeingComposed);
  231052. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231053. [super keyDown: ev];
  231054. }
  231055. - (void) keyUp: (NSEvent*) ev
  231056. {
  231057. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231058. [super keyUp: ev];
  231059. }
  231060. - (void) insertText: (id) aString
  231061. {
  231062. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231063. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231064. if ([newText length] > 0)
  231065. {
  231066. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231067. if (target != 0)
  231068. {
  231069. target->insertTextAtCaret (nsStringToJuce (newText));
  231070. textWasInserted = true;
  231071. }
  231072. }
  231073. deleteAndZero (stringBeingComposed);
  231074. }
  231075. - (void) doCommandBySelector: (SEL) aSelector
  231076. {
  231077. (void) aSelector;
  231078. }
  231079. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231080. {
  231081. (void) selectionRange;
  231082. if (stringBeingComposed == 0)
  231083. stringBeingComposed = new String();
  231084. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231085. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231086. if (target != 0)
  231087. {
  231088. const Range<int> currentHighlight (target->getHighlightedRegion());
  231089. target->insertTextAtCaret (*stringBeingComposed);
  231090. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231091. textWasInserted = true;
  231092. }
  231093. }
  231094. - (void) unmarkText
  231095. {
  231096. if (stringBeingComposed != 0)
  231097. {
  231098. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231099. if (target != 0)
  231100. {
  231101. target->insertTextAtCaret (*stringBeingComposed);
  231102. textWasInserted = true;
  231103. }
  231104. }
  231105. deleteAndZero (stringBeingComposed);
  231106. }
  231107. - (BOOL) hasMarkedText
  231108. {
  231109. return stringBeingComposed != 0;
  231110. }
  231111. - (long) conversationIdentifier
  231112. {
  231113. return (long) (pointer_sized_int) self;
  231114. }
  231115. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231116. {
  231117. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231118. if (target != 0)
  231119. {
  231120. const Range<int> r ((int) theRange.location,
  231121. (int) (theRange.location + theRange.length));
  231122. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231123. }
  231124. return nil;
  231125. }
  231126. - (NSRange) markedRange
  231127. {
  231128. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231129. : NSMakeRange (NSNotFound, 0);
  231130. }
  231131. - (NSRange) selectedRange
  231132. {
  231133. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231134. if (target != 0)
  231135. {
  231136. const Range<int> highlight (target->getHighlightedRegion());
  231137. if (! highlight.isEmpty())
  231138. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231139. }
  231140. return NSMakeRange (NSNotFound, 0);
  231141. }
  231142. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231143. {
  231144. (void) theRange;
  231145. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231146. if (comp == 0)
  231147. return NSMakeRect (0, 0, 0, 0);
  231148. const Rectangle<int> bounds (comp->getScreenBounds());
  231149. return NSMakeRect (bounds.getX(),
  231150. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231151. bounds.getWidth(),
  231152. bounds.getHeight());
  231153. }
  231154. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231155. {
  231156. (void) thePoint;
  231157. return NSNotFound;
  231158. }
  231159. - (NSArray*) validAttributesForMarkedText
  231160. {
  231161. return [NSArray array];
  231162. }
  231163. - (void) flagsChanged: (NSEvent*) ev
  231164. {
  231165. if (owner != 0)
  231166. owner->redirectModKeyChange (ev);
  231167. }
  231168. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231169. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231170. {
  231171. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231172. return true;
  231173. return [super performKeyEquivalent: ev];
  231174. }
  231175. #endif
  231176. - (BOOL) becomeFirstResponder
  231177. {
  231178. if (owner != 0)
  231179. owner->viewFocusGain();
  231180. return true;
  231181. }
  231182. - (BOOL) resignFirstResponder
  231183. {
  231184. if (owner != 0)
  231185. owner->viewFocusLoss();
  231186. return true;
  231187. }
  231188. - (BOOL) acceptsFirstResponder
  231189. {
  231190. return owner != 0 && owner->canBecomeKeyWindow();
  231191. }
  231192. - (NSArray*) getSupportedDragTypes
  231193. {
  231194. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231195. }
  231196. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231197. {
  231198. return owner != 0 && owner->sendDragCallback (type, sender);
  231199. }
  231200. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231201. {
  231202. if ([self sendDragCallback: 0 sender: sender])
  231203. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231204. else
  231205. return NSDragOperationNone;
  231206. }
  231207. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231208. {
  231209. if ([self sendDragCallback: 0 sender: sender])
  231210. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231211. else
  231212. return NSDragOperationNone;
  231213. }
  231214. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231215. {
  231216. [self sendDragCallback: 1 sender: sender];
  231217. }
  231218. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231219. {
  231220. [self sendDragCallback: 1 sender: sender];
  231221. }
  231222. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231223. {
  231224. (void) sender;
  231225. return YES;
  231226. }
  231227. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231228. {
  231229. return [self sendDragCallback: 2 sender: sender];
  231230. }
  231231. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231232. {
  231233. (void) sender;
  231234. }
  231235. @end
  231236. @implementation JuceNSWindow
  231237. - (void) setOwner: (NSViewComponentPeer*) owner_
  231238. {
  231239. owner = owner_;
  231240. isZooming = false;
  231241. }
  231242. - (BOOL) canBecomeKeyWindow
  231243. {
  231244. return owner != 0 && owner->canBecomeKeyWindow();
  231245. }
  231246. - (void) becomeKeyWindow
  231247. {
  231248. [super becomeKeyWindow];
  231249. if (owner != 0)
  231250. owner->grabFocus();
  231251. }
  231252. - (BOOL) windowShouldClose: (id) window
  231253. {
  231254. (void) window;
  231255. return owner == 0 || owner->windowShouldClose();
  231256. }
  231257. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231258. {
  231259. (void) screen;
  231260. if (owner != 0)
  231261. frameRect = owner->constrainRect (frameRect);
  231262. return frameRect;
  231263. }
  231264. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231265. {
  231266. (void) window;
  231267. if (isZooming)
  231268. return proposedFrameSize;
  231269. NSRect frameRect = [self frame];
  231270. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231271. frameRect.size = proposedFrameSize;
  231272. if (owner != 0)
  231273. frameRect = owner->constrainRect (frameRect);
  231274. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231275. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231276. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231277. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231278. return frameRect.size;
  231279. }
  231280. - (void) zoom: (id) sender
  231281. {
  231282. isZooming = true;
  231283. [super zoom: sender];
  231284. isZooming = false;
  231285. }
  231286. - (void) windowWillMove: (NSNotification*) notification
  231287. {
  231288. (void) notification;
  231289. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231290. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231291. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231292. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231293. }
  231294. @end
  231295. BEGIN_JUCE_NAMESPACE
  231296. ModifierKeys NSViewComponentPeer::currentModifiers;
  231297. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231298. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231299. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231300. {
  231301. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231302. return true;
  231303. if (keyCode >= 'A' && keyCode <= 'Z'
  231304. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231305. return true;
  231306. if (keyCode >= 'a' && keyCode <= 'z'
  231307. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231308. return true;
  231309. return false;
  231310. }
  231311. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231312. {
  231313. int m = 0;
  231314. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231315. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231316. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231317. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231318. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231319. }
  231320. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231321. {
  231322. updateModifiers (ev);
  231323. int keyCode = getKeyCodeFromEvent (ev);
  231324. if (keyCode != 0)
  231325. {
  231326. if (isKeyDown)
  231327. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231328. else
  231329. keysCurrentlyDown.removeValue (keyCode);
  231330. }
  231331. }
  231332. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231333. {
  231334. return NSViewComponentPeer::currentModifiers;
  231335. }
  231336. void ModifierKeys::updateCurrentModifiers() throw()
  231337. {
  231338. currentModifiers = NSViewComponentPeer::currentModifiers;
  231339. }
  231340. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231341. const int windowStyleFlags,
  231342. NSView* viewToAttachTo)
  231343. : ComponentPeer (component_, windowStyleFlags),
  231344. window (0),
  231345. view (0),
  231346. isSharedWindow (viewToAttachTo != 0),
  231347. fullScreen (false),
  231348. insideDrawRect (false),
  231349. #if USE_COREGRAPHICS_RENDERING
  231350. usingCoreGraphics (true),
  231351. #else
  231352. usingCoreGraphics (false),
  231353. #endif
  231354. recursiveToFrontCall (false)
  231355. {
  231356. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231357. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231358. [view setPostsFrameChangedNotifications: YES];
  231359. if (isSharedWindow)
  231360. {
  231361. window = [viewToAttachTo window];
  231362. [viewToAttachTo addSubview: view];
  231363. }
  231364. else
  231365. {
  231366. r.origin.x = (float) component->getX();
  231367. r.origin.y = (float) component->getY();
  231368. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231369. unsigned int style = 0;
  231370. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231371. style = NSBorderlessWindowMask;
  231372. else
  231373. style = NSTitledWindowMask;
  231374. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231375. style |= NSMiniaturizableWindowMask;
  231376. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231377. style |= NSClosableWindowMask;
  231378. if ((windowStyleFlags & windowIsResizable) != 0)
  231379. style |= NSResizableWindowMask;
  231380. window = [[JuceNSWindow alloc] initWithContentRect: r
  231381. styleMask: style
  231382. backing: NSBackingStoreBuffered
  231383. defer: YES];
  231384. [((JuceNSWindow*) window) setOwner: this];
  231385. [window orderOut: nil];
  231386. [window setDelegate: (JuceNSWindow*) window];
  231387. [window setOpaque: component->isOpaque()];
  231388. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231389. if (component->isAlwaysOnTop())
  231390. [window setLevel: NSFloatingWindowLevel];
  231391. [window setContentView: view];
  231392. [window setAutodisplay: YES];
  231393. [window setAcceptsMouseMovedEvents: YES];
  231394. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231395. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231396. [window setReleasedWhenClosed: YES];
  231397. [window retain];
  231398. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231399. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231400. }
  231401. const float alpha = component->getAlpha();
  231402. if (alpha < 1.0f)
  231403. setAlpha (alpha);
  231404. setTitle (component->getName());
  231405. }
  231406. NSViewComponentPeer::~NSViewComponentPeer()
  231407. {
  231408. view->owner = 0;
  231409. [view removeFromSuperview];
  231410. [view release];
  231411. if (! isSharedWindow)
  231412. {
  231413. [((JuceNSWindow*) window) setOwner: 0];
  231414. [window close];
  231415. [window release];
  231416. }
  231417. }
  231418. void* NSViewComponentPeer::getNativeHandle() const
  231419. {
  231420. return view;
  231421. }
  231422. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231423. {
  231424. if (isSharedWindow)
  231425. {
  231426. [view setHidden: ! shouldBeVisible];
  231427. }
  231428. else
  231429. {
  231430. if (shouldBeVisible)
  231431. {
  231432. [window orderFront: nil];
  231433. handleBroughtToFront();
  231434. }
  231435. else
  231436. {
  231437. [window orderOut: nil];
  231438. }
  231439. }
  231440. }
  231441. void NSViewComponentPeer::setTitle (const String& title)
  231442. {
  231443. const ScopedAutoReleasePool pool;
  231444. if (! isSharedWindow)
  231445. [window setTitle: juceStringToNS (title)];
  231446. }
  231447. void NSViewComponentPeer::setPosition (int x, int y)
  231448. {
  231449. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231450. }
  231451. void NSViewComponentPeer::setSize (int w, int h)
  231452. {
  231453. setBounds (component->getX(), component->getY(), w, h, false);
  231454. }
  231455. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231456. {
  231457. fullScreen = isNowFullScreen;
  231458. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231459. if (isSharedWindow)
  231460. {
  231461. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231462. if ([view frame].size.width != r.size.width
  231463. || [view frame].size.height != r.size.height)
  231464. [view setNeedsDisplay: true];
  231465. [view setFrame: r];
  231466. }
  231467. else
  231468. {
  231469. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231470. [window setFrame: [window frameRectForContentRect: r]
  231471. display: true];
  231472. }
  231473. }
  231474. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231475. {
  231476. NSRect r = [view frame];
  231477. if (global && [view window] != 0)
  231478. {
  231479. r = [view convertRect: r toView: nil];
  231480. NSRect wr = [[view window] frame];
  231481. r.origin.x += wr.origin.x;
  231482. r.origin.y += wr.origin.y;
  231483. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231484. }
  231485. else
  231486. {
  231487. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231488. }
  231489. return Rectangle<int> (convertToRectInt (r));
  231490. }
  231491. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231492. {
  231493. return getBounds (! isSharedWindow);
  231494. }
  231495. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231496. {
  231497. return getBounds (true).getPosition();
  231498. }
  231499. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  231500. {
  231501. return relativePosition + getScreenPosition();
  231502. }
  231503. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  231504. {
  231505. return screenPosition - getScreenPosition();
  231506. }
  231507. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231508. {
  231509. if (constrainer != 0)
  231510. {
  231511. NSRect current = [window frame];
  231512. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231513. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231514. Rectangle<int> pos (convertToRectInt (r));
  231515. Rectangle<int> original (convertToRectInt (current));
  231516. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  231517. if ([window inLiveResize])
  231518. #else
  231519. if ([window respondsToSelector: @selector (inLiveResize)]
  231520. && [window performSelector: @selector (inLiveResize)])
  231521. #endif
  231522. {
  231523. constrainer->checkBounds (pos, original,
  231524. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231525. false, false, true, true);
  231526. }
  231527. else
  231528. {
  231529. constrainer->checkBounds (pos, original,
  231530. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231531. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231532. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231533. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231534. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231535. }
  231536. r.origin.x = pos.getX();
  231537. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231538. r.size.width = pos.getWidth();
  231539. r.size.height = pos.getHeight();
  231540. }
  231541. return r;
  231542. }
  231543. void NSViewComponentPeer::setAlpha (float newAlpha)
  231544. {
  231545. if (! isSharedWindow)
  231546. [window setAlphaValue: (CGFloat) newAlpha];
  231547. else
  231548. [view setAlphaValue: (CGFloat) newAlpha];
  231549. }
  231550. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231551. {
  231552. if (! isSharedWindow)
  231553. {
  231554. if (shouldBeMinimised)
  231555. [window miniaturize: nil];
  231556. else
  231557. [window deminiaturize: nil];
  231558. }
  231559. }
  231560. bool NSViewComponentPeer::isMinimised() const
  231561. {
  231562. return window != 0 && [window isMiniaturized];
  231563. }
  231564. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231565. {
  231566. if (! isSharedWindow)
  231567. {
  231568. Rectangle<int> r (lastNonFullscreenBounds);
  231569. setMinimised (false);
  231570. if (fullScreen != shouldBeFullScreen)
  231571. {
  231572. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231573. {
  231574. fullScreen = true;
  231575. [window performZoom: nil];
  231576. }
  231577. else
  231578. {
  231579. if (shouldBeFullScreen)
  231580. r = Desktop::getInstance().getMainMonitorArea();
  231581. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231582. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231583. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231584. }
  231585. }
  231586. }
  231587. }
  231588. bool NSViewComponentPeer::isFullScreen() const
  231589. {
  231590. return fullScreen;
  231591. }
  231592. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231593. {
  231594. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  231595. && isPositiveAndBelow (position.getY(), component->getHeight())))
  231596. return false;
  231597. NSPoint p;
  231598. p.x = (float) position.getX();
  231599. p.y = (float) position.getY();
  231600. NSView* v = [view hitTest: p];
  231601. if (trueIfInAChildWindow)
  231602. return v != nil;
  231603. return v == view;
  231604. }
  231605. const BorderSize NSViewComponentPeer::getFrameSize() const
  231606. {
  231607. BorderSize b;
  231608. if (! isSharedWindow)
  231609. {
  231610. NSRect v = [view convertRect: [view frame] toView: nil];
  231611. NSRect w = [window frame];
  231612. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231613. b.setBottom ((int) v.origin.y);
  231614. b.setLeft ((int) v.origin.x);
  231615. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231616. }
  231617. return b;
  231618. }
  231619. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231620. {
  231621. if (! isSharedWindow)
  231622. {
  231623. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231624. : NSNormalWindowLevel];
  231625. }
  231626. return true;
  231627. }
  231628. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231629. {
  231630. if (isSharedWindow)
  231631. {
  231632. [[view superview] addSubview: view
  231633. positioned: NSWindowAbove
  231634. relativeTo: nil];
  231635. }
  231636. if (window != 0 && component->isVisible())
  231637. {
  231638. if (makeActiveWindow)
  231639. [window makeKeyAndOrderFront: nil];
  231640. else
  231641. [window orderFront: nil];
  231642. if (! recursiveToFrontCall)
  231643. {
  231644. recursiveToFrontCall = true;
  231645. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231646. handleBroughtToFront();
  231647. recursiveToFrontCall = false;
  231648. }
  231649. }
  231650. }
  231651. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231652. {
  231653. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231654. jassert (otherPeer != 0); // wrong type of window?
  231655. if (otherPeer != 0)
  231656. {
  231657. if (isSharedWindow)
  231658. {
  231659. [[view superview] addSubview: view
  231660. positioned: NSWindowBelow
  231661. relativeTo: otherPeer->view];
  231662. }
  231663. else
  231664. {
  231665. [window orderWindow: NSWindowBelow
  231666. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231667. : nil ];
  231668. }
  231669. }
  231670. }
  231671. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231672. {
  231673. // to do..
  231674. }
  231675. void NSViewComponentPeer::viewFocusGain()
  231676. {
  231677. if (currentlyFocusedPeer != this)
  231678. {
  231679. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231680. currentlyFocusedPeer->handleFocusLoss();
  231681. currentlyFocusedPeer = this;
  231682. handleFocusGain();
  231683. }
  231684. }
  231685. void NSViewComponentPeer::viewFocusLoss()
  231686. {
  231687. if (currentlyFocusedPeer == this)
  231688. {
  231689. currentlyFocusedPeer = 0;
  231690. handleFocusLoss();
  231691. }
  231692. }
  231693. void juce_HandleProcessFocusChange()
  231694. {
  231695. NSViewComponentPeer::keysCurrentlyDown.clear();
  231696. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231697. {
  231698. if (Process::isForegroundProcess())
  231699. {
  231700. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231701. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  231702. }
  231703. else
  231704. {
  231705. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231706. // turn kiosk mode off if we lose focus..
  231707. Desktop::getInstance().setKioskModeComponent (0);
  231708. }
  231709. }
  231710. }
  231711. bool NSViewComponentPeer::isFocused() const
  231712. {
  231713. return isSharedWindow ? this == currentlyFocusedPeer
  231714. : (window != 0 && [window isKeyWindow]);
  231715. }
  231716. void NSViewComponentPeer::grabFocus()
  231717. {
  231718. if (window != 0)
  231719. {
  231720. [window makeKeyWindow];
  231721. [window makeFirstResponder: view];
  231722. viewFocusGain();
  231723. }
  231724. }
  231725. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231726. {
  231727. }
  231728. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231729. {
  231730. String unicode (nsStringToJuce ([ev characters]));
  231731. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231732. int keyCode = getKeyCodeFromEvent (ev);
  231733. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231734. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231735. if (unicode.isNotEmpty() || keyCode != 0)
  231736. {
  231737. if (isKeyDown)
  231738. {
  231739. bool used = false;
  231740. while (unicode.length() > 0)
  231741. {
  231742. juce_wchar textCharacter = unicode[0];
  231743. unicode = unicode.substring (1);
  231744. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231745. textCharacter = 0;
  231746. used = handleKeyUpOrDown (true) || used;
  231747. used = handleKeyPress (keyCode, textCharacter) || used;
  231748. }
  231749. return used;
  231750. }
  231751. else
  231752. {
  231753. if (handleKeyUpOrDown (false))
  231754. return true;
  231755. }
  231756. }
  231757. return false;
  231758. }
  231759. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231760. {
  231761. updateKeysDown (ev, true);
  231762. bool used = handleKeyEvent (ev, true);
  231763. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231764. {
  231765. // for command keys, the key-up event is thrown away, so simulate one..
  231766. updateKeysDown (ev, false);
  231767. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231768. }
  231769. // (If we're running modally, don't allow unused keystrokes to be passed
  231770. // along to other blocked views..)
  231771. if (Component::getCurrentlyModalComponent() != 0)
  231772. used = true;
  231773. return used;
  231774. }
  231775. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231776. {
  231777. updateKeysDown (ev, false);
  231778. return handleKeyEvent (ev, false)
  231779. || Component::getCurrentlyModalComponent() != 0;
  231780. }
  231781. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231782. {
  231783. keysCurrentlyDown.clear();
  231784. handleKeyUpOrDown (true);
  231785. updateModifiers (ev);
  231786. handleModifierKeysChange();
  231787. }
  231788. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231789. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231790. {
  231791. if ([ev type] == NSKeyDown)
  231792. return redirectKeyDown (ev);
  231793. else if ([ev type] == NSKeyUp)
  231794. return redirectKeyUp (ev);
  231795. return false;
  231796. }
  231797. #endif
  231798. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231799. {
  231800. updateModifiers (ev);
  231801. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231802. }
  231803. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231804. {
  231805. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231806. sendMouseEvent (ev);
  231807. }
  231808. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231809. {
  231810. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231811. sendMouseEvent (ev);
  231812. showArrowCursorIfNeeded();
  231813. }
  231814. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  231815. {
  231816. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231817. sendMouseEvent (ev);
  231818. }
  231819. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  231820. {
  231821. currentModifiers = currentModifiers.withoutMouseButtons();
  231822. sendMouseEvent (ev);
  231823. showArrowCursorIfNeeded();
  231824. }
  231825. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  231826. {
  231827. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231828. currentModifiers = currentModifiers.withoutMouseButtons();
  231829. sendMouseEvent (ev);
  231830. }
  231831. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  231832. {
  231833. currentModifiers = currentModifiers.withoutMouseButtons();
  231834. sendMouseEvent (ev);
  231835. }
  231836. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  231837. {
  231838. updateModifiers (ev);
  231839. float x = 0, y = 0;
  231840. @try
  231841. {
  231842. x = [ev deviceDeltaX] * 0.5f;
  231843. y = [ev deviceDeltaY] * 0.5f;
  231844. }
  231845. @catch (...)
  231846. {}
  231847. if (x == 0 && y == 0)
  231848. {
  231849. x = [ev deltaX] * 10.0f;
  231850. y = [ev deltaY] * 10.0f;
  231851. }
  231852. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  231853. }
  231854. void NSViewComponentPeer::showArrowCursorIfNeeded()
  231855. {
  231856. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  231857. if (mouse.getComponentUnderMouse() == 0
  231858. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  231859. {
  231860. [[NSCursor arrowCursor] set];
  231861. }
  231862. }
  231863. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  231864. {
  231865. NSString* bestType
  231866. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  231867. if (bestType == nil)
  231868. return false;
  231869. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  231870. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  231871. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  231872. if (list == nil)
  231873. return false;
  231874. StringArray files;
  231875. if ([list isKindOfClass: [NSArray class]])
  231876. {
  231877. NSArray* items = (NSArray*) list;
  231878. for (unsigned int i = 0; i < [items count]; ++i)
  231879. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  231880. }
  231881. if (files.size() == 0)
  231882. return false;
  231883. if (type == 0)
  231884. handleFileDragMove (files, pos);
  231885. else if (type == 1)
  231886. handleFileDragExit (files);
  231887. else if (type == 2)
  231888. handleFileDragDrop (files, pos);
  231889. return true;
  231890. }
  231891. bool NSViewComponentPeer::isOpaque()
  231892. {
  231893. return component == 0 || component->isOpaque();
  231894. }
  231895. void NSViewComponentPeer::drawRect (NSRect r)
  231896. {
  231897. if (r.size.width < 1.0f || r.size.height < 1.0f)
  231898. return;
  231899. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  231900. if (! component->isOpaque())
  231901. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  231902. #if USE_COREGRAPHICS_RENDERING
  231903. if (usingCoreGraphics)
  231904. {
  231905. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  231906. insideDrawRect = true;
  231907. handlePaint (context);
  231908. insideDrawRect = false;
  231909. }
  231910. else
  231911. #endif
  231912. {
  231913. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  231914. (int) (r.size.width + 0.5f),
  231915. (int) (r.size.height + 0.5f),
  231916. ! getComponent()->isOpaque());
  231917. const int xOffset = -roundToInt (r.origin.x);
  231918. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  231919. const NSRect* rects = 0;
  231920. NSInteger numRects = 0;
  231921. [view getRectsBeingDrawn: &rects count: &numRects];
  231922. const Rectangle<int> clipBounds (temp.getBounds());
  231923. RectangleList clip;
  231924. for (int i = 0; i < numRects; ++i)
  231925. {
  231926. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  231927. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  231928. roundToInt (rects[i].size.width),
  231929. roundToInt (rects[i].size.height))));
  231930. }
  231931. if (! clip.isEmpty())
  231932. {
  231933. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  231934. insideDrawRect = true;
  231935. handlePaint (context);
  231936. insideDrawRect = false;
  231937. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  231938. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  231939. CGColorSpaceRelease (colourSpace);
  231940. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  231941. CGImageRelease (image);
  231942. }
  231943. }
  231944. }
  231945. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  231946. {
  231947. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  231948. #if USE_COREGRAPHICS_RENDERING
  231949. s.add ("CoreGraphics Renderer");
  231950. #endif
  231951. return s;
  231952. }
  231953. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  231954. {
  231955. return usingCoreGraphics ? 1 : 0;
  231956. }
  231957. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  231958. {
  231959. #if USE_COREGRAPHICS_RENDERING
  231960. if (usingCoreGraphics != (index > 0))
  231961. {
  231962. usingCoreGraphics = index > 0;
  231963. [view setNeedsDisplay: true];
  231964. }
  231965. #endif
  231966. }
  231967. bool NSViewComponentPeer::canBecomeKeyWindow()
  231968. {
  231969. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  231970. }
  231971. bool NSViewComponentPeer::windowShouldClose()
  231972. {
  231973. if (! isValidPeer (this))
  231974. return YES;
  231975. handleUserClosingWindow();
  231976. return NO;
  231977. }
  231978. void NSViewComponentPeer::redirectMovedOrResized()
  231979. {
  231980. handleMovedOrResized();
  231981. }
  231982. void NSViewComponentPeer::viewMovedToWindow()
  231983. {
  231984. if (isSharedWindow)
  231985. window = [view window];
  231986. }
  231987. void Desktop::createMouseInputSources()
  231988. {
  231989. mouseSources.add (new MouseInputSource (0, true));
  231990. }
  231991. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  231992. {
  231993. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  231994. if (enableOrDisable)
  231995. {
  231996. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  231997. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  231998. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231999. }
  232000. else
  232001. {
  232002. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  232003. }
  232004. #else
  232005. if (enableOrDisable)
  232006. {
  232007. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232008. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232009. }
  232010. else
  232011. {
  232012. SetSystemUIMode (kUIModeNormal, 0);
  232013. }
  232014. #endif
  232015. }
  232016. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232017. {
  232018. if (insideDrawRect)
  232019. {
  232020. class AsyncRepaintMessage : public CallbackMessage
  232021. {
  232022. public:
  232023. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232024. : peer (peer_), rect (rect_)
  232025. {
  232026. }
  232027. void messageCallback()
  232028. {
  232029. if (ComponentPeer::isValidPeer (peer))
  232030. peer->repaint (rect);
  232031. }
  232032. private:
  232033. NSViewComponentPeer* const peer;
  232034. const Rectangle<int> rect;
  232035. };
  232036. (new AsyncRepaintMessage (this, area))->post();
  232037. }
  232038. else
  232039. {
  232040. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232041. (float) area.getWidth(), (float) area.getHeight())];
  232042. }
  232043. }
  232044. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232045. {
  232046. [view displayIfNeeded];
  232047. }
  232048. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232049. {
  232050. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232051. }
  232052. const Image juce_createIconForFile (const File& file)
  232053. {
  232054. const ScopedAutoReleasePool pool;
  232055. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232056. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232057. [NSGraphicsContext saveGraphicsState];
  232058. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232059. [image drawAtPoint: NSMakePoint (0, 0)
  232060. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232061. operation: NSCompositeSourceOver fraction: 1.0f];
  232062. [[NSGraphicsContext currentContext] flushGraphics];
  232063. [NSGraphicsContext restoreGraphicsState];
  232064. return Image (result);
  232065. }
  232066. const int KeyPress::spaceKey = ' ';
  232067. const int KeyPress::returnKey = 0x0d;
  232068. const int KeyPress::escapeKey = 0x1b;
  232069. const int KeyPress::backspaceKey = 0x7f;
  232070. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232071. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232072. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232073. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232074. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232075. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232076. const int KeyPress::endKey = NSEndFunctionKey;
  232077. const int KeyPress::homeKey = NSHomeFunctionKey;
  232078. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232079. const int KeyPress::insertKey = -1;
  232080. const int KeyPress::tabKey = 9;
  232081. const int KeyPress::F1Key = NSF1FunctionKey;
  232082. const int KeyPress::F2Key = NSF2FunctionKey;
  232083. const int KeyPress::F3Key = NSF3FunctionKey;
  232084. const int KeyPress::F4Key = NSF4FunctionKey;
  232085. const int KeyPress::F5Key = NSF5FunctionKey;
  232086. const int KeyPress::F6Key = NSF6FunctionKey;
  232087. const int KeyPress::F7Key = NSF7FunctionKey;
  232088. const int KeyPress::F8Key = NSF8FunctionKey;
  232089. const int KeyPress::F9Key = NSF9FunctionKey;
  232090. const int KeyPress::F10Key = NSF10FunctionKey;
  232091. const int KeyPress::F11Key = NSF1FunctionKey;
  232092. const int KeyPress::F12Key = NSF12FunctionKey;
  232093. const int KeyPress::F13Key = NSF13FunctionKey;
  232094. const int KeyPress::F14Key = NSF14FunctionKey;
  232095. const int KeyPress::F15Key = NSF15FunctionKey;
  232096. const int KeyPress::F16Key = NSF16FunctionKey;
  232097. const int KeyPress::numberPad0 = 0x30020;
  232098. const int KeyPress::numberPad1 = 0x30021;
  232099. const int KeyPress::numberPad2 = 0x30022;
  232100. const int KeyPress::numberPad3 = 0x30023;
  232101. const int KeyPress::numberPad4 = 0x30024;
  232102. const int KeyPress::numberPad5 = 0x30025;
  232103. const int KeyPress::numberPad6 = 0x30026;
  232104. const int KeyPress::numberPad7 = 0x30027;
  232105. const int KeyPress::numberPad8 = 0x30028;
  232106. const int KeyPress::numberPad9 = 0x30029;
  232107. const int KeyPress::numberPadAdd = 0x3002a;
  232108. const int KeyPress::numberPadSubtract = 0x3002b;
  232109. const int KeyPress::numberPadMultiply = 0x3002c;
  232110. const int KeyPress::numberPadDivide = 0x3002d;
  232111. const int KeyPress::numberPadSeparator = 0x3002e;
  232112. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232113. const int KeyPress::numberPadEquals = 0x30030;
  232114. const int KeyPress::numberPadDelete = 0x30031;
  232115. const int KeyPress::playKey = 0x30000;
  232116. const int KeyPress::stopKey = 0x30001;
  232117. const int KeyPress::fastForwardKey = 0x30002;
  232118. const int KeyPress::rewindKey = 0x30003;
  232119. #endif
  232120. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232121. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232122. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232123. // compiled on its own).
  232124. #if JUCE_INCLUDED_FILE
  232125. #if JUCE_MAC
  232126. namespace MouseCursorHelpers
  232127. {
  232128. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232129. {
  232130. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232131. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232132. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232133. [im release];
  232134. return c;
  232135. }
  232136. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232137. {
  232138. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232139. BufferedInputStream buf (fileStream, 4096);
  232140. PNGImageFormat pngFormat;
  232141. Image im (pngFormat.decodeImage (buf));
  232142. if (im.isValid())
  232143. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232144. jassertfalse;
  232145. return 0;
  232146. }
  232147. }
  232148. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232149. {
  232150. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232151. }
  232152. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232153. {
  232154. const ScopedAutoReleasePool pool;
  232155. NSCursor* c = 0;
  232156. switch (type)
  232157. {
  232158. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232159. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232160. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232161. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232162. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232163. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232164. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232165. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232166. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232167. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232168. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232169. case UpDownResizeCursor:
  232170. case TopEdgeResizeCursor:
  232171. case BottomEdgeResizeCursor:
  232172. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232173. case TopLeftCornerResizeCursor:
  232174. case BottomRightCornerResizeCursor:
  232175. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232176. case TopRightCornerResizeCursor:
  232177. case BottomLeftCornerResizeCursor:
  232178. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232179. case UpDownLeftRightResizeCursor:
  232180. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232181. default:
  232182. jassertfalse;
  232183. break;
  232184. }
  232185. [c retain];
  232186. return c;
  232187. }
  232188. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232189. {
  232190. [((NSCursor*) cursorHandle) release];
  232191. }
  232192. void MouseCursor::showInAllWindows() const
  232193. {
  232194. showInWindow (0);
  232195. }
  232196. void MouseCursor::showInWindow (ComponentPeer*) const
  232197. {
  232198. NSCursor* c = (NSCursor*) getHandle();
  232199. if (c == 0)
  232200. c = [NSCursor arrowCursor];
  232201. [c set];
  232202. }
  232203. #else
  232204. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232205. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232206. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232207. void MouseCursor::showInAllWindows() const {}
  232208. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232209. #endif
  232210. #endif
  232211. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232212. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232213. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232214. // compiled on its own).
  232215. #if JUCE_INCLUDED_FILE
  232216. class NSViewComponentInternal : public ComponentMovementWatcher
  232217. {
  232218. public:
  232219. NSViewComponentInternal (NSView* const view_, Component& owner_)
  232220. : ComponentMovementWatcher (&owner_),
  232221. owner (owner_),
  232222. currentPeer (0),
  232223. view (view_)
  232224. {
  232225. [view_ retain];
  232226. if (owner.isShowing())
  232227. componentPeerChanged();
  232228. }
  232229. ~NSViewComponentInternal()
  232230. {
  232231. [view removeFromSuperview];
  232232. [view release];
  232233. }
  232234. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232235. {
  232236. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232237. // The ComponentMovementWatcher version of this method avoids calling
  232238. // us when the top-level comp is resized, but for an NSView we need to know this
  232239. // because with inverted co-ords, we need to update the position even if the
  232240. // top-left pos hasn't changed
  232241. if (comp.isOnDesktop() && wasResized)
  232242. componentMovedOrResized (wasMoved, wasResized);
  232243. }
  232244. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232245. {
  232246. Component* const topComp = owner.getTopLevelComponent();
  232247. if (topComp->getPeer() != 0)
  232248. {
  232249. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  232250. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner.getWidth(), (float) owner.getHeight());
  232251. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232252. [view setFrame: r];
  232253. }
  232254. }
  232255. void componentPeerChanged()
  232256. {
  232257. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner.getPeer());
  232258. if (currentPeer != peer)
  232259. {
  232260. if ([view superview] != nil)
  232261. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  232262. // override the call and use it as a sign that they're being deleted, which breaks everything..
  232263. currentPeer = peer;
  232264. if (peer != 0)
  232265. {
  232266. [peer->view addSubview: view];
  232267. componentMovedOrResized (false, false);
  232268. }
  232269. }
  232270. [view setHidden: ! owner.isShowing()];
  232271. }
  232272. void componentVisibilityChanged()
  232273. {
  232274. componentPeerChanged();
  232275. }
  232276. const Rectangle<int> getViewBounds() const
  232277. {
  232278. NSRect r = [view frame];
  232279. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  232280. }
  232281. private:
  232282. Component& owner;
  232283. NSViewComponentPeer* currentPeer;
  232284. public:
  232285. NSView* const view;
  232286. private:
  232287. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentInternal);
  232288. };
  232289. NSViewComponent::NSViewComponent()
  232290. {
  232291. }
  232292. NSViewComponent::~NSViewComponent()
  232293. {
  232294. }
  232295. void NSViewComponent::setView (void* view)
  232296. {
  232297. if (view != getView())
  232298. {
  232299. if (view != 0)
  232300. info = new NSViewComponentInternal ((NSView*) view, *this);
  232301. else
  232302. info = 0;
  232303. }
  232304. }
  232305. void* NSViewComponent::getView() const
  232306. {
  232307. return info == 0 ? 0 : info->view;
  232308. }
  232309. void NSViewComponent::resizeToFitView()
  232310. {
  232311. if (info != 0)
  232312. setBounds (info->getViewBounds());
  232313. }
  232314. void NSViewComponent::paint (Graphics&)
  232315. {
  232316. }
  232317. #endif
  232318. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232319. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232320. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232321. // compiled on its own).
  232322. #if JUCE_INCLUDED_FILE
  232323. AppleRemoteDevice::AppleRemoteDevice()
  232324. : device (0),
  232325. queue (0),
  232326. remoteId (0)
  232327. {
  232328. }
  232329. AppleRemoteDevice::~AppleRemoteDevice()
  232330. {
  232331. stop();
  232332. }
  232333. namespace
  232334. {
  232335. io_object_t getAppleRemoteDevice()
  232336. {
  232337. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232338. io_iterator_t iter = 0;
  232339. io_object_t iod = 0;
  232340. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232341. && iter != 0)
  232342. {
  232343. iod = IOIteratorNext (iter);
  232344. }
  232345. IOObjectRelease (iter);
  232346. return iod;
  232347. }
  232348. bool createAppleRemoteInterface (io_object_t iod, void** device)
  232349. {
  232350. jassert (*device == 0);
  232351. io_name_t classname;
  232352. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232353. {
  232354. IOCFPlugInInterface** cfPlugInInterface = 0;
  232355. SInt32 score = 0;
  232356. if (IOCreatePlugInInterfaceForService (iod,
  232357. kIOHIDDeviceUserClientTypeID,
  232358. kIOCFPlugInInterfaceID,
  232359. &cfPlugInInterface,
  232360. &score) == kIOReturnSuccess)
  232361. {
  232362. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232363. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232364. device);
  232365. (void) hr;
  232366. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232367. }
  232368. }
  232369. return *device != 0;
  232370. }
  232371. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232372. {
  232373. if (result == kIOReturnSuccess)
  232374. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232375. }
  232376. }
  232377. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232378. {
  232379. if (queue != 0)
  232380. return true;
  232381. stop();
  232382. bool result = false;
  232383. io_object_t iod = getAppleRemoteDevice();
  232384. if (iod != 0)
  232385. {
  232386. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232387. result = true;
  232388. else
  232389. stop();
  232390. IOObjectRelease (iod);
  232391. }
  232392. return result;
  232393. }
  232394. void AppleRemoteDevice::stop()
  232395. {
  232396. if (queue != 0)
  232397. {
  232398. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232399. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232400. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232401. queue = 0;
  232402. }
  232403. if (device != 0)
  232404. {
  232405. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232406. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232407. device = 0;
  232408. }
  232409. }
  232410. bool AppleRemoteDevice::isActive() const
  232411. {
  232412. return queue != 0;
  232413. }
  232414. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232415. {
  232416. Array <int> cookies;
  232417. CFArrayRef elements;
  232418. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232419. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232420. return false;
  232421. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232422. {
  232423. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232424. // get the cookie
  232425. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232426. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232427. continue;
  232428. long number;
  232429. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232430. continue;
  232431. cookies.add ((int) number);
  232432. }
  232433. CFRelease (elements);
  232434. if ((*(IOHIDDeviceInterface**) device)
  232435. ->open ((IOHIDDeviceInterface**) device,
  232436. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232437. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232438. {
  232439. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232440. if (queue != 0)
  232441. {
  232442. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232443. for (int i = 0; i < cookies.size(); ++i)
  232444. {
  232445. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232446. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232447. }
  232448. CFRunLoopSourceRef eventSource;
  232449. if ((*(IOHIDQueueInterface**) queue)
  232450. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232451. {
  232452. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232453. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232454. {
  232455. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232456. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232457. return true;
  232458. }
  232459. }
  232460. }
  232461. }
  232462. return false;
  232463. }
  232464. void AppleRemoteDevice::handleCallbackInternal()
  232465. {
  232466. int totalValues = 0;
  232467. AbsoluteTime nullTime = { 0, 0 };
  232468. char cookies [12];
  232469. int numCookies = 0;
  232470. while (numCookies < numElementsInArray (cookies))
  232471. {
  232472. IOHIDEventStruct e;
  232473. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232474. break;
  232475. if ((int) e.elementCookie == 19)
  232476. {
  232477. remoteId = e.value;
  232478. buttonPressed (switched, false);
  232479. }
  232480. else
  232481. {
  232482. totalValues += e.value;
  232483. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232484. }
  232485. }
  232486. cookies [numCookies++] = 0;
  232487. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232488. static const char buttonPatterns[] =
  232489. {
  232490. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232491. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232492. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232493. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232494. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232495. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232496. 0x1f, 0x12, 0x04, 0x02, 0,
  232497. 0x1f, 0x12, 0x03, 0x02, 0,
  232498. 0x1f, 0x12, 0x1f, 0x12, 0,
  232499. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232500. 19, 0
  232501. };
  232502. int buttonNum = (int) menuButton;
  232503. int i = 0;
  232504. while (i < numElementsInArray (buttonPatterns))
  232505. {
  232506. if (strcmp (cookies, buttonPatterns + i) == 0)
  232507. {
  232508. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232509. break;
  232510. }
  232511. i += (int) strlen (buttonPatterns + i) + 1;
  232512. ++buttonNum;
  232513. }
  232514. }
  232515. #endif
  232516. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232517. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232518. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232519. // compiled on its own).
  232520. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232521. #if JUCE_MAC
  232522. END_JUCE_NAMESPACE
  232523. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232524. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232525. {
  232526. CriticalSection* contextLock;
  232527. bool needsUpdate;
  232528. }
  232529. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232530. - (bool) makeActive;
  232531. - (void) makeInactive;
  232532. - (void) reshape;
  232533. @end
  232534. @implementation ThreadSafeNSOpenGLView
  232535. - (id) initWithFrame: (NSRect) frameRect
  232536. pixelFormat: (NSOpenGLPixelFormat*) format
  232537. {
  232538. contextLock = new CriticalSection();
  232539. self = [super initWithFrame: frameRect pixelFormat: format];
  232540. if (self != nil)
  232541. [[NSNotificationCenter defaultCenter] addObserver: self
  232542. selector: @selector (_surfaceNeedsUpdate:)
  232543. name: NSViewGlobalFrameDidChangeNotification
  232544. object: self];
  232545. return self;
  232546. }
  232547. - (void) dealloc
  232548. {
  232549. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232550. delete contextLock;
  232551. [super dealloc];
  232552. }
  232553. - (bool) makeActive
  232554. {
  232555. const ScopedLock sl (*contextLock);
  232556. if ([self openGLContext] == 0)
  232557. return false;
  232558. [[self openGLContext] makeCurrentContext];
  232559. if (needsUpdate)
  232560. {
  232561. [super update];
  232562. needsUpdate = false;
  232563. }
  232564. return true;
  232565. }
  232566. - (void) makeInactive
  232567. {
  232568. const ScopedLock sl (*contextLock);
  232569. [NSOpenGLContext clearCurrentContext];
  232570. }
  232571. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232572. {
  232573. (void) notification;
  232574. const ScopedLock sl (*contextLock);
  232575. needsUpdate = true;
  232576. }
  232577. - (void) update
  232578. {
  232579. const ScopedLock sl (*contextLock);
  232580. needsUpdate = true;
  232581. }
  232582. - (void) reshape
  232583. {
  232584. const ScopedLock sl (*contextLock);
  232585. needsUpdate = true;
  232586. }
  232587. @end
  232588. BEGIN_JUCE_NAMESPACE
  232589. class WindowedGLContext : public OpenGLContext
  232590. {
  232591. public:
  232592. WindowedGLContext (Component& component,
  232593. const OpenGLPixelFormat& pixelFormat_,
  232594. NSOpenGLContext* sharedContext)
  232595. : renderContext (0),
  232596. pixelFormat (pixelFormat_)
  232597. {
  232598. NSOpenGLPixelFormatAttribute attribs [64];
  232599. int n = 0;
  232600. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232601. attribs[n++] = NSOpenGLPFAAccelerated;
  232602. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232603. attribs[n++] = NSOpenGLPFAColorSize;
  232604. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232605. pixelFormat.greenBits,
  232606. pixelFormat.blueBits);
  232607. attribs[n++] = NSOpenGLPFAAlphaSize;
  232608. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232609. attribs[n++] = NSOpenGLPFADepthSize;
  232610. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232611. attribs[n++] = NSOpenGLPFAStencilSize;
  232612. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232613. attribs[n++] = NSOpenGLPFAAccumSize;
  232614. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232615. pixelFormat.accumulationBufferGreenBits,
  232616. pixelFormat.accumulationBufferBlueBits,
  232617. pixelFormat.accumulationBufferAlphaBits);
  232618. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232619. attribs[n++] = NSOpenGLPFASampleBuffers;
  232620. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232621. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232622. attribs[n++] = NSOpenGLPFANoRecovery;
  232623. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232624. NSOpenGLPixelFormat* format
  232625. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232626. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232627. pixelFormat: format];
  232628. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232629. shareContext: sharedContext] autorelease];
  232630. const GLint swapInterval = 1;
  232631. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232632. [view setOpenGLContext: renderContext];
  232633. [format release];
  232634. viewHolder = new NSViewComponentInternal (view, component);
  232635. }
  232636. ~WindowedGLContext()
  232637. {
  232638. deleteContext();
  232639. viewHolder = 0;
  232640. }
  232641. void deleteContext()
  232642. {
  232643. makeInactive();
  232644. [renderContext clearDrawable];
  232645. [renderContext setView: nil];
  232646. [view setOpenGLContext: nil];
  232647. renderContext = nil;
  232648. }
  232649. bool makeActive() const throw()
  232650. {
  232651. jassert (renderContext != 0);
  232652. if ([renderContext view] != view)
  232653. [renderContext setView: view];
  232654. [view makeActive];
  232655. return isActive();
  232656. }
  232657. bool makeInactive() const throw()
  232658. {
  232659. [view makeInactive];
  232660. return true;
  232661. }
  232662. bool isActive() const throw()
  232663. {
  232664. return [NSOpenGLContext currentContext] == renderContext;
  232665. }
  232666. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232667. void* getRawContext() const throw() { return renderContext; }
  232668. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  232669. {
  232670. }
  232671. void swapBuffers()
  232672. {
  232673. [renderContext flushBuffer];
  232674. }
  232675. bool setSwapInterval (const int numFramesPerSwap)
  232676. {
  232677. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232678. forParameter: NSOpenGLCPSwapInterval];
  232679. return true;
  232680. }
  232681. int getSwapInterval() const
  232682. {
  232683. GLint numFrames = 0;
  232684. [renderContext getValues: &numFrames
  232685. forParameter: NSOpenGLCPSwapInterval];
  232686. return numFrames;
  232687. }
  232688. void repaint()
  232689. {
  232690. // we need to invalidate the juce view that holds this gl view, to make it
  232691. // cause a repaint callback
  232692. NSView* v = (NSView*) viewHolder->view;
  232693. NSRect r = [v frame];
  232694. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232695. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232696. // repaint message, thus never causing our paint() callback, and never repainting
  232697. // the comp. So invalidating just a little bit around the edge helps..
  232698. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232699. }
  232700. void* getNativeWindowHandle() const { return viewHolder->view; }
  232701. NSOpenGLContext* renderContext;
  232702. ThreadSafeNSOpenGLView* view;
  232703. private:
  232704. OpenGLPixelFormat pixelFormat;
  232705. ScopedPointer <NSViewComponentInternal> viewHolder;
  232706. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  232707. };
  232708. OpenGLContext* OpenGLComponent::createContext()
  232709. {
  232710. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  232711. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232712. return (c->renderContext != 0) ? c.release() : 0;
  232713. }
  232714. void* OpenGLComponent::getNativeWindowHandle() const
  232715. {
  232716. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232717. : 0;
  232718. }
  232719. void juce_glViewport (const int w, const int h)
  232720. {
  232721. glViewport (0, 0, w, h);
  232722. }
  232723. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232724. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232725. {
  232726. /* GLint attribs [64];
  232727. int n = 0;
  232728. attribs[n++] = AGL_RGBA;
  232729. attribs[n++] = AGL_DOUBLEBUFFER;
  232730. attribs[n++] = AGL_ACCELERATED;
  232731. attribs[n++] = AGL_NO_RECOVERY;
  232732. attribs[n++] = AGL_NONE;
  232733. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232734. while (p != 0)
  232735. {
  232736. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232737. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232738. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232739. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232740. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232741. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232742. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232743. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232744. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232745. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232746. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232747. results.add (pf);
  232748. p = aglNextPixelFormat (p);
  232749. }*/
  232750. //jassertfalse // can't see how you do this in cocoa!
  232751. }
  232752. #else
  232753. END_JUCE_NAMESPACE
  232754. @interface JuceGLView : UIView
  232755. {
  232756. }
  232757. + (Class) layerClass;
  232758. @end
  232759. @implementation JuceGLView
  232760. + (Class) layerClass
  232761. {
  232762. return [CAEAGLLayer class];
  232763. }
  232764. @end
  232765. BEGIN_JUCE_NAMESPACE
  232766. class GLESContext : public OpenGLContext
  232767. {
  232768. public:
  232769. GLESContext (UIViewComponentPeer* peer,
  232770. Component* const component_,
  232771. const OpenGLPixelFormat& pixelFormat_,
  232772. const GLESContext* const sharedContext,
  232773. NSUInteger apiType)
  232774. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232775. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232776. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232777. {
  232778. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232779. view.opaque = YES;
  232780. view.hidden = NO;
  232781. view.backgroundColor = [UIColor blackColor];
  232782. view.userInteractionEnabled = NO;
  232783. glLayer = (CAEAGLLayer*) [view layer];
  232784. [peer->view addSubview: view];
  232785. if (sharedContext != 0)
  232786. context = [[EAGLContext alloc] initWithAPI: apiType
  232787. sharegroup: [sharedContext->context sharegroup]];
  232788. else
  232789. context = [[EAGLContext alloc] initWithAPI: apiType];
  232790. createGLBuffers();
  232791. }
  232792. ~GLESContext()
  232793. {
  232794. deleteContext();
  232795. [view removeFromSuperview];
  232796. [view release];
  232797. freeGLBuffers();
  232798. }
  232799. void deleteContext()
  232800. {
  232801. makeInactive();
  232802. [context release];
  232803. context = nil;
  232804. }
  232805. bool makeActive() const throw()
  232806. {
  232807. jassert (context != 0);
  232808. [EAGLContext setCurrentContext: context];
  232809. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232810. return true;
  232811. }
  232812. void swapBuffers()
  232813. {
  232814. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232815. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  232816. }
  232817. bool makeInactive() const throw()
  232818. {
  232819. return [EAGLContext setCurrentContext: nil];
  232820. }
  232821. bool isActive() const throw()
  232822. {
  232823. return [EAGLContext currentContext] == context;
  232824. }
  232825. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232826. void* getRawContext() const throw() { return glLayer; }
  232827. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232828. {
  232829. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  232830. if (lastWidth != w || lastHeight != h)
  232831. {
  232832. lastWidth = w;
  232833. lastHeight = h;
  232834. freeGLBuffers();
  232835. createGLBuffers();
  232836. }
  232837. }
  232838. bool setSwapInterval (const int numFramesPerSwap)
  232839. {
  232840. numFrames = numFramesPerSwap;
  232841. return true;
  232842. }
  232843. int getSwapInterval() const
  232844. {
  232845. return numFrames;
  232846. }
  232847. void repaint()
  232848. {
  232849. }
  232850. void createGLBuffers()
  232851. {
  232852. makeActive();
  232853. glGenFramebuffersOES (1, &frameBufferHandle);
  232854. glGenRenderbuffersOES (1, &colorBufferHandle);
  232855. glGenRenderbuffersOES (1, &depthBufferHandle);
  232856. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232857. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  232858. GLint width, height;
  232859. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  232860. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  232861. if (useDepthBuffer)
  232862. {
  232863. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  232864. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  232865. }
  232866. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232867. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232868. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  232869. if (useDepthBuffer)
  232870. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  232871. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  232872. }
  232873. void freeGLBuffers()
  232874. {
  232875. if (frameBufferHandle != 0)
  232876. {
  232877. glDeleteFramebuffersOES (1, &frameBufferHandle);
  232878. frameBufferHandle = 0;
  232879. }
  232880. if (colorBufferHandle != 0)
  232881. {
  232882. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  232883. colorBufferHandle = 0;
  232884. }
  232885. if (depthBufferHandle != 0)
  232886. {
  232887. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  232888. depthBufferHandle = 0;
  232889. }
  232890. }
  232891. private:
  232892. WeakReference<Component> component;
  232893. OpenGLPixelFormat pixelFormat;
  232894. JuceGLView* view;
  232895. CAEAGLLayer* glLayer;
  232896. EAGLContext* context;
  232897. bool useDepthBuffer;
  232898. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  232899. int numFrames;
  232900. int lastWidth, lastHeight;
  232901. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  232902. };
  232903. OpenGLContext* OpenGLComponent::createContext()
  232904. {
  232905. ScopedAutoReleasePool pool;
  232906. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  232907. if (peer != 0)
  232908. return new GLESContext (peer, this, preferredPixelFormat,
  232909. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  232910. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  232911. return 0;
  232912. }
  232913. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232914. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232915. {
  232916. }
  232917. void juce_glViewport (const int w, const int h)
  232918. {
  232919. glViewport (0, 0, w, h);
  232920. }
  232921. #endif
  232922. #endif
  232923. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  232924. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  232925. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232926. // compiled on its own).
  232927. #if JUCE_INCLUDED_FILE
  232928. class JuceMainMenuHandler;
  232929. END_JUCE_NAMESPACE
  232930. using namespace JUCE_NAMESPACE;
  232931. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  232932. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232933. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  232934. #else
  232935. @interface JuceMenuCallback : NSObject
  232936. #endif
  232937. {
  232938. JuceMainMenuHandler* owner;
  232939. }
  232940. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  232941. - (void) dealloc;
  232942. - (void) menuItemInvoked: (id) menu;
  232943. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232944. @end
  232945. BEGIN_JUCE_NAMESPACE
  232946. class JuceMainMenuHandler : private MenuBarModel::Listener,
  232947. private DeletedAtShutdown
  232948. {
  232949. public:
  232950. JuceMainMenuHandler()
  232951. : currentModel (0),
  232952. lastUpdateTime (0)
  232953. {
  232954. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  232955. }
  232956. ~JuceMainMenuHandler()
  232957. {
  232958. setMenu (0);
  232959. jassert (instance == this);
  232960. instance = 0;
  232961. [callback release];
  232962. }
  232963. void setMenu (MenuBarModel* const newMenuBarModel)
  232964. {
  232965. if (currentModel != newMenuBarModel)
  232966. {
  232967. if (currentModel != 0)
  232968. currentModel->removeListener (this);
  232969. currentModel = newMenuBarModel;
  232970. if (currentModel != 0)
  232971. currentModel->addListener (this);
  232972. menuBarItemsChanged (0);
  232973. }
  232974. }
  232975. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  232976. const String& name, const int menuId, const int tag)
  232977. {
  232978. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  232979. action: nil
  232980. keyEquivalent: @""];
  232981. [item setTag: tag];
  232982. NSMenu* sub = createMenu (child, name, menuId, tag);
  232983. [parent setSubmenu: sub forItem: item];
  232984. [sub setAutoenablesItems: false];
  232985. [sub release];
  232986. }
  232987. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  232988. const String& name, const int menuId, const int tag)
  232989. {
  232990. [parentItem setTag: tag];
  232991. NSMenu* menu = [parentItem submenu];
  232992. [menu setTitle: juceStringToNS (name)];
  232993. while ([menu numberOfItems] > 0)
  232994. [menu removeItemAtIndex: 0];
  232995. PopupMenu::MenuItemIterator iter (menuToCopy);
  232996. while (iter.next())
  232997. addMenuItem (iter, menu, menuId, tag);
  232998. [menu setAutoenablesItems: false];
  232999. [menu update];
  233000. }
  233001. void menuBarItemsChanged (MenuBarModel*)
  233002. {
  233003. lastUpdateTime = Time::getMillisecondCounter();
  233004. StringArray menuNames;
  233005. if (currentModel != 0)
  233006. menuNames = currentModel->getMenuBarNames();
  233007. NSMenu* menuBar = [NSApp mainMenu];
  233008. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233009. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233010. int menuId = 1;
  233011. for (int i = 0; i < menuNames.size(); ++i)
  233012. {
  233013. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233014. if (i >= [menuBar numberOfItems] - 1)
  233015. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233016. else
  233017. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233018. }
  233019. }
  233020. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233021. {
  233022. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233023. if (item != 0)
  233024. flashMenuBar ([item menu]);
  233025. }
  233026. void updateMenus (NSMenu* menu)
  233027. {
  233028. if (PopupMenu::dismissAllActiveMenus())
  233029. {
  233030. // If we were running a juce menu, then we should let that modal loop finish before allowing
  233031. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  233032. if ([menu respondsToSelector: @selector (cancelTracking)])
  233033. [menu performSelector: @selector (cancelTracking)];
  233034. }
  233035. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233036. menuBarItemsChanged (0);
  233037. }
  233038. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233039. {
  233040. if (currentModel != 0)
  233041. {
  233042. if (commandManager != 0)
  233043. {
  233044. ApplicationCommandTarget::InvocationInfo info (commandId);
  233045. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233046. commandManager->invoke (info, true);
  233047. }
  233048. currentModel->menuItemSelected (commandId, topLevelIndex);
  233049. }
  233050. }
  233051. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233052. const int topLevelMenuId, const int topLevelIndex)
  233053. {
  233054. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233055. if (text == 0)
  233056. text = @"";
  233057. if (iter.isSeparator)
  233058. {
  233059. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233060. }
  233061. else if (iter.isSectionHeader)
  233062. {
  233063. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233064. action: nil
  233065. keyEquivalent: @""];
  233066. [item setEnabled: false];
  233067. }
  233068. else if (iter.subMenu != 0)
  233069. {
  233070. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233071. action: nil
  233072. keyEquivalent: @""];
  233073. [item setTag: iter.itemId];
  233074. [item setEnabled: iter.isEnabled];
  233075. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233076. [sub setDelegate: nil];
  233077. [menuToAddTo setSubmenu: sub forItem: item];
  233078. [sub release];
  233079. }
  233080. else
  233081. {
  233082. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233083. action: @selector (menuItemInvoked:)
  233084. keyEquivalent: @""];
  233085. [item setTag: iter.itemId];
  233086. [item setEnabled: iter.isEnabled];
  233087. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233088. [item setTarget: (id) callback];
  233089. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233090. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233091. [item setRepresentedObject: info];
  233092. if (iter.commandManager != 0)
  233093. {
  233094. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233095. ->getKeyPressesAssignedToCommand (iter.itemId));
  233096. if (keyPresses.size() > 0)
  233097. {
  233098. const KeyPress& kp = keyPresses.getReference(0);
  233099. if (kp.getKeyCode() != KeyPress::backspaceKey
  233100. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233101. // every time you press the key while editing text)
  233102. {
  233103. juce_wchar key = kp.getTextCharacter();
  233104. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233105. key = NSBackspaceCharacter;
  233106. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233107. key = NSDeleteCharacter;
  233108. else if (key == 0)
  233109. key = (juce_wchar) kp.getKeyCode();
  233110. unsigned int mods = 0;
  233111. if (kp.getModifiers().isShiftDown())
  233112. mods |= NSShiftKeyMask;
  233113. if (kp.getModifiers().isCtrlDown())
  233114. mods |= NSControlKeyMask;
  233115. if (kp.getModifiers().isAltDown())
  233116. mods |= NSAlternateKeyMask;
  233117. if (kp.getModifiers().isCommandDown())
  233118. mods |= NSCommandKeyMask;
  233119. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233120. [item setKeyEquivalentModifierMask: mods];
  233121. }
  233122. }
  233123. }
  233124. }
  233125. }
  233126. static JuceMainMenuHandler* instance;
  233127. MenuBarModel* currentModel;
  233128. uint32 lastUpdateTime;
  233129. JuceMenuCallback* callback;
  233130. private:
  233131. NSMenu* createMenu (const PopupMenu menu,
  233132. const String& menuName,
  233133. const int topLevelMenuId,
  233134. const int topLevelIndex)
  233135. {
  233136. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233137. [m setAutoenablesItems: false];
  233138. [m setDelegate: callback];
  233139. PopupMenu::MenuItemIterator iter (menu);
  233140. while (iter.next())
  233141. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233142. [m update];
  233143. return m;
  233144. }
  233145. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233146. {
  233147. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233148. {
  233149. NSMenuItem* m = [menu itemAtIndex: i];
  233150. if ([m tag] == info.commandID)
  233151. return m;
  233152. if ([m submenu] != 0)
  233153. {
  233154. NSMenuItem* found = findMenuItem ([m submenu], info);
  233155. if (found != 0)
  233156. return found;
  233157. }
  233158. }
  233159. return 0;
  233160. }
  233161. static void flashMenuBar (NSMenu* menu)
  233162. {
  233163. if ([[menu title] isEqualToString: @"Apple"])
  233164. return;
  233165. [menu retain];
  233166. const unichar f35Key = NSF35FunctionKey;
  233167. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233168. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233169. action: nil
  233170. keyEquivalent: f35String];
  233171. [item setTarget: nil];
  233172. [menu insertItem: item atIndex: [menu numberOfItems]];
  233173. [item release];
  233174. if ([menu indexOfItem: item] >= 0)
  233175. {
  233176. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233177. location: NSZeroPoint
  233178. modifierFlags: NSCommandKeyMask
  233179. timestamp: 0
  233180. windowNumber: 0
  233181. context: [NSGraphicsContext currentContext]
  233182. characters: f35String
  233183. charactersIgnoringModifiers: f35String
  233184. isARepeat: NO
  233185. keyCode: 0];
  233186. [menu performKeyEquivalent: f35Event];
  233187. if ([menu indexOfItem: item] >= 0)
  233188. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233189. }
  233190. [menu release];
  233191. }
  233192. };
  233193. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233194. END_JUCE_NAMESPACE
  233195. @implementation JuceMenuCallback
  233196. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233197. {
  233198. [super init];
  233199. owner = owner_;
  233200. return self;
  233201. }
  233202. - (void) dealloc
  233203. {
  233204. [super dealloc];
  233205. }
  233206. - (void) menuItemInvoked: (id) menu
  233207. {
  233208. NSMenuItem* item = (NSMenuItem*) menu;
  233209. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233210. {
  233211. // 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
  233212. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233213. // into the focused component and let it trigger the menu item indirectly.
  233214. NSEvent* e = [NSApp currentEvent];
  233215. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233216. {
  233217. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233218. {
  233219. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233220. if (peer != 0)
  233221. {
  233222. if ([e type] == NSKeyDown)
  233223. peer->redirectKeyDown (e);
  233224. else
  233225. peer->redirectKeyUp (e);
  233226. return;
  233227. }
  233228. }
  233229. }
  233230. NSArray* info = (NSArray*) [item representedObject];
  233231. owner->invoke ((int) [item tag],
  233232. (ApplicationCommandManager*) (pointer_sized_int)
  233233. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233234. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233235. }
  233236. }
  233237. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233238. {
  233239. if (JuceMainMenuHandler::instance != 0)
  233240. JuceMainMenuHandler::instance->updateMenus (menu);
  233241. }
  233242. @end
  233243. BEGIN_JUCE_NAMESPACE
  233244. namespace MainMenuHelpers
  233245. {
  233246. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  233247. {
  233248. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233249. {
  233250. PopupMenu::MenuItemIterator iter (*extraItems);
  233251. while (iter.next())
  233252. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233253. [menu addItem: [NSMenuItem separatorItem]];
  233254. }
  233255. NSMenuItem* item;
  233256. // Services...
  233257. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233258. action: nil keyEquivalent: @""];
  233259. [menu addItem: item];
  233260. [item release];
  233261. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233262. [menu setSubmenu: servicesMenu forItem: item];
  233263. [NSApp setServicesMenu: servicesMenu];
  233264. [servicesMenu release];
  233265. [menu addItem: [NSMenuItem separatorItem]];
  233266. // Hide + Show stuff...
  233267. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233268. action: @selector (hide:) keyEquivalent: @"h"];
  233269. [item setTarget: NSApp];
  233270. [menu addItem: item];
  233271. [item release];
  233272. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233273. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233274. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233275. [item setTarget: NSApp];
  233276. [menu addItem: item];
  233277. [item release];
  233278. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233279. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233280. [item setTarget: NSApp];
  233281. [menu addItem: item];
  233282. [item release];
  233283. [menu addItem: [NSMenuItem separatorItem]];
  233284. // Quit item....
  233285. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233286. action: @selector (terminate:) keyEquivalent: @"q"];
  233287. [item setTarget: NSApp];
  233288. [menu addItem: item];
  233289. [item release];
  233290. return menu;
  233291. }
  233292. // Since our app has no NIB, this initialises a standard app menu...
  233293. void rebuildMainMenu (const PopupMenu* extraItems)
  233294. {
  233295. // this can't be used in a plugin!
  233296. jassert (JUCEApplication::isStandaloneApp());
  233297. if (JUCEApplication::getInstance() != 0)
  233298. {
  233299. const ScopedAutoReleasePool pool;
  233300. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233301. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233302. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233303. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233304. [mainMenu setSubmenu: appMenu forItem: item];
  233305. [NSApp setMainMenu: mainMenu];
  233306. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233307. [appMenu release];
  233308. [mainMenu release];
  233309. }
  233310. }
  233311. }
  233312. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233313. const PopupMenu* extraAppleMenuItems)
  233314. {
  233315. if (getMacMainMenu() != newMenuBarModel)
  233316. {
  233317. const ScopedAutoReleasePool pool;
  233318. if (newMenuBarModel == 0)
  233319. {
  233320. delete JuceMainMenuHandler::instance;
  233321. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233322. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233323. extraAppleMenuItems = 0;
  233324. }
  233325. else
  233326. {
  233327. if (JuceMainMenuHandler::instance == 0)
  233328. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233329. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233330. }
  233331. }
  233332. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  233333. if (newMenuBarModel != 0)
  233334. newMenuBarModel->menuItemsChanged();
  233335. }
  233336. MenuBarModel* MenuBarModel::getMacMainMenu()
  233337. {
  233338. return JuceMainMenuHandler::instance != 0
  233339. ? JuceMainMenuHandler::instance->currentModel : 0;
  233340. }
  233341. void juce_initialiseMacMainMenu()
  233342. {
  233343. if (JuceMainMenuHandler::instance == 0)
  233344. MainMenuHelpers::rebuildMainMenu (0);
  233345. }
  233346. #endif
  233347. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233348. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233349. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233350. // compiled on its own).
  233351. #if JUCE_INCLUDED_FILE
  233352. #if JUCE_MAC
  233353. END_JUCE_NAMESPACE
  233354. using namespace JUCE_NAMESPACE;
  233355. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233356. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233357. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233358. #else
  233359. @interface JuceFileChooserDelegate : NSObject
  233360. #endif
  233361. {
  233362. StringArray* filters;
  233363. }
  233364. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233365. - (void) dealloc;
  233366. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233367. @end
  233368. @implementation JuceFileChooserDelegate
  233369. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233370. {
  233371. [super init];
  233372. filters = filters_;
  233373. return self;
  233374. }
  233375. - (void) dealloc
  233376. {
  233377. delete filters;
  233378. [super dealloc];
  233379. }
  233380. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233381. {
  233382. (void) sender;
  233383. const File f (nsStringToJuce (filename));
  233384. for (int i = filters->size(); --i >= 0;)
  233385. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233386. return true;
  233387. return f.isDirectory();
  233388. }
  233389. @end
  233390. BEGIN_JUCE_NAMESPACE
  233391. void FileChooser::showPlatformDialog (Array<File>& results,
  233392. const String& title,
  233393. const File& currentFileOrDirectory,
  233394. const String& filter,
  233395. bool selectsDirectory,
  233396. bool selectsFiles,
  233397. bool isSaveDialogue,
  233398. bool /*warnAboutOverwritingExistingFiles*/,
  233399. bool selectMultipleFiles,
  233400. FilePreviewComponent* /*extraInfoComponent*/)
  233401. {
  233402. const ScopedAutoReleasePool pool;
  233403. StringArray* filters = new StringArray();
  233404. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233405. filters->trim();
  233406. filters->removeEmptyStrings();
  233407. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233408. [delegate autorelease];
  233409. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233410. : [NSOpenPanel openPanel];
  233411. [panel setTitle: juceStringToNS (title)];
  233412. if (! isSaveDialogue)
  233413. {
  233414. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233415. [openPanel setCanChooseDirectories: selectsDirectory];
  233416. [openPanel setCanChooseFiles: selectsFiles];
  233417. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233418. }
  233419. [panel setDelegate: delegate];
  233420. if (isSaveDialogue || selectsDirectory)
  233421. [panel setCanCreateDirectories: YES];
  233422. String directory, filename;
  233423. if (currentFileOrDirectory.isDirectory())
  233424. {
  233425. directory = currentFileOrDirectory.getFullPathName();
  233426. }
  233427. else
  233428. {
  233429. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233430. filename = currentFileOrDirectory.getFileName();
  233431. }
  233432. if ([panel runModalForDirectory: juceStringToNS (directory)
  233433. file: juceStringToNS (filename)]
  233434. == NSOKButton)
  233435. {
  233436. if (isSaveDialogue)
  233437. {
  233438. results.add (File (nsStringToJuce ([panel filename])));
  233439. }
  233440. else
  233441. {
  233442. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233443. NSArray* urls = [openPanel filenames];
  233444. for (unsigned int i = 0; i < [urls count]; ++i)
  233445. {
  233446. NSString* f = [urls objectAtIndex: i];
  233447. results.add (File (nsStringToJuce (f)));
  233448. }
  233449. }
  233450. }
  233451. [panel setDelegate: nil];
  233452. }
  233453. #else
  233454. void FileChooser::showPlatformDialog (Array<File>& results,
  233455. const String& title,
  233456. const File& currentFileOrDirectory,
  233457. const String& filter,
  233458. bool selectsDirectory,
  233459. bool selectsFiles,
  233460. bool isSaveDialogue,
  233461. bool warnAboutOverwritingExistingFiles,
  233462. bool selectMultipleFiles,
  233463. FilePreviewComponent* extraInfoComponent)
  233464. {
  233465. const ScopedAutoReleasePool pool;
  233466. jassertfalse; //xxx to do
  233467. }
  233468. #endif
  233469. #endif
  233470. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233471. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233472. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233473. // compiled on its own).
  233474. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233475. END_JUCE_NAMESPACE
  233476. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233477. @interface NonInterceptingQTMovieView : QTMovieView
  233478. {
  233479. }
  233480. - (id) initWithFrame: (NSRect) frame;
  233481. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233482. - (NSView*) hitTest: (NSPoint) p;
  233483. @end
  233484. @implementation NonInterceptingQTMovieView
  233485. - (id) initWithFrame: (NSRect) frame
  233486. {
  233487. self = [super initWithFrame: frame];
  233488. [self setNextResponder: [self superview]];
  233489. return self;
  233490. }
  233491. - (void) dealloc
  233492. {
  233493. [super dealloc];
  233494. }
  233495. - (NSView*) hitTest: (NSPoint) point
  233496. {
  233497. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233498. }
  233499. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233500. {
  233501. return YES;
  233502. }
  233503. @end
  233504. BEGIN_JUCE_NAMESPACE
  233505. #define theMovie (static_cast <QTMovie*> (movie))
  233506. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233507. : movie (0)
  233508. {
  233509. setOpaque (true);
  233510. setVisible (true);
  233511. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233512. setView (view);
  233513. [view release];
  233514. }
  233515. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233516. {
  233517. closeMovie();
  233518. setView (0);
  233519. }
  233520. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233521. {
  233522. return true;
  233523. }
  233524. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233525. {
  233526. // unfortunately, QTMovie objects can only be created on the main thread..
  233527. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233528. QTMovie* movie = 0;
  233529. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233530. if (fin != 0)
  233531. {
  233532. movieFile = fin->getFile();
  233533. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233534. error: nil];
  233535. }
  233536. else
  233537. {
  233538. MemoryBlock temp;
  233539. movieStream->readIntoMemoryBlock (temp);
  233540. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233541. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233542. {
  233543. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233544. length: temp.getSize()]
  233545. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233546. MIMEType: @""]
  233547. error: nil];
  233548. if (movie != 0)
  233549. break;
  233550. }
  233551. }
  233552. return movie;
  233553. }
  233554. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233555. const bool isControllerVisible_)
  233556. {
  233557. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233558. }
  233559. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233560. const bool controllerVisible_)
  233561. {
  233562. closeMovie();
  233563. if (getPeer() == 0)
  233564. {
  233565. // To open a movie, this component must be visible inside a functioning window, so that
  233566. // the QT control can be assigned to the window.
  233567. jassertfalse;
  233568. return false;
  233569. }
  233570. movie = openMovieFromStream (movieStream, movieFile);
  233571. [theMovie retain];
  233572. QTMovieView* view = (QTMovieView*) getView();
  233573. [view setMovie: theMovie];
  233574. [view setControllerVisible: controllerVisible_];
  233575. setLooping (looping);
  233576. return movie != nil;
  233577. }
  233578. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233579. const bool isControllerVisible_)
  233580. {
  233581. // unfortunately, QTMovie objects can only be created on the main thread..
  233582. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233583. closeMovie();
  233584. if (getPeer() == 0)
  233585. {
  233586. // To open a movie, this component must be visible inside a functioning window, so that
  233587. // the QT control can be assigned to the window.
  233588. jassertfalse;
  233589. return false;
  233590. }
  233591. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233592. NSError* err;
  233593. if ([QTMovie canInitWithURL: url])
  233594. movie = [QTMovie movieWithURL: url error: &err];
  233595. [theMovie retain];
  233596. QTMovieView* view = (QTMovieView*) getView();
  233597. [view setMovie: theMovie];
  233598. [view setControllerVisible: controllerVisible];
  233599. setLooping (looping);
  233600. return movie != nil;
  233601. }
  233602. void QuickTimeMovieComponent::closeMovie()
  233603. {
  233604. stop();
  233605. QTMovieView* view = (QTMovieView*) getView();
  233606. [view setMovie: nil];
  233607. [theMovie release];
  233608. movie = 0;
  233609. movieFile = File::nonexistent;
  233610. }
  233611. bool QuickTimeMovieComponent::isMovieOpen() const
  233612. {
  233613. return movie != nil;
  233614. }
  233615. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233616. {
  233617. return movieFile;
  233618. }
  233619. void QuickTimeMovieComponent::play()
  233620. {
  233621. [theMovie play];
  233622. }
  233623. void QuickTimeMovieComponent::stop()
  233624. {
  233625. [theMovie stop];
  233626. }
  233627. bool QuickTimeMovieComponent::isPlaying() const
  233628. {
  233629. return movie != 0 && [theMovie rate] != 0;
  233630. }
  233631. void QuickTimeMovieComponent::setPosition (const double seconds)
  233632. {
  233633. if (movie != 0)
  233634. {
  233635. QTTime t;
  233636. t.timeValue = (uint64) (100000.0 * seconds);
  233637. t.timeScale = 100000;
  233638. t.flags = 0;
  233639. [theMovie setCurrentTime: t];
  233640. }
  233641. }
  233642. double QuickTimeMovieComponent::getPosition() const
  233643. {
  233644. if (movie == 0)
  233645. return 0.0;
  233646. QTTime t = [theMovie currentTime];
  233647. return t.timeValue / (double) t.timeScale;
  233648. }
  233649. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233650. {
  233651. [theMovie setRate: newSpeed];
  233652. }
  233653. double QuickTimeMovieComponent::getMovieDuration() const
  233654. {
  233655. if (movie == 0)
  233656. return 0.0;
  233657. QTTime t = [theMovie duration];
  233658. return t.timeValue / (double) t.timeScale;
  233659. }
  233660. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233661. {
  233662. looping = shouldLoop;
  233663. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233664. forKey: QTMovieLoopsAttribute];
  233665. }
  233666. bool QuickTimeMovieComponent::isLooping() const
  233667. {
  233668. return looping;
  233669. }
  233670. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233671. {
  233672. [theMovie setVolume: newVolume];
  233673. }
  233674. float QuickTimeMovieComponent::getMovieVolume() const
  233675. {
  233676. return movie != 0 ? [theMovie volume] : 0.0f;
  233677. }
  233678. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233679. {
  233680. width = 0;
  233681. height = 0;
  233682. if (movie != 0)
  233683. {
  233684. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233685. width = (int) s.width;
  233686. height = (int) s.height;
  233687. }
  233688. }
  233689. void QuickTimeMovieComponent::paint (Graphics& g)
  233690. {
  233691. if (movie == 0)
  233692. g.fillAll (Colours::black);
  233693. }
  233694. bool QuickTimeMovieComponent::isControllerVisible() const
  233695. {
  233696. return controllerVisible;
  233697. }
  233698. void QuickTimeMovieComponent::goToStart()
  233699. {
  233700. setPosition (0.0);
  233701. }
  233702. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233703. const RectanglePlacement& placement)
  233704. {
  233705. int normalWidth, normalHeight;
  233706. getMovieNormalSize (normalWidth, normalHeight);
  233707. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  233708. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  233709. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  233710. else
  233711. setBounds (spaceToFitWithin);
  233712. }
  233713. #if ! (JUCE_MAC && JUCE_64BIT)
  233714. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233715. {
  233716. if (movieStream == 0)
  233717. return false;
  233718. File file;
  233719. QTMovie* movie = openMovieFromStream (movieStream, file);
  233720. if (movie != nil)
  233721. result = [movie quickTimeMovie];
  233722. return movie != nil;
  233723. }
  233724. #endif
  233725. #endif
  233726. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233727. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233728. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233729. // compiled on its own).
  233730. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233731. const int kilobytesPerSecond1x = 176;
  233732. END_JUCE_NAMESPACE
  233733. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233734. @interface OpenDiskDevice : NSObject
  233735. {
  233736. @public
  233737. DRDevice* device;
  233738. NSMutableArray* tracks;
  233739. bool underrunProtection;
  233740. }
  233741. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233742. - (void) dealloc;
  233743. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233744. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233745. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233746. @end
  233747. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233748. @interface AudioTrackProducer : NSObject
  233749. {
  233750. JUCE_NAMESPACE::AudioSource* source;
  233751. int readPosition, lengthInFrames;
  233752. }
  233753. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233754. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233755. - (void) dealloc;
  233756. - (void) setupTrackProperties: (DRTrack*) track;
  233757. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233758. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233759. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233760. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233761. toMedia:(NSDictionary*)mediaInfo;
  233762. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233763. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233764. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233765. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233766. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233767. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233768. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233769. ioFlags:(uint32_t*)flags;
  233770. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233771. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233772. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233773. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233774. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233775. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233776. ioFlags:(uint32_t*)flags;
  233777. @end
  233778. @implementation OpenDiskDevice
  233779. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233780. {
  233781. [super init];
  233782. device = device_;
  233783. tracks = [[NSMutableArray alloc] init];
  233784. underrunProtection = true;
  233785. return self;
  233786. }
  233787. - (void) dealloc
  233788. {
  233789. [tracks release];
  233790. [super dealloc];
  233791. }
  233792. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233793. {
  233794. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233795. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233796. [p setupTrackProperties: t];
  233797. [tracks addObject: t];
  233798. [t release];
  233799. [p release];
  233800. }
  233801. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233802. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  233803. {
  233804. DRBurn* burn = [DRBurn burnForDevice: device];
  233805. if (! [device acquireExclusiveAccess])
  233806. {
  233807. *error = "Couldn't open or write to the CD device";
  233808. return;
  233809. }
  233810. [device acquireMediaReservation];
  233811. NSMutableDictionary* d = [[burn properties] mutableCopy];
  233812. [d autorelease];
  233813. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  233814. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  233815. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  233816. if (burnSpeed > 0)
  233817. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  233818. if (! underrunProtection)
  233819. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  233820. [burn setProperties: d];
  233821. [burn writeLayout: tracks];
  233822. for (;;)
  233823. {
  233824. JUCE_NAMESPACE::Thread::sleep (300);
  233825. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  233826. if (listener != 0 && listener->audioCDBurnProgress (progress))
  233827. {
  233828. [burn abort];
  233829. *error = "User cancelled the write operation";
  233830. break;
  233831. }
  233832. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  233833. {
  233834. *error = "Write operation failed";
  233835. break;
  233836. }
  233837. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  233838. {
  233839. break;
  233840. }
  233841. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  233842. objectForKey: DRErrorStatusErrorStringKey];
  233843. if ([err length] > 0)
  233844. {
  233845. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  233846. break;
  233847. }
  233848. }
  233849. [device releaseMediaReservation];
  233850. [device releaseExclusiveAccess];
  233851. }
  233852. @end
  233853. @implementation AudioTrackProducer
  233854. - (AudioTrackProducer*) init: (int) lengthInFrames_
  233855. {
  233856. lengthInFrames = lengthInFrames_;
  233857. readPosition = 0;
  233858. return self;
  233859. }
  233860. - (void) setupTrackProperties: (DRTrack*) track
  233861. {
  233862. NSMutableDictionary* p = [[track properties] mutableCopy];
  233863. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  233864. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  233865. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  233866. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  233867. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  233868. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  233869. [track setProperties: p];
  233870. [p release];
  233871. }
  233872. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  233873. {
  233874. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  233875. if (s != nil)
  233876. s->source = source_;
  233877. return s;
  233878. }
  233879. - (void) dealloc
  233880. {
  233881. if (source != 0)
  233882. {
  233883. source->releaseResources();
  233884. delete source;
  233885. }
  233886. [super dealloc];
  233887. }
  233888. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  233889. {
  233890. (void) track;
  233891. }
  233892. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  233893. {
  233894. (void) track;
  233895. return true;
  233896. }
  233897. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  233898. {
  233899. (void) track;
  233900. return lengthInFrames;
  233901. }
  233902. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  233903. toMedia: (NSDictionary*) mediaInfo
  233904. {
  233905. (void) track; (void) burn; (void) mediaInfo;
  233906. if (source != 0)
  233907. source->prepareToPlay (44100 / 75, 44100);
  233908. readPosition = 0;
  233909. return true;
  233910. }
  233911. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  233912. {
  233913. (void) track;
  233914. if (source != 0)
  233915. source->prepareToPlay (44100 / 75, 44100);
  233916. return true;
  233917. }
  233918. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  233919. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233920. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233921. {
  233922. (void) track; (void) address; (void) blockSize; (void) flags;
  233923. if (source != 0)
  233924. {
  233925. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  233926. if (numSamples > 0)
  233927. {
  233928. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  233929. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  233930. info.buffer = &tempBuffer;
  233931. info.startSample = 0;
  233932. info.numSamples = numSamples;
  233933. source->getNextAudioBlock (info);
  233934. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  233935. JUCE_NAMESPACE::AudioData::LittleEndian,
  233936. JUCE_NAMESPACE::AudioData::Interleaved,
  233937. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  233938. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  233939. JUCE_NAMESPACE::AudioData::NativeEndian,
  233940. JUCE_NAMESPACE::AudioData::NonInterleaved,
  233941. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  233942. CDSampleFormat left (buffer, 2);
  233943. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  233944. CDSampleFormat right (buffer + 2, 2);
  233945. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  233946. readPosition += numSamples;
  233947. }
  233948. return numSamples * 4;
  233949. }
  233950. return 0;
  233951. }
  233952. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  233953. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  233954. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  233955. ioFlags: (uint32_t*) flags
  233956. {
  233957. (void) track; (void) address; (void) blockSize; (void) flags;
  233958. zeromem (buffer, bufferLength);
  233959. return bufferLength;
  233960. }
  233961. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  233962. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233963. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233964. {
  233965. (void) track; (void) buffer; (void) bufferLength; (void) address; (void) blockSize; (void) flags;
  233966. return true;
  233967. }
  233968. @end
  233969. BEGIN_JUCE_NAMESPACE
  233970. class AudioCDBurner::Pimpl : public Timer
  233971. {
  233972. public:
  233973. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  233974. : device (0), owner (owner_)
  233975. {
  233976. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  233977. if (dev != 0)
  233978. {
  233979. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  233980. lastState = getDiskState();
  233981. startTimer (1000);
  233982. }
  233983. }
  233984. ~Pimpl()
  233985. {
  233986. stopTimer();
  233987. [device release];
  233988. }
  233989. void timerCallback()
  233990. {
  233991. const DiskState state = getDiskState();
  233992. if (state != lastState)
  233993. {
  233994. lastState = state;
  233995. owner.sendChangeMessage();
  233996. }
  233997. }
  233998. DiskState getDiskState() const
  233999. {
  234000. if ([device->device isValid])
  234001. {
  234002. NSDictionary* status = [device->device status];
  234003. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234004. if ([state isEqualTo: DRDeviceMediaStateNone])
  234005. {
  234006. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234007. return trayOpen;
  234008. return noDisc;
  234009. }
  234010. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234011. {
  234012. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234013. return writableDiskPresent;
  234014. else
  234015. return readOnlyDiskPresent;
  234016. }
  234017. }
  234018. return unknown;
  234019. }
  234020. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234021. const Array<int> getAvailableWriteSpeeds() const
  234022. {
  234023. Array<int> results;
  234024. if ([device->device isValid])
  234025. {
  234026. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234027. for (unsigned int i = 0; i < [speeds count]; ++i)
  234028. {
  234029. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234030. results.add (kbPerSec / kilobytesPerSecond1x);
  234031. }
  234032. }
  234033. return results;
  234034. }
  234035. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234036. {
  234037. if ([device->device isValid])
  234038. {
  234039. device->underrunProtection = shouldBeEnabled;
  234040. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234041. }
  234042. return false;
  234043. }
  234044. int getNumAvailableAudioBlocks() const
  234045. {
  234046. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234047. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234048. }
  234049. OpenDiskDevice* device;
  234050. private:
  234051. DiskState lastState;
  234052. AudioCDBurner& owner;
  234053. };
  234054. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234055. {
  234056. pimpl = new Pimpl (*this, deviceIndex);
  234057. }
  234058. AudioCDBurner::~AudioCDBurner()
  234059. {
  234060. }
  234061. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234062. {
  234063. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234064. if (b->pimpl->device == 0)
  234065. b = 0;
  234066. return b.release();
  234067. }
  234068. namespace
  234069. {
  234070. NSArray* findDiskBurnerDevices()
  234071. {
  234072. NSMutableArray* results = [NSMutableArray array];
  234073. NSArray* devs = [DRDevice devices];
  234074. for (int i = 0; i < [devs count]; ++i)
  234075. {
  234076. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234077. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234078. if (name != nil)
  234079. [results addObject: name];
  234080. }
  234081. return results;
  234082. }
  234083. }
  234084. const StringArray AudioCDBurner::findAvailableDevices()
  234085. {
  234086. NSArray* names = findDiskBurnerDevices();
  234087. StringArray s;
  234088. for (unsigned int i = 0; i < [names count]; ++i)
  234089. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234090. return s;
  234091. }
  234092. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234093. {
  234094. return pimpl->getDiskState();
  234095. }
  234096. bool AudioCDBurner::isDiskPresent() const
  234097. {
  234098. return getDiskState() == writableDiskPresent;
  234099. }
  234100. bool AudioCDBurner::openTray()
  234101. {
  234102. return pimpl->openTray();
  234103. }
  234104. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234105. {
  234106. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234107. DiskState oldState = getDiskState();
  234108. DiskState newState = oldState;
  234109. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234110. {
  234111. newState = getDiskState();
  234112. Thread::sleep (100);
  234113. }
  234114. return newState;
  234115. }
  234116. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234117. {
  234118. return pimpl->getAvailableWriteSpeeds();
  234119. }
  234120. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234121. {
  234122. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234123. }
  234124. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234125. {
  234126. return pimpl->getNumAvailableAudioBlocks();
  234127. }
  234128. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234129. {
  234130. if ([pimpl->device->device isValid])
  234131. {
  234132. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234133. return true;
  234134. }
  234135. return false;
  234136. }
  234137. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234138. bool ejectDiscAfterwards,
  234139. bool performFakeBurnForTesting,
  234140. int writeSpeed)
  234141. {
  234142. String error ("Couldn't open or write to the CD device");
  234143. if ([pimpl->device->device isValid])
  234144. {
  234145. error = String::empty;
  234146. [pimpl->device burn: listener
  234147. errorString: &error
  234148. ejectAfterwards: ejectDiscAfterwards
  234149. isFake: performFakeBurnForTesting
  234150. speed: writeSpeed];
  234151. }
  234152. return error;
  234153. }
  234154. #endif
  234155. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234156. void AudioCDReader::ejectDisk()
  234157. {
  234158. const ScopedAutoReleasePool p;
  234159. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234160. }
  234161. #endif
  234162. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234163. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234164. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234165. // compiled on its own).
  234166. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234167. namespace CDReaderHelpers
  234168. {
  234169. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234170. {
  234171. forEachXmlChildElementWithTagName (xml, child, "key")
  234172. if (child->getAllSubText().trim() == key)
  234173. return child->getNextElement();
  234174. return 0;
  234175. }
  234176. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234177. {
  234178. const XmlElement* const block = getElementForKey (xml, key);
  234179. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234180. }
  234181. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234182. // Returns NULL on success, otherwise a const char* representing an error.
  234183. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234184. {
  234185. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234186. if (xml == 0)
  234187. return "Couldn't parse XML in file";
  234188. const XmlElement* const dict = xml->getChildByName ("dict");
  234189. if (dict == 0)
  234190. return "Couldn't get top level dictionary";
  234191. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234192. if (sessions == 0)
  234193. return "Couldn't find sessions key";
  234194. const XmlElement* const session = sessions->getFirstChildElement();
  234195. if (session == 0)
  234196. return "Couldn't find first session";
  234197. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234198. if (leadOut < 0)
  234199. return "Couldn't find Leadout Block";
  234200. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234201. if (trackArray == 0)
  234202. return "Couldn't find Track Array";
  234203. forEachXmlChildElement (*trackArray, track)
  234204. {
  234205. const int trackValue = getIntValueForKey (*track, "Start Block");
  234206. if (trackValue < 0)
  234207. return "Couldn't find Start Block in the track";
  234208. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234209. }
  234210. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234211. return 0;
  234212. }
  234213. static void findDevices (Array<File>& cds)
  234214. {
  234215. File volumes ("/Volumes");
  234216. volumes.findChildFiles (cds, File::findDirectories, false);
  234217. for (int i = cds.size(); --i >= 0;)
  234218. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234219. cds.remove (i);
  234220. }
  234221. struct TrackSorter
  234222. {
  234223. static int getCDTrackNumber (const File& file)
  234224. {
  234225. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234226. }
  234227. static int compareElements (const File& first, const File& second)
  234228. {
  234229. const int firstTrack = getCDTrackNumber (first);
  234230. const int secondTrack = getCDTrackNumber (second);
  234231. jassert (firstTrack > 0 && secondTrack > 0);
  234232. return firstTrack - secondTrack;
  234233. }
  234234. };
  234235. }
  234236. const StringArray AudioCDReader::getAvailableCDNames()
  234237. {
  234238. Array<File> cds;
  234239. CDReaderHelpers::findDevices (cds);
  234240. StringArray names;
  234241. for (int i = 0; i < cds.size(); ++i)
  234242. names.add (cds.getReference(i).getFileName());
  234243. return names;
  234244. }
  234245. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234246. {
  234247. Array<File> cds;
  234248. CDReaderHelpers::findDevices (cds);
  234249. if (cds[index].exists())
  234250. return new AudioCDReader (cds[index]);
  234251. return 0;
  234252. }
  234253. AudioCDReader::AudioCDReader (const File& volume)
  234254. : AudioFormatReader (0, "CD Audio"),
  234255. volumeDir (volume),
  234256. currentReaderTrack (-1),
  234257. reader (0)
  234258. {
  234259. sampleRate = 44100.0;
  234260. bitsPerSample = 16;
  234261. numChannels = 2;
  234262. usesFloatingPointData = false;
  234263. refreshTrackLengths();
  234264. }
  234265. AudioCDReader::~AudioCDReader()
  234266. {
  234267. }
  234268. void AudioCDReader::refreshTrackLengths()
  234269. {
  234270. tracks.clear();
  234271. trackStartSamples.clear();
  234272. lengthInSamples = 0;
  234273. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234274. CDReaderHelpers::TrackSorter sorter;
  234275. tracks.sort (sorter);
  234276. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234277. if (toc.exists())
  234278. {
  234279. XmlDocument doc (toc);
  234280. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234281. (void) error; // could be logged..
  234282. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234283. }
  234284. }
  234285. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234286. int64 startSampleInFile, int numSamples)
  234287. {
  234288. while (numSamples > 0)
  234289. {
  234290. int track = -1;
  234291. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234292. {
  234293. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234294. {
  234295. track = i;
  234296. break;
  234297. }
  234298. }
  234299. if (track < 0)
  234300. return false;
  234301. if (track != currentReaderTrack)
  234302. {
  234303. reader = 0;
  234304. FileInputStream* const in = tracks [track].createInputStream();
  234305. if (in != 0)
  234306. {
  234307. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234308. AiffAudioFormat format;
  234309. reader = format.createReaderFor (bin, true);
  234310. if (reader == 0)
  234311. currentReaderTrack = -1;
  234312. else
  234313. currentReaderTrack = track;
  234314. }
  234315. }
  234316. if (reader == 0)
  234317. return false;
  234318. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234319. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234320. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234321. numSamples -= numAvailable;
  234322. startSampleInFile += numAvailable;
  234323. }
  234324. return true;
  234325. }
  234326. bool AudioCDReader::isCDStillPresent() const
  234327. {
  234328. return volumeDir.exists();
  234329. }
  234330. bool AudioCDReader::isTrackAudio (int trackNum) const
  234331. {
  234332. return tracks [trackNum].hasFileExtension (".aiff");
  234333. }
  234334. void AudioCDReader::enableIndexScanning (bool)
  234335. {
  234336. // any way to do this on a Mac??
  234337. }
  234338. int AudioCDReader::getLastIndex() const
  234339. {
  234340. return 0;
  234341. }
  234342. const Array <int> AudioCDReader::findIndexesInTrack (const int /*trackNumber*/)
  234343. {
  234344. return Array <int>();
  234345. }
  234346. #endif
  234347. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234348. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234349. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234350. // compiled on its own).
  234351. #if JUCE_INCLUDED_FILE
  234352. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234353. for example having more than one juce plugin loaded into a host, then when a
  234354. method is called, the actual code that runs might actually be in a different module
  234355. than the one you expect... So any calls to library functions or statics that are
  234356. made inside obj-c methods will probably end up getting executed in a different DLL's
  234357. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234358. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234359. virtual methods of an object that's known to live inside the right module's space.
  234360. */
  234361. class AppDelegateRedirector
  234362. {
  234363. public:
  234364. AppDelegateRedirector()
  234365. {
  234366. }
  234367. virtual ~AppDelegateRedirector()
  234368. {
  234369. }
  234370. virtual NSApplicationTerminateReply shouldTerminate()
  234371. {
  234372. if (JUCEApplication::getInstance() != 0)
  234373. {
  234374. JUCEApplication::getInstance()->systemRequestedQuit();
  234375. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234376. return NSTerminateCancel;
  234377. }
  234378. return NSTerminateNow;
  234379. }
  234380. virtual void willTerminate()
  234381. {
  234382. JUCEApplication::appWillTerminateByForce();
  234383. }
  234384. virtual BOOL openFile (NSString* filename)
  234385. {
  234386. if (JUCEApplication::getInstance() != 0)
  234387. {
  234388. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234389. return YES;
  234390. }
  234391. return NO;
  234392. }
  234393. virtual void openFiles (NSArray* filenames)
  234394. {
  234395. StringArray files;
  234396. for (unsigned int i = 0; i < [filenames count]; ++i)
  234397. {
  234398. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234399. if (filename.containsChar (' '))
  234400. filename = filename.quoted('"');
  234401. files.add (filename);
  234402. }
  234403. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234404. {
  234405. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234406. }
  234407. }
  234408. virtual void focusChanged()
  234409. {
  234410. juce_HandleProcessFocusChange();
  234411. }
  234412. struct CallbackMessagePayload
  234413. {
  234414. MessageCallbackFunction* function;
  234415. void* parameter;
  234416. void* volatile result;
  234417. bool volatile hasBeenExecuted;
  234418. };
  234419. virtual void performCallback (CallbackMessagePayload* pl)
  234420. {
  234421. pl->result = (*pl->function) (pl->parameter);
  234422. pl->hasBeenExecuted = true;
  234423. }
  234424. virtual void deleteSelf()
  234425. {
  234426. delete this;
  234427. }
  234428. void postMessage (Message* const m)
  234429. {
  234430. messageQueue.post (m);
  234431. }
  234432. private:
  234433. CFRunLoopRef runLoop;
  234434. CFRunLoopSourceRef runLoopSource;
  234435. MessageQueue messageQueue;
  234436. };
  234437. END_JUCE_NAMESPACE
  234438. using namespace JUCE_NAMESPACE;
  234439. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234440. @interface JuceAppDelegate : NSObject
  234441. {
  234442. @private
  234443. id oldDelegate;
  234444. @public
  234445. AppDelegateRedirector* redirector;
  234446. }
  234447. - (JuceAppDelegate*) init;
  234448. - (void) dealloc;
  234449. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234450. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234451. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234452. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234453. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234454. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234455. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234456. - (void) performCallback: (id) info;
  234457. - (void) dummyMethod;
  234458. @end
  234459. @implementation JuceAppDelegate
  234460. - (JuceAppDelegate*) init
  234461. {
  234462. [super init];
  234463. redirector = new AppDelegateRedirector();
  234464. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234465. if (JUCEApplication::isStandaloneApp())
  234466. {
  234467. oldDelegate = [NSApp delegate];
  234468. [NSApp setDelegate: self];
  234469. }
  234470. else
  234471. {
  234472. oldDelegate = 0;
  234473. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234474. name: NSApplicationDidResignActiveNotification object: NSApp];
  234475. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234476. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234477. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234478. name: NSApplicationWillUnhideNotification object: NSApp];
  234479. }
  234480. return self;
  234481. }
  234482. - (void) dealloc
  234483. {
  234484. if (oldDelegate != 0)
  234485. [NSApp setDelegate: oldDelegate];
  234486. redirector->deleteSelf();
  234487. [super dealloc];
  234488. }
  234489. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234490. {
  234491. (void) app;
  234492. return redirector->shouldTerminate();
  234493. }
  234494. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234495. {
  234496. (void) aNotification;
  234497. redirector->willTerminate();
  234498. }
  234499. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234500. {
  234501. (void) app;
  234502. return redirector->openFile (filename);
  234503. }
  234504. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234505. {
  234506. (void) sender;
  234507. return redirector->openFiles (filenames);
  234508. }
  234509. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234510. {
  234511. (void) notification;
  234512. redirector->focusChanged();
  234513. }
  234514. - (void) applicationDidResignActive: (NSNotification*) notification
  234515. {
  234516. (void) notification;
  234517. redirector->focusChanged();
  234518. }
  234519. - (void) applicationWillUnhide: (NSNotification*) notification
  234520. {
  234521. (void) notification;
  234522. redirector->focusChanged();
  234523. }
  234524. - (void) performCallback: (id) info
  234525. {
  234526. if ([info isKindOfClass: [NSData class]])
  234527. {
  234528. AppDelegateRedirector::CallbackMessagePayload* pl
  234529. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234530. if (pl != 0)
  234531. redirector->performCallback (pl);
  234532. }
  234533. else
  234534. {
  234535. jassertfalse; // should never get here!
  234536. }
  234537. }
  234538. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234539. @end
  234540. BEGIN_JUCE_NAMESPACE
  234541. static JuceAppDelegate* juceAppDelegate = 0;
  234542. void MessageManager::runDispatchLoop()
  234543. {
  234544. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234545. {
  234546. const ScopedAutoReleasePool pool;
  234547. // must only be called by the message thread!
  234548. jassert (isThisTheMessageThread());
  234549. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234550. @try
  234551. {
  234552. [NSApp run];
  234553. }
  234554. @catch (NSException* e)
  234555. {
  234556. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234557. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234558. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234559. }
  234560. @finally
  234561. {
  234562. }
  234563. #else
  234564. [NSApp run];
  234565. #endif
  234566. }
  234567. }
  234568. void MessageManager::stopDispatchLoop()
  234569. {
  234570. quitMessagePosted = true;
  234571. [NSApp stop: nil];
  234572. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234573. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234574. }
  234575. namespace
  234576. {
  234577. bool isEventBlockedByModalComps (NSEvent* e)
  234578. {
  234579. if (Component::getNumCurrentlyModalComponents() == 0)
  234580. return false;
  234581. NSWindow* const w = [e window];
  234582. if (w == 0 || [w worksWhenModal])
  234583. return false;
  234584. bool isKey = false, isInputAttempt = false;
  234585. switch ([e type])
  234586. {
  234587. case NSKeyDown:
  234588. case NSKeyUp:
  234589. isKey = isInputAttempt = true;
  234590. break;
  234591. case NSLeftMouseDown:
  234592. case NSRightMouseDown:
  234593. case NSOtherMouseDown:
  234594. isInputAttempt = true;
  234595. break;
  234596. case NSLeftMouseDragged:
  234597. case NSRightMouseDragged:
  234598. case NSLeftMouseUp:
  234599. case NSRightMouseUp:
  234600. case NSOtherMouseUp:
  234601. case NSOtherMouseDragged:
  234602. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234603. return false;
  234604. break;
  234605. case NSMouseMoved:
  234606. case NSMouseEntered:
  234607. case NSMouseExited:
  234608. case NSCursorUpdate:
  234609. case NSScrollWheel:
  234610. case NSTabletPoint:
  234611. case NSTabletProximity:
  234612. break;
  234613. default:
  234614. return false;
  234615. }
  234616. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234617. {
  234618. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234619. NSView* const compView = (NSView*) peer->getNativeHandle();
  234620. if ([compView window] == w)
  234621. {
  234622. if (isKey)
  234623. {
  234624. if (compView == [w firstResponder])
  234625. return false;
  234626. }
  234627. else
  234628. {
  234629. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234630. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234631. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234632. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234633. return false;
  234634. }
  234635. }
  234636. }
  234637. if (isInputAttempt)
  234638. {
  234639. if (! [NSApp isActive])
  234640. [NSApp activateIgnoringOtherApps: YES];
  234641. Component* const modal = Component::getCurrentlyModalComponent (0);
  234642. if (modal != 0)
  234643. modal->inputAttemptWhenModal();
  234644. }
  234645. return true;
  234646. }
  234647. }
  234648. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234649. {
  234650. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234651. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234652. while (! quitMessagePosted)
  234653. {
  234654. const ScopedAutoReleasePool pool;
  234655. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234656. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234657. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234658. inMode: NSDefaultRunLoopMode
  234659. dequeue: YES];
  234660. if (e != 0 && ! isEventBlockedByModalComps (e))
  234661. [NSApp sendEvent: e];
  234662. if (Time::getMillisecondCounter() >= endTime)
  234663. break;
  234664. }
  234665. return ! quitMessagePosted;
  234666. }
  234667. void MessageManager::doPlatformSpecificInitialisation()
  234668. {
  234669. if (juceAppDelegate == 0)
  234670. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234671. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234672. // correctly (needed prior to 10.5)
  234673. if (! [NSThread isMultiThreaded])
  234674. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234675. toTarget: juceAppDelegate
  234676. withObject: nil];
  234677. }
  234678. void MessageManager::doPlatformSpecificShutdown()
  234679. {
  234680. if (juceAppDelegate != 0)
  234681. {
  234682. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234683. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234684. [juceAppDelegate release];
  234685. juceAppDelegate = 0;
  234686. }
  234687. }
  234688. bool juce_postMessageToSystemQueue (Message* message)
  234689. {
  234690. juceAppDelegate->redirector->postMessage (message);
  234691. return true;
  234692. }
  234693. void MessageManager::broadcastMessage (const String&)
  234694. {
  234695. }
  234696. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234697. {
  234698. if (isThisTheMessageThread())
  234699. {
  234700. return (*callback) (data);
  234701. }
  234702. else
  234703. {
  234704. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234705. // deadlock because the message manager is blocked from running, so can never
  234706. // call your function..
  234707. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234708. const ScopedAutoReleasePool pool;
  234709. AppDelegateRedirector::CallbackMessagePayload cmp;
  234710. cmp.function = callback;
  234711. cmp.parameter = data;
  234712. cmp.result = 0;
  234713. cmp.hasBeenExecuted = false;
  234714. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234715. withObject: [NSData dataWithBytesNoCopy: &cmp
  234716. length: sizeof (cmp)
  234717. freeWhenDone: NO]
  234718. waitUntilDone: YES];
  234719. return cmp.result;
  234720. }
  234721. }
  234722. #endif
  234723. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234724. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234725. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234726. // compiled on its own).
  234727. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234728. #if JUCE_MAC
  234729. END_JUCE_NAMESPACE
  234730. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234731. @interface DownloadClickDetector : NSObject
  234732. {
  234733. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234734. }
  234735. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234736. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234737. request: (NSURLRequest*) request
  234738. frame: (WebFrame*) frame
  234739. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234740. @end
  234741. @implementation DownloadClickDetector
  234742. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234743. {
  234744. [super init];
  234745. ownerComponent = ownerComponent_;
  234746. return self;
  234747. }
  234748. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234749. request: (NSURLRequest*) request
  234750. frame: (WebFrame*) frame
  234751. decisionListener: (id <WebPolicyDecisionListener>) listener
  234752. {
  234753. (void) sender;
  234754. (void) request;
  234755. (void) frame;
  234756. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234757. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234758. [listener use];
  234759. else
  234760. [listener ignore];
  234761. }
  234762. @end
  234763. BEGIN_JUCE_NAMESPACE
  234764. class WebBrowserComponentInternal : public NSViewComponent
  234765. {
  234766. public:
  234767. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234768. {
  234769. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234770. frameName: @""
  234771. groupName: @""];
  234772. setView (webView);
  234773. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234774. [webView setPolicyDelegate: clickListener];
  234775. }
  234776. ~WebBrowserComponentInternal()
  234777. {
  234778. [webView setPolicyDelegate: nil];
  234779. [clickListener release];
  234780. setView (0);
  234781. }
  234782. void goToURL (const String& url,
  234783. const StringArray* headers,
  234784. const MemoryBlock* postData)
  234785. {
  234786. NSMutableURLRequest* r
  234787. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  234788. cachePolicy: NSURLRequestUseProtocolCachePolicy
  234789. timeoutInterval: 30.0];
  234790. if (postData != 0 && postData->getSize() > 0)
  234791. {
  234792. [r setHTTPMethod: @"POST"];
  234793. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  234794. length: postData->getSize()]];
  234795. }
  234796. if (headers != 0)
  234797. {
  234798. for (int i = 0; i < headers->size(); ++i)
  234799. {
  234800. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  234801. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  234802. [r setValue: juceStringToNS (headerValue)
  234803. forHTTPHeaderField: juceStringToNS (headerName)];
  234804. }
  234805. }
  234806. stop();
  234807. [[webView mainFrame] loadRequest: r];
  234808. }
  234809. void goBack()
  234810. {
  234811. [webView goBack];
  234812. }
  234813. void goForward()
  234814. {
  234815. [webView goForward];
  234816. }
  234817. void stop()
  234818. {
  234819. [webView stopLoading: nil];
  234820. }
  234821. void refresh()
  234822. {
  234823. [webView reload: nil];
  234824. }
  234825. void mouseMove (const MouseEvent&)
  234826. {
  234827. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  234828. // them work is to push them via this non-public method..
  234829. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  234830. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  234831. }
  234832. private:
  234833. WebView* webView;
  234834. DownloadClickDetector* clickListener;
  234835. };
  234836. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234837. : browser (0),
  234838. blankPageShown (false),
  234839. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  234840. {
  234841. setOpaque (true);
  234842. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  234843. }
  234844. WebBrowserComponent::~WebBrowserComponent()
  234845. {
  234846. deleteAndZero (browser);
  234847. }
  234848. void WebBrowserComponent::goToURL (const String& url,
  234849. const StringArray* headers,
  234850. const MemoryBlock* postData)
  234851. {
  234852. lastURL = url;
  234853. lastHeaders.clear();
  234854. if (headers != 0)
  234855. lastHeaders = *headers;
  234856. lastPostData.setSize (0);
  234857. if (postData != 0)
  234858. lastPostData = *postData;
  234859. blankPageShown = false;
  234860. browser->goToURL (url, headers, postData);
  234861. }
  234862. void WebBrowserComponent::stop()
  234863. {
  234864. browser->stop();
  234865. }
  234866. void WebBrowserComponent::goBack()
  234867. {
  234868. lastURL = String::empty;
  234869. blankPageShown = false;
  234870. browser->goBack();
  234871. }
  234872. void WebBrowserComponent::goForward()
  234873. {
  234874. lastURL = String::empty;
  234875. browser->goForward();
  234876. }
  234877. void WebBrowserComponent::refresh()
  234878. {
  234879. browser->refresh();
  234880. }
  234881. void WebBrowserComponent::paint (Graphics&)
  234882. {
  234883. }
  234884. void WebBrowserComponent::checkWindowAssociation()
  234885. {
  234886. if (isShowing())
  234887. {
  234888. if (blankPageShown)
  234889. goBack();
  234890. }
  234891. else
  234892. {
  234893. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  234894. {
  234895. // when the component becomes invisible, some stuff like flash
  234896. // carries on playing audio, so we need to force it onto a blank
  234897. // page to avoid this, (and send it back when it's made visible again).
  234898. blankPageShown = true;
  234899. browser->goToURL ("about:blank", 0, 0);
  234900. }
  234901. }
  234902. }
  234903. void WebBrowserComponent::reloadLastURL()
  234904. {
  234905. if (lastURL.isNotEmpty())
  234906. {
  234907. goToURL (lastURL, &lastHeaders, &lastPostData);
  234908. lastURL = String::empty;
  234909. }
  234910. }
  234911. void WebBrowserComponent::parentHierarchyChanged()
  234912. {
  234913. checkWindowAssociation();
  234914. }
  234915. void WebBrowserComponent::resized()
  234916. {
  234917. browser->setSize (getWidth(), getHeight());
  234918. }
  234919. void WebBrowserComponent::visibilityChanged()
  234920. {
  234921. checkWindowAssociation();
  234922. }
  234923. bool WebBrowserComponent::pageAboutToLoad (const String&)
  234924. {
  234925. return true;
  234926. }
  234927. #else
  234928. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234929. {
  234930. }
  234931. WebBrowserComponent::~WebBrowserComponent()
  234932. {
  234933. }
  234934. void WebBrowserComponent::goToURL (const String& url,
  234935. const StringArray* headers,
  234936. const MemoryBlock* postData)
  234937. {
  234938. }
  234939. void WebBrowserComponent::stop()
  234940. {
  234941. }
  234942. void WebBrowserComponent::goBack()
  234943. {
  234944. }
  234945. void WebBrowserComponent::goForward()
  234946. {
  234947. }
  234948. void WebBrowserComponent::refresh()
  234949. {
  234950. }
  234951. void WebBrowserComponent::paint (Graphics& g)
  234952. {
  234953. }
  234954. void WebBrowserComponent::checkWindowAssociation()
  234955. {
  234956. }
  234957. void WebBrowserComponent::reloadLastURL()
  234958. {
  234959. }
  234960. void WebBrowserComponent::parentHierarchyChanged()
  234961. {
  234962. }
  234963. void WebBrowserComponent::resized()
  234964. {
  234965. }
  234966. void WebBrowserComponent::visibilityChanged()
  234967. {
  234968. }
  234969. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  234970. {
  234971. return true;
  234972. }
  234973. #endif
  234974. #endif
  234975. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234976. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  234977. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234978. // compiled on its own).
  234979. #if JUCE_INCLUDED_FILE
  234980. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234981. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  234982. #endif
  234983. #undef log
  234984. #if JUCE_COREAUDIO_LOGGING_ENABLED
  234985. #define log(a) Logger::writeToLog (a)
  234986. #else
  234987. #define log(a)
  234988. #endif
  234989. #undef OK
  234990. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234991. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  234992. {
  234993. if (err == noErr)
  234994. return true;
  234995. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234996. jassertfalse;
  234997. return false;
  234998. }
  234999. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235000. #else
  235001. #define OK(a) (a == noErr)
  235002. #endif
  235003. class CoreAudioInternal : public Timer
  235004. {
  235005. public:
  235006. CoreAudioInternal (AudioDeviceID id)
  235007. : inputLatency (0),
  235008. outputLatency (0),
  235009. callback (0),
  235010. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235011. audioProcID (0),
  235012. #endif
  235013. isSlaveDevice (false),
  235014. deviceID (id),
  235015. started (false),
  235016. sampleRate (0),
  235017. bufferSize (512),
  235018. numInputChans (0),
  235019. numOutputChans (0),
  235020. callbacksAllowed (true),
  235021. numInputChannelInfos (0),
  235022. numOutputChannelInfos (0)
  235023. {
  235024. jassert (deviceID != 0);
  235025. updateDetailsFromDevice();
  235026. AudioObjectPropertyAddress pa;
  235027. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235028. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235029. pa.mElement = kAudioObjectPropertyElementWildcard;
  235030. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235031. }
  235032. ~CoreAudioInternal()
  235033. {
  235034. AudioObjectPropertyAddress pa;
  235035. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235036. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235037. pa.mElement = kAudioObjectPropertyElementWildcard;
  235038. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235039. stop (false);
  235040. }
  235041. void allocateTempBuffers()
  235042. {
  235043. const int tempBufSize = bufferSize + 4;
  235044. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235045. tempInputBuffers.calloc (numInputChans + 2);
  235046. tempOutputBuffers.calloc (numOutputChans + 2);
  235047. int i, count = 0;
  235048. for (i = 0; i < numInputChans; ++i)
  235049. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235050. for (i = 0; i < numOutputChans; ++i)
  235051. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235052. }
  235053. // returns the number of actual available channels
  235054. void fillInChannelInfo (const bool input)
  235055. {
  235056. int chanNum = 0;
  235057. UInt32 size;
  235058. AudioObjectPropertyAddress pa;
  235059. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235060. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235061. pa.mElement = kAudioObjectPropertyElementMaster;
  235062. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235063. {
  235064. HeapBlock <AudioBufferList> bufList;
  235065. bufList.calloc (size, 1);
  235066. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235067. {
  235068. const int numStreams = bufList->mNumberBuffers;
  235069. for (int i = 0; i < numStreams; ++i)
  235070. {
  235071. const AudioBuffer& b = bufList->mBuffers[i];
  235072. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235073. {
  235074. String name;
  235075. {
  235076. char channelName [256];
  235077. zerostruct (channelName);
  235078. UInt32 nameSize = sizeof (channelName);
  235079. UInt32 channelNum = chanNum + 1;
  235080. pa.mSelector = kAudioDevicePropertyChannelName;
  235081. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235082. name = String::fromUTF8 (channelName, nameSize);
  235083. }
  235084. if (input)
  235085. {
  235086. if (activeInputChans[chanNum])
  235087. {
  235088. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235089. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235090. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235091. ++numInputChannelInfos;
  235092. }
  235093. if (name.isEmpty())
  235094. name << "Input " << (chanNum + 1);
  235095. inChanNames.add (name);
  235096. }
  235097. else
  235098. {
  235099. if (activeOutputChans[chanNum])
  235100. {
  235101. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235102. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235103. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235104. ++numOutputChannelInfos;
  235105. }
  235106. if (name.isEmpty())
  235107. name << "Output " << (chanNum + 1);
  235108. outChanNames.add (name);
  235109. }
  235110. ++chanNum;
  235111. }
  235112. }
  235113. }
  235114. }
  235115. }
  235116. void updateDetailsFromDevice()
  235117. {
  235118. stopTimer();
  235119. if (deviceID == 0)
  235120. return;
  235121. const ScopedLock sl (callbackLock);
  235122. Float64 sr;
  235123. UInt32 size = sizeof (Float64);
  235124. AudioObjectPropertyAddress pa;
  235125. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235126. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235127. pa.mElement = kAudioObjectPropertyElementMaster;
  235128. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235129. sampleRate = sr;
  235130. UInt32 framesPerBuf;
  235131. size = sizeof (framesPerBuf);
  235132. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235133. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235134. {
  235135. bufferSize = framesPerBuf;
  235136. allocateTempBuffers();
  235137. }
  235138. bufferSizes.clear();
  235139. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235140. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235141. {
  235142. HeapBlock <AudioValueRange> ranges;
  235143. ranges.calloc (size, 1);
  235144. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235145. {
  235146. bufferSizes.add ((int) ranges[0].mMinimum);
  235147. for (int i = 32; i < 2048; i += 32)
  235148. {
  235149. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235150. {
  235151. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235152. {
  235153. bufferSizes.addIfNotAlreadyThere (i);
  235154. break;
  235155. }
  235156. }
  235157. }
  235158. if (bufferSize > 0)
  235159. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235160. }
  235161. }
  235162. if (bufferSizes.size() == 0 && bufferSize > 0)
  235163. bufferSizes.add (bufferSize);
  235164. sampleRates.clear();
  235165. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235166. String rates;
  235167. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235168. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235169. {
  235170. HeapBlock <AudioValueRange> ranges;
  235171. ranges.calloc (size, 1);
  235172. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235173. {
  235174. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235175. {
  235176. bool ok = false;
  235177. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235178. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235179. ok = true;
  235180. if (ok)
  235181. {
  235182. sampleRates.add (possibleRates[i]);
  235183. rates << possibleRates[i] << ' ';
  235184. }
  235185. }
  235186. }
  235187. }
  235188. if (sampleRates.size() == 0 && sampleRate > 0)
  235189. {
  235190. sampleRates.add (sampleRate);
  235191. rates << sampleRate;
  235192. }
  235193. log ("sr: " + rates);
  235194. inputLatency = 0;
  235195. outputLatency = 0;
  235196. UInt32 lat;
  235197. size = sizeof (lat);
  235198. pa.mSelector = kAudioDevicePropertyLatency;
  235199. pa.mScope = kAudioDevicePropertyScopeInput;
  235200. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235201. inputLatency = (int) lat;
  235202. pa.mScope = kAudioDevicePropertyScopeOutput;
  235203. size = sizeof (lat);
  235204. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235205. outputLatency = (int) lat;
  235206. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235207. inChanNames.clear();
  235208. outChanNames.clear();
  235209. inputChannelInfo.calloc (numInputChans + 2);
  235210. numInputChannelInfos = 0;
  235211. outputChannelInfo.calloc (numOutputChans + 2);
  235212. numOutputChannelInfos = 0;
  235213. fillInChannelInfo (true);
  235214. fillInChannelInfo (false);
  235215. }
  235216. const StringArray getSources (bool input)
  235217. {
  235218. StringArray s;
  235219. HeapBlock <OSType> types;
  235220. const int num = getAllDataSourcesForDevice (deviceID, types);
  235221. for (int i = 0; i < num; ++i)
  235222. {
  235223. AudioValueTranslation avt;
  235224. char buffer[256];
  235225. avt.mInputData = &(types[i]);
  235226. avt.mInputDataSize = sizeof (UInt32);
  235227. avt.mOutputData = buffer;
  235228. avt.mOutputDataSize = 256;
  235229. UInt32 transSize = sizeof (avt);
  235230. AudioObjectPropertyAddress pa;
  235231. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235232. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235233. pa.mElement = kAudioObjectPropertyElementMaster;
  235234. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235235. {
  235236. DBG (buffer);
  235237. s.add (buffer);
  235238. }
  235239. }
  235240. return s;
  235241. }
  235242. int getCurrentSourceIndex (bool input) const
  235243. {
  235244. OSType currentSourceID = 0;
  235245. UInt32 size = sizeof (currentSourceID);
  235246. int result = -1;
  235247. AudioObjectPropertyAddress pa;
  235248. pa.mSelector = kAudioDevicePropertyDataSource;
  235249. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235250. pa.mElement = kAudioObjectPropertyElementMaster;
  235251. if (deviceID != 0)
  235252. {
  235253. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235254. {
  235255. HeapBlock <OSType> types;
  235256. const int num = getAllDataSourcesForDevice (deviceID, types);
  235257. for (int i = 0; i < num; ++i)
  235258. {
  235259. if (types[num] == currentSourceID)
  235260. {
  235261. result = i;
  235262. break;
  235263. }
  235264. }
  235265. }
  235266. }
  235267. return result;
  235268. }
  235269. void setCurrentSourceIndex (int index, bool input)
  235270. {
  235271. if (deviceID != 0)
  235272. {
  235273. HeapBlock <OSType> types;
  235274. const int num = getAllDataSourcesForDevice (deviceID, types);
  235275. if (isPositiveAndBelow (index, num))
  235276. {
  235277. AudioObjectPropertyAddress pa;
  235278. pa.mSelector = kAudioDevicePropertyDataSource;
  235279. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235280. pa.mElement = kAudioObjectPropertyElementMaster;
  235281. OSType typeId = types[index];
  235282. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235283. }
  235284. }
  235285. }
  235286. const String reopen (const BigInteger& inputChannels,
  235287. const BigInteger& outputChannels,
  235288. double newSampleRate,
  235289. int bufferSizeSamples)
  235290. {
  235291. String error;
  235292. log ("CoreAudio reopen");
  235293. callbacksAllowed = false;
  235294. stopTimer();
  235295. stop (false);
  235296. activeInputChans = inputChannels;
  235297. activeInputChans.setRange (inChanNames.size(),
  235298. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235299. false);
  235300. activeOutputChans = outputChannels;
  235301. activeOutputChans.setRange (outChanNames.size(),
  235302. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235303. false);
  235304. numInputChans = activeInputChans.countNumberOfSetBits();
  235305. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235306. // set sample rate
  235307. AudioObjectPropertyAddress pa;
  235308. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235309. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235310. pa.mElement = kAudioObjectPropertyElementMaster;
  235311. Float64 sr = newSampleRate;
  235312. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235313. {
  235314. error = "Couldn't change sample rate";
  235315. }
  235316. else
  235317. {
  235318. // change buffer size
  235319. UInt32 framesPerBuf = bufferSizeSamples;
  235320. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235321. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235322. {
  235323. error = "Couldn't change buffer size";
  235324. }
  235325. else
  235326. {
  235327. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235328. // correctly report their new settings until some random time in the future, so
  235329. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235330. // to make sure we're using the correct numbers..
  235331. updateDetailsFromDevice();
  235332. sampleRate = newSampleRate;
  235333. bufferSize = bufferSizeSamples;
  235334. if (sampleRates.size() == 0)
  235335. error = "Device has no available sample-rates";
  235336. else if (bufferSizes.size() == 0)
  235337. error = "Device has no available buffer-sizes";
  235338. else if (inputDevice != 0)
  235339. error = inputDevice->reopen (inputChannels,
  235340. outputChannels,
  235341. newSampleRate,
  235342. bufferSizeSamples);
  235343. }
  235344. }
  235345. callbacksAllowed = true;
  235346. return error;
  235347. }
  235348. bool start (AudioIODeviceCallback* cb)
  235349. {
  235350. if (! started)
  235351. {
  235352. callback = 0;
  235353. if (deviceID != 0)
  235354. {
  235355. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235356. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235357. #else
  235358. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235359. #endif
  235360. {
  235361. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235362. {
  235363. started = true;
  235364. }
  235365. else
  235366. {
  235367. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235368. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235369. #else
  235370. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235371. audioProcID = 0;
  235372. #endif
  235373. }
  235374. }
  235375. }
  235376. }
  235377. if (started)
  235378. {
  235379. const ScopedLock sl (callbackLock);
  235380. callback = cb;
  235381. }
  235382. if (inputDevice != 0)
  235383. return started && inputDevice->start (cb);
  235384. else
  235385. return started;
  235386. }
  235387. void stop (bool leaveInterruptRunning)
  235388. {
  235389. {
  235390. const ScopedLock sl (callbackLock);
  235391. callback = 0;
  235392. }
  235393. if (started
  235394. && (deviceID != 0)
  235395. && ! leaveInterruptRunning)
  235396. {
  235397. OK (AudioDeviceStop (deviceID, audioIOProc));
  235398. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235399. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235400. #else
  235401. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235402. audioProcID = 0;
  235403. #endif
  235404. started = false;
  235405. { const ScopedLock sl (callbackLock); }
  235406. // wait until it's definately stopped calling back..
  235407. for (int i = 40; --i >= 0;)
  235408. {
  235409. Thread::sleep (50);
  235410. UInt32 running = 0;
  235411. UInt32 size = sizeof (running);
  235412. AudioObjectPropertyAddress pa;
  235413. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235414. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235415. pa.mElement = kAudioObjectPropertyElementMaster;
  235416. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235417. if (running == 0)
  235418. break;
  235419. }
  235420. const ScopedLock sl (callbackLock);
  235421. }
  235422. if (inputDevice != 0)
  235423. inputDevice->stop (leaveInterruptRunning);
  235424. }
  235425. double getSampleRate() const
  235426. {
  235427. return sampleRate;
  235428. }
  235429. int getBufferSize() const
  235430. {
  235431. return bufferSize;
  235432. }
  235433. void audioCallback (const AudioBufferList* inInputData,
  235434. AudioBufferList* outOutputData)
  235435. {
  235436. int i;
  235437. const ScopedLock sl (callbackLock);
  235438. if (callback != 0)
  235439. {
  235440. if (inputDevice == 0)
  235441. {
  235442. for (i = numInputChans; --i >= 0;)
  235443. {
  235444. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235445. float* dest = tempInputBuffers [i];
  235446. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235447. + info.dataOffsetSamples;
  235448. const int stride = info.dataStrideSamples;
  235449. if (stride != 0) // if this is zero, info is invalid
  235450. {
  235451. for (int j = bufferSize; --j >= 0;)
  235452. {
  235453. *dest++ = *src;
  235454. src += stride;
  235455. }
  235456. }
  235457. }
  235458. }
  235459. if (! isSlaveDevice)
  235460. {
  235461. if (inputDevice == 0)
  235462. {
  235463. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235464. numInputChans,
  235465. tempOutputBuffers,
  235466. numOutputChans,
  235467. bufferSize);
  235468. }
  235469. else
  235470. {
  235471. jassert (inputDevice->bufferSize == bufferSize);
  235472. // Sometimes the two linked devices seem to get their callbacks in
  235473. // parallel, so we need to lock both devices to stop the input data being
  235474. // changed while inside our callback..
  235475. const ScopedLock sl2 (inputDevice->callbackLock);
  235476. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235477. inputDevice->numInputChans,
  235478. tempOutputBuffers,
  235479. numOutputChans,
  235480. bufferSize);
  235481. }
  235482. for (i = numOutputChans; --i >= 0;)
  235483. {
  235484. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235485. const float* src = tempOutputBuffers [i];
  235486. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235487. + info.dataOffsetSamples;
  235488. const int stride = info.dataStrideSamples;
  235489. if (stride != 0) // if this is zero, info is invalid
  235490. {
  235491. for (int j = bufferSize; --j >= 0;)
  235492. {
  235493. *dest = *src++;
  235494. dest += stride;
  235495. }
  235496. }
  235497. }
  235498. }
  235499. }
  235500. else
  235501. {
  235502. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235503. {
  235504. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235505. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235506. + info.dataOffsetSamples;
  235507. const int stride = info.dataStrideSamples;
  235508. if (stride != 0) // if this is zero, info is invalid
  235509. {
  235510. for (int j = bufferSize; --j >= 0;)
  235511. {
  235512. *dest = 0.0f;
  235513. dest += stride;
  235514. }
  235515. }
  235516. }
  235517. }
  235518. }
  235519. // called by callbacks
  235520. void deviceDetailsChanged()
  235521. {
  235522. if (callbacksAllowed)
  235523. startTimer (100);
  235524. }
  235525. void timerCallback()
  235526. {
  235527. stopTimer();
  235528. log ("CoreAudio device changed callback");
  235529. const double oldSampleRate = sampleRate;
  235530. const int oldBufferSize = bufferSize;
  235531. updateDetailsFromDevice();
  235532. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235533. {
  235534. callbacksAllowed = false;
  235535. stop (false);
  235536. updateDetailsFromDevice();
  235537. callbacksAllowed = true;
  235538. }
  235539. }
  235540. CoreAudioInternal* getRelatedDevice() const
  235541. {
  235542. UInt32 size = 0;
  235543. ScopedPointer <CoreAudioInternal> result;
  235544. AudioObjectPropertyAddress pa;
  235545. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235546. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235547. pa.mElement = kAudioObjectPropertyElementMaster;
  235548. if (deviceID != 0
  235549. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235550. && size > 0)
  235551. {
  235552. HeapBlock <AudioDeviceID> devs;
  235553. devs.calloc (size, 1);
  235554. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235555. {
  235556. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235557. {
  235558. if (devs[i] != deviceID && devs[i] != 0)
  235559. {
  235560. result = new CoreAudioInternal (devs[i]);
  235561. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235562. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235563. if (thisIsInput != otherIsInput
  235564. || (inChanNames.size() + outChanNames.size() == 0)
  235565. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235566. break;
  235567. result = 0;
  235568. }
  235569. }
  235570. }
  235571. }
  235572. return result.release();
  235573. }
  235574. int inputLatency, outputLatency;
  235575. BigInteger activeInputChans, activeOutputChans;
  235576. StringArray inChanNames, outChanNames;
  235577. Array <double> sampleRates;
  235578. Array <int> bufferSizes;
  235579. AudioIODeviceCallback* callback;
  235580. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235581. AudioDeviceIOProcID audioProcID;
  235582. #endif
  235583. ScopedPointer<CoreAudioInternal> inputDevice;
  235584. bool isSlaveDevice;
  235585. private:
  235586. CriticalSection callbackLock;
  235587. AudioDeviceID deviceID;
  235588. bool started;
  235589. double sampleRate;
  235590. int bufferSize;
  235591. HeapBlock <float> audioBuffer;
  235592. int numInputChans, numOutputChans;
  235593. bool callbacksAllowed;
  235594. struct CallbackDetailsForChannel
  235595. {
  235596. int streamNum;
  235597. int dataOffsetSamples;
  235598. int dataStrideSamples;
  235599. };
  235600. int numInputChannelInfos, numOutputChannelInfos;
  235601. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235602. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235603. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235604. const AudioTimeStamp* /*inNow*/,
  235605. const AudioBufferList* inInputData,
  235606. const AudioTimeStamp* /*inInputTime*/,
  235607. AudioBufferList* outOutputData,
  235608. const AudioTimeStamp* /*inOutputTime*/,
  235609. void* device)
  235610. {
  235611. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235612. return noErr;
  235613. }
  235614. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235615. {
  235616. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235617. switch (pa->mSelector)
  235618. {
  235619. case kAudioDevicePropertyBufferSize:
  235620. case kAudioDevicePropertyBufferFrameSize:
  235621. case kAudioDevicePropertyNominalSampleRate:
  235622. case kAudioDevicePropertyStreamFormat:
  235623. case kAudioDevicePropertyDeviceIsAlive:
  235624. intern->deviceDetailsChanged();
  235625. break;
  235626. case kAudioDevicePropertyBufferSizeRange:
  235627. case kAudioDevicePropertyVolumeScalar:
  235628. case kAudioDevicePropertyMute:
  235629. case kAudioDevicePropertyPlayThru:
  235630. case kAudioDevicePropertyDataSource:
  235631. case kAudioDevicePropertyDeviceIsRunning:
  235632. break;
  235633. }
  235634. return noErr;
  235635. }
  235636. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235637. {
  235638. AudioObjectPropertyAddress pa;
  235639. pa.mSelector = kAudioDevicePropertyDataSources;
  235640. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235641. pa.mElement = kAudioObjectPropertyElementMaster;
  235642. UInt32 size = 0;
  235643. if (deviceID != 0
  235644. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235645. {
  235646. types.calloc (size, 1);
  235647. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235648. return size / (int) sizeof (OSType);
  235649. }
  235650. return 0;
  235651. }
  235652. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal);
  235653. };
  235654. class CoreAudioIODevice : public AudioIODevice
  235655. {
  235656. public:
  235657. CoreAudioIODevice (const String& deviceName,
  235658. AudioDeviceID inputDeviceId,
  235659. const int inputIndex_,
  235660. AudioDeviceID outputDeviceId,
  235661. const int outputIndex_)
  235662. : AudioIODevice (deviceName, "CoreAudio"),
  235663. inputIndex (inputIndex_),
  235664. outputIndex (outputIndex_),
  235665. isOpen_ (false),
  235666. isStarted (false)
  235667. {
  235668. CoreAudioInternal* device = 0;
  235669. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235670. {
  235671. jassert (inputDeviceId != 0);
  235672. device = new CoreAudioInternal (inputDeviceId);
  235673. }
  235674. else
  235675. {
  235676. device = new CoreAudioInternal (outputDeviceId);
  235677. if (inputDeviceId != 0)
  235678. {
  235679. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235680. device->inputDevice = secondDevice;
  235681. secondDevice->isSlaveDevice = true;
  235682. }
  235683. }
  235684. internal = device;
  235685. AudioObjectPropertyAddress pa;
  235686. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235687. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235688. pa.mElement = kAudioObjectPropertyElementWildcard;
  235689. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235690. }
  235691. ~CoreAudioIODevice()
  235692. {
  235693. AudioObjectPropertyAddress pa;
  235694. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235695. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235696. pa.mElement = kAudioObjectPropertyElementWildcard;
  235697. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235698. }
  235699. const StringArray getOutputChannelNames()
  235700. {
  235701. return internal->outChanNames;
  235702. }
  235703. const StringArray getInputChannelNames()
  235704. {
  235705. if (internal->inputDevice != 0)
  235706. return internal->inputDevice->inChanNames;
  235707. else
  235708. return internal->inChanNames;
  235709. }
  235710. int getNumSampleRates()
  235711. {
  235712. return internal->sampleRates.size();
  235713. }
  235714. double getSampleRate (int index)
  235715. {
  235716. return internal->sampleRates [index];
  235717. }
  235718. int getNumBufferSizesAvailable()
  235719. {
  235720. return internal->bufferSizes.size();
  235721. }
  235722. int getBufferSizeSamples (int index)
  235723. {
  235724. return internal->bufferSizes [index];
  235725. }
  235726. int getDefaultBufferSize()
  235727. {
  235728. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235729. if (getBufferSizeSamples(i) >= 512)
  235730. return getBufferSizeSamples(i);
  235731. return 512;
  235732. }
  235733. const String open (const BigInteger& inputChannels,
  235734. const BigInteger& outputChannels,
  235735. double sampleRate,
  235736. int bufferSizeSamples)
  235737. {
  235738. isOpen_ = true;
  235739. if (bufferSizeSamples <= 0)
  235740. bufferSizeSamples = getDefaultBufferSize();
  235741. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235742. isOpen_ = lastError.isEmpty();
  235743. return lastError;
  235744. }
  235745. void close()
  235746. {
  235747. isOpen_ = false;
  235748. internal->stop (false);
  235749. }
  235750. bool isOpen()
  235751. {
  235752. return isOpen_;
  235753. }
  235754. int getCurrentBufferSizeSamples()
  235755. {
  235756. return internal != 0 ? internal->getBufferSize() : 512;
  235757. }
  235758. double getCurrentSampleRate()
  235759. {
  235760. return internal != 0 ? internal->getSampleRate() : 0;
  235761. }
  235762. int getCurrentBitDepth()
  235763. {
  235764. return 32; // no way to find out, so just assume it's high..
  235765. }
  235766. const BigInteger getActiveOutputChannels() const
  235767. {
  235768. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235769. }
  235770. const BigInteger getActiveInputChannels() const
  235771. {
  235772. BigInteger chans;
  235773. if (internal != 0)
  235774. {
  235775. chans = internal->activeInputChans;
  235776. if (internal->inputDevice != 0)
  235777. chans |= internal->inputDevice->activeInputChans;
  235778. }
  235779. return chans;
  235780. }
  235781. int getOutputLatencyInSamples()
  235782. {
  235783. if (internal == 0)
  235784. return 0;
  235785. // this seems like a good guess at getting the latency right - comparing
  235786. // this with a round-trip measurement, it gets it to within a few millisecs
  235787. // for the built-in mac soundcard
  235788. return internal->outputLatency + internal->getBufferSize() * 2;
  235789. }
  235790. int getInputLatencyInSamples()
  235791. {
  235792. if (internal == 0)
  235793. return 0;
  235794. return internal->inputLatency + internal->getBufferSize() * 2;
  235795. }
  235796. void start (AudioIODeviceCallback* callback)
  235797. {
  235798. if (internal != 0 && ! isStarted)
  235799. {
  235800. if (callback != 0)
  235801. callback->audioDeviceAboutToStart (this);
  235802. isStarted = true;
  235803. internal->start (callback);
  235804. }
  235805. }
  235806. void stop()
  235807. {
  235808. if (isStarted && internal != 0)
  235809. {
  235810. AudioIODeviceCallback* const lastCallback = internal->callback;
  235811. isStarted = false;
  235812. internal->stop (true);
  235813. if (lastCallback != 0)
  235814. lastCallback->audioDeviceStopped();
  235815. }
  235816. }
  235817. bool isPlaying()
  235818. {
  235819. if (internal->callback == 0)
  235820. isStarted = false;
  235821. return isStarted;
  235822. }
  235823. const String getLastError()
  235824. {
  235825. return lastError;
  235826. }
  235827. int inputIndex, outputIndex;
  235828. private:
  235829. ScopedPointer<CoreAudioInternal> internal;
  235830. bool isOpen_, isStarted;
  235831. String lastError;
  235832. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235833. {
  235834. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235835. switch (pa->mSelector)
  235836. {
  235837. case kAudioHardwarePropertyDevices:
  235838. intern->deviceDetailsChanged();
  235839. break;
  235840. case kAudioHardwarePropertyDefaultOutputDevice:
  235841. case kAudioHardwarePropertyDefaultInputDevice:
  235842. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  235843. break;
  235844. }
  235845. return noErr;
  235846. }
  235847. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice);
  235848. };
  235849. class CoreAudioIODeviceType : public AudioIODeviceType
  235850. {
  235851. public:
  235852. CoreAudioIODeviceType()
  235853. : AudioIODeviceType ("CoreAudio"),
  235854. hasScanned (false)
  235855. {
  235856. }
  235857. ~CoreAudioIODeviceType()
  235858. {
  235859. }
  235860. void scanForDevices()
  235861. {
  235862. hasScanned = true;
  235863. inputDeviceNames.clear();
  235864. outputDeviceNames.clear();
  235865. inputIds.clear();
  235866. outputIds.clear();
  235867. UInt32 size;
  235868. AudioObjectPropertyAddress pa;
  235869. pa.mSelector = kAudioHardwarePropertyDevices;
  235870. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235871. pa.mElement = kAudioObjectPropertyElementMaster;
  235872. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  235873. {
  235874. HeapBlock <AudioDeviceID> devs;
  235875. devs.calloc (size, 1);
  235876. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  235877. {
  235878. const int num = size / (int) sizeof (AudioDeviceID);
  235879. for (int i = 0; i < num; ++i)
  235880. {
  235881. char name [1024];
  235882. size = sizeof (name);
  235883. pa.mSelector = kAudioDevicePropertyDeviceName;
  235884. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  235885. {
  235886. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  235887. const int numIns = getNumChannels (devs[i], true);
  235888. const int numOuts = getNumChannels (devs[i], false);
  235889. if (numIns > 0)
  235890. {
  235891. inputDeviceNames.add (nameString);
  235892. inputIds.add (devs[i]);
  235893. }
  235894. if (numOuts > 0)
  235895. {
  235896. outputDeviceNames.add (nameString);
  235897. outputIds.add (devs[i]);
  235898. }
  235899. }
  235900. }
  235901. }
  235902. }
  235903. inputDeviceNames.appendNumbersToDuplicates (false, true);
  235904. outputDeviceNames.appendNumbersToDuplicates (false, true);
  235905. }
  235906. const StringArray getDeviceNames (bool wantInputNames) const
  235907. {
  235908. jassert (hasScanned); // need to call scanForDevices() before doing this
  235909. if (wantInputNames)
  235910. return inputDeviceNames;
  235911. else
  235912. return outputDeviceNames;
  235913. }
  235914. int getDefaultDeviceIndex (bool forInput) const
  235915. {
  235916. jassert (hasScanned); // need to call scanForDevices() before doing this
  235917. AudioDeviceID deviceID;
  235918. UInt32 size = sizeof (deviceID);
  235919. // if they're asking for any input channels at all, use the default input, so we
  235920. // get the built-in mic rather than the built-in output with no inputs..
  235921. AudioObjectPropertyAddress pa;
  235922. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  235923. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235924. pa.mElement = kAudioObjectPropertyElementMaster;
  235925. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  235926. {
  235927. if (forInput)
  235928. {
  235929. for (int i = inputIds.size(); --i >= 0;)
  235930. if (inputIds[i] == deviceID)
  235931. return i;
  235932. }
  235933. else
  235934. {
  235935. for (int i = outputIds.size(); --i >= 0;)
  235936. if (outputIds[i] == deviceID)
  235937. return i;
  235938. }
  235939. }
  235940. return 0;
  235941. }
  235942. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  235943. {
  235944. jassert (hasScanned); // need to call scanForDevices() before doing this
  235945. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  235946. if (d == 0)
  235947. return -1;
  235948. return asInput ? d->inputIndex
  235949. : d->outputIndex;
  235950. }
  235951. bool hasSeparateInputsAndOutputs() const { return true; }
  235952. AudioIODevice* createDevice (const String& outputDeviceName,
  235953. const String& inputDeviceName)
  235954. {
  235955. jassert (hasScanned); // need to call scanForDevices() before doing this
  235956. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  235957. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  235958. String deviceName (outputDeviceName);
  235959. if (deviceName.isEmpty())
  235960. deviceName = inputDeviceName;
  235961. if (index >= 0)
  235962. return new CoreAudioIODevice (deviceName,
  235963. inputIds [inputIndex],
  235964. inputIndex,
  235965. outputIds [outputIndex],
  235966. outputIndex);
  235967. return 0;
  235968. }
  235969. private:
  235970. StringArray inputDeviceNames, outputDeviceNames;
  235971. Array <AudioDeviceID> inputIds, outputIds;
  235972. bool hasScanned;
  235973. static int getNumChannels (AudioDeviceID deviceID, bool input)
  235974. {
  235975. int total = 0;
  235976. UInt32 size;
  235977. AudioObjectPropertyAddress pa;
  235978. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235979. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235980. pa.mElement = kAudioObjectPropertyElementMaster;
  235981. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235982. {
  235983. HeapBlock <AudioBufferList> bufList;
  235984. bufList.calloc (size, 1);
  235985. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235986. {
  235987. const int numStreams = bufList->mNumberBuffers;
  235988. for (int i = 0; i < numStreams; ++i)
  235989. {
  235990. const AudioBuffer& b = bufList->mBuffers[i];
  235991. total += b.mNumberChannels;
  235992. }
  235993. }
  235994. }
  235995. return total;
  235996. }
  235997. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType);
  235998. };
  235999. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236000. {
  236001. return new CoreAudioIODeviceType();
  236002. }
  236003. #undef log
  236004. #endif
  236005. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236006. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236007. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236008. // compiled on its own).
  236009. #if JUCE_INCLUDED_FILE
  236010. #if JUCE_MAC
  236011. namespace CoreMidiHelpers
  236012. {
  236013. bool logError (const OSStatus err, const int lineNum)
  236014. {
  236015. if (err == noErr)
  236016. return true;
  236017. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236018. jassertfalse;
  236019. return false;
  236020. }
  236021. #undef CHECK_ERROR
  236022. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236023. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236024. {
  236025. String result;
  236026. CFStringRef str = 0;
  236027. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236028. if (str != 0)
  236029. {
  236030. result = PlatformUtilities::cfStringToJuceString (str);
  236031. CFRelease (str);
  236032. str = 0;
  236033. }
  236034. MIDIEntityRef entity = 0;
  236035. MIDIEndpointGetEntity (endpoint, &entity);
  236036. if (entity == 0)
  236037. return result; // probably virtual
  236038. if (result.isEmpty())
  236039. {
  236040. // endpoint name has zero length - try the entity
  236041. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236042. if (str != 0)
  236043. {
  236044. result += PlatformUtilities::cfStringToJuceString (str);
  236045. CFRelease (str);
  236046. str = 0;
  236047. }
  236048. }
  236049. // now consider the device's name
  236050. MIDIDeviceRef device = 0;
  236051. MIDIEntityGetDevice (entity, &device);
  236052. if (device == 0)
  236053. return result;
  236054. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236055. if (str != 0)
  236056. {
  236057. const String s (PlatformUtilities::cfStringToJuceString (str));
  236058. CFRelease (str);
  236059. // if an external device has only one entity, throw away
  236060. // the endpoint name and just use the device name
  236061. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236062. {
  236063. result = s;
  236064. }
  236065. else if (! result.startsWithIgnoreCase (s))
  236066. {
  236067. // prepend the device name to the entity name
  236068. result = (s + " " + result).trimEnd();
  236069. }
  236070. }
  236071. return result;
  236072. }
  236073. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236074. {
  236075. String result;
  236076. // Does the endpoint have connections?
  236077. CFDataRef connections = 0;
  236078. int numConnections = 0;
  236079. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236080. if (connections != 0)
  236081. {
  236082. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236083. if (numConnections > 0)
  236084. {
  236085. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236086. for (int i = 0; i < numConnections; ++i, ++pid)
  236087. {
  236088. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236089. MIDIObjectRef connObject;
  236090. MIDIObjectType connObjectType;
  236091. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236092. if (err == noErr)
  236093. {
  236094. String s;
  236095. if (connObjectType == kMIDIObjectType_ExternalSource
  236096. || connObjectType == kMIDIObjectType_ExternalDestination)
  236097. {
  236098. // Connected to an external device's endpoint (10.3 and later).
  236099. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236100. }
  236101. else
  236102. {
  236103. // Connected to an external device (10.2) (or something else, catch-all)
  236104. CFStringRef str = 0;
  236105. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236106. if (str != 0)
  236107. {
  236108. s = PlatformUtilities::cfStringToJuceString (str);
  236109. CFRelease (str);
  236110. }
  236111. }
  236112. if (s.isNotEmpty())
  236113. {
  236114. if (result.isNotEmpty())
  236115. result += ", ";
  236116. result += s;
  236117. }
  236118. }
  236119. }
  236120. }
  236121. CFRelease (connections);
  236122. }
  236123. if (result.isNotEmpty())
  236124. return result;
  236125. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236126. return getEndpointName (endpoint, false);
  236127. }
  236128. MIDIClientRef getGlobalMidiClient()
  236129. {
  236130. static MIDIClientRef globalMidiClient = 0;
  236131. if (globalMidiClient == 0)
  236132. {
  236133. String name ("JUCE");
  236134. if (JUCEApplication::getInstance() != 0)
  236135. name = JUCEApplication::getInstance()->getApplicationName();
  236136. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236137. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236138. CFRelease (appName);
  236139. }
  236140. return globalMidiClient;
  236141. }
  236142. class MidiPortAndEndpoint
  236143. {
  236144. public:
  236145. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236146. : port (port_), endPoint (endPoint_)
  236147. {
  236148. }
  236149. ~MidiPortAndEndpoint()
  236150. {
  236151. if (port != 0)
  236152. MIDIPortDispose (port);
  236153. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236154. MIDIEndpointDispose (endPoint);
  236155. }
  236156. void send (const MIDIPacketList* const packets)
  236157. {
  236158. if (port != 0)
  236159. MIDISend (port, endPoint, packets);
  236160. else
  236161. MIDIReceived (endPoint, packets);
  236162. }
  236163. MIDIPortRef port;
  236164. MIDIEndpointRef endPoint;
  236165. };
  236166. class MidiPortAndCallback;
  236167. CriticalSection callbackLock;
  236168. Array<MidiPortAndCallback*> activeCallbacks;
  236169. class MidiPortAndCallback
  236170. {
  236171. public:
  236172. MidiPortAndCallback (MidiInputCallback& callback_)
  236173. : input (0), active (false), callback (callback_), concatenator (2048)
  236174. {
  236175. }
  236176. ~MidiPortAndCallback()
  236177. {
  236178. active = false;
  236179. {
  236180. const ScopedLock sl (callbackLock);
  236181. activeCallbacks.removeValue (this);
  236182. }
  236183. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236184. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236185. }
  236186. void handlePackets (const MIDIPacketList* const pktlist)
  236187. {
  236188. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236189. const ScopedLock sl (callbackLock);
  236190. if (activeCallbacks.contains (this) && active)
  236191. {
  236192. const MIDIPacket* packet = &pktlist->packet[0];
  236193. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236194. {
  236195. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236196. input, callback);
  236197. packet = MIDIPacketNext (packet);
  236198. }
  236199. }
  236200. }
  236201. MidiInput* input;
  236202. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236203. volatile bool active;
  236204. private:
  236205. MidiInputCallback& callback;
  236206. MidiDataConcatenator concatenator;
  236207. };
  236208. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236209. {
  236210. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236211. }
  236212. }
  236213. const StringArray MidiOutput::getDevices()
  236214. {
  236215. StringArray s;
  236216. const ItemCount num = MIDIGetNumberOfDestinations();
  236217. for (ItemCount i = 0; i < num; ++i)
  236218. {
  236219. MIDIEndpointRef dest = MIDIGetDestination (i);
  236220. if (dest != 0)
  236221. {
  236222. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  236223. if (name.isEmpty())
  236224. name = "<error>";
  236225. s.add (name);
  236226. }
  236227. else
  236228. {
  236229. s.add ("<error>");
  236230. }
  236231. }
  236232. return s;
  236233. }
  236234. int MidiOutput::getDefaultDeviceIndex()
  236235. {
  236236. return 0;
  236237. }
  236238. MidiOutput* MidiOutput::openDevice (int index)
  236239. {
  236240. MidiOutput* mo = 0;
  236241. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  236242. {
  236243. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236244. CFStringRef pname;
  236245. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236246. {
  236247. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236248. MIDIPortRef port;
  236249. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236250. {
  236251. mo = new MidiOutput();
  236252. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236253. }
  236254. CFRelease (pname);
  236255. }
  236256. }
  236257. return mo;
  236258. }
  236259. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236260. {
  236261. MidiOutput* mo = 0;
  236262. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236263. MIDIEndpointRef endPoint;
  236264. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236265. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236266. {
  236267. mo = new MidiOutput();
  236268. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236269. }
  236270. CFRelease (name);
  236271. return mo;
  236272. }
  236273. MidiOutput::~MidiOutput()
  236274. {
  236275. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236276. }
  236277. void MidiOutput::reset()
  236278. {
  236279. }
  236280. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236281. {
  236282. return false;
  236283. }
  236284. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236285. {
  236286. }
  236287. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236288. {
  236289. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236290. if (message.isSysEx())
  236291. {
  236292. const int maxPacketSize = 256;
  236293. int pos = 0, bytesLeft = message.getRawDataSize();
  236294. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236295. HeapBlock <MIDIPacketList> packets;
  236296. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236297. packets->numPackets = numPackets;
  236298. MIDIPacket* p = packets->packet;
  236299. for (int i = 0; i < numPackets; ++i)
  236300. {
  236301. p->timeStamp = AudioGetCurrentHostTime();
  236302. p->length = jmin (maxPacketSize, bytesLeft);
  236303. memcpy (p->data, message.getRawData() + pos, p->length);
  236304. pos += p->length;
  236305. bytesLeft -= p->length;
  236306. p = MIDIPacketNext (p);
  236307. }
  236308. mpe->send (packets);
  236309. }
  236310. else
  236311. {
  236312. MIDIPacketList packets;
  236313. packets.numPackets = 1;
  236314. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  236315. packets.packet[0].length = message.getRawDataSize();
  236316. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236317. mpe->send (&packets);
  236318. }
  236319. }
  236320. const StringArray MidiInput::getDevices()
  236321. {
  236322. StringArray s;
  236323. const ItemCount num = MIDIGetNumberOfSources();
  236324. for (ItemCount i = 0; i < num; ++i)
  236325. {
  236326. MIDIEndpointRef source = MIDIGetSource (i);
  236327. if (source != 0)
  236328. {
  236329. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236330. if (name.isEmpty())
  236331. name = "<error>";
  236332. s.add (name);
  236333. }
  236334. else
  236335. {
  236336. s.add ("<error>");
  236337. }
  236338. }
  236339. return s;
  236340. }
  236341. int MidiInput::getDefaultDeviceIndex()
  236342. {
  236343. return 0;
  236344. }
  236345. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236346. {
  236347. jassert (callback != 0);
  236348. using namespace CoreMidiHelpers;
  236349. MidiInput* newInput = 0;
  236350. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  236351. {
  236352. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236353. if (endPoint != 0)
  236354. {
  236355. CFStringRef name;
  236356. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236357. {
  236358. MIDIClientRef client = getGlobalMidiClient();
  236359. if (client != 0)
  236360. {
  236361. MIDIPortRef port;
  236362. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236363. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236364. {
  236365. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236366. {
  236367. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236368. newInput = new MidiInput (getDevices() [index]);
  236369. mpc->input = newInput;
  236370. newInput->internal = mpc;
  236371. const ScopedLock sl (callbackLock);
  236372. activeCallbacks.add (mpc.release());
  236373. }
  236374. else
  236375. {
  236376. CHECK_ERROR (MIDIPortDispose (port));
  236377. }
  236378. }
  236379. }
  236380. }
  236381. CFRelease (name);
  236382. }
  236383. }
  236384. return newInput;
  236385. }
  236386. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236387. {
  236388. jassert (callback != 0);
  236389. using namespace CoreMidiHelpers;
  236390. MidiInput* mi = 0;
  236391. MIDIClientRef client = getGlobalMidiClient();
  236392. if (client != 0)
  236393. {
  236394. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236395. mpc->active = false;
  236396. MIDIEndpointRef endPoint;
  236397. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236398. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236399. {
  236400. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236401. mi = new MidiInput (deviceName);
  236402. mpc->input = mi;
  236403. mi->internal = mpc;
  236404. const ScopedLock sl (callbackLock);
  236405. activeCallbacks.add (mpc.release());
  236406. }
  236407. CFRelease (name);
  236408. }
  236409. return mi;
  236410. }
  236411. MidiInput::MidiInput (const String& name_)
  236412. : name (name_)
  236413. {
  236414. }
  236415. MidiInput::~MidiInput()
  236416. {
  236417. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236418. }
  236419. void MidiInput::start()
  236420. {
  236421. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236422. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236423. }
  236424. void MidiInput::stop()
  236425. {
  236426. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236427. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236428. }
  236429. #undef CHECK_ERROR
  236430. #else // Stubs for iOS...
  236431. MidiOutput::~MidiOutput() {}
  236432. void MidiOutput::reset() {}
  236433. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236434. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236435. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236436. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236437. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236438. const StringArray MidiInput::getDevices() { return StringArray(); }
  236439. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236440. #endif
  236441. #endif
  236442. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236443. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236444. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236445. // compiled on its own).
  236446. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236447. #if ! JUCE_QUICKTIME
  236448. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236449. #endif
  236450. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236451. class QTCameraDeviceInteral;
  236452. END_JUCE_NAMESPACE
  236453. @interface QTCaptureCallbackDelegate : NSObject
  236454. {
  236455. @public
  236456. CameraDevice* owner;
  236457. QTCameraDeviceInteral* internal;
  236458. int64 firstPresentationTime;
  236459. int64 averageTimeOffset;
  236460. }
  236461. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236462. - (void) dealloc;
  236463. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236464. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236465. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236466. fromConnection: (QTCaptureConnection*) connection;
  236467. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236468. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236469. fromConnection: (QTCaptureConnection*) connection;
  236470. @end
  236471. BEGIN_JUCE_NAMESPACE
  236472. class QTCameraDeviceInteral
  236473. {
  236474. public:
  236475. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236476. {
  236477. const ScopedAutoReleasePool pool;
  236478. session = [[QTCaptureSession alloc] init];
  236479. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236480. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236481. input = 0;
  236482. audioInput = 0;
  236483. audioDevice = 0;
  236484. fileOutput = 0;
  236485. imageOutput = 0;
  236486. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236487. internalDev: this];
  236488. NSError* err = 0;
  236489. [device retain];
  236490. [device open: &err];
  236491. if (err == 0)
  236492. {
  236493. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236494. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236495. [session addInput: input error: &err];
  236496. if (err == 0)
  236497. {
  236498. resetFile();
  236499. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236500. [imageOutput setDelegate: callbackDelegate];
  236501. if (err == 0)
  236502. {
  236503. [session startRunning];
  236504. return;
  236505. }
  236506. }
  236507. }
  236508. openingError = nsStringToJuce ([err description]);
  236509. DBG (openingError);
  236510. }
  236511. ~QTCameraDeviceInteral()
  236512. {
  236513. [session stopRunning];
  236514. [session removeOutput: imageOutput];
  236515. [session release];
  236516. [input release];
  236517. [device release];
  236518. [audioDevice release];
  236519. [audioInput release];
  236520. [fileOutput release];
  236521. [imageOutput release];
  236522. [callbackDelegate release];
  236523. }
  236524. void resetFile()
  236525. {
  236526. [fileOutput recordToOutputFileURL: nil];
  236527. [session removeOutput: fileOutput];
  236528. [fileOutput release];
  236529. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236530. [session removeInput: audioInput];
  236531. [audioInput release];
  236532. audioInput = 0;
  236533. [audioDevice release];
  236534. audioDevice = 0;
  236535. [fileOutput setDelegate: callbackDelegate];
  236536. }
  236537. void addDefaultAudioInput()
  236538. {
  236539. NSError* err = nil;
  236540. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236541. if ([audioDevice open: &err])
  236542. [audioDevice retain];
  236543. else
  236544. audioDevice = nil;
  236545. if (audioDevice != 0)
  236546. {
  236547. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236548. [session addInput: audioInput error: &err];
  236549. }
  236550. }
  236551. void addListener (CameraDevice::Listener* listenerToAdd)
  236552. {
  236553. const ScopedLock sl (listenerLock);
  236554. if (listeners.size() == 0)
  236555. [session addOutput: imageOutput error: nil];
  236556. listeners.addIfNotAlreadyThere (listenerToAdd);
  236557. }
  236558. void removeListener (CameraDevice::Listener* listenerToRemove)
  236559. {
  236560. const ScopedLock sl (listenerLock);
  236561. listeners.removeValue (listenerToRemove);
  236562. if (listeners.size() == 0)
  236563. [session removeOutput: imageOutput];
  236564. }
  236565. void callListeners (CIImage* frame, int w, int h)
  236566. {
  236567. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236568. Image image (cgImage);
  236569. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236570. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236571. CGContextFlush (cgImage->context);
  236572. const ScopedLock sl (listenerLock);
  236573. for (int i = listeners.size(); --i >= 0;)
  236574. {
  236575. CameraDevice::Listener* const l = listeners[i];
  236576. if (l != 0)
  236577. l->imageReceived (image);
  236578. }
  236579. }
  236580. QTCaptureDevice* device;
  236581. QTCaptureDeviceInput* input;
  236582. QTCaptureDevice* audioDevice;
  236583. QTCaptureDeviceInput* audioInput;
  236584. QTCaptureSession* session;
  236585. QTCaptureMovieFileOutput* fileOutput;
  236586. QTCaptureDecompressedVideoOutput* imageOutput;
  236587. QTCaptureCallbackDelegate* callbackDelegate;
  236588. String openingError;
  236589. Array<CameraDevice::Listener*> listeners;
  236590. CriticalSection listenerLock;
  236591. };
  236592. END_JUCE_NAMESPACE
  236593. @implementation QTCaptureCallbackDelegate
  236594. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236595. internalDev: (QTCameraDeviceInteral*) d
  236596. {
  236597. [super init];
  236598. owner = owner_;
  236599. internal = d;
  236600. firstPresentationTime = 0;
  236601. averageTimeOffset = 0;
  236602. return self;
  236603. }
  236604. - (void) dealloc
  236605. {
  236606. [super dealloc];
  236607. }
  236608. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236609. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236610. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236611. fromConnection: (QTCaptureConnection*) connection
  236612. {
  236613. if (internal->listeners.size() > 0)
  236614. {
  236615. const ScopedAutoReleasePool pool;
  236616. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236617. CVPixelBufferGetWidth (videoFrame),
  236618. CVPixelBufferGetHeight (videoFrame));
  236619. }
  236620. }
  236621. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236622. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236623. fromConnection: (QTCaptureConnection*) connection
  236624. {
  236625. const Time now (Time::getCurrentTime());
  236626. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236627. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236628. #else
  236629. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236630. #endif
  236631. int64 presentationTime = (hosttime != nil)
  236632. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236633. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236634. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236635. if (firstPresentationTime == 0)
  236636. {
  236637. firstPresentationTime = presentationTime;
  236638. averageTimeOffset = timeDiff;
  236639. }
  236640. else
  236641. {
  236642. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236643. }
  236644. }
  236645. @end
  236646. BEGIN_JUCE_NAMESPACE
  236647. class QTCaptureViewerComp : public NSViewComponent
  236648. {
  236649. public:
  236650. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236651. {
  236652. const ScopedAutoReleasePool pool;
  236653. captureView = [[QTCaptureView alloc] init];
  236654. [captureView setCaptureSession: internal->session];
  236655. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236656. setView (captureView);
  236657. }
  236658. ~QTCaptureViewerComp()
  236659. {
  236660. setView (0);
  236661. [captureView setCaptureSession: nil];
  236662. [captureView release];
  236663. }
  236664. QTCaptureView* captureView;
  236665. };
  236666. CameraDevice::CameraDevice (const String& name_, int index)
  236667. : name (name_)
  236668. {
  236669. isRecording = false;
  236670. internal = new QTCameraDeviceInteral (this, index);
  236671. }
  236672. CameraDevice::~CameraDevice()
  236673. {
  236674. stopRecording();
  236675. delete static_cast <QTCameraDeviceInteral*> (internal);
  236676. internal = 0;
  236677. }
  236678. Component* CameraDevice::createViewerComponent()
  236679. {
  236680. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236681. }
  236682. const String CameraDevice::getFileExtension()
  236683. {
  236684. return ".mov";
  236685. }
  236686. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236687. {
  236688. stopRecording();
  236689. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236690. d->callbackDelegate->firstPresentationTime = 0;
  236691. file.deleteFile();
  236692. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236693. // out wrong, so we'll put some audio in there too..,
  236694. d->addDefaultAudioInput();
  236695. [d->session addOutput: d->fileOutput error: nil];
  236696. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236697. for (;;)
  236698. {
  236699. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236700. if (connection == 0)
  236701. break;
  236702. QTCompressionOptions* options = 0;
  236703. NSString* mediaType = [connection mediaType];
  236704. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236705. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236706. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236707. : @"QTCompressionOptions240SizeH264Video"];
  236708. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236709. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236710. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236711. }
  236712. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236713. isRecording = true;
  236714. }
  236715. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236716. {
  236717. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236718. if (d->callbackDelegate->firstPresentationTime != 0)
  236719. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236720. return Time();
  236721. }
  236722. void CameraDevice::stopRecording()
  236723. {
  236724. if (isRecording)
  236725. {
  236726. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236727. isRecording = false;
  236728. }
  236729. }
  236730. void CameraDevice::addListener (Listener* listenerToAdd)
  236731. {
  236732. if (listenerToAdd != 0)
  236733. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236734. }
  236735. void CameraDevice::removeListener (Listener* listenerToRemove)
  236736. {
  236737. if (listenerToRemove != 0)
  236738. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236739. }
  236740. const StringArray CameraDevice::getAvailableDevices()
  236741. {
  236742. const ScopedAutoReleasePool pool;
  236743. StringArray results;
  236744. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236745. for (int i = 0; i < (int) [devs count]; ++i)
  236746. {
  236747. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236748. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236749. }
  236750. return results;
  236751. }
  236752. CameraDevice* CameraDevice::openDevice (int index,
  236753. int minWidth, int minHeight,
  236754. int maxWidth, int maxHeight)
  236755. {
  236756. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236757. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236758. return d.release();
  236759. return 0;
  236760. }
  236761. #endif
  236762. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236763. #endif
  236764. #endif
  236765. END_JUCE_NAMESPACE
  236766. #endif
  236767. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236768. #endif
  236769. #endif